@apextelemed/partner-core 0.4.1 → 0.5.0

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.
Files changed (44) hide show
  1. package/dist/api/index.d.ts +2 -2
  2. package/dist/api/index.js +3 -3
  3. package/dist/api/index.jsx +5 -3
  4. package/dist/{cart-CBH8Em8f.d.ts → cart-BwUwSzWh.d.ts} +25 -2
  5. package/dist/chunk/{OJSQZEB3.js → 4W5ONAFF.js} +7 -6
  6. package/dist/chunk/4W5ONAFF.js.map +1 -0
  7. package/dist/chunk/{DS4E7FAI.js → 4YUUZ532.js} +14 -4
  8. package/dist/chunk/4YUUZ532.js.map +1 -0
  9. package/dist/chunk/{T6IKS76T.jsx → 5CXUPFZU.jsx} +33 -15
  10. package/dist/chunk/{EIXZJX6R.js → 6MDLP62Y.js} +34 -17
  11. package/dist/chunk/6MDLP62Y.js.map +1 -0
  12. package/dist/chunk/{NYLIUR7O.jsx → 6QC4BETO.jsx} +6 -5
  13. package/dist/chunk/{MN4GWQC4.js → 7COJH6FZ.js} +308 -155
  14. package/dist/chunk/7COJH6FZ.js.map +1 -0
  15. package/dist/chunk/{MEF3FUQB.jsx → B5RBZKAK.jsx} +1 -1
  16. package/dist/chunk/{STEVQZ6U.jsx → CXBPVQ7W.jsx} +2 -2
  17. package/dist/chunk/{NP4CMOLW.jsx → GGY7VMZ2.jsx} +5 -3
  18. package/dist/chunk/{2XJBOTK5.js → ITK5F5AI.js} +2 -2
  19. package/dist/chunk/{2XJBOTK5.js.map → ITK5F5AI.js.map} +1 -1
  20. package/dist/chunk/{YHWX4NMV.js → NNTB7KL5.js} +3 -3
  21. package/dist/chunk/{YHWX4NMV.js.map → NNTB7KL5.js.map} +1 -1
  22. package/dist/chunk/{XMYPS7PT.js → O4V2YXBF.js} +5 -4
  23. package/dist/chunk/O4V2YXBF.js.map +1 -0
  24. package/dist/chunk/{LPERM6T7.jsx → YPZVHEBG.jsx} +152 -20
  25. package/dist/chunk/{I46Y2J5W.jsx → Z2CR6WKF.jsx} +15 -2
  26. package/dist/{client-DUrhrzOG.d.ts → client-Cm6n4V0r.d.ts} +8 -0
  27. package/dist/flows/index.d.ts +49 -3
  28. package/dist/flows/index.js +6 -6
  29. package/dist/flows/index.jsx +10 -8
  30. package/dist/index/index.d.ts +3 -3
  31. package/dist/index/index.js +7 -7
  32. package/dist/index/index.jsx +13 -9
  33. package/dist/pages/index.d.ts +1 -1
  34. package/dist/pages/index.js +5 -5
  35. package/dist/pages/index.jsx +5 -5
  36. package/dist/stores/index.d.ts +1 -1
  37. package/dist/stores/index.js +2 -2
  38. package/dist/stores/index.jsx +2 -2
  39. package/package.json +1 -1
  40. package/dist/chunk/DS4E7FAI.js.map +0 -1
  41. package/dist/chunk/EIXZJX6R.js.map +0 -1
  42. package/dist/chunk/MN4GWQC4.js.map +0 -1
  43. package/dist/chunk/OJSQZEB3.js.map +0 -1
  44. package/dist/chunk/XMYPS7PT.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/flows/survey.ts","../../src/flows/address.ts","../../src/flows/_internal/cardTokenizer.ts","../../src/flows/checkout.ts","../../src/flows/cartCheckout.ts","../../src/flows/signup.ts","../../src/flows/register.ts","../../src/flows/subscriptionStatus.ts","../../src/flows/subscribe.ts","../../src/flows/dashboard.ts","../../src/flows/shipping.ts","../../src/utils/calendarDate.ts","../../src/flows/tracker.ts","../../src/flows/customer360.ts","../../src/flows/memberPortal.ts","../../src/flows/updatePaymentMethod.ts","../../src/flows/supportRealtime.ts","../../src/flows/messages.ts","../../src/flows/affiliate.ts","../../src/flows/funnel.ts","../../src/flows/surveyV2.ts"],"names":["step","err","ms","createSignal","onMount","createEffect","dollars","DRAFT_TTL_MS","MAX_RESTORABLE_STEP","draftKey","loadDraft","saveDraft","clearDraft","stages","events","DAY_MS","at","fetchPendingSurveys","createResource","primarySubscription","toTrackerRequest","onCleanup","usePackageSurveyV2Flow"],"mappings":";;;;;;;;AAyHA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AAAA,EAER;AACA,EAAA,IAAI,CAAC,GAAA,CAAI,EAAA,IAAM,CAAC,QAAQ,OAAA,EAAS;AAC/B,IAAA,MAAM,IAAI,KAAA,CAAM,MAAA,EAAQ,SAAS,CAAA,0BAAA,EAA6B,GAAA,CAAI,MAAM,CAAA,CAAA,CAAG,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,EAAE,OAAA,EAAS,MAAA,CAAO,OAAA,EAAQ;AACnC","file":"4W5ONAFF.js","sourcesContent":["import { createSignal, createEffect, onMount, type Accessor } from 'solid-js';\nimport { apexApi, usersApi, ApiError, newIdempotencyKey, type User } from '../api/client';\nimport cartStore from '../stores/cart';\nimport medicationStore from '../stores/medication';\nimport { getConfig } from '../config';\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface SurveyOption {\n id: string;\n text: string;\n value: string;\n}\n\nexport interface VisibilityCondition {\n conditionId: string;\n questionId: string;\n operator: string;\n value: string;\n}\n\nexport interface SurveyQuestion {\n id: string;\n type: string;\n text: string;\n required: boolean;\n options?: SurveyOption[];\n helpText?: string;\n visibilityConditions?: VisibilityCondition[];\n}\n\nexport interface FlatStep {\n sectionIndex: number;\n stepIndex: number;\n sectionTitle: string;\n stepTitle?: string;\n stepDescription?: string;\n questions: SurveyQuestion[];\n}\n\ninterface RawSection {\n sectionId: string;\n order: number;\n title: string;\n description?: string;\n steps: RawStep[];\n}\n\ninterface RawStep {\n stepId: string;\n order: number;\n title?: string;\n description?: string;\n questions: RawQuestion[];\n}\n\ninterface RawQuestion {\n questionId: string;\n order: number;\n text: string;\n type: string;\n required: boolean;\n options?: { optionId: string; text: string; value: string }[];\n helpText?: string;\n visibilityConditions?: VisibilityCondition[];\n}\n\ninterface SurveyData {\n surveyId: string;\n name: string;\n description?: string;\n sections: RawSection[];\n drugs?: { drugId: string; name: string; description?: string }[];\n}\n\nexport interface DrugResult {\n drugId: string;\n drugName: string;\n qualified: boolean;\n disqualificationReason?: string;\n isRecommended?: boolean;\n recommendationReasons?: string[];\n}\n\ninterface QualificationResult {\n qualified: boolean;\n disqualified?: boolean;\n disqualificationReason?: string;\n drugResults?: DrugResult[];\n allDisqualified?: boolean;\n}\n\ninterface SubmissionResult {\n responseId: string;\n qualified: boolean;\n disqualificationReason?: string;\n drugResults?: DrugResult[];\n allowSelection?: boolean;\n}\n\nexport type AnswerValue = string | string[] | number | boolean | Record<string, unknown>;\n\nexport type SurveyOutcome =\n | { kind: 'loading' }\n | { kind: 'needs_medication_selection' }\n | { kind: 'load_failed'; error: string }\n | { kind: 'in_progress' }\n | { kind: 'disqualified'; reason: string }\n | { kind: 'drug_selection'; drugs: DrugResult[] }\n | { kind: 'completed' };\n\n// ── Draft persistence ───────────────────────────────────────────────\n//\n// Answers, step, and submission identity survive a refresh / accidental back\n// so a patient 9 steps into the wizard doesn't lose everything. Deliberately\n// sessionStorage, NOT localStorage: answers are health information — they\n// should outlive a reload of the same tab, not the tab itself (and never leak\n// to the next user of a shared machine the way the shopping cart may).\n// The idempotency keys ride along so a refresh mid-submit retries the SAME\n// logical operation and the backend dedupes it.\n\nconst SURVEY_DRAFT_TTL_MS = 24 * 3600 * 1000;\n\ninterface SurveyDraft {\n surveyId?: string;\n currentStep?: number;\n answers?: Record<string, AnswerValue>;\n responseId?: string;\n submitSurveyKey?: string;\n createRequestKey?: string;\n savedAt?: number;\n}\n\nfunction surveyDraftKey(): string {\n return `${getConfig().storagePrefix}-survey-draft`;\n}\n\n/** Never throws: an unconfigured host or blocked storage just means no draft. */\nfunction loadSurveyDraft(): SurveyDraft {\n try {\n const raw = sessionStorage.getItem(surveyDraftKey());\n if (!raw) return {};\n const parsed = JSON.parse(raw) as SurveyDraft;\n if (parsed.savedAt && Date.now() - parsed.savedAt > SURVEY_DRAFT_TTL_MS) {\n sessionStorage.removeItem(surveyDraftKey());\n return {};\n }\n return parsed ?? {};\n } catch {\n return {};\n }\n}\n\nfunction saveSurveyDraft(draft: SurveyDraft): void {\n try {\n sessionStorage.setItem(surveyDraftKey(), JSON.stringify({ ...draft, savedAt: Date.now() }));\n } catch {\n // noop — persistence is best-effort\n }\n}\n\nfunction clearSurveyDraft(): void {\n try {\n sessionStorage.removeItem(surveyDraftKey());\n } catch {\n // noop\n }\n}\n\n// ── Pure helpers ────────────────────────────────────────────────────\n\nfunction flattenSurveyToSteps(data: SurveyData): FlatStep[] {\n const steps: FlatStep[] = [];\n const sortedSections = [...(data.sections || [])].sort((a, b) => a.order - b.order);\n\n sortedSections.forEach((section, sectionIndex) => {\n const sortedSteps = [...(section.steps || [])].sort((a, b) => a.order - b.order);\n\n sortedSteps.forEach((step, stepIndex) => {\n const sortedQuestions = [...(step.questions || [])].sort((a, b) => a.order - b.order);\n\n const questions: SurveyQuestion[] = sortedQuestions.map((q) => ({\n id: q.questionId,\n type: q.type,\n text: q.text,\n required: q.required ?? true,\n helpText: q.helpText,\n options: q.options?.map((opt) => ({\n id: opt.optionId,\n text: opt.text,\n value: opt.value,\n })),\n visibilityConditions: q.visibilityConditions,\n }));\n\n if (questions.length > 0) {\n steps.push({\n sectionIndex,\n stepIndex,\n sectionTitle: section.title,\n stepTitle: step.title,\n stepDescription: step.description,\n questions,\n });\n }\n });\n });\n\n return steps;\n}\n\nfunction evaluateCondition(\n condition: VisibilityCondition,\n answers: Record<string, AnswerValue>,\n): boolean {\n const answer = answers[condition.questionId];\n if (answer === undefined || answer === null || answer === '') return false;\n\n const answerStr = String(answer).toLowerCase();\n const conditionValue = condition.value.toLowerCase();\n\n switch (condition.operator.toLowerCase()) {\n case 'equals':\n case 'eq':\n case '=':\n case '==':\n return answerStr === conditionValue;\n case 'not_equals':\n case 'neq':\n case 'ne':\n case '!=':\n return answerStr !== conditionValue;\n case 'contains':\n if (Array.isArray(answer)) {\n return answer.some((v) => String(v).toLowerCase() === conditionValue);\n }\n return answerStr.includes(conditionValue);\n default:\n return answerStr === conditionValue;\n }\n}\n\nexport function isQuestionVisible(\n question: SurveyQuestion,\n answers: Record<string, AnswerValue>,\n): boolean {\n if (!question.visibilityConditions || question.visibilityConditions.length === 0) return true;\n return question.visibilityConditions.every((c) => evaluateCondition(c, answers));\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport interface UseSurveyFlowOptions {\n /** ms to wait on the completion screen before firing `onComplete`. Default 3000. */\n completionRedirectDelayMs?: number;\n}\n\nexport interface SurveyFlow {\n // Outcome state machine — drives top-level rendering\n outcome: Accessor<SurveyOutcome>;\n\n // Survey metadata (valid once outcome is in_progress / drug_selection / completed)\n surveyTitle: Accessor<string>;\n totalSteps: Accessor<number>;\n\n // Active step\n currentStep: Accessor<number>;\n step: Accessor<FlatStep | null>;\n visibleQuestions: Accessor<SurveyQuestion[]>;\n\n // Answer state\n answers: Accessor<Record<string, AnswerValue>>;\n setAnswer: (questionId: string, value: AnswerValue) => void;\n\n // Inline state for the active step\n validationError: Accessor<string | null>;\n submitting: Accessor<boolean>;\n\n // Navigation\n next: () => Promise<void>;\n back: () => void;\n isLastStep: Accessor<boolean>;\n\n // Drug selection (rare — qualified for multiple drugs)\n selectedDrugId: Accessor<string>;\n setSelectedDrugId: (id: string) => void;\n confirmDrugSelection: () => Promise<void>;\n}\n\nexport function useSurveyFlow(options: UseSurveyFlowOptions = {}): SurveyFlow {\n const { completionRedirectDelayMs: _ignored = 3000 } = options;\n\n const [outcome, setOutcome] = createSignal<SurveyOutcome>({ kind: 'loading' });\n const [surveyId, setSurveyId] = createSignal('');\n const [surveyTitle, setSurveyTitle] = createSignal('');\n const [steps, setSteps] = createSignal<FlatStep[]>([]);\n\n const [currentStep, setCurrentStep] = createSignal(0);\n const [answers, setAnswers] = createSignal<Record<string, AnswerValue>>({});\n\n const [validationError, setValidationError] = createSignal<string | null>(null);\n const [submitting, setSubmitting] = createSignal(false);\n\n const [userProfile, setUserProfile] = createSignal<User | null>(null);\n const [responseId, setResponseId] = createSignal('');\n const [selectedDrugId, setSelectedDrugId] = createSignal('');\n\n // Idempotency keys, reused across retries so the backend dedupes. Separate\n // keys for the two distinct writes (survey submit vs. prescription request);\n // each rotates only after a DEFINITIVE failure and is reused after an\n // ambiguous one (the write may have committed — dedupe it rather than\n // duplicate it).\n const [submitSurveyKey, setSubmitSurveyKey] = createSignal(newIdempotencyKey());\n const [createRequestKey, setCreateRequestKey] = createSignal(newIdempotencyKey());\n\n // Draft writes are armed only after the mount rehydrate has run, so the\n // initial empty state can never clobber a stored draft before it's read.\n const [hydrated, setHydrated] = createSignal(false);\n\n const totalSteps = () => steps().length;\n const isLastStep = () => currentStep() >= totalSteps() - 1;\n const step = () => steps()[currentStep()] ?? null;\n\n const visibleQuestions = () => {\n const s = step();\n if (!s) return [];\n return s.questions.filter((q) => isQuestionVisible(q, answers()));\n };\n\n // ── Load on mount ────────────────────────────────────────────────\n\n onMount(async () => {\n const cartItems = cartStore.items();\n const hasCart = cartItems.length > 0;\n\n if (!hasCart && !medicationStore.selected()) {\n setOutcome({ kind: 'needs_medication_selection' });\n return;\n }\n\n try {\n let sid: string | undefined;\n\n if (hasCart) {\n if (cartStore.isMultiItem() || cartStore.hasGlp1()) {\n const configRes = (await apexApi.getConfig('glp1')) as { surveyId?: string };\n sid = configRes.surveyId;\n }\n\n if (!sid) {\n const firstDrugId = cartItems[0].drugId;\n if (firstDrugId) {\n try {\n const match = await apexApi.getSurveyForDrug(firstDrugId);\n sid = match?.surveyId;\n } catch (err) {\n console.warn('[useSurveyFlow] getSurveyForDrug failed for cart item:', err);\n }\n }\n }\n } else {\n const drugId = medicationStore.selected()?.drugId;\n if (drugId) {\n try {\n const match = await apexApi.getSurveyForDrug(drugId);\n sid = match?.surveyId;\n } catch (err) {\n console.warn('[useSurveyFlow] getSurveyForDrug failed:', err);\n }\n }\n }\n\n if (!sid) {\n const configRes = (await apexApi.getConfig('generic')) as { surveyId?: string };\n sid = configRes.surveyId;\n }\n\n if (!sid) {\n setOutcome({ kind: 'load_failed', error: 'No survey configured. Please contact support.' });\n return;\n }\n setSurveyId(sid);\n\n // Patient info hydration — non-fatal\n try {\n const profileRes = await usersApi.getProfile();\n if (profileRes.data) setUserProfile(profileRes.data);\n } catch {\n // ignore\n }\n\n const surveyData = (await apexApi.getSurvey(sid)) as SurveyData;\n if (!surveyData || !surveyData.sections?.length) {\n setOutcome({ kind: 'load_failed', error: 'Survey not found.' });\n return;\n }\n\n setSurveyTitle(surveyData.name);\n const flat = flattenSurveyToSteps(surveyData);\n setSteps(flat);\n\n // Rehydrate a same-survey draft BEFORE going in_progress, so a refresh\n // resumes at the saved step with the saved answers instead of step 0.\n // A draft for a DIFFERENT survey (the patient switched medications) is\n // stale — its answers don't map onto these questions — so it's dropped.\n const draft = loadSurveyDraft();\n if (draft.surveyId === sid) {\n if (draft.answers) setAnswers(draft.answers);\n setCurrentStep(Math.min(Math.max(draft.currentStep ?? 0, 0), Math.max(flat.length - 1, 0)));\n if (draft.responseId) setResponseId(draft.responseId);\n if (draft.submitSurveyKey) setSubmitSurveyKey(draft.submitSurveyKey);\n if (draft.createRequestKey) setCreateRequestKey(draft.createRequestKey);\n } else if (draft.surveyId) {\n clearSurveyDraft();\n }\n setHydrated(true);\n\n setOutcome({ kind: 'in_progress' });\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Failed to load survey.';\n setOutcome({ kind: 'load_failed', error: msg });\n }\n });\n\n // ── Auto-save draft ──────────────────────────────────────────────\n\n onMount(() => {\n createEffect(() => {\n if (!hydrated()) return;\n const kind = outcome().kind;\n // A recorded terminal outcome must not be resumable: restoring answers\n // after completion (or disqualification) would invite a duplicate\n // submission of an already-decided survey.\n if (kind === 'completed' || kind === 'disqualified') {\n clearSurveyDraft();\n return;\n }\n saveSurveyDraft({\n surveyId: surveyId(),\n currentStep: currentStep(),\n answers: answers(),\n responseId: responseId() || undefined,\n submitSurveyKey: submitSurveyKey(),\n createRequestKey: createRequestKey(),\n });\n });\n });\n\n // ── Answers ──────────────────────────────────────────────────────\n\n function setAnswer(questionId: string, value: AnswerValue) {\n setAnswers((prev) => ({ ...prev, [questionId]: value }));\n }\n\n function validateCurrentStep(): string | null {\n const visible = visibleQuestions();\n for (const q of visible) {\n if (!q.required) continue;\n const val = answers()[q.id];\n if (val === undefined || val === null || val === '') {\n return `Please answer: ${q.text}`;\n }\n if (Array.isArray(val) && val.length === 0) {\n return `Please select at least one option for: ${q.text}`;\n }\n }\n return null;\n }\n\n // ── Submission ───────────────────────────────────────────────────\n\n function buildPatientInfo() {\n const profile = userProfile();\n const p = profile as Record<string, unknown> | null;\n return {\n firstName: profile?.firstName || (p?.first_name as string) || '',\n lastName: profile?.lastName || (p?.last_name as string) || '',\n email: profile?.email || '',\n phone: (p?.phone as string) || undefined,\n // No fabricated fallbacks: a missing field stays empty rather than being\n // filled with fake PII (dob 1990-01-01, 123 Main St, TX 00000) that would\n // otherwise be forwarded to Apex and could ship a real Rx to a fake\n // address. `hasCompletePatientInfo` gates the cart/Rx path on these.\n dob: (p?.dateOfBirth as string) || (p?.date_of_birth as string) || (p?.dob as string) || '',\n street1: (p?.address1 as string) || (p?.street1 as string) || '',\n street2: (p?.address2 as string) || (p?.street2 as string) || undefined,\n city: (p?.city as string) || '',\n state: (p?.state as string) || '',\n zipCode: (p?.zip as string) || (p?.zipCode as string) || '',\n };\n }\n\n /** True only when every field the cart/Rx path forwards to Apex is real.\n * Defined over buildPatientInfo()'s output — with fabrication removed, an\n * incomplete profile yields empty strings here, so this genuinely gates. */\n function hasCompletePatientInfo(info: ReturnType<typeof buildPatientInfo>): boolean {\n return Boolean(\n info.firstName &&\n info.lastName &&\n info.email &&\n info.dob &&\n info.street1 &&\n info.city &&\n info.state &&\n info.zipCode,\n );\n }\n\n async function submit() {\n // Re-entrancy guard: a double-click / impatient retry must not fire a second\n // survey submission or a second prescription request.\n if (submitting()) return;\n\n const err = validateCurrentStep();\n if (err) {\n setValidationError(err);\n return;\n }\n setValidationError(null);\n setSubmitting(true);\n\n try {\n const patientInfo = buildPatientInfo();\n\n // Apex validates patientInfo at the submit step itself — dob (YYYY-MM-DD),\n // street1/city, state (2 chars) and zipCode are all required and\n // format-checked — so a submit with blank or partial PII 400s before we\n // ever reach qualification or drug selection. This legacy flow derives\n // patientInfo from the account profile with no fabricated fallbacks, so an\n // anonymous or incomplete-profile user would otherwise fire a doomed submit\n // and see a generic \"Submission failed.\" Fail closed here instead, with\n // actionable copy. (SurveyV2 collects PII in-survey and is unaffected.)\n if (!hasCompletePatientInfo(patientInfo)) {\n setValidationError(\n 'We couldn’t confirm your account details. Please make sure you’re signed in and your profile — name, date of birth, and shipping address — is complete, then try again.',\n );\n return;\n }\n\n // Submit the survey only if a prior attempt hasn't already produced a\n // responseId. Re-submitting would create a duplicate survey response; on a\n // retry we reuse the existing responseId and go straight to the request.\n let respId = responseId();\n if (!respId) {\n const formattedAnswers = Object.entries(answers()).map(([questionId, value]) => ({\n questionId,\n value,\n }));\n\n let result: SubmissionResult;\n try {\n result = (await apexApi.submitSurvey(\n {\n surveyId: surveyId(),\n answers: formattedAnswers,\n patientInfo,\n },\n { idempotencyKey: submitSurveyKey() },\n )) as SubmissionResult;\n } catch (e) {\n // Mirror the createRequest handling below: reuse the key on an\n // ambiguous failure (a submit that may have committed dedupes on\n // retry); rotate it on a definitive failure so a corrected retry is a\n // fresh operation and doesn't replay the cached stale 4xx.\n const ambiguous = e instanceof ApiError && e.ambiguous;\n if (!ambiguous) setSubmitSurveyKey(newIdempotencyKey());\n setValidationError(\n ambiguous\n ? \"We couldn't confirm your submission went through. Please try again.\"\n : e instanceof Error\n ? e.message\n : 'Submission failed. Please try again.',\n );\n return;\n }\n\n if (!result) {\n setValidationError('Submission failed. Please try again.');\n return;\n }\n\n setResponseId(result.responseId);\n respId = result.responseId;\n\n if (!result.qualified) {\n setOutcome({\n kind: 'disqualified',\n reason:\n result.disqualificationReason ??\n 'Based on your responses, you do not qualify at this time.',\n });\n return;\n }\n }\n\n const cartItems = cartStore.items();\n const promoCode = cartStore.appliedPromo()?.code;\n\n if (cartItems.length > 0) {\n // patientInfo completeness is gated before submitSurvey above, so the\n // cart/Rx path here always carries real PII — never a fabricated address.\n try {\n await apexApi.createRequest(\n {\n surveyResponseId: respId,\n patientInfo,\n promoCode,\n medications: cartItems.map((i) => ({\n productId: i.productId,\n productName: i.productName,\n quantity: i.quantity,\n dosage: i.dosage,\n // Dose redesign (Phase 8) + SKU identity (S4): forward intake hints\n // only when present, so an absent value leaves the payload\n // byte-identical. `requestedSkuId` is the preferred stable form.\n ...(i.requestedSku ? { requestedSku: i.requestedSku } : {}),\n ...(i.requestedSkuId ? { requestedSkuId: i.requestedSkuId } : {}),\n ...(i.requestedClinicalDose ? { requestedClinicalDose: i.requestedClinicalDose } : {}),\n })),\n caseNotes: `Multi-drug cart checkout (${cartItems.length} item${cartItems.length === 1 ? '' : 's'}).`,\n },\n { idempotencyKey: createRequestKey() },\n );\n } catch (e) {\n console.error('[useSurveyFlow] createRequest failed:', e);\n // responseId is retained, so a retry skips resubmission and only\n // re-attempts the request. Reuse the same key on an ambiguous failure\n // (a request that may have committed dedupes); rotate it on a\n // definitive failure so a corrected retry is a fresh operation.\n const ambiguous = e instanceof ApiError && e.ambiguous;\n if (!ambiguous) setCreateRequestKey(newIdempotencyKey());\n setValidationError(\n ambiguous\n ? \"We couldn't confirm your request went through. Please try again.\"\n : e instanceof Error\n ? e.message\n : 'Failed to create prescription request.',\n );\n return;\n }\n cartStore.clear();\n } else {\n const preSelected = medicationStore.selected();\n const preSelectedDrugId = preSelected?.drugId;\n\n if (preSelectedDrugId) {\n try {\n await apexApi.createRequest(\n {\n drugId: preSelectedDrugId,\n surveyResponseId: respId,\n promoCode,\n caseNotes: `Patient selected: ${preSelected.drugName}`,\n },\n { idempotencyKey: createRequestKey() },\n );\n } catch {\n // non-fatal — survey submission already saved\n }\n } else {\n try {\n await apexApi.createRequest(\n {\n surveyResponseId: respId,\n promoCode,\n caseNotes: 'Patient requesting general consultation. No medication pre-selected.',\n },\n { idempotencyKey: createRequestKey() },\n );\n } catch {\n // non-fatal\n }\n }\n }\n\n medicationStore.clear();\n setOutcome({ kind: 'completed' });\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Submission failed.';\n setValidationError(msg);\n } finally {\n setSubmitting(false);\n }\n }\n\n // ── Step navigation ──────────────────────────────────────────────\n\n async function next() {\n const err = validateCurrentStep();\n if (err) {\n setValidationError(err);\n return;\n }\n setValidationError(null);\n\n if (isLastStep()) {\n await submit();\n return;\n }\n\n // Per-step qualification check — short-circuits to disqualified if a hard fail is detected.\n try {\n setSubmitting(true);\n const formattedAnswers = Object.entries(answers()).map(([questionId, value]) => ({\n questionId,\n value,\n }));\n const qual = (await apexApi.checkQualification(\n surveyId(),\n formattedAnswers,\n )) as QualificationResult;\n\n if (qual && (qual.disqualified || qual.allDisqualified)) {\n setOutcome({\n kind: 'disqualified',\n reason:\n qual.disqualificationReason ??\n 'Based on your responses, you do not qualify for this medication at this time.',\n });\n return;\n }\n } catch {\n // Soft-fail — re-validate on submit\n } finally {\n setSubmitting(false);\n }\n\n setCurrentStep((s) => s + 1);\n }\n\n function back() {\n setValidationError(null);\n if (currentStep() > 0) setCurrentStep((s) => s - 1);\n }\n\n // ── Drug selection (qualified for multiple drugs) ────────────────\n\n async function confirmDrugSelection() {\n if (!selectedDrugId()) {\n setValidationError('Please select a medication.');\n return;\n }\n setValidationError(null);\n setSubmitting(true);\n\n try {\n await apexApi.selectDrug({\n surveyId: surveyId(),\n drugId: selectedDrugId(),\n responseId: responseId(),\n });\n\n try {\n await apexApi.createRequest({\n drugId: selectedDrugId(),\n surveyResponseId: responseId(),\n });\n } catch {\n // non-fatal — survey + selection are already saved\n }\n\n setOutcome({ kind: 'completed' });\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Selection failed.';\n setValidationError(msg);\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n outcome,\n surveyTitle,\n totalSteps,\n currentStep,\n step,\n visibleQuestions,\n answers,\n setAnswer,\n validationError,\n submitting,\n next,\n back,\n isLastStep,\n selectedDrugId,\n setSelectedDrugId,\n confirmDrugSelection,\n };\n}\n","import { createSignal, type Accessor } from 'solid-js';\nimport { addressesApi, type AddressVerifyResult, type CheckoutAddress } from '../api/client';\nimport { getConfig } from '../config';\n\n// ── US states ───────────────────────────────────────────────────────\n// Canonical list. Signup/Subscribe/Survey/SurveyV2 each hard-code their own\n// copy today; those should migrate to these exports as the flows unify.\n\n/**\n * The canonical state list, ordered by full name (DC last). Single source of\n * truth for the abbreviations, the dropdown labels, and the name→abbreviation\n * normalization below — they drifted while they were three separate literals.\n */\nconst US_STATE_LIST = [\n { value: 'AL', label: 'Alabama' }, { value: 'AK', label: 'Alaska' },\n { value: 'AZ', label: 'Arizona' }, { value: 'AR', label: 'Arkansas' },\n { value: 'CA', label: 'California' }, { value: 'CO', label: 'Colorado' },\n { value: 'CT', label: 'Connecticut' }, { value: 'DE', label: 'Delaware' },\n { value: 'FL', label: 'Florida' }, { value: 'GA', label: 'Georgia' },\n { value: 'HI', label: 'Hawaii' }, { value: 'ID', label: 'Idaho' },\n { value: 'IL', label: 'Illinois' }, { value: 'IN', label: 'Indiana' },\n { value: 'IA', label: 'Iowa' }, { value: 'KS', label: 'Kansas' },\n { value: 'KY', label: 'Kentucky' }, { value: 'LA', label: 'Louisiana' },\n { value: 'ME', label: 'Maine' }, { value: 'MD', label: 'Maryland' },\n { value: 'MA', label: 'Massachusetts' }, { value: 'MI', label: 'Michigan' },\n { value: 'MN', label: 'Minnesota' }, { value: 'MS', label: 'Mississippi' },\n { value: 'MO', label: 'Missouri' }, { value: 'MT', label: 'Montana' },\n { value: 'NE', label: 'Nebraska' }, { value: 'NV', label: 'Nevada' },\n { value: 'NH', label: 'New Hampshire' }, { value: 'NJ', label: 'New Jersey' },\n { value: 'NM', label: 'New Mexico' }, { value: 'NY', label: 'New York' },\n { value: 'NC', label: 'North Carolina' }, { value: 'ND', label: 'North Dakota' },\n { value: 'OH', label: 'Ohio' }, { value: 'OK', label: 'Oklahoma' },\n { value: 'OR', label: 'Oregon' }, { value: 'PA', label: 'Pennsylvania' },\n { value: 'RI', label: 'Rhode Island' }, { value: 'SC', label: 'South Carolina' },\n { value: 'SD', label: 'South Dakota' }, { value: 'TN', label: 'Tennessee' },\n { value: 'TX', label: 'Texas' }, { value: 'UT', label: 'Utah' },\n { value: 'VT', label: 'Vermont' }, { value: 'VA', label: 'Virginia' },\n { value: 'WA', label: 'Washington' }, { value: 'WV', label: 'West Virginia' },\n { value: 'WI', label: 'Wisconsin' }, { value: 'WY', label: 'Wyoming' },\n { value: 'DC', label: 'District of Columbia' },\n] as const;\n\nexport const US_STATES: readonly string[] = US_STATE_LIST.map((s) => s.value);\n\n/** Options for a state `<Select>`, labelled by full name. */\nexport const US_STATE_OPTIONS: Array<{ value: string; label: string }> = US_STATE_LIST.map((s) => ({\n value: s.value,\n label: s.label,\n}));\n\nconst US_STATE_SET = new Set<string>(US_STATES);\n\nconst US_STATE_LABELS = new Map<string, string>(US_STATE_LIST.map((s) => [s.value, s.label]));\n\n/** Full state name for an abbreviation (`'TX'` → `'Texas'`); the input back if unknown. */\nexport function stateLabel(abbreviation: string): string {\n return US_STATE_LABELS.get(abbreviation.trim().toUpperCase()) ?? abbreviation;\n}\n\n// ── Tenant state availability ───────────────────────────────────────\n// Some tenants can't serve every state (licensing/pharmacy coverage). The\n// tenant declares `unavailableStates` (+ an optional user-facing note) in\n// configure(); dropdowns should use the filtered exports below instead of the\n// raw US_STATE_OPTIONS. Reading config is guarded so pure helpers stay usable\n// before configure() (tests, early boot) — unconfigured means unrestricted.\n//\n// A second source exists for surveys: the composed survey carries the Apex\n// partner's own `excludedStates`, which is the list the server actually\n// enforces at qualification time. Callers pass it as `extraExcluded` so the\n// dropdown matches the server instead of relying on each site restating the\n// list in configure() — restating it is how a state ends up selectable and\n// then denied on submit.\n\nfunction unavailableStateSet(extraExcluded?: readonly string[]): Set<string> {\n const extra = (extraExcluded ?? []).map((s) => s.toUpperCase());\n try {\n return new Set([...(getConfig().unavailableStates ?? []).map((s) => s.toUpperCase()), ...extra]);\n } catch {\n return new Set(extra);\n }\n}\n\n/** US_STATES minus the tenant's `unavailableStates` and any `extraExcluded`. */\nexport function availableStates(extraExcluded?: readonly string[]): string[] {\n const excluded = unavailableStateSet(extraExcluded);\n if (excluded.size === 0) return [...US_STATES];\n return US_STATES.filter((s) => !excluded.has(s));\n}\n\n/** `availableStates()` as `<Select>` options — use for state dropdowns. */\nexport function availableStateOptions(\n extraExcluded?: readonly string[],\n): Array<{ value: string; label: string }> {\n return availableStates(extraExcluded).map((s) => ({ value: s, label: stateLabel(s) }));\n}\n\n/** True when anything restricts the state list — config, `extraExcluded`, or both. */\nexport function hasStateRestrictions(extraExcluded?: readonly string[]): boolean {\n return unavailableStateSet(extraExcluded).size > 0;\n}\n\n/** The tenant's configured availability note (e.g. \"…cannot provide\n * medications to customers in Delaware.\"), or null when unrestricted. */\nexport function stateAvailabilityNote(): string | null {\n try {\n return getConfig().unavailableStatesNote ?? null;\n } catch {\n return null;\n }\n}\n\n// Full state name → abbreviation, for normalizing values that arrive as names.\nconst US_STATE_NAMES = new Map(\n US_STATE_LIST.map((s) => [s.label.toLowerCase(), s.value] as const),\n);\n\n/**\n * Coerce a state value into a canonical 2-letter abbreviation for the `<Select>`.\n * Accepts an abbreviation in any case (`tx` → `TX`) or a full name\n * (`Texas` → `TX`). Returns `''` for anything unrecognized so the field falls\n * back to its placeholder and validation prompts the user to pick a state.\n */\nexport function normalizeState(input: string | null | undefined): string {\n const t = (input ?? '').trim();\n if (!t) return '';\n const upper = t.toUpperCase();\n if (US_STATE_SET.has(upper)) return upper;\n return US_STATE_NAMES.get(t.toLowerCase()) ?? '';\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface AddressValue {\n street: string;\n street2?: string;\n city: string;\n state: string;\n zip: string;\n}\n\nexport interface AddressErrors {\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n}\n\nconst ZIP_RE = /^\\d{5}(-\\d{4})?$/;\nconst EMPTY: AddressValue = { street: '', street2: '', city: '', state: '', zip: '' };\n\n// Client-side ceiling on the deliverability round-trip. The backend fails open,\n// but a hung/slow response would still leave the awaited verify (and the Pay\n// button) spinning indefinitely. Race it against this timeout so latency fails\n// open to `unchecked` exactly like a thrown rejection does — checkout never hangs.\nconst VERIFY_TIMEOUT_MS = 3500;\n\n/** Fail-open result: unconfigured verifier, thrown error, or client timeout. */\nconst UNCHECKED_RESULT: AddressVerifyResult = { status: 'unchecked', corrected: false, messages: [] };\n\n/** Resolve `p`, or `fallback` if it doesn't settle within `ms`. Clears the timer\n * either way so a resolved verify doesn't leave a dangling timeout. */\nfunction withTimeout<T>(p: Promise<T>, ms: number, fallback: T): Promise<T> {\n let timer: ReturnType<typeof setTimeout>;\n const timeout = new Promise<T>((resolve) => {\n timer = setTimeout(() => resolve(fallback), ms);\n });\n return Promise.race([p, timeout]).finally(() => clearTimeout(timer));\n}\n\n// ── Tier-1 validation ───────────────────────────────────────────────\n// Instant, client-side: presence + US ZIP format + a known US state.\n// Deliverability (Tier-2) is a separate server-side check (Shippo).\n\nfunction requiredMsg(label: string, field: string): string {\n return label\n ? `${label} ${field} is required.`\n : `${field.charAt(0).toUpperCase()}${field.slice(1)} is required.`;\n}\n\nexport interface ValidateAddressOptions {\n /** Also reject states in the tenant's `unavailableStates`. Turn on for\n * SHIPPING addresses only — the dropdown already omits them, but a saved\n * profile address can arrive prefilled with one. Billing stays unrestricted. */\n enforceAvailability?: boolean;\n}\n\n/** `label` (e.g. \"Billing\") prefixes the messages; omit for the shipping form. */\nexport function validateAddress(a: AddressValue, label = '', opts: ValidateAddressOptions = {}): AddressErrors {\n const errors: AddressErrors = {};\n if (!a.street.trim()) errors.street = requiredMsg(label, 'street address');\n if (!a.city.trim()) errors.city = requiredMsg(label, 'city');\n if (!a.state.trim()) errors.state = requiredMsg(label, 'state');\n else if (!US_STATE_SET.has(a.state.trim().toUpperCase())) {\n errors.state = label ? `Enter a valid ${label.toLowerCase()} state.` : 'Enter a valid state.';\n } else if (opts.enforceAvailability && unavailableStateSet().has(a.state.trim().toUpperCase())) {\n errors.state = stateAvailabilityNote() ?? 'We are unable to serve this state.';\n }\n if (!a.zip.trim()) errors.zip = requiredMsg(label, 'ZIP code');\n else if (!ZIP_RE.test(a.zip.trim())) {\n errors.zip = label ? `Enter a valid ${label.toLowerCase()} ZIP code.` : 'Enter a valid ZIP code.';\n }\n return errors;\n}\n\nexport function hasErrors(e: AddressErrors): boolean {\n return Boolean(e.street || e.city || e.state || e.zip);\n}\n\n/** First error message in field order, or null — bridges the `validateAddress`\n * errors object to flows that surface a single message at a time. */\nexport function firstAddressError(e: AddressErrors): string | null {\n return e.street ?? e.city ?? e.state ?? e.zip ?? null;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport interface UseAddressPairOptions {\n /** Prefill the shipping address (e.g. from the member profile). */\n initialShipping?: Partial<AddressValue>;\n /** Prefill billing when it starts as an override; usually omitted. */\n initialBilling?: Partial<AddressValue>;\n /** Start with \"billing same as shipping\" checked. Default FALSE — see the\n * useAddressPair docs for why the billing address is surfaced rather than\n * assumed (AVS declines are otherwise invisible to the customer). */\n billingSameAsShippingDefault?: boolean;\n /** Override the deliverability verifier (defaults to `addressesApi.verify`).\n * Injectable for testing / alternate providers. */\n verify?: (a: CheckoutAddress) => Promise<AddressVerifyResult>;\n}\n\nexport interface AddressPair {\n // Shipping\n shipping: Accessor<AddressValue>;\n setShippingField: (field: keyof AddressValue, value: string) => void;\n setShipping: (patch: Partial<AddressValue>) => void;\n\n // Billing (override)\n billingSameAsShipping: Accessor<boolean>;\n setBillingSameAsShipping: (v: boolean) => void;\n billing: Accessor<AddressValue>;\n setBillingField: (field: keyof AddressValue, value: string) => void;\n\n /** True only when billing is a distinct override the user actually entered —\n * i.e. \"same as\" is unchecked AND a billing field has been edited. Until then\n * `billing`/`effectiveBilling` track live shipping. */\n billingIsOverride: Accessor<boolean>;\n\n /** Address to bill/charge to: live shipping unless billing is an override. */\n effectiveBilling: Accessor<AddressValue>;\n\n // Validation\n shippingErrors: Accessor<AddressErrors>;\n billingErrors: Accessor<AddressErrors>;\n /** Validate shipping (always) + billing (only when it's an override). Publishes\n * errors to shippingErrors()/billingErrors() for inline display. Returns true if ok. */\n validate: () => boolean;\n\n // Deliverability (server-side, Shippo)\n /** Last deliverability result for the shipping address; null until verified or\n * after any shipping edit. */\n deliverability: Accessor<AddressVerifyResult | null>;\n verifying: Accessor<boolean>;\n /** Verify the shipping address's deliverability. No-ops (returns null) when the\n * address is syntactically incomplete. Fails open (`unchecked`) on any error. */\n verifyShipping: () => Promise<AddressVerifyResult | null>;\n /** Adopt the verifier's normalized address into the shipping fields (used for a\n * `corrected` result's \"use suggested address\" action). */\n applyNormalized: () => void;\n}\n\n/**\n * Shared shipping + billing address state for checkout-bearing flows. Until the\n * user actually edits a billing field, `billing` mirrors the LIVE shipping\n * address — so the billing form always reads as populated, stays in sync if\n * shipping is later corrected, and the address charged always matches what's\n * displayed. The first billing edit \"forks\" billing into an independent\n * override; from then on it holds the user's entered values.\n *\n * \"Billing same as shipping\" defaults OFF, and consumers render the billing\n * fields unconditionally. The card's billing address is what the gateway runs\n * AVS against, so a mismatch there is charged back to the customer as a bare\n * \"This transaction has been declined.\" Defaulting the box on and hiding the\n * fields behind it meant a customer whose card bills to a different address\n * had no obvious way to notice, let alone fix it. Showing the fields (mirrored\n * from shipping, so the common case still needs no typing) makes the address\n * being billed visible before the charge rather than after the decline.\n */\nexport function useAddressPair(options: UseAddressPairOptions = {}): AddressPair {\n const [shipping, setShippingSig] = createSignal<AddressValue>({ ...EMPTY, ...options.initialShipping });\n const [billingSig, setBillingSig] = createSignal<AddressValue>({ ...EMPTY, ...options.initialBilling });\n const [billingSameAsShipping, setSame] = createSignal(options.billingSameAsShippingDefault ?? false);\n // \"Dirty\" once the user edits a billing field (or an initial override was seeded).\n const [billingDirty, setBillingDirty] = createSignal(Boolean(options.initialBilling));\n const [shippingErrors, setShippingErrors] = createSignal<AddressErrors>({});\n const [billingErrors, setBillingErrors] = createSignal<AddressErrors>({});\n const [deliverability, setDeliverability] = createSignal<AddressVerifyResult | null>(null);\n const [verifying, setVerifying] = createSignal(false);\n const verifyFn = options.verify ?? ((a: CheckoutAddress) => addressesApi.verify(a));\n\n // Monotonic generation counter guarding against stale/overlapping verifies:\n // every edit and every new verify bumps it, so a slow in-flight request that\n // resolves after a newer edit (or a newer verify) is discarded instead of\n // clobbering fresher state. verifyShipping() captures the value it started at\n // and only writes its result back while that value is still current.\n let verifyGen = 0;\n\n const invalidateVerification = () => {\n verifyGen++; // discard any in-flight verify's result\n setDeliverability(null); // editing invalidates a prior verification\n };\n\n // Billing mirrors live shipping until the user forks it with an explicit edit.\n const billing = () => (billingDirty() ? billingSig() : shipping());\n\n const setShippingField = (field: keyof AddressValue, value: string) => {\n setShippingSig((s) => ({ ...s, [field]: value }));\n invalidateVerification();\n };\n const setBillingField = (field: keyof AddressValue, value: string) => {\n // First edit seeds the override from the currently-mirrored shipping values\n // so untouched fields keep their pre-filled content instead of blanking.\n setBillingSig((b) => ({ ...(billingDirty() ? b : shipping()), [field]: value }));\n setBillingDirty(true);\n };\n const setShipping = (patch: Partial<AddressValue>) => {\n setShippingSig((s) => ({ ...s, ...patch }));\n invalidateVerification();\n };\n\n function setBillingSameAsShipping(v: boolean) {\n // No copy needed: while not dirty, `billing` already reflects live shipping,\n // so the fields appear pre-filled on uncheck and re-toggling never clobbers\n // an entered billing address.\n setSame(v);\n }\n\n const billingIsOverride = () => !billingSameAsShipping() && billingDirty();\n const effectiveBilling = () => (billingIsOverride() ? billingSig() : shipping());\n\n function validate(): boolean {\n const sErr = validateAddress(shipping(), '', { enforceAvailability: true });\n setShippingErrors(sErr);\n let bErr: AddressErrors = {};\n if (billingIsOverride()) {\n bErr = validateAddress(billingSig(), 'Billing');\n }\n setBillingErrors(bErr);\n return !hasErrors(sErr) && !hasErrors(bErr);\n }\n\n async function verifyShipping(): Promise<AddressVerifyResult | null> {\n const s = shipping();\n // Only verify a syntactically complete address (skip while still typing).\n if (hasErrors(validateAddress(s))) {\n invalidateVerification();\n return null;\n }\n const gen = ++verifyGen;\n setVerifying(true);\n try {\n // Race the round-trip against a client timeout: a hung verifier resolves\n // to `unchecked` (fail open) rather than leaving checkout spinning.\n const result = await withTimeout(\n verifyFn({\n street: s.street,\n street2: s.street2,\n city: s.city,\n state: s.state,\n zip: s.zip,\n }),\n VERIFY_TIMEOUT_MS,\n UNCHECKED_RESULT,\n );\n // A newer edit or verify superseded this one — drop the stale result.\n if (gen !== verifyGen) return null;\n setDeliverability(result);\n return result;\n } catch {\n // Fail open — a client-side error must never block checkout.\n if (gen !== verifyGen) return null;\n setDeliverability(UNCHECKED_RESULT);\n return UNCHECKED_RESULT;\n } finally {\n // Only the latest verify owns the spinner; an out-of-order finish must not\n // clear it while a newer request is still in flight.\n if (gen === verifyGen) setVerifying(false);\n }\n }\n\n function applyNormalized() {\n const d = deliverability();\n if (!d?.normalized) return;\n const n = d.normalized;\n setShippingSig((s) => ({ ...s, street: n.street, street2: n.street2, city: n.city, state: n.state, zip: n.zip }));\n // Adopting the suggestion is a resolution, not an edit: mark it verified and\n // bump the generation so any verify still in flight can't overwrite it.\n verifyGen++;\n setDeliverability({ ...d, status: 'verified', corrected: false });\n }\n\n return {\n shipping,\n setShippingField,\n setShipping,\n billingSameAsShipping,\n setBillingSameAsShipping,\n billing,\n setBillingField,\n billingIsOverride,\n effectiveBilling,\n shippingErrors,\n billingErrors,\n validate,\n deliverability,\n verifying,\n verifyShipping,\n applyNormalized,\n };\n}\n","/**\n * Provider-aware CARD TOKENIZER — not AuthNet-only, despite its history.\n * Dispatches on GET /config/payment: Authorize.Net tenants load Accept.js;\n * QuickBooks/Intuit tenants tokenize against the returned `tokenizeUrl`.\n * (Renamed from useCardTokenizer/acceptJs.ts, whose name cost real debugging time\n * by implying the AuthNet path was the only one.)\n */\nimport { createSignal, onMount, onCleanup, type Accessor } from 'solid-js';\nimport { paymentsApi } from '../../api/client';\n\n// ── Types ───────────────────────────────────────────────────────────\n\n// Provider-discriminated public payment config from GET /config/payment.\n// Authorize.Net ships Accept.js keys; QuickBooks ships the Intuit tokenize URL.\ntype PaymentConfig =\n | { provider: 'authorizenet'; apiLoginId: string; clientKey: string; sandbox: boolean }\n | { provider: 'quickbooks'; tokenizeUrl: string };\n\ninterface AcceptJsResponse {\n opaqueData?: { dataDescriptor: string; dataValue: string };\n messages: {\n resultCode: 'Ok' | 'Error';\n message: Array<{ code: string; text: string }>;\n };\n}\n\ndeclare global {\n interface Window {\n Accept?: {\n dispatchData: (\n secureData: Record<string, unknown>,\n callback: (response: AcceptJsResponse) => void,\n ) => void;\n };\n }\n}\n\nexport interface CardData {\n /** Card number, may include spaces (will be stripped). */\n cardNumber: string;\n /** Expiration in MM/YY format. */\n expiry: string;\n /** Card verification code. */\n cvv: string;\n}\n\n/**\n * The neutral tokenized payment method forwarded to the backend as `opaqueData`.\n * The provider adapter unpacks its own shape: Authorize.Net reads\n * `{ dataDescriptor, dataValue }`, QuickBooks reads `{ token }`.\n */\nexport type PaymentToken = Record<string, unknown>;\n\nexport type TokenizerStatus = 'loading' | 'ready' | 'failed';\n\nexport interface CardTokenizer {\n /** True once tokenization is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */\n ready: Accessor<boolean>;\n /**\n * Init lifecycle. `failed` is terminal for this mount (config fetch failed,\n * tenant misconfigured, or the provider SDK was blocked): without it, a\n * failure left `ready()` false forever and the Pay button silently disabled —\n * a dead end with no signal. Surface `error()` as a user-facing banner.\n */\n status: Accessor<TokenizerStatus>;\n /** User-facing description of why init failed; null unless status is 'failed'. */\n error: Accessor<string | null>;\n /** Tokenizes card data for the tenant's provider. Rejects with a user-facing error on failure. */\n tokenize: (card: CardData) => Promise<PaymentToken>;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\n/**\n * Provider-aware client-side card tokenizer used by useCheckoutFlow,\n * useSignupFlow, and useSubscribeFlow.\n *\n * - **Authorize.Net:** loads Accept.js and tokenizes to `{ dataDescriptor, dataValue }`.\n * - **QuickBooks:** POSTs the card directly to the Intuit tokens endpoint\n * (CORS-allowed, no auth — the PAN never touches our backend) and returns\n * `{ token }`.\n *\n * Internal — not exported from the package's public surface.\n */\nexport function useCardTokenizer(): CardTokenizer {\n const [config, setConfig] = createSignal<PaymentConfig | null>(null);\n const [scriptLoaded, setScriptLoaded] = createSignal(false);\n const [error, setError] = createSignal<string | null>(null);\n\n const ready = () => {\n const cfg = config();\n if (!cfg) return false;\n // QuickBooks needs no SDK — ready as soon as config is known.\n return cfg.provider === 'quickbooks' ? true : scriptLoaded();\n };\n\n const status = (): TokenizerStatus => (error() ? 'failed' : ready() ? 'ready' : 'loading');\n\n function fail(userMessage: string, logDetail?: unknown) {\n console.warn(`[useCardTokenizer] ${userMessage}`, logDetail ?? '');\n setError(userMessage);\n }\n\n onMount(async () => {\n try {\n const raw = (await paymentsApi.getConfig()) as Record<string, unknown> | null;\n if (!raw) {\n fail('Payment setup is unavailable right now. Please refresh the page or try again shortly.');\n return;\n }\n\n if (raw.provider === 'quickbooks' && typeof raw.tokenizeUrl === 'string') {\n setConfig({ provider: 'quickbooks', tokenizeUrl: raw.tokenizeUrl });\n return;\n }\n\n // Default / Authorize.Net.\n if (!raw.apiLoginId || !raw.clientKey) {\n fail('Payments are not fully configured for this site yet. Please contact support.');\n return;\n }\n const cfg: PaymentConfig = {\n provider: 'authorizenet',\n apiLoginId: raw.apiLoginId as string,\n clientKey: raw.clientKey as string,\n sandbox: raw.sandbox !== false,\n };\n setConfig(cfg);\n loadScript(cfg.sandbox);\n } catch (err) {\n fail('Payment setup is unavailable right now. Please refresh the page or try again shortly.', err);\n }\n });\n\n function loadScript(sandbox: boolean) {\n if (typeof window === 'undefined') return;\n if (window.Accept) {\n setScriptLoaded(true);\n return;\n }\n const url = sandbox\n ? 'https://jstest.authorize.net/v1/Accept.js'\n : 'https://js.authorize.net/v1/Accept.js';\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n script.onload = () => setScriptLoaded(true);\n script.onerror = () =>\n fail(\n 'The secure payment library could not load. Check your connection (or ad blocker) and refresh the page.',\n );\n document.head.appendChild(script);\n onCleanup(() => {\n script.onload = null;\n script.onerror = null;\n });\n }\n\n function splitExpiry(expiry: string): { month: string; year: string } {\n const parts = expiry.split('/');\n if (parts.length !== 2) throw new Error('Enter expiration in MM/YY format.');\n return { month: parts[0].padStart(2, '0'), year: '20' + parts[1] };\n }\n\n // Authorize.Net Accept.js → { dataDescriptor, dataValue }.\n function tokenizeAcceptJs(card: CardData, cfg: Extract<PaymentConfig, { provider: 'authorizenet' }>): Promise<PaymentToken> {\n return new Promise((resolve, reject) => {\n if (!window.Accept) {\n reject(new Error('Payment processor not loaded. Please refresh.'));\n return;\n }\n const { month, year } = splitExpiry(card.expiry);\n window.Accept.dispatchData(\n {\n authData: { clientKey: cfg.clientKey, apiLoginID: cfg.apiLoginId },\n cardData: { cardNumber: card.cardNumber.replace(/\\s/g, ''), month, year, cardCode: card.cvv },\n },\n (response: AcceptJsResponse) => {\n if (response.messages.resultCode !== 'Ok' || !response.opaqueData) {\n reject(new Error(response.messages.message.map((m) => m.text).join(', ') || 'Card processing failed.'));\n return;\n }\n resolve(response.opaqueData);\n },\n );\n });\n }\n\n // QuickBooks: tokenize directly against Intuit from the browser → { token }.\n async function tokenizeQuickBooks(card: CardData, cfg: Extract<PaymentConfig, { provider: 'quickbooks' }>): Promise<PaymentToken> {\n const { month, year } = splitExpiry(card.expiry);\n const res = await fetch(cfg.tokenizeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n card: { number: card.cardNumber.replace(/\\s/g, ''), expMonth: month, expYear: year, cvc: card.cvv },\n }),\n });\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { errors?: Array<{ message?: string }> };\n throw new Error(body.errors?.[0]?.message || 'Card processing failed.');\n }\n const data = (await res.json()) as { value?: string; token?: string };\n const token = data.value || data.token;\n if (!token) throw new Error('Card tokenization returned no token.');\n return { token };\n }\n\n function tokenize(card: CardData): Promise<PaymentToken> {\n const cfg = config();\n if (!cfg) return Promise.reject(new Error('Payment configuration not loaded. Please refresh.'));\n return cfg.provider === 'quickbooks' ? tokenizeQuickBooks(card, cfg) : tokenizeAcceptJs(card, cfg);\n }\n\n return { ready, status, error, tokenize };\n}\n","import { createSignal, createEffect, onMount, type Accessor } from 'solid-js';\nimport {\n usersApi,\n apexApi,\n paymentsApi,\n subscriptionsApi,\n ApiError,\n newIdempotencyKey,\n type User,\n} from '../api/client';\nimport cartStore from '../stores/cart';\nimport { getConfig } from '../config';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { useAddressPair, hasErrors, normalizeState, type AddressPair } from './address';\n\n// ── Attempt-scoped idempotency key ──────────────────────────────────\n//\n// The backend's idempotency() middleware can only collapse a concurrent or\n// replayed charge when the client presents the SAME Idempotency-Key — the\n// server-side already-paid guard alone has a seconds-wide window, because the\n// item's `paid` flag is stamped after the response returns, behind an Apex\n// round-trip. One key per purchase attempt, scoped to (requestId, drugId) and\n// kept in sessionStorage so a refresh mid-submit retries the same logical\n// operation; rotated on a definitive rejection (a corrected retry is a new\n// operation) and cleared on success. Falls back to in-memory when storage or\n// config is unavailable — the key still holds within the page's lifetime.\n\nconst memoryCheckoutKeys = new Map<string, string>();\n\nfunction checkoutKeyStorageKey(scope: string): string {\n return `${getConfig().storagePrefix}-rx-checkout-key-${scope}`;\n}\n\nfunction readCheckoutKey(scope: string): string | null {\n try {\n return sessionStorage.getItem(checkoutKeyStorageKey(scope));\n } catch {\n return memoryCheckoutKeys.get(scope) ?? null;\n }\n}\n\nfunction writeCheckoutKey(scope: string, key: string): void {\n try {\n sessionStorage.setItem(checkoutKeyStorageKey(scope), key);\n } catch {\n memoryCheckoutKeys.set(scope, key);\n }\n}\n\nfunction clearCheckoutKey(scope: string): void {\n try {\n sessionStorage.removeItem(checkoutKeyStorageKey(scope));\n } catch {\n // fall through to the memory map\n }\n memoryCheckoutKeys.delete(scope);\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface RequestStatus {\n status: 'pending' | 'approved' | 'denied' | 'new';\n drugName?: string;\n drugId?: string;\n dosage?: string;\n price?: number;\n /** Locked catalog price for this prescription (cents). */\n priceCents?: number;\n /** Locked discount applied at request creation (cents). */\n discountCents?: number;\n /** Locked total to charge (cents). */\n finalCents?: number;\n /** The request has already been paid for. Guards against re-charging a request\n * that was paid up front (pay-before-review) if the checkout is revisited. */\n paymentConfirmed?: boolean;\n reason?: string;\n requestId?: string;\n [key: string]: unknown;\n}\n\nexport type CheckoutOutcome =\n | { kind: 'loading' }\n | { kind: 'load_failed'; error: string }\n | { kind: 'no_prescription' }\n | { kind: 'pending_review'; prescription: RequestStatus }\n | { kind: 'denied'; prescription: RequestStatus }\n | { kind: 'awaiting_purchase'; prescription: RequestStatus }\n | { kind: 'completed' };\n\nexport interface PricingBreakdown {\n baseMedicationCents: number;\n promoDiscountCents: number;\n finalMedicationCents: number;\n promoCode?: string;\n}\n\n// ── Card formatting helpers ─────────────────────────────────────────\n\nexport function formatCardNumber(raw: string): string {\n const digits = raw.replace(/\\D/g, '').slice(0, 16);\n return digits.replace(/(.{4})/g, '$1 ').trim();\n}\n\nexport function formatExpiry(raw: string): string {\n const digits = raw.replace(/\\D/g, '').slice(0, 4);\n if (digits.length > 2) return digits.slice(0, 2) + '/' + digits.slice(2);\n return digits;\n}\n\nexport function formatCvv(raw: string): string {\n return raw.replace(/\\D/g, '').slice(0, 4);\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport interface UseCheckoutFlowOptions {\n /** The prescription request ID to check out. Typically read from a URL query param by the site. If absent, the hook falls back to `user.apex_request_id` for legacy single-request flows. */\n requestId?: string;\n /** Specific drug (Apex drugId) within a multi-drug request to purchase. When set, the backend returns THAT line item's status + locked price, so an approved item in a partially-approved request is purchasable independently. */\n drugId?: string;\n /**\n * Pay-before-review: treat a `pending` (not-yet-approved) request as\n * purchasable, so the card form is shown immediately after the survey instead\n * of only after a prescriber approves. Off by default — the standard flow\n * collects payment only on an `approved` request. When on, the backend's\n * approved+paid fulfilment gate still holds the order until a prescriber\n * approves; this only moves WHEN the card is collected, not what ships.\n */\n allowPendingPurchase?: boolean;\n}\n\nexport interface CheckoutFlow {\n outcome: Accessor<CheckoutOutcome>;\n profile: Accessor<User | null>;\n\n /** Shipping + billing address state (pre-filled from the profile). Render with\n * <AddressFields address={flow.address} />. */\n address: AddressPair;\n\n // Pricing\n pricing: Accessor<PricingBreakdown>;\n\n // Payment-method state\n hasPaymentMethod: Accessor<boolean>;\n /** True once the card tokenizer is ready. Gate submission on this. */\n tokenizerReady: Accessor<boolean>;\n /** @deprecated alias of tokenizerReady (pre-rename name). */\n acceptJsLoaded: Accessor<boolean>;\n /** Non-null when payment setup failed to initialize (config/SDK load) —\n * render as a banner; the pay button will never enable in this state. */\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 // Card form state (only relevant when hasPaymentMethod() is false)\n cardNumber: Accessor<string>;\n setCardNumber: (v: string) => void;\n expiry: Accessor<string>;\n setExpiry: (v: string) => void;\n cvv: Accessor<string>;\n setCvv: (v: string) => void;\n\n // Inline state\n paymentError: Accessor<string | null>;\n processing: Accessor<boolean>;\n canSubmit: Accessor<boolean>;\n\n // Actions\n submit: () => Promise<void>;\n}\n\nexport function useCheckoutFlow(options: UseCheckoutFlowOptions = {}): CheckoutFlow {\n const accept = useCardTokenizer();\n const address = useAddressPair();\n\n const [outcome, setOutcome] = createSignal<CheckoutOutcome>({ kind: 'loading' });\n const [profile, setProfile] = createSignal<User | null>(null);\n const [prescription, setPrescription] = createSignal<RequestStatus | null>(null);\n const [hasPaymentMethod, setHasPaymentMethod] = createSignal(false);\n\n // equals:false so a setter that clamps back to the same formatted string\n // still fires reactivity — otherwise Solid skips the input re-bind and the\n // DOM keeps any character the formatter rejected (e.g. a 17th card digit).\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n\n const [paymentError, setPaymentError] = createSignal<string | null>(null);\n const [processing, setProcessing] = createSignal(false);\n\n // A `corrected` deliverability result soft-stops the FIRST submit (show the\n // suggestion, charge nothing) so the user can accept the carrier's correction\n // or knowingly proceed with their own entry on a second click. This flag\n // remembers that we've already surfaced the current correction; any edit to\n // the shipping address clears the underlying deliverability, so we reset it\n // whenever the shipping address changes to re-arm the soft-stop for a fresh\n // correction.\n const [correctionAcknowledged, setCorrectionAcknowledged] = createSignal(false);\n createEffect(() => {\n address.shipping(); // track edits (and suggestion adoption)\n setCorrectionAcknowledged(false);\n });\n\n // ── Pricing (locked snapshot from request creation; falls back to cart) ──\n\n const pricing = (): PricingBreakdown => {\n const rx = prescription();\n const baseMedicationCents = (() => {\n const cents = rx?.priceCents;\n if (typeof cents === 'number') return cents;\n const dollars = rx?.price;\n return typeof dollars === 'number' ? Math.round(dollars * 100) : 0;\n })();\n\n // Backend writes a locked snapshot (priceCents/discountCents/finalCents)\n // at request creation time so promos can't expire out from under an\n // approved prescription. Prefer those numbers; fall back to the cart's\n // currently applied promo for legacy rows that predate the snapshot.\n const promoDiscountCents = (() => {\n const locked = rx?.discountCents;\n if (typeof locked === 'number') return locked;\n const promo = cartStore.appliedPromo();\n if (!promo || baseMedicationCents <= 0) return 0;\n if (promo.discountType === 'percent') {\n return Math.min(\n baseMedicationCents,\n Math.round((baseMedicationCents * promo.discountValueCents) / 100),\n );\n }\n return Math.min(baseMedicationCents, promo.discountValueCents);\n })();\n\n const finalMedicationCents = (() => {\n const locked = rx?.finalCents;\n if (typeof locked === 'number') return locked;\n return Math.max(0, baseMedicationCents - promoDiscountCents);\n })();\n\n return {\n baseMedicationCents,\n promoDiscountCents,\n finalMedicationCents,\n promoCode: cartStore.appliedPromo()?.code,\n };\n };\n\n const canSubmit = () => hasPaymentMethod() || accept.ready();\n\n // ── Load on mount ────────────────────────────────────────────────\n\n onMount(async () => {\n try {\n const [profileRes, subsRes] = await Promise.all([\n usersApi.getProfile(),\n subscriptionsApi.list().catch(() => null),\n ]);\n\n const userData = profileRes.data ?? null;\n setProfile(userData);\n\n // Pre-fill the shipping address from the member profile; the patient can\n // confirm or override it before purchase.\n const u = userData as Record<string, unknown> | null;\n address.setShipping({\n street: (u?.address1 as string) || (u?.street as string) || '',\n street2: (u?.address2 as string) || (u?.street2 as string) || '',\n city: (u?.city as string) || '',\n state: normalizeState((u?.state as string) || ''),\n zip: (u?.zip as string) || (u?.zipCode as string) || '',\n });\n\n const subs = (subsRes as {\n subscriptions?: Array<{ id: string; status: string; hasPaymentMethod?: boolean }>;\n } | null)?.subscriptions;\n // \"Card on file\" must mean an actual chargeable gateway profile, NOT just an\n // active subscription: a $0/promo-covered membership is active but has no\n // stored payment method, so we must still collect a card at medication\n // checkout. Require both an active/paused sub AND its hasPaymentMethod flag.\n setHasPaymentMethod(\n !!subs?.some(\n (s) => (s.status === 'active' || s.status === 'paused') && s.hasPaymentMethod === true,\n ),\n );\n\n const requestId =\n options.requestId ??\n ((userData as Record<string, unknown> | null)?.apex_request_id as string | undefined);\n\n if (!requestId) {\n setOutcome({ kind: 'no_prescription' });\n return;\n }\n\n const statusRes = (await apexApi.getRequestStatus(requestId, options.drugId)) as RequestStatus;\n const rx: RequestStatus | null = statusRes ? { ...statusRes, requestId } : null;\n setPrescription(rx);\n\n if (!rx) {\n setOutcome({ kind: 'no_prescription' });\n return;\n }\n\n // Never re-collect payment for a request that's already paid. In the\n // pay-before-review flow a request is paid while still pending; if the\n // customer navigates back here we must not show the card form again and\n // charge them twice. A paid request reads as its real state instead\n // (approved → order placed; pending → under review).\n const alreadyPaid = rx.paymentConfirmed === true;\n\n switch (rx.status) {\n case 'approved':\n setOutcome(\n alreadyPaid\n ? { kind: 'completed' }\n : { kind: 'awaiting_purchase', prescription: rx },\n );\n break;\n case 'pending':\n // Pay-before-review sites surface the card form now — but only for an\n // UNPAID request; an already-paid pending request shows \"under review\".\n // The default flow always waits for approval.\n setOutcome(\n options.allowPendingPurchase && !alreadyPaid\n ? { kind: 'awaiting_purchase', prescription: rx }\n : { kind: 'pending_review', prescription: rx },\n );\n break;\n case 'denied':\n setOutcome({ kind: 'denied', prescription: rx });\n break;\n case 'new':\n default:\n setOutcome({ kind: 'no_prescription' });\n break;\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Failed to load prescription status.';\n setOutcome({ kind: 'load_failed', error: msg });\n }\n });\n\n function validateCard(): string | null {\n if (!cardNumberRaw().replace(/\\s/g, '').trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n return null;\n }\n\n async function submit() {\n setPaymentError(null);\n setProcessing(true);\n\n try {\n const rx = prescription();\n if (!rx?.drugId) {\n setPaymentError('Missing medication details.');\n return;\n }\n\n // Validate shipping (+ billing when it's an override). Field-level errors\n // render inline via <AddressFields>; the banner carries a summary that\n // names whichever address(es) actually failed.\n if (!address.validate()) {\n const badShipping = hasErrors(address.shippingErrors());\n const badBilling = hasErrors(address.billingErrors());\n const which =\n badShipping && badBilling\n ? 'shipping and billing addresses'\n : badBilling\n ? 'billing address'\n : 'shipping address';\n setPaymentError(`Please complete the ${which}.`);\n return;\n }\n\n // Server-side deliverability check (Shippo). Prefer the result already\n // cached by the on-blur verify; only re-verify here when the field-blur\n // path hasn't produced one yet (e.g. a profile-prefilled address the user\n // never touched). Fails open — 'unchecked' (unconfigured / verifier\n // outage) and 'verified' proceed; a confirmed-undeliverable address is a\n // hard block; a 'corrected' address soft-stops the first submit.\n const deliverability = address.deliverability() ?? (await address.verifyShipping());\n\n if (deliverability?.status === 'undeliverable') {\n setPaymentError(\n 'We couldn’t verify your shipping address as deliverable. Please check it and try again.',\n );\n return;\n }\n\n // `corrected`: surface the carrier's suggestion and stop WITHOUT charging\n // on the first attempt. The user either clicks \"Use suggested address\"\n // (applyNormalized → the suggestion becomes the shipping address and the\n // status flips to 'verified') or clicks Pay again to proceed with their\n // own entry. Never auto-charge the raw address on the click that first\n // discovers the correction.\n if (deliverability?.status === 'corrected' && !correctionAcknowledged()) {\n setCorrectionAcknowledged(true);\n setPaymentError(\n 'We found a suggested correction to your shipping address. Review it above — use the suggested address, or press Pay again to continue with the address you entered.',\n );\n return;\n }\n\n let opaqueData: Record<string, unknown> | undefined;\n if (!hasPaymentMethod()) {\n const cardErr = validateCard();\n if (cardErr) {\n setPaymentError(cardErr);\n return;\n }\n opaqueData = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n }\n\n // Same key across retries of THIS attempt (incl. across a refresh);\n // minted lazily on the first submit for this request+drug.\n const attemptScope = `${rx.requestId ?? 'rx'}:${rx.drugId}`;\n let idempotencyKey = readCheckoutKey(attemptScope);\n if (!idempotencyKey) {\n idempotencyKey = newIdempotencyKey();\n writeCheckoutKey(attemptScope, idempotencyKey);\n }\n\n await paymentsApi.prescriptionCheckout({\n drugId: rx.drugId,\n prescriptionRequestId: rx.requestId,\n opaqueData,\n promoCode: cartStore.appliedPromo()?.code,\n shippingAddress: address.shipping(),\n billingAddress: address.effectiveBilling(),\n }, { idempotencyKey });\n\n clearCheckoutKey(attemptScope);\n setOutcome({ kind: 'completed' });\n } catch (err) {\n // 409 = the backend refused to charge an already-paid request (this tab\n // went stale after a payment elsewhere — another tab, or a retried\n // submit whose first attempt actually landed). Reconcile against the\n // server: if it confirms the payment, this purchase is genuinely\n // complete — show success, not a dead-end error. (A 409 can also be the\n // idempotency middleware rejecting an in-flight replay; the reconcile\n // handles both — paymentConfirmed decides.)\n if (err instanceof ApiError && err.status === 409) {\n try {\n const rx = prescription();\n const live = rx?.requestId\n ? ((await apexApi.getRequestStatus(rx.requestId, options.drugId)) as RequestStatus | null)\n : null;\n if (live?.paymentConfirmed === true) {\n const rxScope = `${rx?.requestId ?? 'rx'}:${rx?.drugId}`;\n clearCheckoutKey(rxScope);\n setOutcome({ kind: 'completed' });\n return;\n }\n } catch {\n // reconcile failed — fall through to the generic error\n }\n }\n // A definitive rejection means nothing committed — the corrected retry\n // is a NEW operation and must not be deduped against this one. An\n // ambiguous failure keeps the key so the retry collapses server-side.\n const maybeCommitted = err instanceof ApiError && err.ambiguous;\n if (!maybeCommitted) {\n const rx = prescription();\n if (rx?.drugId) clearCheckoutKey(`${rx.requestId ?? 'rx'}:${rx.drugId}`);\n }\n const msg = err instanceof Error ? err.message : 'Payment failed. Please try again.';\n setPaymentError(msg);\n } finally {\n setProcessing(false);\n }\n }\n\n return {\n outcome,\n profile,\n address,\n pricing,\n hasPaymentMethod,\n tokenizerReady: accept.ready,\n acceptJsLoaded: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\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 paymentError,\n processing,\n canSubmit,\n submit,\n };\n}\n","import { createSignal, createEffect, onMount, type Accessor } from 'solid-js';\nimport {\n usersApi,\n paymentsApi,\n ordersApi,\n ApiError,\n newIdempotencyKey,\n type User,\n type Order,\n type OrderItemInput,\n} from '../api/client';\nimport cartStore, { type CartItem } from '../stores/cart';\nimport authStore from '../stores/auth';\nimport { getConfig } from '../config';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { useAddressPair, hasErrors, normalizeState, type AddressPair } from './address';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\n\n// ── Attempt-scoped idempotency key ──────────────────────────────────\n//\n// Same shape as the Rx checkout's helper (flows/checkout.ts), scoped to the\n// cart rather than a (requestId, drugId) pair — one logical cart purchase per\n// storage. IMPORTANT: the backend does NOT yet run its idempotency()\n// middleware on POST /payments/checkout, so this key protects nothing today.\n// It exists so the flow is already correct the day the backend adds the\n// middleware (the SDK will have been presenting stable keys all along) — it is\n// never a license to auto-retry an ambiguous failure, which remains a possible\n// second real charge. Rotated on a definitive rejection (a corrected retry is\n// a new operation) and cleared on success.\n\nconst memoryKeys = new Map<string, string>();\n\nconst ATTEMPT_SCOPE = 'cart';\n\nfunction keyStorageKey(scope: string): string {\n return `${getConfig().storagePrefix}-cart-checkout-key-${scope}`;\n}\n\nfunction readAttemptKey(scope: string): string | null {\n try {\n return sessionStorage.getItem(keyStorageKey(scope));\n } catch {\n return memoryKeys.get(scope) ?? null;\n }\n}\n\nfunction writeAttemptKey(scope: string, key: string): void {\n try {\n sessionStorage.setItem(keyStorageKey(scope), key);\n } catch {\n memoryKeys.set(scope, key);\n }\n}\n\nfunction clearAttemptKey(scope: string): void {\n try {\n sessionStorage.removeItem(keyStorageKey(scope));\n } catch {\n // fall through to the memory map\n }\n memoryKeys.delete(scope);\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport type CartCheckoutOutcome =\n /** Initial profile load in flight. */\n | { kind: 'loading' }\n /** No authenticated session. Sites route to signup/login (for a model-3\n * tenant, typically RegisterPage) and back here afterwards. */\n | { kind: 'needs_auth' }\n /** The cart holds no one-time-purchasable items (empty, or subscription\n * items only). Sites route to the catalog. */\n | { kind: 'needs_cart' }\n /** Ready: order summary + address + card form are live. */\n | { kind: 'in_progress' }\n /** A submit failed ambiguously; the flow is checking the order history\n * before letting the user near the Pay button again. */\n | { kind: 'reconciling' }\n /** Charge succeeded (or was confirmed via reconcile). */\n | { kind: 'completed'; orderId?: string; amountCents?: number };\n\nexport interface CartCheckoutPricing {\n /** Quantity-honoring subtotal of the purchasable items, in cents. */\n subtotalCents: number;\n /** Client-side ESTIMATE from the applied promo — the server re-validates the\n * code and stacks active sales itself, so the charged amount can differ.\n * `completed.amountCents` carries the authoritative figure. */\n promoDiscountCents: number;\n estimatedTotalCents: number;\n promoCode?: string;\n}\n\nexport interface CartCheckoutFlow {\n outcome: Accessor<CartCheckoutOutcome>;\n profile: Accessor<User | null>;\n\n /** Shipping + billing address state (pre-filled from the profile). Render\n * with <AddressFields address={flow.address} />. */\n address: AddressPair;\n\n /** The one-time-purchasable subset of the cart — what will actually be\n * charged. Subscription-flagged items are excluded (the backend 400s a\n * checkout containing one). */\n items: Accessor<CartItem[]>;\n /** Subscription-flagged cart items excluded from this purchase, so pages can\n * tell the customer those aren't part of the order. */\n skippedSubscriptionItems: Accessor<CartItem[]>;\n\n pricing: Accessor<CartCheckoutPricing>;\n\n // Payment-method state. Unlike the Rx checkout there is no card-on-file\n // path: POST /payments/checkout requires opaqueData (it charges the raw\n // token, no gateway profile), so the card form always renders.\n /** True once the card tokenizer is ready. Gate submission on this. */\n tokenizerReady: Accessor<boolean>;\n /** @deprecated alias of tokenizerReady (pre-rename name). */\n acceptJsLoaded: Accessor<boolean>;\n /** Non-null when payment setup failed to initialize (config/SDK load) —\n * render as a banner; the pay button will never enable in this state. */\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 cardNumber: Accessor<string>;\n setCardNumber: (v: string) => void;\n expiry: Accessor<string>;\n setExpiry: (v: string) => void;\n cvv: Accessor<string>;\n setCvv: (v: string) => void;\n\n paymentError: Accessor<string | null>;\n processing: Accessor<boolean>;\n canSubmit: Accessor<boolean>;\n\n submit: () => Promise<void>;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\n/**\n * One-time cart checkout (model-3 support): charges the cart's non-subscription\n * items once via POST /payments/checkout. No prescription, no recurring\n * subscription, no card kept on file. Requires an authenticated member (the\n * backend route is member-JWT only) — unauthenticated mounts emit `needs_auth`\n * for the site to route to its signup/register page.\n */\nexport function useCartCheckoutFlow(): CartCheckoutFlow {\n const accept = useCardTokenizer();\n const address = useAddressPair();\n\n const [outcome, setOutcome] = createSignal<CartCheckoutOutcome>({ kind: 'loading' });\n const [profile, setProfile] = createSignal<User | null>(null);\n\n // equals:false so a setter that clamps back to the same formatted string\n // still fires reactivity (see flows/checkout.ts for the full rationale).\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n\n const [paymentError, setPaymentError] = createSignal<string | null>(null);\n const [processing, setProcessing] = createSignal(false);\n\n // `corrected` deliverability soft-stops the FIRST submit; re-armed whenever\n // the shipping address changes (same mechanism as the Rx checkout).\n const [correctionAcknowledged, setCorrectionAcknowledged] = createSignal(false);\n createEffect(() => {\n address.shipping(); // track edits (and suggestion adoption)\n setCorrectionAcknowledged(false);\n });\n\n const items = () => cartStore.items().filter((i) => i.isSubscription !== true);\n const skippedSubscriptionItems = () => cartStore.items().filter((i) => i.isSubscription === true);\n\n const pricing = (): CartCheckoutPricing => {\n const subtotalCents = items().reduce((sum, i) => sum + i.priceCents * (i.quantity || 1), 0);\n const promo = cartStore.appliedPromo();\n const promoDiscountCents = (() => {\n if (!promo || subtotalCents <= 0) return 0;\n if (promo.discountType === 'percent') {\n return Math.min(subtotalCents, Math.round((subtotalCents * promo.discountValueCents) / 100));\n }\n return Math.min(subtotalCents, promo.discountValueCents);\n })();\n return {\n subtotalCents,\n promoDiscountCents,\n estimatedTotalCents: Math.max(0, subtotalCents - promoDiscountCents),\n promoCode: promo?.code,\n };\n };\n\n const canSubmit = () => accept.ready();\n\n // ── Load on mount ────────────────────────────────────────────────\n\n onMount(async () => {\n if (!authStore.isAuthenticated()) {\n setOutcome({ kind: 'needs_auth' });\n return;\n }\n if (items().length === 0) {\n setOutcome({ kind: 'needs_cart' });\n return;\n }\n\n // Profile prefill is best-effort: a failed fetch still lands on the form\n // with a blank address rather than dead-ending the purchase.\n try {\n const profileRes = await usersApi.getProfile();\n const userData = profileRes.data ?? null;\n setProfile(userData);\n const u = userData as Record<string, unknown> | null;\n address.setShipping({\n street: (u?.address1 as string) || (u?.street as string) || '',\n street2: (u?.address2 as string) || (u?.street2 as string) || '',\n city: (u?.city as string) || '',\n state: normalizeState((u?.state as string) || ''),\n zip: (u?.zip as string) || (u?.zipCode as string) || '',\n });\n } catch {\n // proceed with a blank address\n }\n setOutcome({ kind: 'in_progress' });\n });\n\n function validateCard(): string | null {\n if (!cardNumberRaw().replace(/\\s/g, '').trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n return null;\n }\n\n /** Multiset match: does this order contain exactly the items we submitted?\n * Used to recognize our own charge in the order history after an ambiguous\n * failure. Defensive against untyped/partial order rows. */\n function orderMatchesSubmission(order: Order, submitted: OrderItemInput[]): boolean {\n const orderItems = Array.isArray(order.items) ? order.items : [];\n if (orderItems.length !== submitted.length) return false;\n const keyOf = (productId: string, dosage: string | undefined, quantity: number) =>\n `${productId}::${dosage ?? ''}::${quantity}`;\n const remaining = new Map<string, number>();\n for (const s of submitted) {\n const k = keyOf(s.productId, s.dosage, s.quantity ?? 1);\n remaining.set(k, (remaining.get(k) ?? 0) + 1);\n }\n for (const o of orderItems) {\n const k = keyOf(o.productId, o.dosage, o.quantity);\n const n = remaining.get(k);\n if (!n) return false;\n remaining.set(k, n - 1);\n }\n for (const n of remaining.values()) if (n !== 0) return false;\n return true;\n }\n\n function finishPurchase(purchased: CartItem[], orderId?: string, amountCents?: number) {\n clearAttemptKey(ATTEMPT_SCOPE);\n // Remove exactly what was purchased — subscription leftovers (and the\n // applied promo, per the store's clear() contract) survive.\n for (const i of purchased) cartStore.remove(cartStore.itemKey(i.productId, i.dosage));\n setOutcome({ kind: 'completed', orderId, amountCents });\n }\n\n async function submit() {\n if (processing()) return;\n setPaymentError(null);\n setProcessing(true);\n\n try {\n // Stale-tab re-checks: a logout or emptied cart in another tab must not\n // produce a charge from this one.\n if (!authStore.isAuthenticated()) {\n setOutcome({ kind: 'needs_auth' });\n return;\n }\n const purchasable = items();\n if (purchasable.length === 0) {\n setOutcome({ kind: 'needs_cart' });\n return;\n }\n\n if (!address.validate()) {\n const badShipping = hasErrors(address.shippingErrors());\n const badBilling = hasErrors(address.billingErrors());\n const which =\n badShipping && badBilling\n ? 'shipping and billing addresses'\n : badBilling\n ? 'billing address'\n : 'shipping address';\n setPaymentError(`Please complete the ${which}.`);\n return;\n }\n\n // Deliverability (Shippo, fails open): undeliverable is a hard block; a\n // corrected address soft-stops the first submit (see the Rx checkout).\n const deliverability = address.deliverability() ?? (await address.verifyShipping());\n\n if (deliverability?.status === 'undeliverable') {\n setPaymentError(\n 'We couldn’t verify your shipping address as deliverable. Please check it and try again.',\n );\n return;\n }\n\n if (deliverability?.status === 'corrected' && !correctionAcknowledged()) {\n setCorrectionAcknowledged(true);\n setPaymentError(\n 'We found a suggested correction to your shipping address. Review it above — use the suggested address, or press Pay again to continue with the address you entered.',\n );\n return;\n }\n\n const cardErr = validateCard();\n if (cardErr) {\n setPaymentError(cardErr);\n return;\n }\n const opaqueData = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n\n let idempotencyKey = readAttemptKey(ATTEMPT_SCOPE);\n if (!idempotencyKey) {\n idempotencyKey = newIdempotencyKey();\n writeAttemptKey(ATTEMPT_SCOPE, idempotencyKey);\n }\n\n const submittedItems: OrderItemInput[] = purchasable.map((i) => ({\n productId: i.productId,\n quantity: i.quantity || 1,\n ...(i.dosage ? { dosage: i.dosage } : {}),\n }));\n\n const res = await paymentsApi.checkout(\n {\n items: submittedItems,\n shippingAddress: address.shipping(),\n billingAddress: address.effectiveBilling(),\n promoCode: cartStore.appliedPromo()?.code,\n opaqueData,\n },\n { idempotencyKey },\n );\n\n finishPurchase(purchasable, res?.orderId, res?.amountCents);\n } catch (err) {\n const purchasable = items();\n if (err instanceof ApiError && err.ambiguous) {\n // NEVER auto-retry an ambiguous cart charge: the backend has no\n // idempotency middleware on this route, so a replay is a possible\n // second real charge. Instead reconcile against the order history —\n // if our exact submission shows up paid, the charge landed.\n setOutcome({ kind: 'reconciling' });\n try {\n const submittedItems: OrderItemInput[] = purchasable.map((i) => ({\n productId: i.productId,\n quantity: i.quantity || 1,\n ...(i.dosage ? { dosage: i.dosage } : {}),\n }));\n const listRes = await ordersApi.list();\n const orders = Array.isArray(listRes?.orders) ? listRes.orders : [];\n const cutoff = Date.now() - 5 * 60 * 1000;\n const match = orders.find((o) => {\n if (o?.status !== 'paid') return false;\n // created_at guards against matching an identical older purchase;\n // when the row lacks it, fall back to the item match alone.\n if (o.created_at) {\n const t = Date.parse(o.created_at);\n if (Number.isFinite(t) && t < cutoff) return false;\n }\n return orderMatchesSubmission(o, submittedItems);\n });\n if (match) {\n finishPurchase(purchasable, match.id, match.total_cents);\n return;\n }\n } catch {\n // reconcile failed — fall through to the manual-check message\n }\n // Keep the idempotency key: harmless today, and correct the day the\n // backend adds the middleware.\n setOutcome({ kind: 'in_progress' });\n setPaymentError(\n 'We couldn’t confirm whether your payment went through. Please check your email or order history before trying again.',\n );\n return;\n }\n\n // Definitive rejection (declined card, validation): nothing committed —\n // the corrected retry is a NEW operation, so rotate the key.\n clearAttemptKey(ATTEMPT_SCOPE);\n const msg = err instanceof Error ? err.message : 'Payment failed. Please try again.';\n setPaymentError(msg);\n } finally {\n setProcessing(false);\n }\n }\n\n return {\n outcome,\n profile,\n address,\n items,\n skippedSubscriptionItems,\n pricing,\n tokenizerReady: accept.ready,\n acceptJsLoaded: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\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 paymentError,\n processing,\n canSubmit,\n submit,\n };\n}\n","import { createEffect, createSignal, onMount, type Accessor } from 'solid-js';\nimport authStore from '../stores/auth';\nimport cartStore from '../stores/cart';\nimport { authApi, ApiError, newIdempotencyKey } from '../api/client';\nimport { getConfig } from '../config';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\n\n// ── Draft persistence ───────────────────────────────────────────────\n//\n// Preserve non-sensitive fields across refresh. Password and card data\n// are deliberately excluded — they must be re-entered each session.\n// Step 3 (Confirm) depends on ephemeral tokenized card data, so the\n// max restorable step is 2 (Payment).\n\nconst DRAFT_TTL_MS = 7 * 24 * 3600 * 1000;\nconst MAX_RESTORABLE_STEP = 2;\n\ninterface SignupDraft {\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 savedAt?: number;\n}\n\nfunction draftKey(): string {\n return `${getConfig().storagePrefix}-signup-draft`;\n}\n\nfunction loadDraft(): SignupDraft {\n try {\n const raw = localStorage.getItem(draftKey());\n if (!raw) return {};\n const parsed = JSON.parse(raw) as SignupDraft;\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: SignupDraft) {\n try {\n localStorage.setItem(draftKey(), JSON.stringify({ ...draft, savedAt: Date.now() }));\n } catch {\n // noop — quota or privacy mode\n }\n}\n\nfunction clearDraft() {\n try {\n localStorage.removeItem(draftKey());\n } catch {\n // noop\n }\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport type SignupOutcome =\n | { kind: 'in_progress' }\n | { kind: 'submitting' }\n /** Register+charge response was lost mid-flight; we're checking whether the\n * account was actually created before letting the user retry. */\n | { kind: 'reconciling' }\n | { kind: 'completed' };\n\nexport interface UseSignupFlowOptions {\n /** Membership amount charged on signup, in cents. Required — sites set their own pricing. */\n membershipAmountCents: number;\n /** Billing interval in days. Default 30. */\n membershipIntervalDays?: number;\n /** Label used when the cart is empty. Defaults to \"Membership\". */\n membershipProductLabel?: string;\n}\n\nexport interface SignupFlow {\n // Step 0..3\n step: Accessor<number>;\n /** True only on the very last step (Confirm). */\n isConfirmStep: Accessor<boolean>;\n next: () => Promise<void>;\n back: () => void;\n\n // Inline state\n error: Accessor<string | null>;\n /** True while tokenizing the card on the Payment step. */\n tokenizing: Accessor<boolean>;\n /** True while submitting on the Confirm step. */\n submitting: Accessor<boolean>;\n outcome: Accessor<SignupOutcome>;\n /** True once the card tokenizer is ready. The Payment step \"Continue\" button gates on this. */\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 * the Payment step can never proceed in this state. */\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\n street: Accessor<string>; setStreet: (v: string) => void;\n city: Accessor<string>; setCity: (v: string) => void;\n state: Accessor<string>; setState: (v: string) => void;\n zip: Accessor<string>; setZip: (v: string) => void;\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 /**\n * Optional promo / referral code applied at submit. Not persisted to the\n * draft — codes can change and shouldn't survive a refresh. Sites surface\n * this via `<SignupPage promoField={...}>`.\n */\n promoCode: Accessor<string>; setPromoCode: (v: string) => void;\n\n /** Submit the signup at the Confirm step. */\n submit: () => Promise<void>;\n}\n\nexport function useSignupFlow(options: UseSignupFlowOptions): SignupFlow {\n const accept = useCardTokenizer();\n\n // Restore draft (only up to MAX_RESTORABLE_STEP — never restore past Payment)\n let restored: SignupDraft = {};\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<SignupOutcome>({ 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\n const [street, setStreet] = createSignal(restored.street ?? '');\n const [city, setCity] = createSignal(restored.city ?? '');\n const [state, setState] = createSignal(restored.state ?? '');\n const [zip, setZip] = createSignal(restored.zip ?? '');\n\n // Payment\n // equals:false so format-clamped setters still fire reactivity; otherwise\n // Solid skips the input re-bind and the DOM keeps rejected characters.\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n const [tokenizedData, setTokenizedData] = createSignal<Record<string, unknown> | null>(null);\n\n // Optional promo / referral code. Deliberately not persisted to the draft.\n const [promoCode, setPromoCode] = createSignal('');\n\n // One idempotency key per logical registration attempt. Reused on a retry\n // after an ambiguous (network-drop / 5xx) failure so the backend replays the\n // original register+charge instead of creating a second account / second\n // charge; rotated after a definitive failure.\n const [idempotencyKey, setIdempotencyKey] = createSignal(newIdempotencyKey());\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 });\n });\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 if (!email().trim()) return 'Email is required.';\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email().trim())) return 'Enter a valid email address.';\n if (!password().trim()) return 'Password is required.';\n if (password().length < 8) return 'Password must be at least 8 characters.';\n if (!phone().trim()) return 'Phone number is required.';\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 if (!street().trim()) return 'Street address is required.';\n if (!city().trim()) return 'City is required.';\n if (!state()) return 'State is required.';\n if (!zip().trim()) return 'ZIP code is required.';\n if (!/^\\d{5}(-\\d{4})?$/.test(zip().trim())) return 'Enter a valid ZIP code.';\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 // In-flight guard: `next()` awaits (checkEmail / tokenize), so without this a\n // double-click fires twice and two relative setStep increments could skip a\n // step (e.g. Account -> Payment, past Address, with a blank shipping address).\n let advancing = false;\n\n async function next() {\n if (advancing) return;\n advancing = true;\n try {\n await advance();\n } finally {\n advancing = false;\n }\n }\n\n async function advance() {\n // Capture the step at entry so we advance from a fixed point, not from\n // whatever step() reads back after the awaits.\n const startStep = step();\n const err = validateStep(startStep);\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n\n // Check email availability before leaving the Account step\n if (startStep === 0) {\n try {\n const { exists } = await authApi.checkEmail(email().trim());\n if (exists) {\n setError('An account with this email already exists.');\n return;\n }\n } catch {\n setError('Unable to verify email. Please try again.');\n return;\n }\n }\n\n // Tokenize card when leaving the Payment step\n if (startStep === 2) {\n setTokenizing(true);\n try {\n const opaque = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n setTokenizedData(opaque);\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Card tokenization failed.');\n setTokenizing(false);\n return;\n }\n setTokenizing(false);\n }\n\n // Absolute (not relative) so a stale/racing increment can't over-advance.\n setStep(startStep + 1);\n }\n\n function back() {\n setError(null);\n // Going back from Confirm to Payment invalidates the tokenized data —\n // user must re-enter their card to re-tokenize.\n if (step() === 3) setTokenizedData(null);\n setStep((s) => Math.max(0, s - 1));\n }\n\n // ── Submit ───────────────────────────────────────────────────────\n\n /** Mark the signup done, but only if a session was actually established —\n * never declare success (and clear the draft) on a half-completed register\n * that left the user unauthenticated. */\n function finishIfAuthenticated(): boolean {\n if (!authStore.isAuthenticated()) return false;\n clearDraft();\n setOutcome({ kind: 'completed' });\n return true;\n }\n\n async function submit() {\n // Re-entrancy guard: a double-click must not fire two register+charge calls.\n if (submitting()) return;\n\n const opaque = tokenizedData();\n if (!opaque) {\n setError('Card not tokenized. Please go back and re-enter your card details.');\n return;\n }\n\n setError(null);\n setSubmitting(true);\n setOutcome({ kind: 'submitting' });\n\n try {\n const cartItems = cartStore.items();\n const products =\n cartItems.length > 0\n ? cartItems.map((i) => ({\n productId: i.productId,\n productName: i.productName,\n quantity: i.quantity,\n dosage: i.dosage,\n }))\n : undefined;\n\n await authStore.signupAndSubscribe(\n {\n email: email().trim(),\n password: password(),\n member: {\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim(),\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n opaqueData: opaque,\n amountCents: options.membershipAmountCents,\n intervalDays: options.membershipIntervalDays ?? 30,\n medication:\n cartItems.length === 0 ? options.membershipProductLabel ?? 'Membership' : undefined,\n products,\n billingAddress: {\n street: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n promoCode: promoCode().trim() || undefined,\n },\n { idempotencyKey: idempotencyKey() },\n );\n\n // register+charge resolved. If the profile hydration inside the store hit\n // a transient error it may have cleared the just-set tokens — in that case\n // reconcile by logging in rather than declaring a success we don't have.\n if (finishIfAuthenticated()) return;\n if (await reconcileViaLogin()) return;\n setError('Your account was created but we could not sign you in. Please try logging in.');\n setOutcome({ kind: 'in_progress' });\n } catch (err) {\n if (err instanceof ApiError && err.ambiguous) {\n // The account may already exist and the card may already be charged even\n // though we never saw a response. Reconcile by logging in with the same\n // credentials; if that succeeds the registration went through. A genuine\n // retry reuses the same idempotency key, so the backend replays the\n // original result instead of double-charging.\n setOutcome({ kind: 'reconciling' });\n if (await reconcileViaLogin()) return;\n setError(\n \"We couldn't confirm whether your registration went through. Please check your connection and try again.\",\n );\n setOutcome({ kind: 'in_progress' });\n } else {\n // Definitive failure (declined card, validation). Nothing was created;\n // rotate the key so the corrected retry is a fresh operation.\n setIdempotencyKey(newIdempotencyKey());\n // The Accept.js nonce is single-use — the gateway attempt may have\n // consumed it, and it expires minutes after minting regardless — so a\n // resubmit from Confirm would replay a dead token into a second,\n // misleading failure. Drop it and return to the Payment step (card\n // fields still populated) so the retry path necessarily runs through a\n // fresh tokenization. The AMBIGUOUS branch above deliberately keeps the\n // nonce: its retry must replay the byte-identical request for the\n // backend's idempotent replay to match.\n setTokenizedData(null);\n setStep(2);\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n }\n } finally {\n setSubmitting(false);\n }\n }\n\n /** Best-effort reconcile: try to log in with the entered credentials. Returns\n * true and finishes the flow if a session is established. */\n async function reconcileViaLogin(): Promise<boolean> {\n try {\n await authStore.login(email().trim(), password());\n } catch {\n // login failed — the registration likely did not commit\n return false;\n }\n return finishIfAuthenticated();\n }\n\n return {\n step,\n isConfirmStep: () => step() === 3,\n next,\n back,\n error,\n tokenizing,\n submitting,\n outcome,\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 street, setStreet,\n city, setCity,\n state, setState,\n zip, setZip,\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\n submit,\n };\n}\n","import { createEffect, createSignal, onMount, type Accessor } from 'solid-js';\nimport authStore from '../stores/auth';\nimport { authApi, ApiError } from '../api/client';\nimport { getConfig } from '../config';\n\n// ── Draft persistence ───────────────────────────────────────────────\n//\n// Same shape as the signup flow's draft (flows/signup.ts): non-sensitive\n// fields survive a refresh, password never does. Because the Confirm step\n// would submit a blank (unpersisted) password, the max restorable step is 1\n// (Address); submit additionally re-validates every step as a backstop.\n\nconst DRAFT_TTL_MS = 7 * 24 * 3600 * 1000;\nconst MAX_RESTORABLE_STEP = 1;\n\ninterface RegisterDraft {\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 savedAt?: number;\n}\n\nfunction draftKey(): string {\n return `${getConfig().storagePrefix}-register-draft`;\n}\n\nfunction loadDraft(): RegisterDraft {\n try {\n const raw = localStorage.getItem(draftKey());\n if (!raw) return {};\n const parsed = JSON.parse(raw) as RegisterDraft;\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: RegisterDraft) {\n try {\n localStorage.setItem(draftKey(), JSON.stringify({ ...draft, savedAt: Date.now() }));\n } catch {\n // noop — quota or privacy mode\n }\n}\n\nfunction clearDraft() {\n try {\n localStorage.removeItem(draftKey());\n } catch {\n // noop\n }\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport type RegisterOutcome =\n | { kind: 'in_progress' }\n /** Emitted on mount when a session already exists — there is nothing to\n * register. Sites route back to wherever sent the visitor here (for a\n * model-3 tenant, typically the one-time checkout). */\n | { kind: 'already_authenticated' }\n | { kind: 'submitting' }\n /** Register response was lost mid-flight; we're checking whether the account\n * was actually created (by logging in) before letting the user retry. */\n | { kind: 'reconciling' }\n | { kind: 'completed' };\n\nexport interface RegisterFlow {\n // Step 0..2 (Account, Address, Confirm)\n step: Accessor<number>;\n /** True only on the very last step (Confirm). */\n isConfirmStep: Accessor<boolean>;\n next: () => Promise<void>;\n back: () => void;\n\n // Inline state\n error: Accessor<string | null>;\n /** True while submitting on the Confirm step. */\n submitting: Accessor<boolean>;\n outcome: Accessor<RegisterOutcome>;\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\n street: Accessor<string>; setStreet: (v: string) => void;\n city: Accessor<string>; setCity: (v: string) => void;\n state: Accessor<string>; setState: (v: string) => void;\n zip: Accessor<string>; setZip: (v: string) => void;\n\n /** Submit the registration at the Confirm step. */\n submit: () => Promise<void>;\n}\n\n/**\n * Non-subscribing signup (model-3 support): creates an account via\n * POST /auth/register and establishes a session — no membership charge, no\n * recurring subscription, no card collected. The subscribing signup\n * (useSignupFlow / SignupPage) is untouched and remains the right surface for\n * membership tenants.\n *\n * Backend note: POST /auth/register is functional but currently marked\n * @deprecated server-side (its successor is the subscribing\n * register-and-subscribe). Model-3 is exactly the use case that endpoint still\n * serves; un-deprecating it is a tracked backend follow-up. It leaves the new\n * user's `payment_status` as 'pending' — the one-time checkout charge does not\n * change that today (see the \"requirePaidSubscription 402\" backend card).\n */\nexport function useRegisterFlow(): RegisterFlow {\n // Restore draft (only up to MAX_RESTORABLE_STEP — never restore into Confirm,\n // whose submit depends on the deliberately-unpersisted password)\n let restored: RegisterDraft = {};\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 [submitting, setSubmitting] = createSignal(false);\n const [outcome, setOutcome] = createSignal<RegisterOutcome>({ 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\n const [street, setStreet] = createSignal(restored.street ?? '');\n const [city, setCity] = createSignal(restored.city ?? '');\n const [state, setState] = createSignal(restored.state ?? '');\n const [zip, setZip] = createSignal(restored.zip ?? '');\n\n onMount(() => {\n // An existing session means there is nothing to register — emit for the\n // site to route onwards instead of letting the user create a duplicate.\n if (authStore.isAuthenticated()) {\n setOutcome({ kind: 'already_authenticated' });\n return;\n }\n // Auto-save draft\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 });\n });\n });\n\n // ── Validation per step (mirrors flows/signup.ts steps 0/1) ─────\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 if (!email().trim()) return 'Email is required.';\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email().trim())) return 'Enter a valid email address.';\n if (!password().trim()) return 'Password is required.';\n if (password().length < 8) return 'Password must be at least 8 characters.';\n if (!phone().trim()) return 'Phone number is required.';\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 if (!street().trim()) return 'Street address is required.';\n if (!city().trim()) return 'City is required.';\n if (!state()) return 'State is required.';\n if (!zip().trim()) return 'ZIP code is required.';\n if (!/^\\d{5}(-\\d{4})?$/.test(zip().trim())) return 'Enter a valid ZIP code.';\n }\n return null;\n }\n\n // ── Navigation ───────────────────────────────────────────────────\n\n // In-flight guard: `next()` awaits (checkEmail), so without this a\n // double-click fires twice and two relative setStep increments could skip\n // the Address step entirely.\n let advancing = false;\n\n async function next() {\n if (advancing) return;\n advancing = true;\n try {\n await advance();\n } finally {\n advancing = false;\n }\n }\n\n async function advance() {\n // Capture the step at entry so we advance from a fixed point, not from\n // whatever step() reads back after the awaits.\n const startStep = step();\n // Confirm is the last step — there is nothing to advance to; leaving it\n // goes through submit() (or back()).\n if (startStep >= 2) return;\n const err = validateStep(startStep);\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n\n // Check email availability before leaving the Account step\n if (startStep === 0) {\n try {\n const { exists } = await authApi.checkEmail(email().trim());\n if (exists) {\n setError('An account with this email already exists.');\n return;\n }\n } catch {\n setError('Unable to verify email. Please try again.');\n return;\n }\n }\n\n // Absolute (not relative) so a stale/racing increment can't over-advance.\n setStep(startStep + 1);\n }\n\n function back() {\n setError(null);\n setStep((s) => Math.max(0, s - 1));\n }\n\n // ── Submit ───────────────────────────────────────────────────────\n\n /** Mark the registration done, but only if a session was actually\n * established — never declare success (and clear the draft) on a\n * half-completed register that left the user unauthenticated. */\n function finishIfAuthenticated(): boolean {\n if (!authStore.isAuthenticated()) return false;\n clearDraft();\n setOutcome({ kind: 'completed' });\n return true;\n }\n\n async function submit() {\n // Re-entrancy guard: a double-click must not fire two register calls.\n if (submitting()) return;\n\n // Re-validate every step before submitting. This is the backstop for a\n // restored draft: the draft can place the user on Address with a blank\n // (never-persisted) password, and Confirm must not submit it. Jump back to\n // the offending step with its error instead.\n for (const s of [0, 1]) {\n const err = validateStep(s);\n if (err) {\n setStep(s);\n setError(err);\n return;\n }\n }\n\n setError(null);\n setSubmitting(true);\n setOutcome({ kind: 'submitting' });\n\n try {\n await authStore.signup({\n email: email().trim(),\n password: password(),\n member: {\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim(),\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n });\n\n // Register resolved. If the profile hydration inside the store hit a\n // transient error it may have cleared the just-set tokens — reconcile by\n // logging in rather than declaring a success we don't have.\n if (finishIfAuthenticated()) return;\n if (await reconcileViaLogin()) return;\n setError('Your account was created but we could not sign you in. Please try logging in.');\n setOutcome({ kind: 'in_progress' });\n } catch (err) {\n if (err instanceof ApiError && err.ambiguous) {\n // The account may already exist even though we never saw a response.\n // Reconcile by logging in with the same credentials. No idempotency\n // key is needed here (nothing is charged): a duplicated register fails\n // with email-exists and the login resolves it either way.\n setOutcome({ kind: 'reconciling' });\n if (await reconcileViaLogin()) return;\n setError(\n \"We couldn't confirm whether your registration went through. Please check your connection and try again.\",\n );\n setOutcome({ kind: 'in_progress' });\n } else {\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n }\n } finally {\n setSubmitting(false);\n }\n }\n\n /** Best-effort reconcile: try to log in with the entered credentials. Returns\n * true and finishes the flow if a session is established. */\n async function reconcileViaLogin(): Promise<boolean> {\n try {\n await authStore.login(email().trim(), password());\n } catch {\n // login failed — the registration likely did not commit\n return false;\n }\n return finishIfAuthenticated();\n }\n\n return {\n step,\n isConfirmStep: () => step() === 2,\n next,\n back,\n error,\n submitting,\n outcome,\n\n firstName, setFirstName,\n lastName, setLastName,\n email, setEmail,\n password, setPassword,\n dateOfBirth, setDateOfBirth,\n phone, setPhone,\n\n street, setStreet,\n city, setCity,\n state, setState,\n zip, setZip,\n\n submit,\n };\n}\n","/**\n * Shared vocabulary for reading a subscription's status.\n *\n * Two DIFFERENT questions get asked about the same field, and conflating them\n * is how members get stuck:\n *\n * - **\"Did my create land?\"** (`isReconcilable`) — asked after an ambiguous\n * failure, when we need to know whether the server committed something. Any\n * non-terminal row counts, including the transient `pending` / `incomplete` /\n * `trialing` states a just-created subscription passes through, because\n * matching only `active` would report \"nothing happened\" and scare the member\n * into retrying a purchase that actually succeeded. Errs toward \"it exists\".\n *\n * - **\"Is this member already subscribed?\"** (`isLive`) — asked to BLOCK a new\n * subscribe on a single-subscription tenant. Must mirror the server's rule\n * exactly (`LIVE_SUBSCRIPTION_STATUSES` in the-backend's subscriptions route),\n * or the two disagree in the worst direction: an `incomplete` row from a\n * declined card would make this client refuse an intake the server would have\n * accepted, and the member could never subscribe at all. Errs toward \"let them\n * through\" — the server has the final say and cannot be bypassed.\n */\n\n/** Statuses that mean NO live subscription resulted — a terminal, dead record. */\nexport const TERMINAL_SUBSCRIPTION_STATUSES: ReadonlySet<string> = new Set([\n 'canceled',\n 'cancelled',\n 'failed',\n 'expired',\n 'incomplete_expired',\n 'unpaid',\n]);\n\n/**\n * Statuses the billing engine still acts on (or is waiting on the member to\n * make actable). Mirrors the-backend `LIVE_SUBSCRIPTION_STATUSES` — keep the two\n * lists in step.\n */\nexport const LIVE_SUBSCRIPTION_STATUSES: ReadonlySet<string> = new Set([\n 'active',\n 'past_due',\n 'paused',\n 'pending_verification',\n]);\n\n/** True when this row proves a create committed (see the module docstring). */\nexport function isReconcilable(status: string | undefined | null): boolean {\n return !TERMINAL_SUBSCRIPTION_STATUSES.has((status ?? '').toLowerCase());\n}\n\n/** True when this row means the member currently HOLDS a subscription. */\nexport function isLive(status: string | undefined | null): boolean {\n return LIVE_SUBSCRIPTION_STATUSES.has((status ?? '').toLowerCase());\n}\n","import { createSignal, onMount, type Accessor } from 'solid-js';\nimport {\n subscriptionsApi,\n usersApi,\n ApiError,\n newIdempotencyKey,\n type ApiResponse,\n} from '../api/client';\nimport authStore from '../stores/auth';\nimport cartStore from '../stores/cart';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { validateAddress, normalizeState, firstAddressError } from './address';\nimport { isReconcilable } from './subscriptionStatus';\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport type SubscribeOutcome =\n | { kind: 'loading' }\n | { kind: 'needs_auth' }\n | { kind: 'needs_cart' }\n | { kind: 'already_subscribed' }\n | { kind: 'in_progress' }\n /** Submit response was lost mid-flight; re-checking server state before we\n * let the user retry, so we never double-charge a charge that succeeded. */\n | { kind: 'reconciling' }\n | { kind: 'completed' };\n\n/** True if the member already has an active subscription server-side. */\nasync function hasActiveSubscription(): Promise<boolean> {\n const subsRes = (await subscriptionsApi.list()) as {\n subscriptions?: Array<{ status?: string }>;\n };\n return (subsRes?.subscriptions ?? []).some((s) => s.status === 'active');\n}\n\n/** True if the member has ANY non-terminal subscription server-side. Used for\n * post-ambiguous reconcile: a just-created subscription often sits in a\n * transient status (pending / incomplete / trialing) before it flips to\n * active, so matching only 'active' would falsely report \"no subscription\" and\n * scare the user, even though the ambiguous create actually committed. */\nasync function hasReconcilableSubscription(): Promise<boolean> {\n const subsRes = (await subscriptionsApi.list()) as {\n subscriptions?: Array<{ status?: string }>;\n };\n return (subsRes?.subscriptions ?? []).some((s) => isReconcilable(s.status));\n}\n\nexport interface UseSubscribeFlowOptions {\n /** Membership amount in cents charged on subscription start. Required. */\n membershipAmountCents: number;\n /** Billing interval in days. Default 30. */\n membershipIntervalDays?: number;\n}\n\nexport interface SubscribeFlow {\n outcome: Accessor<SubscribeOutcome>;\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 // Inline state\n error: Accessor<string | null>;\n submitting: Accessor<boolean>;\n\n // Billing address (prefilled from profile)\n street: Accessor<string>; setStreet: (v: string) => void;\n city: Accessor<string>; setCity: (v: string) => void;\n state: Accessor<string>; setState: (v: string) => void;\n zip: Accessor<string>; setZip: (v: string) => void;\n\n // Card\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 submit: () => Promise<void>;\n}\n\nexport function useSubscribeFlow(options: UseSubscribeFlowOptions): SubscribeFlow {\n const accept = useCardTokenizer();\n\n const [outcome, setOutcome] = createSignal<SubscribeOutcome>({ kind: 'loading' });\n const [error, setError] = createSignal<string | null>(null);\n const [submitting, setSubmitting] = createSignal(false);\n\n const [street, setStreet] = createSignal('');\n const [city, setCity] = createSignal('');\n const [state, setState] = createSignal('');\n const [zip, setZip] = createSignal('');\n\n // equals:false so format-clamped setters still fire reactivity; otherwise\n // Solid skips the input re-bind and the DOM keeps rejected characters.\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n\n // One idempotency key per logical subscription attempt. Reused verbatim on a\n // retry after an ambiguous (network-drop / 5xx) failure so the backend can\n // dedupe a charge that may have already committed; rotated after a definitive\n // failure (declined card) so a corrected retry isn't replayed as that error.\n const [idempotencyKey, setIdempotencyKey] = createSignal(newIdempotencyKey());\n\n // ── Guards + prefill on mount ────────────────────────────────────\n\n onMount(async () => {\n if (!authStore.isAuthenticated()) {\n setOutcome({ kind: 'needs_auth' });\n return;\n }\n if (cartStore.items().length === 0) {\n setOutcome({ kind: 'needs_cart' });\n return;\n }\n\n try {\n if (await hasActiveSubscription()) {\n setOutcome({ kind: 'already_subscribed' });\n return;\n }\n } catch {\n // Non-fatal — proceed with subscribe\n }\n\n // Prefill billing address from profile\n try {\n const profileRes = await usersApi.getProfile();\n const p = profileRes.data as Record<string, unknown> | undefined;\n if (p) {\n setStreet((p.address1 as string) || (p.street as string) || '');\n setCity((p.city as string) || '');\n setState(normalizeState((p.state as string) || ''));\n setZip((p.zip as string) || '');\n }\n } catch {\n // Non-fatal\n }\n\n setOutcome({ kind: 'in_progress' });\n });\n\n // ── Validation + submit ──────────────────────────────────────────\n\n function validate(): string | null {\n const a = validateAddress(\n { street: street(), city: city(), state: state(), zip: zip() },\n '',\n { enforceAvailability: true },\n );\n const addrErr = firstAddressError(a);\n if (addrErr) return addrErr;\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 return null;\n }\n\n async function submit() {\n // Re-entrancy guard: ignore a second click while a submit is in flight so a\n // double-click can't fire two create() calls (two charges).\n if (submitting()) return;\n\n // The mount-time guards go stale in a long-lived tab: another tab may have\n // logged out (the shared store now converges live), or completed this\n // purchase — which clears the shared cart. Re-check the cheap local guards\n // before tokenizing and charging. Deliberately NO client re-check of\n // already-subscribed here: that's TOCTOU-racy across tabs — the\n // authoritative dedupe is the backend's membership idempotency guard,\n // which returns the EXISTING subscription (idempotent 200) instead of\n // creating and charging a second one.\n if (!authStore.isAuthenticated()) {\n setOutcome({ kind: 'needs_auth' });\n return;\n }\n if (cartStore.items().length === 0) {\n setOutcome({ kind: 'needs_cart' });\n return;\n }\n\n const err = validate();\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n setSubmitting(true);\n\n try {\n const opaque = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n\n const products = cartStore.items().map((i) => ({\n productId: i.productId,\n productName: i.productName,\n quantity: i.quantity,\n dosage: i.dosage,\n }));\n\n const promo = cartStore.appliedPromo();\n const res = await subscriptionsApi.create(\n {\n opaqueData: opaque,\n amountCents: options.membershipAmountCents,\n intervalDays: options.membershipIntervalDays ?? 30,\n billingAddress: {\n street: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n products,\n productId: products[0]?.productId,\n promoCode: promo?.code,\n },\n { idempotencyKey: idempotencyKey() },\n );\n\n if ((res as ApiResponse).error) {\n throw new Error((res as ApiResponse).error || 'Failed to create subscription.');\n }\n\n setOutcome({ kind: 'completed' });\n } catch (e) {\n if (e instanceof ApiError && e.ambiguous) {\n // The create() outcome is unknown — the subscription may have been\n // created and the card charged even though we never saw a response.\n // Reconcile against the server before letting the user retry; if a\n // retry does happen it reuses the same idempotency key so the backend\n // dedupes rather than double-charging.\n setOutcome({ kind: 'reconciling' });\n try {\n if (await hasReconcilableSubscription()) {\n setOutcome({ kind: 'completed' });\n return;\n }\n } catch {\n // Reconcile request also failed — fall through to the retry prompt.\n }\n setOutcome({ kind: 'in_progress' });\n setError(\n \"We couldn't confirm whether your subscription went through. Please check your connection and try again.\",\n );\n } else {\n // Definitive failure (declined card, validation, business rejection):\n // nothing was created. Rotate the key so the corrected retry is treated\n // as a fresh operation, not deduped to this failed attempt.\n setIdempotencyKey(newIdempotencyKey());\n setError(e instanceof Error ? e.message : 'Failed to create subscription.');\n }\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n outcome,\n tokenizerReady: accept.ready,\n acceptJsReady: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\n error,\n submitting,\n street, setStreet,\n city, setCity,\n state, setState,\n zip, setZip,\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 submit,\n };\n}\n","import { createResource, type Resource } from 'solid-js';\nimport {\n usersApi,\n subscriptionsApi,\n apexApi,\n membersApi,\n type User,\n type PendingRenewalSurvey,\n type DeliveryInfo,\n type RenewalStatus,\n} from '../api/client';\nimport authStore from '../stores/auth';\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface DashboardSubscription {\n id: string;\n status: 'active' | 'paused' | 'cancelled';\n nextBillingDate?: string;\n amount?: number;\n [key: string]: unknown;\n}\n\nexport type RxRequestStatus =\n | 'pending'\n | 'approved'\n | 'denied'\n | 'shipped'\n | 'new'\n | 'processing'\n | 'completed';\n\nexport interface DashboardRxStatus {\n status: RxRequestStatus;\n reason?: string;\n delivery?: DeliveryInfo | null;\n [key: string]: unknown;\n}\n\nexport interface DashboardRxListItem {\n requestId: string;\n status: RxRequestStatus;\n drugId?: string;\n drugName?: string;\n dosage?: string;\n priceCents?: number;\n paymentConfirmed?: boolean;\n pharmacySent?: boolean;\n reason?: string;\n createdAt: string;\n delivery?: DeliveryInfo | null;\n renewal?: {\n renewalId: string;\n cycleNumber: number;\n status: RenewalStatus;\n pharmacyFillDate: string | null;\n } | null;\n}\n\nexport interface DashboardActivityItem {\n id: string;\n label: string;\n /** Relative-time string like \"5m ago\" or a fallback like \"Next bill: May 4\". */\n time: string;\n /** Single-character symbol or short emoji indicating the kind of event. Sites can map these to icons. */\n icon: string;\n}\n\nexport interface DashboardData {\n profile: Resource<User | null>;\n subscription: Resource<DashboardSubscription | null>;\n rxStatus: Resource<DashboardRxStatus | null>;\n rxList: Resource<DashboardRxListItem[]>;\n /** Re-fetch the prescription list (e.g. after cancelling a request). */\n refetchRxList: () => void;\n pendingSurveys: Resource<PendingRenewalSurvey[]>;\n /** First name from profile or authStore, falling back to \"Member\". */\n displayName: () => string;\n /** Recent activity feed derived from profile + subscription + rxStatus. */\n activity: () => DashboardActivityItem[];\n /**\n * Non-null when any dashboard read failed. A transient 500 used to render as\n * genuine emptiness (\"No prescriptions\"); surface this and offer `retry()`\n * instead of presenting a failure as truth. Individual resources also carry\n * a real `.error` now — but their value reads stay safe (empty/null\n * fallback), so existing consumers never crash on an errored read.\n */\n error: () => string | null;\n /** Re-fetch every dashboard resource (use from the error state's retry CTA). */\n retry: () => void;\n}\n\n// ── Public helpers ──────────────────────────────────────────────────\n\nexport function formatRelativeTime(dateStr: string): string {\n const now = Date.now();\n const then = new Date(dateStr).getTime();\n if (Number.isNaN(then)) return '';\n const diffMs = now - then;\n const mins = Math.floor(diffMs / 60_000);\n if (mins < 1) return 'Just now';\n if (mins < 60) return `${mins}m ago`;\n const hours = Math.floor(mins / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n if (days < 7) return `${days}d ago`;\n const weeks = Math.floor(days / 7);\n if (weeks < 5) return `${weeks}w ago`;\n return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });\n}\n\n// ── Internal fetchers ───────────────────────────────────────────────\n//\n// Fetchers THROW on failure so each Resource enters a real `.error` state —\n// a transient 500 must be distinguishable from genuine emptiness. The hook\n// wraps every exposed resource in a guarded reader (below), so value reads\n// still fall back to empty/null and never crash a consumer's render.\n\nasync function fetchProfile(authToken?: string): Promise<User | null> {\n const res = await usersApi.getProfile({ authToken });\n return (res.data as User) ?? null;\n}\n\nasync function fetchSubscription(authToken?: string): Promise<DashboardSubscription | null> {\n const res = (await subscriptionsApi.list(undefined, { authToken })) as {\n subscriptions?: DashboardSubscription[];\n };\n return res?.subscriptions?.[0] ?? null;\n}\n\nasync function fetchRxStatus(\n profile: User | null,\n authToken?: string,\n): Promise<DashboardRxStatus | null> {\n const requestId = (profile as Record<string, unknown> | null)?.apex_request_id as\n | string\n | undefined;\n if (!requestId) return null;\n const res = (await apexApi.getRequestStatus(requestId, undefined, {\n authToken,\n })) as DashboardRxStatus;\n return res ?? null;\n}\n\nasync function fetchRxList(authToken?: string): Promise<DashboardRxListItem[]> {\n const res = await membersApi.getRequests({ authToken });\n return (res.requests ?? []).map((r) => ({\n requestId: r.requestId,\n status: r.status as RxRequestStatus,\n drugId: r.drugId,\n drugName: r.drugName,\n dosage: r.dosage,\n priceCents: r.priceCents,\n paymentConfirmed: r.paymentConfirmed,\n createdAt: r.createdAt,\n delivery: r.delivery,\n renewal: r.renewal ?? null,\n }));\n}\n\nasync function fetchPendingSurveys(authToken?: string): Promise<PendingRenewalSurvey[]> {\n const res = await membersApi.getPendingSurveys({ authToken });\n return res.surveys ?? [];\n}\n\n/**\n * Wrap a resource so its VALUE read is safe in the error state (returns the\n * fallback instead of rethrowing, which is Solid's default for an errored\n * resource read) while `.loading`/`.error`/`.state` still reflect the real\n * resource. This is what lets the fetchers above throw — giving consumers a\n * genuine `.error` to render — without turning every existing `data.rxList()`\n * call site into a crash.\n */\nfunction guardedResource<T>(res: Resource<T>, fallback: T): Resource<T> {\n const read = (() => (res.error ? fallback : (res() ?? fallback))) as Resource<T>;\n Object.defineProperties(read, {\n loading: { get: () => res.loading },\n error: { get: () => res.error },\n state: { get: () => res.state },\n latest: { get: () => (res.error ? fallback : (res.latest ?? fallback)) },\n });\n return read;\n}\n\nfunction buildActivity(\n profile: User | null,\n sub: DashboardSubscription | null,\n rx: DashboardRxStatus | null,\n): DashboardActivityItem[] {\n const items: DashboardActivityItem[] = [];\n\n if (rx) {\n const statusLabels: Record<string, string> = {\n approved: 'Prescription approved',\n denied: 'Prescription request denied',\n pending: 'Prescription under review',\n shipped: 'Prescription shipped',\n };\n const statusIcons: Record<string, string> = {\n approved: '✓',\n denied: '✗',\n pending: '⌛',\n shipped: '📦',\n };\n const updatedAt = (rx as Record<string, unknown>).updated_at as string | undefined;\n items.push({\n id: 'rx',\n label: statusLabels[rx.status] || `Prescription status: ${rx.status}`,\n time: updatedAt ? formatRelativeTime(updatedAt) : '',\n icon: statusIcons[rx.status] || '✸',\n });\n }\n\n if (sub) {\n items.push({\n id: 'sub',\n label: `Subscription ${sub.status}`,\n time: sub.nextBillingDate\n ? `Next bill: ${new Date(sub.nextBillingDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`\n : '',\n icon: '✓',\n });\n }\n\n const createdAt = (profile as Record<string, unknown> | null)?.created_at as string | undefined;\n if (createdAt) {\n items.push({\n id: 'created',\n label: 'Account created',\n time: formatRelativeTime(createdAt),\n icon: '★',\n });\n }\n\n if (items.length === 0) {\n items.push({ id: 'empty', label: 'No recent activity', time: '', icon: '—' });\n }\n\n return items;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\n/**\n * Loads the data needed for the patient dashboard. No JSX — sites compose\n * their own layouts on top of this. Auth/admin guards are intentionally\n * not bundled here; the consuming site handles routing.\n *\n * Pass `opts.authToken` (a reactive accessor) to load the whole dashboard AS\n * another user — e.g. an admin \"view as customer\" preview using a short-lived\n * impersonation token. When provided, every read carries that token instead of\n * the auth store's session, so it never touches the caller's own login.\n */\nexport function useDashboardData(opts?: { authToken?: () => string | undefined }): DashboardData {\n const authToken = () => opts?.authToken?.();\n const [profileRes, { refetch: refetchProfile }] = createResource(() => fetchProfile(authToken()));\n const [subscriptionRes, { refetch: refetchSubscription }] = createResource(() =>\n fetchSubscription(authToken()),\n );\n // Guard the source read: an errored profile resource rethrows on access, and\n // a throw inside the source tracker would take the derived resource with it.\n const [rxStatusRes, { refetch: refetchRxStatus }] = createResource(\n () => (profileRes.error ? null : profileRes()),\n (p) => fetchRxStatus(p, authToken()),\n );\n const [rxListRes, { refetch: refetchRxList }] = createResource(() => fetchRxList(authToken()));\n const [pendingSurveysRes, { refetch: refetchPendingSurveys }] = createResource(() =>\n fetchPendingSurveys(authToken()),\n );\n\n const profile = guardedResource(profileRes, null);\n const subscription = guardedResource(subscriptionRes, null);\n const rxStatus = guardedResource(rxStatusRes, null);\n const rxList = guardedResource(rxListRes, [] as DashboardRxListItem[]);\n const pendingSurveys = guardedResource(pendingSurveysRes, [] as PendingRenewalSurvey[]);\n\n const displayName = () => {\n const p = profile();\n if (p?.firstName) return p.firstName;\n const u = authStore.user();\n if (u?.firstName) return u.firstName;\n return 'Member';\n };\n\n const activity = () =>\n buildActivity(profile() ?? null, subscription() ?? null, rxStatus() ?? null);\n\n const error = () =>\n profileRes.error || subscriptionRes.error || rxStatusRes.error || rxListRes.error ||\n pendingSurveysRes.error\n ? 'We couldn’t load your dashboard. Please try again.'\n : null;\n\n const retry = () => {\n void refetchProfile();\n void refetchSubscription();\n void refetchRxStatus();\n void refetchRxList();\n void refetchPendingSurveys();\n };\n\n return {\n profile,\n subscription,\n rxStatus,\n rxList,\n refetchRxList: () => void refetchRxList(),\n pendingSurveys,\n displayName,\n activity,\n error,\n retry,\n };\n}\n","import type { DeliveryInfo } from '../api/client';\n\nexport type TrackingUrlCarrier = 'fedex' | 'ups' | 'usps';\n\nconst TRACKING_URLS: Record<TrackingUrlCarrier, (n: string) => string> = {\n fedex: (n) => `https://www.fedex.com/fedextrack/?trknbr=${n}`,\n ups: (n) => `https://www.ups.com/track?tracknum=${n}`,\n usps: (n) => `https://tools.usps.com/go/TrackConfirmAction?tLabels=${n}`,\n};\n\nexport function buildTrackingUrl(delivery: DeliveryInfo | null | undefined): string | null {\n if (!delivery?.trackingNumber) return null;\n if (delivery.trackingUrl) return delivery.trackingUrl;\n const carrier = delivery.shipCarrier?.toLowerCase() as TrackingUrlCarrier;\n const builder = TRACKING_URLS[carrier];\n return builder ? builder(delivery.trackingNumber) : null;\n}\n","/**\n * Calendar-date helpers.\n *\n * A date-only string (\"1988-11-22\") is a CALENDAR date — a label on a wall\n * calendar, with no instant and no timezone attached. `new Date()` disagrees:\n * per the ES spec a date-only form is parsed as UTC midnight, so rendering it\n * with `toLocaleDateString()` shifts it back a day for every viewer west of\n * Greenwich. That is how a member's date of birth shows as the 21st in a US\n * browser while the stored value (\"1988-11-22\") is perfectly correct.\n *\n * Parse date-only strings at LOCAL midnight so the calendar date survives.\n * Values carrying a time (`createdAt`, `currentPeriodEnd`) are real instants\n * and go through `new Date` untouched.\n */\n\nconst DATE_ONLY = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** Parse a date value without shifting a date-only string across a timezone. */\nexport function parseCalendarDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const m = DATE_ONLY.exec(value.trim());\n const d = m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : new Date(value);\n return Number.isNaN(d.getTime()) ? null : d;\n}\n\n/**\n * Render a date for a member, without the UTC shift. Returns the input\n * unchanged when it can't be parsed, so a surprising value stays visible\n * instead of turning into \"Invalid Date\".\n */\nexport function formatCalendarDate(\n value: string | null | undefined,\n options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' },\n): string {\n if (!value) return '';\n const d = parseCalendarDate(value);\n if (!d) return value;\n return d.toLocaleDateString('en-US', options);\n}\n","/**\n * Pure derivation logic for the member portal order tracker and refill timeline.\n *\n * Design intent (\"Apothecary\" direction): one continuous vertical thread of\n * fulfillment \"beads\". The thread fills to wherever REAL backend data reaches and\n * never fabricates a state. Today the backend reliably exposes\n * pending/approved/denied/call_requested (+ shipped/delivery/renewal when present),\n * so beads beyond the known state render as honest \"upcoming\" nodes.\n *\n * No JSX and no data-fetching: the `MemberPortal` page maps its dashboard\n * resources into the small `TrackerRequest`/`TrackerSubscription` input shapes\n * below and renders the returned view. Kept framework-light and fully testable\n * (`now` is injected — no `Date.now()` inside the derivations).\n */\n\nimport { buildTrackingUrl } from './shipping';\nimport type { DeliveryInfo } from '../api/client';\nimport { parseCalendarDate } from '../utils/calendarDate';\n\n// ── Input contract ──────────────────────────────────────────────────\n// Deliberately self-contained (not the dashboard resource types): the tracker\n// needs a couple of fields the dashboard list doesn't carry (updatedAt, the\n// 'pharmacy' status, a subscription's currentPeriodEnd/intervalDays), so the\n// consuming page adapts its data into these rather than the reverse.\n\nexport type TrackerRequestStatus =\n | 'pending'\n | 'approved'\n | 'denied'\n | 'call_requested'\n | 'pharmacy'\n | 'shipped';\n\nexport interface TrackerRequest {\n status: TrackerRequestStatus;\n createdAt: string | null;\n updatedAt: string | null;\n dosage?: string;\n delivery: DeliveryInfo | null;\n}\n\nexport type TrackerSubscriptionStatus =\n | 'active'\n | 'paused'\n | 'past_due'\n | 'cancelled'\n | 'suspended'\n | 'expired';\n\nexport interface TrackerSubscription {\n status: TrackerSubscriptionStatus;\n /**\n * BILLING mirror — it moves only when a charge succeeds. Kept as the fallback\n * estimate for partners without renewals, but it is NOT a fill date: a $0\n * comped subscription never charges and freezes this at signup, and an\n * ARB→platform migration deliberately leaves it stale. Prefer `nextFillDate`.\n */\n currentPeriodEnd: string | null;\n intervalDays?: number;\n /**\n * The real next-fill date (`YYYY-MM-DD`), from the backend's live renewal row.\n * Null while a cycle is awaiting its fill — the pharmacy has not shipped, so\n * the date is genuinely unknown — and on partners without renewals.\n */\n nextFillDate?: string | null;\n /** When the check-in opens, from the same renewal row. */\n checkInDueAt?: string | null;\n /**\n * The live renewal's status, or null when no cycle is running. Distinguishes\n * \"no renewals here\" (fall back to the estimate) from \"a cycle is running but\n * its fill date isn't knowable yet\" (say so rather than guess).\n */\n checkInStatus?: string | null;\n}\n\n// ── Output types ────────────────────────────────────────────────────\n\nexport type StageState = 'done' | 'active' | 'upcoming' | 'consult' | 'denied';\n\nexport interface FulfillmentStage {\n key: string;\n /** Small-caps \"lab label\" shown on every bead. */\n label: string;\n /** Large display word — only set on the active / branch bead. */\n heroWord?: string;\n /** Plain-language one-liner under the hero word. */\n subCaption?: string;\n state: StageState;\n /** Absolute timestamp string we actually have (createdAt / updatedAt). */\n timestamp?: string | null;\n}\n\nexport interface ShipmentInfo {\n carrier: string | null;\n trackingNumber: string | null;\n trackingUrl: string | null;\n /** Honest ETA copy — relative reassurance when no real estimate exists. */\n etaLabel: string;\n}\n\nexport interface TrackerView {\n stages: FulfillmentStage[];\n /** Index of the active/branch bead, for the \"pour\" fill height. */\n activeIndex: number;\n shipment: ShipmentInfo | null;\n /** True for denied/consult so the UI can pick supportive treatment. */\n branch: 'consult' | 'denied' | null;\n}\n\nconst PIPELINE: Array<{ key: string; label: string; heroWord: string; subCaption: string }> = [\n { key: 'submitted', label: 'Submitted', heroWord: 'Received', subCaption: 'We’ve received your request.' },\n {\n key: 'review',\n label: 'Under review',\n heroWord: 'Under review',\n subCaption: 'A licensed clinician is reviewing your request now.',\n },\n { key: 'approved', label: 'Approved', heroWord: 'Approved', subCaption: 'Your prescription is approved.' },\n {\n key: 'pharmacy',\n label: 'At the pharmacy',\n heroWord: 'At the pharmacy',\n subCaption: 'Your pharmacy is preparing your medication.',\n },\n { key: 'shipped', label: 'Shipped', heroWord: 'On its way', subCaption: 'Your medication has left the pharmacy.' },\n];\n\n// Shipped is the terminal stage — Apex never sends delivery confirmations, so\n// the tracker doesn't model a \"Delivered\" step.\nconst PIPE = {\n submitted: 0,\n review: 1,\n approved: 2,\n pharmacy: 3,\n shipped: 4,\n} as const;\n\n/**\n * Derive the active pipeline index from the request, bumping forward only when\n * real fulfillment data (a tracking number) is present.\n */\nfunction resolveActiveIndex(rx: TrackerRequest): number {\n switch (rx.status) {\n case 'pending':\n return PIPE.review;\n case 'approved':\n return rx.delivery?.trackingNumber ? PIPE.shipped : PIPE.approved;\n case 'pharmacy':\n return rx.delivery?.trackingNumber ? PIPE.shipped : PIPE.pharmacy;\n case 'shipped':\n return PIPE.shipped;\n default:\n return PIPE.review;\n }\n}\n\nfunction buildShipment(rx: TrackerRequest): ShipmentInfo | null {\n const d = rx.delivery;\n if (!d || !d.trackingNumber) return null;\n return {\n carrier: d.shipCarrier || null,\n trackingNumber: d.trackingNumber,\n trackingUrl: buildTrackingUrl(d),\n // Honest ETA: Shipped is the last update we get from Apex, so point members\n // to the carrier's own tracking rather than promising updates we won't send.\n etaLabel: 'On its way — track it with the carrier for the latest updates.',\n };\n}\n\n/**\n * Build the full tracker view from a prescription request. Branches\n * (consultation needed / not approved) stay on the same thread, reframed as a\n * pause rather than an error.\n */\nexport function buildTrackerView(rx: TrackerRequest): TrackerView {\n // ── Branch: consultation requested ──\n if (rx.status === 'call_requested') {\n const stages: FulfillmentStage[] = [\n { key: 'submitted', label: 'Submitted', state: 'done', timestamp: rx.createdAt },\n {\n key: 'consult',\n label: 'Consultation needed',\n heroWord: 'Let’s talk',\n subCaption:\n 'Your clinician would like a quick chat before approving — this is routine and helps us get your care right.',\n state: 'consult',\n timestamp: rx.updatedAt,\n },\n { key: 'approved', label: 'Approved', state: 'upcoming' },\n { key: 'pharmacy', label: 'At the pharmacy', state: 'upcoming' },\n { key: 'shipped', label: 'Shipped', state: 'upcoming' },\n ];\n return { stages, activeIndex: 1, shipment: null, branch: 'consult' };\n }\n\n // ── Branch: not approved ──\n if (rx.status === 'denied') {\n const stages: FulfillmentStage[] = [\n { key: 'submitted', label: 'Submitted', state: 'done', timestamp: rx.createdAt },\n { key: 'review', label: 'Under review', state: 'done' },\n {\n key: 'denied',\n label: 'A pause for now',\n heroWord: 'A pause for now',\n subCaption:\n 'We weren’t able to approve this request right now. Your provider can walk through next steps — and you won’t be charged.',\n state: 'denied',\n timestamp: rx.updatedAt,\n },\n ];\n return { stages, activeIndex: 2, shipment: null, branch: 'denied' };\n }\n\n // ── Main pipeline ──\n const activeIndex = resolveActiveIndex(rx);\n const stages: FulfillmentStage[] = PIPELINE.map((step, i) => {\n const base = { key: step.key, label: step.label };\n if (i < activeIndex) {\n return {\n ...base,\n state: 'done' as const,\n timestamp: i === PIPE.submitted ? rx.createdAt : null,\n };\n }\n if (i === activeIndex) {\n return {\n ...base,\n heroWord: step.heroWord,\n subCaption: step.subCaption,\n state: 'active' as const,\n timestamp: i === PIPE.submitted ? rx.createdAt : rx.updatedAt,\n };\n }\n return { ...base, state: 'upcoming' as const };\n });\n\n return { stages, activeIndex, shipment: buildShipment(rx), branch: null };\n}\n\n// ── Refill timeline ─────────────────────────────────────────────────\n\nexport interface RefillEvent {\n key: 'fill' | 'survey' | 'shipment';\n label: string;\n date: Date | null;\n /** Soft relative copy, e.g. \"in 6 days\". */\n relative: string;\n /** Nearest upcoming event gets the highlight dot. */\n nearest: boolean;\n}\n\nexport interface RefillView {\n events: RefillEvent[];\n /** \"Day 18 of 30\" cycle counter. Meaningless when `pendingFill` — hide it. */\n cycleDay: number;\n cycleLength: number;\n /** 0–1 progress through the current cycle. */\n progress: number;\n /**\n * True when the dates are the backend's real schedule; false when they are the\n * legacy estimate derived from the billing period. Lets the UI soften its copy\n * (\"around the 14th\") only where it is actually guessing.\n */\n precise: boolean;\n /**\n * A cycle is running but its next-fill date is not knowable yet (the current\n * order has not shipped). Events carry no dates — say \"once your order ships\",\n * never a fabricated one.\n */\n pendingFill: boolean;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction softRelative(date: Date | null, now: number): string {\n if (!date) return '';\n const diffDays = Math.round((date.getTime() - now) / DAY_MS);\n if (diffDays < 0) return `${Math.abs(diffDays)}d ago`;\n if (diffDays === 0) return 'today';\n if (diffDays === 1) return 'tomorrow';\n if (diffDays < 14) return `in ${diffDays} days`;\n const weeks = Math.round(diffDays / 7);\n return `in ${weeks} weeks`;\n}\n\n/**\n * Parse a backend date into a Date the member reads correctly.\n *\n * `nextFillDate` is date-only (`YYYY-MM-DD`), which `new Date()` reads as UTC\n * midnight — so every member west of Greenwich would see their fill date a day\n * early (\"2026-09-13\" renders as Sep 12 in New York). Date-only strings are\n * calendar dates, not instants: parse them at LOCAL midnight. Full timestamps\n * (`checkInDueAt`) are real instants and parse normally.\n */\nconst parseBackendDate = parseCalendarDate;\n\n/**\n * Derive the refill/renewal strip from a subscription, in three cases:\n *\n * 1. `nextFillDate` present — the backend's REAL schedule from the live renewal\n * row. Used as-is (`precise: true`).\n * 2. A cycle is running (`checkInStatus`) but has no fill date yet — it is\n * awaiting the pharmacy. Dates are genuinely unknown, so report none\n * (`pendingFill: true`) rather than inventing them.\n * 3. No renewal information at all — a partner without renewals. Falls back to\n * the legacy estimate off `currentPeriodEnd` (`precise: false`), unchanged.\n *\n * Case 3 used to be the only path, and it is why a comped member's plan read\n * \"Day 30 of 30, check-in due 67d ago\" forever: `currentPeriodEnd` only advances\n * on a successful charge, and a $0 subscription never has one.\n *\n * `now` is injected so this stays a pure function (testable; no Date.now()).\n */\nexport function buildRefillView(\n sub: TrackerSubscription | null | undefined,\n now: number = Date.now(),\n): RefillView | null {\n if (!sub) return null;\n // Don't render a refill timeline for terminal subscriptions — nothing is\n // scheduled, and a stale date would otherwise show a misleading \"full cycle\" /\n // open check-in. (Active/paused/past_due still have a live cycle.)\n if (sub.status === 'cancelled' || sub.status === 'expired' || sub.status === 'suspended') {\n return null;\n }\n\n const cycleLength = sub.intervalDays && sub.intervalDays > 0 ? sub.intervalDays : 30;\n const fillDate = parseBackendDate(sub.nextFillDate);\n\n // ── Case 2: a cycle is running, but the pharmacy hasn't shipped yet ──\n if (!fillDate && sub.checkInStatus) {\n const events: RefillEvent[] = [\n { key: 'survey', label: 'Check-in due', date: null, relative: 'after your next fill', nearest: false },\n { key: 'fill', label: 'Next refill', date: null, relative: 'once your order ships', nearest: true },\n { key: 'shipment', label: 'Next shipment', date: null, relative: 'once your order ships', nearest: false },\n ];\n return { events, cycleDay: 0, cycleLength, progress: 0, precise: true, pendingFill: true };\n }\n\n // ── Case 1: the real schedule ── / ── Case 3: the legacy estimate ──\n const periodEnd = fillDate ?? parseBackendDate(sub.currentPeriodEnd);\n if (!periodEnd) return null;\n const precise = fillDate !== null;\n\n const periodStart = new Date(periodEnd.getTime() - cycleLength * DAY_MS);\n const elapsed = (now - periodStart.getTime()) / DAY_MS;\n const cycleDay = Math.min(cycleLength, Math.max(1, Math.round(elapsed)));\n const progress = Math.min(1, Math.max(0, (now - periodStart.getTime()) / (cycleLength * DAY_MS)));\n\n // Check-in: the real `checkInDueAt` when we have it, else ~7 days before the\n // fill (estimate). Whether a check-in is actually actionable is decided by the\n // caller from a real pending renewal, not this date — it is a timeline marker.\n const surveyDate =\n parseBackendDate(sub.checkInDueAt) ?? new Date(periodEnd.getTime() - 7 * DAY_MS);\n\n const events: RefillEvent[] = [\n { key: 'survey', label: 'Check-in due', date: surveyDate, relative: '', nearest: false },\n { key: 'fill', label: 'Next refill', date: periodEnd, relative: '', nearest: false },\n { key: 'shipment', label: 'Next shipment', date: periodEnd, relative: '', nearest: false },\n ];\n\n for (const e of events) e.relative = softRelative(e.date, now);\n\n // Nearest upcoming (future) event gets the dot; fall back to the first.\n const upcoming = events.filter((e) => e.date && e.date.getTime() >= now);\n const nearest = upcoming.sort((a, b) => a.date!.getTime() - b.date!.getTime())[0] || events[0];\n nearest.nearest = true;\n\n return { events, cycleDay, cycleLength, progress, precise, pendingFill: false };\n}\n\n// ── Formatting helpers shared by the portal ─────────────────────────\n\nexport function formatStageDate(value?: string | null): string {\n if (!value) return '';\n const d = new Date(value);\n if (Number.isNaN(d.getTime())) return '';\n return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });\n}\n\nexport function formatEventDate(date: Date | null): string {\n if (!date) return '—';\n return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });\n}\n","/**\n * Pure derivations for the admin customer 360 view.\n *\n * The backend decides the lifecycle BUCKET (one rule table drives both the list\n * filter and the label, so they cannot disagree). This module turns bucket +\n * the raw records into what a support rep reads: the one-sentence reason, the\n * \"needs attention\" list, the journey stepper, and a merged timeline.\n *\n * No JSX, no fetching, `now` injected — same discipline as `tracker.ts`.\n *\n * Honesty rule: a step we have no data for renders as `unknown`, never as\n * \"not done\". Funnel telemetry and cart recovery are per-tenant features and\n * are OFF for some tenants; the overview says which, and this module respects\n * it.\n */\n\nimport type {\n AdminBillingAttempt,\n AdminCustomerOverview,\n AdminCustomerRequest,\n AdminLifecycleBucket,\n AdminPaymentDetail,\n AdminSubscriptionDetail,\n} from '../api/client';\nimport type { TrackerRequest, TrackerRequestStatus } from './tracker';\n\n// ── Shared vocab ────────────────────────────────────────────────────\n\nexport type Severity = 'danger' | 'warning' | 'info';\nexport type Tone = 'success' | 'warning' | 'danger' | 'info' | 'neutral';\n\n/** Fallback labels when the backend omits `lifecycle.label`. */\nexport const LIFECYCLE_LABEL: Record<AdminLifecycleBucket, string> = {\n active: 'Active',\n past_due: 'Past due',\n paused: 'Paused',\n incomplete: 'Incomplete signup',\n cancelled: 'Cancelled',\n card_declined: 'Card declined',\n awaiting_prescriber: 'Awaiting prescriber',\n never_subscribed: 'Never subscribed',\n};\n\nexport const LIFECYCLE_TONE: Record<AdminLifecycleBucket, Tone> = {\n active: 'success',\n past_due: 'warning',\n paused: 'neutral',\n incomplete: 'warning',\n cancelled: 'neutral',\n card_declined: 'danger',\n awaiting_prescriber: 'info',\n never_subscribed: 'neutral',\n};\n\nexport const LIFECYCLE_BUCKETS: AdminLifecycleBucket[] = [\n 'never_subscribed',\n 'card_declined',\n 'awaiting_prescriber',\n 'incomplete',\n 'active',\n 'past_due',\n 'paused',\n 'cancelled',\n];\n\nexport type AccountSource = 'savings' | 'register_and_subscribe' | 'register' | 'unknown';\n\nexport const ACCOUNT_SOURCE_LABEL: Record<AccountSource, string> = {\n savings: 'Savings program registration',\n register_and_subscribe: 'Signed up and subscribed in one step',\n register: 'Created an account first',\n unknown: 'Unknown',\n};\n\n// ── Small helpers ───────────────────────────────────────────────────\n\nconst DAY_MS = 86_400_000;\nconst LIVE = new Set(['active', 'paused', 'past_due']);\n\nfunction ms(iso: string | null | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : t;\n}\n\n/** Deterministic short date (\"Aug 3, 2026\") — UTC so tests do not drift. */\nexport function fmtDay(iso: string | null | undefined): string {\n const t = ms(iso);\n if (t === null) return 'an unknown date';\n return new Date(t).toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n timeZone: 'UTC',\n });\n}\n\n/** Gateway messages sometimes end with a period and sometimes do not; normalise to one. */\nfunction sentence(text: string): string {\n const t = text.trim();\n return /[.!?]$/.test(t) ? t : `${t}.`;\n}\n\nfunction dollars(cents: number | null | undefined): string {\n if (cents == null) return '$0.00';\n return `$${(cents / 100).toFixed(2)}`;\n}\n\nfunction newestFirst<T>(items: T[], at: (t: T) => string | null | undefined): T[] {\n return [...items].sort((a, b) => (ms(at(b)) ?? 0) - (ms(at(a)) ?? 0));\n}\n\nfunction latestSubscription(subs: AdminSubscriptionDetail[]): AdminSubscriptionDetail | null {\n return newestFirst(subs, (s) => s.createdAt)[0] ?? null;\n}\n\n/** The subscription a rep cares about: a live one first, else the newest. */\nexport function primarySubscription(subs: AdminSubscriptionDetail[]): AdminSubscriptionDetail | null {\n const live = newestFirst(\n subs.filter((s) => LIVE.has(s.status)),\n (s) => s.createdAt,\n );\n return live[0] ?? latestSubscription(subs);\n}\n\nfunction latestRequest(reqs: AdminCustomerRequest[]): AdminCustomerRequest | null {\n return newestFirst(reqs, (r) => r.createdAt)[0] ?? null;\n}\n\nfunction latestFailedPayment(payments: AdminPaymentDetail[]): AdminPaymentDetail | null {\n return newestFirst(\n payments.filter((p) => p.status === 'failed'),\n (p) => p.createdAt,\n )[0] ?? null;\n}\n\nfunction hasTracking(r: AdminCustomerRequest): boolean {\n return !!(r.tracking?.trackingNumber || r.delivery?.trackingNumber);\n}\n\n// ── Account source ──────────────────────────────────────────────────\n\n/**\n * Where the account came from. Savings members carry `savingsMemberId`; a\n * fan-out signup creates the subscription in the same request as the user,\n * so a subscription born within two minutes of the account is that path.\n */\nexport function accountSource(o: Pick<AdminCustomerOverview, 'customer' | 'subscriptions'>): AccountSource {\n if (o.customer.savingsMemberId) return 'savings';\n const created = ms(o.customer.createdAt);\n if (created === null) return 'unknown';\n const oldest = [...o.subscriptions].sort(\n (a, b) => (ms(a.createdAt) ?? 0) - (ms(b.createdAt) ?? 0),\n )[0];\n if (oldest) {\n const subAt = ms(oldest.createdAt);\n if (subAt !== null && Math.abs(subAt - created) < 2 * 60_000) return 'register_and_subscribe';\n }\n return 'register';\n}\n\n// ── Lifecycle reason ────────────────────────────────────────────────\n\ntype ReasonInput = Pick<\n AdminCustomerOverview,\n 'customer' | 'lifecycle' | 'subscriptions' | 'payments' | 'requests' | 'funnel' | 'tenant'\n>;\n\n/**\n * One plain sentence answering \"why is this customer in this bucket\". This is\n * the line that answers the truemeds question: an account with no subscription\n * says whether the person never completed intake, completed it and never paid,\n * or tried to pay and was declined.\n */\nexport function lifecycleReason(o: ReasonInput): string {\n const { bucket } = o.lifecycle;\n const facts = o.lifecycle.facts;\n const sub = primarySubscription(o.subscriptions);\n const source = accountSource(o);\n const joined = fmtDay(o.customer.createdAt);\n const captures = newestFirst(o.funnel.captures, (c) => c.capturedAt);\n const capture = captures[0] ?? null;\n\n switch (bucket) {\n case 'never_subscribed': {\n const opener =\n source === 'savings'\n ? `Joined through the savings program on ${joined}.`\n : `Created an account on ${joined}.`;\n if (capture) {\n if (!capture.qualified) {\n return `${opener} Completed the intake survey on ${fmtDay(capture.capturedAt)} but did not qualify.`;\n }\n return `${opener} Completed the intake survey on ${fmtDay(capture.capturedAt)} but never checked out.`;\n }\n if (facts?.hasFunnelCapture) {\n return `${opener} Completed the intake survey but never checked out.`;\n }\n if (facts?.hasOpenCart) {\n return `${opener} Never completed the intake survey; has an abandoned cart.`;\n }\n return `${opener} Never completed the intake survey.`;\n }\n case 'card_declined': {\n const failed = latestFailedPayment(o.payments);\n const when = failed ? fmtDay(failed.createdAt) : fmtDay(facts?.lastPaymentAt);\n const why = failed?.failureReason ? `: ${failed.failureReason}` : '';\n return `Card declined at checkout on ${when}${why}. No subscription was created.`;\n }\n case 'awaiting_prescriber': {\n const req = latestRequest(o.requests.items);\n const when = req ? fmtDay(req.createdAt) : fmtDay(facts?.latestRequestApexStatus ? null : null);\n return req\n ? `Prescription request submitted ${when}; awaiting prescriber review.`\n : 'A prescription request is awaiting prescriber review.';\n }\n case 'incomplete':\n return 'Checkout payment outcome is unknown; the subscription is on hold until the charge is verified.';\n case 'active': {\n if (!sub) return 'Active subscription.';\n const next = sub.nextChargeAt ? ` Next charge ${fmtDay(sub.nextChargeAt)}.` : '';\n return `Subscribed ${fmtDay(sub.createdAt)}.${next}`;\n }\n case 'past_due': {\n const s = o.subscriptions.find((x) => x.status === 'past_due') ?? sub;\n const attempt = s ? newestFirst(s.billingAttempts ?? [], (a) => a.createdAt).find((a) => a.status === 'failed') : null;\n const n = s?.retryCount ? ` (retry ${s.retryCount})` : '';\n const why = attempt?.errorMessage ? `: ${sentence(attempt.errorMessage)}` : '.';\n const retry = s?.nextChargeAt ? ` Next retry ${fmtDay(s.nextChargeAt)}.` : '';\n return `Renewal charge failed${n}${why}${retry}`;\n }\n case 'paused': {\n const s = o.subscriptions.find((x) => x.status === 'paused') ?? sub;\n return s?.pausedAt ? `Paused on ${fmtDay(s.pausedAt)}.` : 'Subscription paused.';\n }\n case 'cancelled': {\n const s = newestFirst(\n o.subscriptions.filter((x) => x.status === 'cancelled'),\n (x) => x.cancelledAt,\n )[0] ?? sub;\n if (!s) return 'Subscription cancelled.';\n const started = ms(s.createdAt);\n const ended = ms(s.cancelledAt);\n const months =\n started !== null && ended !== null ? Math.max(0, Math.round((ended - started) / (30 * DAY_MS))) : null;\n const tenure = months !== null && months > 0 ? ` after ${months} month${months === 1 ? '' : 's'}` : '';\n return `Cancelled on ${fmtDay(s.cancelledAt)}${tenure}.`;\n }\n default:\n return o.lifecycle.label || '';\n }\n}\n\n// ── Attention list ──────────────────────────────────────────────────\n\nexport type AttentionActionKind =\n | 'resolve_attempt'\n | 'edit_schedule'\n | 'cancel_unapproved'\n | 'open_thread'\n | 'open_subscription'\n | 'open_payment'\n | 'open_request';\n\nexport interface AttentionAction {\n kind: AttentionActionKind;\n label: string;\n subscriptionId?: string;\n attemptId?: string;\n threadId?: string;\n paymentId?: string;\n requestId?: string;\n}\n\nexport interface AttentionItem {\n id: string;\n severity: Severity;\n title: string;\n detail?: string;\n action?: AttentionAction;\n}\n\nconst SEVERITY_RANK: Record<Severity, number> = { danger: 0, warning: 1, info: 2 };\n\nexport const STALE_REVIEW_DAYS = 3;\n\n/**\n * Things a rep should act on, worst first. Every rule names the record it\n * came from so the UI can jump to it. Rules are deliberately conservative:\n * they fire only on states the backend records, never on inference.\n */\nexport function deriveAttention(o: AdminCustomerOverview, now: Date = new Date()): AttentionItem[] {\n const items: AttentionItem[] = [];\n const nowMs = now.getTime();\n const liveSubs = o.subscriptions.filter((s) => LIVE.has(s.status));\n\n // Money that is stuck.\n for (const p of o.payments) {\n if (p.status === 'refund_pending') {\n items.push({\n id: `refund-pending-${p.id}`,\n severity: 'danger',\n title: `Refund of ${dollars(p.amountCents)} did not complete at the gateway`,\n detail: p.failureReason ?? 'Finish the refund manually in the gateway, then resolve here.',\n action: { kind: 'open_payment', label: 'View payment', paymentId: p.id },\n });\n }\n }\n\n for (const s of o.subscriptions) {\n for (const a of s.billingAttempts ?? []) {\n if (a.status === 'indeterminate') {\n items.push({\n id: `attempt-indeterminate-${a.id}`,\n severity: 'danger',\n title: 'A charge outcome is unknown; billing is blocked until it is resolved',\n detail: `${dollars(a.amountCents)} for period ${(a.billingPeriod ?? 0) + 1}${a.errorMessage ? ` — ${a.errorMessage}` : ''}`,\n action: { kind: 'resolve_attempt', label: 'Resolve', subscriptionId: s.id, attemptId: a.id },\n });\n }\n }\n\n if (s.status === 'past_due') {\n const failed = newestFirst(s.billingAttempts ?? [], (a) => a.createdAt).find((a) => a.status === 'failed');\n items.push({\n id: `past-due-${s.id}`,\n severity: 'warning',\n title: `Renewal charge failed${s.retryCount ? ` (retry ${s.retryCount})` : ''}`,\n detail: [\n failed?.errorMessage ? sentence(failed.errorMessage) : failed?.errorCode ? `Code ${failed.errorCode}.` : null,\n s.nextChargeAt ? `Next retry ${fmtDay(s.nextChargeAt)}.` : 'No retry scheduled.',\n ]\n .filter(Boolean)\n .join(' '),\n action: { kind: 'edit_schedule', label: 'Edit schedule', subscriptionId: s.id },\n });\n }\n\n if (s.status === 'incomplete') {\n items.push({\n id: `incomplete-${s.id}`,\n severity: 'warning',\n title: 'Checkout payment is unverified',\n detail: 'The gateway did not confirm the first charge. The subscription is held and will not bill until resolved.',\n action: { kind: 'open_subscription', label: 'View subscription', subscriptionId: s.id },\n });\n }\n }\n\n // Declined at checkout with nothing live.\n if (liveSubs.length === 0) {\n const declined = latestFailedPayment(o.payments.filter((p) => p.detached));\n if (declined) {\n items.push({\n id: `declined-${declined.id}`,\n severity: 'warning',\n title: `Card declined at checkout on ${fmtDay(declined.createdAt)}`,\n detail: declined.failureReason ?? undefined,\n action: { kind: 'open_payment', label: 'View payment', paymentId: declined.id },\n });\n }\n }\n\n // Never got going.\n if (o.subscriptions.length === 0 && o.payments.every((p) => p.status !== 'failed')) {\n const captured = o.funnel.captures.length > 0 || o.lifecycle.facts?.hasFunnelCapture;\n if (o.customer.savingsMemberId && !captured) {\n items.push({\n id: 'savings-no-intake',\n severity: 'info',\n title: 'Registered through the savings program but never started the intake survey',\n detail: o.tenant.requirePaidSubscription\n ? 'This site requires a paid subscription before a prescription request can be created.'\n : undefined,\n });\n } else if (captured) {\n const c = newestFirst(o.funnel.captures, (x) => x.capturedAt)[0];\n items.push({\n id: 'intake-no-checkout',\n severity: 'info',\n title: c\n ? `Completed the intake survey on ${fmtDay(c.capturedAt)} but never checked out`\n : 'Completed the intake survey but never checked out',\n detail: c && !c.qualified ? 'Did not qualify.' : undefined,\n });\n }\n }\n\n // Prescriptions.\n for (const r of o.requests.items) {\n if (r.status === 'call_requested') {\n items.push({\n id: `consult-${r.requestId}`,\n severity: 'info',\n title: `Prescriber requested a consultation${r.drugName ? ` for ${r.drugName}` : ''}`,\n action: { kind: 'open_request', label: 'View request', requestId: r.requestId },\n });\n }\n if (r.status === 'pending') {\n const created = ms(r.createdAt);\n const days = created !== null ? Math.floor((nowMs - created) / DAY_MS) : null;\n if (days !== null && days >= STALE_REVIEW_DAYS) {\n items.push({\n id: `stale-review-${r.requestId}`,\n severity: 'info',\n title: `Awaiting prescriber review for ${days} days${r.drugName ? ` (${r.drugName})` : ''}`,\n action: { kind: 'open_request', label: 'View request', requestId: r.requestId },\n });\n }\n }\n if (r.renewal?.needsReviewAt) {\n items.push({\n id: `renewal-review-${r.renewal.id}`,\n severity: 'warning',\n title: 'Renewal needs review',\n detail: r.renewal.reviewReason ?? undefined,\n action: { kind: 'open_request', label: 'View request', requestId: r.requestId },\n });\n }\n }\n\n const pending = o.requests.items.filter((r) => r.status === 'pending');\n if (liveSubs.length === 0 && o.subscriptions.some((s) => s.status === 'cancelled') && pending.length > 0) {\n items.push({\n id: 'cancelled-with-pending',\n severity: 'warning',\n title: `${pending.length} unapproved prescription request${pending.length === 1 ? ' is' : 's are'} still in the prescriber queue after cancellation`,\n detail: 'A cancelled customer should not be prescribed. Cancel the pending requests.',\n action: { kind: 'cancel_unapproved', label: 'Cancel unapproved requests' },\n });\n }\n\n // Support.\n for (const t of o.support.threads) {\n if (t.adminUnread && t.status !== 'closed') {\n items.push({\n id: `support-${t.id}`,\n severity: 'info',\n title: `Support message awaiting reply${t.subject ? `: ${t.subject}` : ''}`,\n detail: t.lastMessageAt ? `Last message ${fmtDay(t.lastMessageAt)}` : undefined,\n action: { kind: 'open_thread', label: 'Open thread', threadId: t.id },\n });\n }\n }\n\n return items.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);\n}\n\n// ── Journey ─────────────────────────────────────────────────────────\n\nexport type JourneyStepKey =\n | 'account'\n | 'intake'\n | 'checkout'\n | 'prescriber'\n | 'pharmacy'\n | 'shipped'\n | 'renewing';\n\nexport type JourneyState = 'done' | 'active' | 'blocked' | 'upcoming' | 'unknown';\n\nexport interface JourneyStep {\n key: JourneyStepKey;\n label: string;\n state: JourneyState;\n /** ISO timestamp we actually have for this step, or null. */\n date: string | null;\n /** One short line under the label. */\n detail: string | null;\n}\n\nconst JOURNEY_LABEL: Record<JourneyStepKey, string> = {\n account: 'Account',\n intake: 'Intake',\n checkout: 'Checkout',\n prescriber: 'Prescriber',\n pharmacy: 'Pharmacy',\n shipped: 'Shipped',\n renewing: 'Renewing',\n};\n\nfunction step(key: JourneyStepKey, state: JourneyState, date: string | null = null, detail: string | null = null): JourneyStep {\n return { key, label: JOURNEY_LABEL[key], state, date, detail };\n}\n\n/**\n * Where the customer is on the account → renewing path. The first non-done\n * step is where they are; `blocked` says why they cannot move; `unknown`\n * says the site does not collect that signal. Only one step is `active`.\n */\nexport function deriveJourney(o: AdminCustomerOverview): JourneyStep[] {\n const steps: JourneyStep[] = [];\n const source = accountSource(o);\n const subs = o.subscriptions;\n const liveSub = primarySubscription(subs.filter((s) => LIVE.has(s.status)));\n const anySub = subs.length > 0;\n const req = latestRequest(o.requests.items);\n const capture = newestFirst(o.funnel.captures, (c) => c.capturedAt)[0] ?? null;\n const session = newestFirst(o.funnel.sessions, (s) => s.lastSeenAt)[0] ?? null;\n const declined = latestFailedPayment(o.payments);\n const paid = newestFirst(\n o.payments.filter((p) => p.status === 'succeeded' || p.status === 'refunded'),\n (p) => p.createdAt,\n )[0];\n\n // 1. Account — always done.\n steps.push(step('account', 'done', o.customer.createdAt, ACCOUNT_SOURCE_LABEL[source]));\n\n // 2. Intake — a capture is the only durable proof. A subscription or a\n // request implies it too (the survey precedes both).\n const intakeDone = !!capture || o.lifecycle.facts?.hasFunnelCapture || anySub || o.requests.items.length > 0;\n if (intakeDone) {\n steps.push(\n step(\n 'intake',\n 'done',\n capture?.capturedAt ?? null,\n capture ? (capture.qualified ? 'Completed and qualified' : 'Completed, did not qualify') : 'Completed',\n ),\n );\n } else if (session) {\n steps.push(\n step(\n 'intake',\n 'active',\n session.lastSeenAt,\n session.lastStep != null && session.stepCount\n ? `Stopped at step ${session.lastStep} of ${session.stepCount}`\n : 'Started, not completed',\n ),\n );\n } else {\n steps.push(\n step(\n 'intake',\n 'active',\n null,\n o.funnel.telemetryEnabled ? 'Not started' : 'Not completed (step data not collected on this site)',\n ),\n );\n }\n\n // 3. Checkout.\n if (anySub || paid) {\n const first = [...subs].sort((a, b) => (ms(a.createdAt) ?? 0) - (ms(b.createdAt) ?? 0))[0];\n steps.push(step('checkout', 'done', first?.createdAt ?? paid?.createdAt ?? null, first ? `${dollars(first.amountCents)} subscription` : 'One-time purchase'));\n } else if (subs.some((s) => s.status === 'incomplete')) {\n steps.push(step('checkout', 'blocked', null, 'Payment outcome unverified'));\n } else if (declined) {\n steps.push(step('checkout', 'blocked', declined.createdAt, declined.failureReason ? `Declined: ${declined.failureReason}` : 'Card declined'));\n } else if (intakeDone) {\n steps.push(step('checkout', 'active', null, 'Not started'));\n } else {\n steps.push(step('checkout', 'upcoming'));\n }\n\n const checkoutDone = anySub || !!paid;\n\n // 4. Prescriber.\n if (req) {\n switch (req.status) {\n case 'pending':\n steps.push(step('prescriber', 'active', req.createdAt, 'Awaiting review'));\n break;\n case 'call_requested':\n steps.push(step('prescriber', 'blocked', req.updatedAt ?? req.createdAt, 'Consultation requested'));\n break;\n case 'denied':\n steps.push(step('prescriber', 'blocked', req.updatedAt ?? req.createdAt, 'Not approved'));\n break;\n default:\n steps.push(step('prescriber', 'done', req.updatedAt ?? req.createdAt, 'Approved'));\n }\n } else if (liveSub) {\n steps.push(step('prescriber', 'blocked', null, 'No prescription request on file'));\n } else if (checkoutDone) {\n steps.push(step('prescriber', 'upcoming', null, 'No prescription request'));\n } else {\n steps.push(step('prescriber', 'upcoming'));\n }\n\n // 5. Pharmacy.\n const approvedStatuses = new Set(['approved', 'pharmacy', 'processing', 'completed', 'shipped']);\n if (req && (req.status === 'pharmacy' || req.status === 'processing' || req.status === 'completed' || req.status === 'shipped' || hasTracking(req))) {\n steps.push(step('pharmacy', 'done', req.updatedAt ?? null, req.pharmacySent ? 'Sent to pharmacy' : 'At the pharmacy'));\n } else if (req && req.status === 'approved') {\n steps.push(\n step(\n 'pharmacy',\n 'active',\n null,\n o.tenant.fulfillmentMode === 'deferred' && !req.paymentConfirmed\n ? 'Approved; waiting on payment confirmation'\n : 'Approved; waiting for pharmacy hand-off',\n ),\n );\n } else if (req && approvedStatuses.has(req.status)) {\n steps.push(step('pharmacy', 'active'));\n } else {\n steps.push(step('pharmacy', 'upcoming'));\n }\n\n // 6. Shipped.\n if (req && hasTracking(req)) {\n const carrier = req.tracking?.shipCarrier ?? req.delivery?.shipCarrier ?? null;\n const number = req.tracking?.trackingNumber ?? req.delivery?.trackingNumber ?? null;\n const delivered = (req.tracking?.deliveryStatus ?? req.delivery?.status ?? '').toLowerCase() === 'delivered';\n steps.push(\n step(\n 'shipped',\n 'done',\n req.tracking?.shippedAt ?? null,\n delivered ? 'Delivered' : [carrier, number].filter(Boolean).join(' ') || 'Shipped',\n ),\n );\n } else if (req && (req.status === 'pharmacy' || req.status === 'processing' || req.status === 'completed')) {\n steps.push(step('shipped', 'active', null, 'Awaiting shipment'));\n } else {\n steps.push(step('shipped', 'upcoming'));\n }\n\n // 7. Renewing.\n if (liveSub) {\n if (liveSub.status === 'past_due') {\n steps.push(step('renewing', 'blocked', liveSub.nextChargeAt, `Renewal charge failed${liveSub.retryCount ? `, retry ${liveSub.retryCount}` : ''}`));\n } else if (liveSub.status === 'paused') {\n steps.push(step('renewing', 'blocked', liveSub.pausedAt, 'Paused'));\n } else {\n const checkIn = req?.renewal?.status ?? null;\n steps.push(\n step(\n 'renewing',\n 'done',\n liveSub.nextChargeAt,\n liveSub.nextChargeAt\n ? `Next charge ${fmtDay(liveSub.nextChargeAt)}${checkIn ? ` · check-in ${checkIn.replace(/_/g, ' ')}` : ''}`\n : 'No next charge scheduled',\n ),\n );\n }\n } else if (subs.some((s) => s.status === 'cancelled')) {\n const c = newestFirst(subs.filter((s) => s.status === 'cancelled'), (s) => s.cancelledAt)[0];\n steps.push(step('renewing', 'blocked', c?.cancelledAt ?? null, 'Cancelled'));\n } else {\n steps.push(step('renewing', 'upcoming'));\n }\n\n // Only the first non-done step may be `active`; later steps that claim\n // `active` without an earlier `done` are demoted to upcoming.\n let seenActive = false;\n for (const s of steps) {\n if (s.state === 'active' || s.state === 'blocked') {\n if (seenActive && s.state === 'active') s.state = 'upcoming';\n seenActive = true;\n }\n }\n return steps;\n}\n\n// ── Tracker adapter ─────────────────────────────────────────────────\n\nconst TRACKER_STATUS: Record<string, TrackerRequestStatus> = {\n pending: 'pending',\n approved: 'approved',\n denied: 'denied',\n call_requested: 'call_requested',\n pharmacy: 'pharmacy',\n processing: 'pharmacy',\n completed: 'pharmacy',\n shipped: 'shipped',\n};\n\n/** Adapt an overview request to the member-portal tracker input. */\nexport function toTrackerRequest(r: AdminCustomerRequest): TrackerRequest {\n const delivery =\n r.delivery ??\n (r.tracking?.trackingNumber\n ? {\n status: r.tracking.deliveryStatus,\n trackingNumber: r.tracking.trackingNumber,\n shipCarrier: r.tracking.shipCarrier ?? '',\n trackingUrl: null,\n }\n : null);\n const status: TrackerRequestStatus = delivery?.trackingNumber ? 'shipped' : (TRACKER_STATUS[r.status] ?? 'pending');\n return {\n status,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n dosage: r.dosage ?? undefined,\n delivery,\n };\n}\n\n// ── Timeline ────────────────────────────────────────────────────────\n\nexport type TimelineKind =\n | 'account'\n | 'intake'\n | 'subscription'\n | 'payment'\n | 'attempt'\n | 'request'\n | 'shipment'\n | 'support'\n | 'renewal'\n | 'cart';\n\nexport interface TimelineEvent {\n id: string;\n at: string;\n kind: TimelineKind;\n title: string;\n detail?: string | null;\n tone: Tone;\n}\n\n/** Wire timestamps are nullable; an event with no date is dropped by `buildTimeline`. */\nconst at = (iso: string | null | undefined): string => iso ?? '';\n\nfunction attemptTone(a: AdminBillingAttempt): Tone {\n if (a.status === 'failed') return 'danger';\n if (a.status === 'indeterminate') return 'warning';\n if (a.status === 'succeeded') return 'success';\n return 'neutral';\n}\n\n/**\n * Every dated record, newest first. Payments and billing attempts both carry\n * money events; attempts are only listed when they failed or are unresolved,\n * since a succeeded attempt is already visible as its payment.\n */\nexport function buildTimeline(o: AdminCustomerOverview, limit = 200): TimelineEvent[] {\n const ev: TimelineEvent[] = [];\n\n ev.push({\n id: 'account',\n at: o.customer.createdAt,\n kind: 'account',\n title: 'Account created',\n detail: ACCOUNT_SOURCE_LABEL[accountSource(o)],\n tone: 'neutral',\n });\n\n for (const c of o.funnel.captures) {\n ev.push({\n id: `capture-${c.responseId}`,\n at: at(c.capturedAt),\n kind: 'intake',\n title: c.qualified ? 'Completed intake survey (qualified)' : 'Completed intake survey (did not qualify)',\n detail: c.remindersSent ? `${c.remindersSent} recovery reminder${c.remindersSent === 1 ? '' : 's'} sent` : null,\n tone: c.qualified ? 'success' : 'neutral',\n });\n }\n for (const s of o.funnel.sessions) {\n ev.push({\n id: `session-${s.sessionId}`,\n at: at(s.startedAt),\n kind: 'intake',\n title: 'Started intake survey',\n detail: s.lastStep != null && s.stepCount ? `Reached step ${s.lastStep} of ${s.stepCount}` : null,\n tone: 'neutral',\n });\n }\n for (const c of o.funnel.carts) {\n ev.push({\n id: `cart-${c.cartId}`,\n at: at(c.updatedAt),\n kind: 'cart',\n title: c.convertedAt ? 'Cart checked out' : 'Cart left open',\n detail: `${c.itemCount} item${c.itemCount === 1 ? '' : 's'} · ${dollars(c.subtotalCents)}`,\n tone: 'neutral',\n });\n }\n\n for (const s of o.subscriptions) {\n // Prefer the server-resolved product name; `medication` may be an internal code.\n const label = s.medicationName || s.medication;\n ev.push({\n id: `sub-created-${s.id}`,\n at: at(s.createdAt),\n kind: 'subscription',\n title: `Subscribed${label ? ` to ${label}` : ''}`,\n detail: `${dollars(s.amountCents)} every ${s.intervalDays} days`,\n tone: 'success',\n });\n if (s.pausedAt && s.status === 'paused') {\n ev.push({ id: `sub-paused-${s.id}`, at: s.pausedAt, kind: 'subscription', title: 'Subscription paused', tone: 'neutral' });\n }\n if (s.cancelledAt) {\n ev.push({ id: `sub-cancelled-${s.id}`, at: s.cancelledAt, kind: 'subscription', title: 'Subscription cancelled', tone: 'danger' });\n }\n for (const a of s.billingAttempts ?? []) {\n if (a.status === 'succeeded') continue;\n ev.push({\n id: `attempt-${a.id}`,\n at: at(a.createdAt),\n kind: 'attempt',\n title:\n a.status === 'failed'\n ? `Renewal charge failed (${dollars(a.amountCents)})`\n : a.status === 'indeterminate'\n ? `Renewal charge outcome unknown (${dollars(a.amountCents)})`\n : `Renewal charge pending (${dollars(a.amountCents)})`,\n detail: a.errorMessage ?? a.errorCode ?? null,\n tone: attemptTone(a),\n });\n }\n }\n\n for (const p of o.payments) {\n const detached = p.detached ? ' at checkout (no subscription created)' : '';\n const title =\n p.status === 'succeeded'\n ? `Paid ${dollars(p.amountCents)}`\n : p.status === 'failed'\n ? `Payment of ${dollars(p.amountCents)} declined${detached}`\n : p.status === 'refunded'\n ? `Refunded ${dollars(p.refundedAmountCents || p.amountCents)}`\n : p.status === 'refund_pending'\n ? `Refund of ${dollars(p.amountCents)} pending`\n : p.status === 'voided'\n ? `Payment of ${dollars(p.amountCents)} voided`\n : `Payment ${p.status} (${dollars(p.amountCents)})`;\n ev.push({\n id: `payment-${p.id}`,\n at: at(p.createdAt),\n kind: 'payment',\n title,\n detail: p.failureReason ?? (p.type ? p.type.replace(/_/g, ' ') : null),\n tone:\n p.status === 'succeeded'\n ? 'success'\n : p.status === 'failed' || p.status === 'refund_pending'\n ? 'danger'\n : p.status === 'refunded' || p.status === 'voided'\n ? 'warning'\n : 'neutral',\n });\n if (p.refundedAt && p.refundedAmountCents > 0 && p.status === 'succeeded') {\n ev.push({\n id: `payment-partial-${p.id}`,\n at: at(p.refundedAt),\n kind: 'payment',\n title: `Partially refunded ${dollars(p.refundedAmountCents)} of ${dollars(p.amountCents)}`,\n tone: 'warning',\n });\n }\n }\n\n for (const r of o.requests.items) {\n if (r.createdAt) {\n ev.push({\n id: `request-${r.requestId}`,\n at: r.createdAt,\n kind: 'request',\n title: `Prescription request submitted${r.drugName ? ` for ${r.drugName}` : ''}`,\n detail: r.dosage ?? null,\n tone: 'neutral',\n });\n }\n if (r.updatedAt && r.updatedAt !== r.createdAt && r.status !== 'pending') {\n ev.push({\n id: `request-status-${r.requestId}`,\n at: r.updatedAt,\n kind: 'request',\n title: `Request ${r.status.replace(/_/g, ' ')}${r.drugName ? ` (${r.drugName})` : ''}`,\n tone: r.status === 'denied' ? 'danger' : r.status === 'call_requested' ? 'warning' : 'success',\n });\n }\n if (r.tracking?.shippedAt) {\n ev.push({\n id: `shipped-${r.requestId}`,\n at: r.tracking.shippedAt,\n kind: 'shipment',\n title: `Shipped${r.drugName ? ` ${r.drugName}` : ''}`,\n detail: [r.tracking.shipCarrier, r.tracking.trackingNumber].filter(Boolean).join(' ') || null,\n tone: 'success',\n });\n }\n if (r.renewal?.triggerAt) {\n ev.push({\n id: `renewal-${r.renewal.id}`,\n at: r.renewal.triggerAt,\n kind: 'renewal',\n title: `Refill check-in ${r.renewal.status.replace(/_/g, ' ')}`,\n detail: r.renewal.pharmacyFillDate ? `Fill date ${r.renewal.pharmacyFillDate}` : null,\n tone: r.renewal.status === 'request_failed' ? 'danger' : 'neutral',\n });\n }\n }\n\n for (const t of o.support.threads) {\n if (t.lastMessageAt) {\n ev.push({\n id: `support-${t.id}`,\n at: t.lastMessageAt,\n kind: 'support',\n title: t.adminUnread ? 'Support message awaiting reply' : `Support thread ${t.status}`,\n detail: t.subject,\n tone: t.adminUnread ? 'info' : 'neutral',\n });\n }\n }\n\n return ev\n .filter((e) => ms(e.at) !== null)\n .sort((a, b) => (ms(b.at) ?? 0) - (ms(a.at) ?? 0))\n .slice(0, limit);\n}\n","/**\n * Data source for the customer member portal. Headless (no JSX): the\n * `MemberPortal` page composes its layout on top of this.\n *\n * Business-model-flexible by design — capabilities are inferred from the data,\n * not hardcoded to one partner's model:\n * - RX requests are a LIST (a member may have several in flight at once).\n * - Subscriptions are OPTIONAL (some partners are one-time-purchase only).\n * The page reads `hasBilling()` / `rxRequests()` to decide which tabs/sections\n * to show, so a no-subscription, multi-RX partner and a single-RX +\n * subscription partner both render correctly from the same component.\n *\n * Sources: `/members/me` (member + subscriptions) and `/members/me/requests`\n * (the RX list — the endpoint the pre-redesign dashboard used successfully).\n */\n\nimport { createResource } from 'solid-js';\nimport {\n membersApi,\n type MemberPrescriptionRequest,\n type PendingRenewalSurvey,\n type DeliveryInfo,\n} from '../api/client';\nimport type {\n TrackerRequest,\n TrackerRequestStatus,\n TrackerSubscription,\n TrackerSubscriptionStatus,\n} from './tracker';\n\n// ── Types ───────────────────────────────────────────────────────────\n\n/** A subscription row from `/members/me` (see `MembersMeResponse.subscriptions`). */\nexport interface MemberPortalSubscription {\n id: string;\n productId: string;\n /** Apex drug id (a code). */\n medication: string;\n /** Friendly product name resolved server-side; falls back to `medication`. */\n medicationName?: string;\n dosage: string;\n status: string;\n amountCents: number;\n intervalDays: number;\n /** Billing mirror — advances only on a successful charge. Not a fill date. */\n currentPeriodEnd: string;\n /** Real next-fill date (`YYYY-MM-DD`) from the live renewal; null when none. */\n nextFillDate?: string | null;\n /** When the check-in opens, from the same renewal row. */\n checkInDueAt?: string | null;\n /** Live renewal status, or null when no cycle is running. */\n checkInStatus?: string | null;\n createdAt: string;\n}\n\n/** A prescription request, flattened for the portal. */\nexport interface MemberPortalRx {\n requestId: string;\n status: TrackerRequestStatus;\n drugName?: string;\n dosage?: string;\n createdAt: string | null;\n updatedAt: string | null;\n delivery: DeliveryInfo | null;\n /** Open check-in renewal id, if any (drives the \"Complete check-in\" link). */\n renewalId: string | null;\n}\n\nexport interface MemberPortalData {\n /** Raw member record (`/members/me` → `member`); shape is backend-defined. */\n member: () => Record<string, unknown> | null;\n subscriptions: () => MemberPortalSubscription[];\n /** The subscription the portal treats as primary (live one first, else first). */\n primarySubscription: () => MemberPortalSubscription | null;\n /** True when this member/partner has any subscription (gates the Plan tab). */\n hasBilling: () => boolean;\n /** All RX requests, newest first. */\n rxRequests: () => MemberPortalRx[];\n /** The RX to feature (newest in-flight, else newest overall). */\n primaryRx: () => MemberPortalRx | null;\n /** The remaining RX requests (everything but the primary), newest first. */\n otherRx: () => MemberPortalRx[];\n pendingSurveys: () => PendingRenewalSurvey[];\n /** First name from the member record (camel or snake), else \"Member\". */\n firstName: () => string;\n loading: () => boolean;\n /** Present when the RX list or member load failed — surfaced, not swallowed. */\n error: () => string | null;\n refetch: () => void;\n /** Adapt an RX into the tracker flow's input contract. */\n toTrackerRequest: (rx: MemberPortalRx) => TrackerRequest;\n /** The subscription driving the refill strip (only when hasBilling). */\n trackerSubscription: () => TrackerSubscription | null;\n}\n\n// ── Fetchers ────────────────────────────────────────────────────────\n\ninterface MembersMe {\n member?: Record<string, unknown> | null;\n subscriptions?: MemberPortalSubscription[];\n}\n\nasync function fetchPendingSurveys(): Promise<PendingRenewalSurvey[]> {\n try {\n const res = await membersApi.getPendingSurveys();\n return res.surveys ?? [];\n } catch {\n return [];\n }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\n// Subscriptions/RX considered \"live\" when active/paused/past-due (subs) or\n// still moving through fulfillment (RX). Terminal states sort last.\nconst LIVE_SUB = new Set(['active', 'paused', 'past_due']);\nconst IN_FLIGHT_RX = new Set(['pending', 'approved', 'call_requested', 'processing', 'pharmacy']);\n\nfunction pickPrimarySub(subs: MemberPortalSubscription[]): MemberPortalSubscription | null {\n return subs.find((s) => LIVE_SUB.has(s.status)) ?? subs[0] ?? null;\n}\n\nfunction readFirstName(member: Record<string, unknown> | null): string {\n if (!member) return 'Member';\n const camel = member.firstName;\n const snake = member.first_name;\n const name = typeof camel === 'string' ? camel : typeof snake === 'string' ? snake : '';\n return name || 'Member';\n}\n\nfunction toRx(r: MemberPrescriptionRequest): MemberPortalRx {\n return {\n requestId: r.requestId,\n status: r.status as TrackerRequestStatus,\n drugName: r.drugName,\n dosage: r.dosage,\n createdAt: r.createdAt ?? null,\n updatedAt: r.updatedAt ?? null,\n delivery: r.delivery,\n renewalId: r.renewal?.renewalId ?? null,\n };\n}\n\n// Newest first by createdAt (missing dates sort last).\nfunction byNewest(a: MemberPortalRx, b: MemberPortalRx): number {\n const ta = a.createdAt ? new Date(a.createdAt).getTime() : 0;\n const tb = b.createdAt ? new Date(b.createdAt).getTime() : 0;\n return tb - ta;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport function useMemberPortalData(): MemberPortalData {\n const [me, { refetch: refetchMe }] = createResource<MembersMe>(() => membersApi.getMe());\n // The RX list is the load-bearing data. Unlike the old dashboard's swallow-to-\n // empty, a failure here becomes a real error state (retry), never a silent\n // \"no prescriptions\".\n const [rxRes, { refetch: refetchRx }] = createResource(async () => {\n const res = await membersApi.getRequests();\n return (res.requests ?? []).map(toRx).sort(byNewest);\n });\n const [pendingSurveys] = createResource(fetchPendingSurveys);\n\n const member = () => (me.error ? null : me()?.member ?? null);\n const subscriptions = () => (me.error ? [] : me()?.subscriptions ?? []);\n const primarySubscription = () => pickPrimarySub(subscriptions());\n const hasBilling = () => subscriptions().length > 0;\n\n const rxRequests = () => (rxRes.error ? [] : rxRes() ?? []);\n const primaryRx = () => {\n const list = rxRequests();\n return list.find((r) => IN_FLIGHT_RX.has(r.status)) ?? list[0] ?? null;\n };\n const otherRx = () => {\n const primary = primaryRx();\n return rxRequests().filter((r) => r.requestId !== primary?.requestId);\n };\n\n const firstName = () => readFirstName(member());\n const loading = () => me.loading || rxRes.loading;\n // Surface an error if the critical RX list fails, or the member load fails.\n const error = () =>\n rxRes.error || me.error ? 'We couldn’t load your portal. Please try again.' : null;\n\n const toTrackerRequest = (rx: MemberPortalRx): TrackerRequest => ({\n status: rx.status,\n createdAt: rx.createdAt,\n updatedAt: rx.updatedAt,\n dosage: rx.dosage,\n delivery: rx.delivery,\n });\n\n const trackerSubscription = (): TrackerSubscription | null => {\n const s = primarySubscription();\n if (!s) return null;\n return {\n status: s.status as TrackerSubscriptionStatus,\n currentPeriodEnd: s.currentPeriodEnd ?? null,\n intervalDays: s.intervalDays,\n // The real schedule. Must be forwarded, or buildRefillView silently falls\n // back to estimating off the billing mirror.\n nextFillDate: s.nextFillDate ?? null,\n checkInDueAt: s.checkInDueAt ?? null,\n checkInStatus: s.checkInStatus ?? null,\n };\n };\n\n return {\n member,\n subscriptions,\n primarySubscription,\n hasBilling,\n rxRequests,\n primaryRx,\n otherRx,\n pendingSurveys: () => pendingSurveys() ?? [],\n firstName,\n loading,\n error,\n refetch: () => {\n void refetchMe();\n void refetchRx();\n },\n toTrackerRequest,\n trackerSubscription,\n };\n}\n","/**\n * Headless flow for updating a subscription's payment method (card on file).\n * Composes the provider-aware tokenizer (useCardTokenizer) with\n * subscriptionsApi.updatePaymentMethod: the raw PAN is tokenized client-side and\n * only the opaque token is sent to the backend.\n *\n * The card-entry UI (UpdatePaymentMethod page) renders these signals; the\n * subscription id is provided reactively so the page can resolve it (e.g. the\n * member's primary subscription) before the card is submitted.\n */\n\nimport { createEffect, createSignal, type Accessor } from 'solid-js';\nimport { subscriptionsApi } from '../api/client';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\n\nexport interface UpdatePaymentMethodFlow {\n cardNumber: Accessor<string>;\n setCardNumber: (v: string) => void;\n expiry: Accessor<string>;\n setExpiry: (v: string) => void;\n cvv: Accessor<string>;\n setCvv: (v: string) => void;\n /** True once the tenant's tokenizer is loaded. */\n ready: Accessor<boolean>;\n submitting: Accessor<boolean>;\n /** User-facing error from tokenization or the update call. */\n error: Accessor<string | null>;\n /** Whether submit is currently allowed (ready, all fields present, idle). */\n canSubmit: Accessor<boolean>;\n /** Tokenize + PUT the new card. Resolves true on success, false on failure. */\n submit: () => Promise<boolean>;\n\n /**\n * Billing address sent as the card's billTo.\n *\n * This screen used to send the card alone, leaving the backend to bill\n * against the member's SHIPPING profile with nothing shown and nothing\n * editable. The gateway validates the card live on update, so a card that\n * bills to a different address failed AVS — surfacing as a bare \"declined\"\n * that named nothing and offered no control to fix. The member could not\n * update their card on file at all.\n *\n * Prefilled from `GET /payment-method` with whatever is already on file at\n * the gateway (falling back to the profile address), so the common case is\n * still confirm-and-save.\n */\n billing: AddressPair;\n /** True once the address on file has loaded (fields prefill on arrival). */\n billingLoaded: Accessor<boolean>;\n}\n\nexport function useUpdatePaymentMethodFlow(\n subscriptionId: () => string | null,\n): UpdatePaymentMethodFlow {\n const accept = useCardTokenizer();\n\n const [cardNumber, setCardNumberRaw] = createSignal('');\n const [expiry, setExpiryRaw] = createSignal('');\n const [cvv, setCvvRaw] = createSignal('');\n const [submitting, setSubmitting] = createSignal(false);\n const [error, setError] = createSignal<string | null>(null);\n\n // Billing address. `billingSameAsShipping` is meaningless here — this screen\n // has no shipping form of its own — so it stays checked-off and the fields\n // are always the live billing values.\n const billing = useAddressPair();\n const [billingLoaded, setBillingLoaded] = createSignal(false);\n\n // Prefill from the address already on file at the gateway. Runs when the\n // subscription id resolves (the page may resolve it asynchronously).\n createEffect(() => {\n const id = subscriptionId();\n if (!id || billingLoaded()) return;\n void (async () => {\n try {\n const res = (await subscriptionsApi.getPaymentMethod(id)) as {\n billingAddress?: { street?: string; city?: string; state?: string; zip?: string } | null;\n };\n const a = res?.billingAddress;\n if (a) {\n billing.setShipping({\n street: a.street ?? '',\n city: a.city ?? '',\n state: a.state ?? '',\n zip: a.zip ?? '',\n });\n }\n } catch {\n // Non-fatal: an empty form the member fills in beats blocking the\n // screen because we couldn't read the current address.\n } finally {\n setBillingLoaded(true);\n }\n })();\n });\n\n const setCardNumber = (v: string) => setCardNumberRaw(formatCardNumber(v));\n const setExpiry = (v: string) => setExpiryRaw(formatExpiry(v));\n const setCvv = (v: string) => setCvvRaw(formatCvv(v));\n\n const canSubmit = () =>\n accept.ready() &&\n !submitting() &&\n cardNumber().trim().length > 0 &&\n expiry().trim().length > 0 &&\n cvv().trim().length > 0;\n\n async function submit(): Promise<boolean> {\n const id = subscriptionId();\n if (!id) {\n setError('We couldn’t find your subscription. Please try again.');\n return false;\n }\n // Validate the billing address before spending the card token on a request\n // the gateway will reject at AVS anyway.\n const addrErrors = validateAddress(billing.shipping(), 'Billing');\n const addrError = firstAddressError(addrErrors);\n if (addrError) {\n setError(addrError);\n return false;\n }\n\n setSubmitting(true);\n setError(null);\n try {\n const opaqueData = await accept.tokenize({\n cardNumber: cardNumber(),\n expiry: expiry(),\n cvv: cvv(),\n });\n await subscriptionsApi.updatePaymentMethod(id, { opaqueData, billingAddress: billing.shipping() });\n return true;\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Could not update your card. Please try again.');\n return false;\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n cardNumber,\n setCardNumber,\n expiry,\n setExpiry,\n cvv,\n setCvv,\n ready: accept.ready,\n submitting,\n // A tokenizer-init failure surfaces through the same error channel the\n // page already renders — without it, `ready()` stayed false forever and\n // the Save button was silently dead.\n error: () => accept.error() ?? error(),\n canSubmit,\n submit,\n billing,\n billingLoaded,\n };\n}\n","import { supportApi } from '../api/client';\n\n/**\n * Live support-thread updates over Supabase Realtime.\n *\n * The backend broadcasts only `{ threadId, tenantId }` to a private channel; no\n * message content crosses it. Subscribers treat a ping purely as \"refetch this\n * thread\" and read the actual content back over the normal authed REST route.\n * So the worst a channel-authorization fault can leak is the existence of a\n * thread id.\n *\n * Everything here is best-effort. Realtime is an accelerator on top of polling,\n * never a replacement: if the token endpoint 503s (no anon key configured), if\n * `@supabase/supabase-js` isn't installed, or if the channel errors, we return\n * null and the caller's existing poll keeps the UI correct — just slower.\n *\n * `@supabase/supabase-js` is an OPTIONAL peer dependency, imported dynamically.\n * That keeps a ~100KB realtime client out of the main bundle for visitors who\n * never open Messages, and keeps core installable by sites that don't want it.\n */\n\nexport interface SupportPing {\n threadId: string;\n tenantId: string;\n}\n\nexport interface SupportRealtimeSubscription {\n unsubscribe: () => Promise<void>;\n}\n\n/** Re-mint before the 5-minute token expires, with room for a slow round trip. */\nconst TOKEN_REFRESH_MS = 4 * 60 * 1000;\n\n/**\n * Subscribe to one support topic.\n *\n * @param topic `support:thread:<id>` for a member, `support:tenant:<id>` for an\n * admin queue. Authorization is enforced server-side by the RLS\n * policy on realtime.messages — naming a topic you don't own\n * fails the subscribe rather than leaking anything.\n * @returns null when realtime is unavailable for any reason; callers must keep\n * polling regardless and treat this as an optimisation that didn't\n * apply.\n */\nexport async function subscribeToSupportTopic(\n topic: string,\n onPing: (ping: SupportPing) => void,\n): Promise<SupportRealtimeSubscription | null> {\n if (typeof window === 'undefined') return null;\n\n try {\n const config = await supportApi.getRealtimeToken();\n if (!config?.token || !config.url || !config.anonKey) return null;\n\n // Dynamic + variable-free so bundlers keep it in its own chunk. Throws when\n // the host site hasn't installed the optional peer — caught below.\n const { createClient } = await import('@supabase/supabase-js');\n const client = createClient(config.url, config.anonKey);\n await client.realtime.setAuth(config.token);\n\n // supabase-js types `.on()` through a chain of literal-typed overloads that\n // don't narrow cleanly for broadcast here. Narrow to the two methods we\n // actually use instead of fighting them — this also pins exactly what we\n // depend on from an optional peer whose types we don't control.\n interface BroadcastChannel {\n on(\n type: 'broadcast',\n filter: { event: string },\n callback: (message: { payload?: SupportPing }) => void,\n ): BroadcastChannel;\n subscribe(callback: (status: string) => void): unknown;\n }\n\n const channel = client.channel(topic, {\n config: { private: true },\n }) as unknown as BroadcastChannel;\n\n channel.on('broadcast', { event: 'thread_updated' }, (message) => {\n if (message?.payload?.threadId) onPing(message.payload);\n });\n\n const subscribed = await new Promise<boolean>((resolve) => {\n // Don't hang forever if the socket never settles.\n const timer = setTimeout(() => resolve(false), 10_000);\n channel.subscribe((status: string) => {\n if (status === 'SUBSCRIBED') {\n clearTimeout(timer);\n resolve(true);\n } else if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT' || status === 'CLOSED') {\n clearTimeout(timer);\n resolve(false);\n }\n });\n });\n\n if (!subscribed) {\n await client.removeAllChannels().catch(() => {});\n client.realtime.disconnect();\n return null;\n }\n\n // The token outlives neither the session nor the subscription, so refresh it\n // in place; setAuth re-authorizes the open socket without resubscribing.\n const refreshTimer = setInterval(() => {\n void (async () => {\n try {\n const next = await supportApi.getRealtimeToken();\n if (next?.token) await client.realtime.setAuth(next.token);\n } catch {\n // Let the socket ride until it drops; polling still covers us.\n }\n })();\n }, TOKEN_REFRESH_MS);\n\n return {\n unsubscribe: async () => {\n clearInterval(refreshTimer);\n try {\n await client.removeAllChannels();\n } catch {\n /* ignore */\n }\n client.realtime.disconnect();\n },\n };\n } catch {\n // 503 (not configured), missing optional peer, network failure — all mean\n // the same thing to the caller: stay on polling.\n return null;\n }\n}\n","import { createSignal, onMount, onCleanup, type Accessor } from 'solid-js';\nimport { subscribeToSupportTopic, type SupportRealtimeSubscription } from './supportRealtime';\nimport {\n messagesApi,\n supportApi,\n newIdempotencyKey,\n type ApiResponse,\n type SupportMessage,\n type SupportThread,\n} from '../api/client';\n\n// ── Types ───────────────────────────────────────────────────────────\n\n/**\n * Which backend a conversation belongs to.\n *\n * `clinical` is Apex's patient <-> prescriber messaging, proxied by the backend.\n * `support` is the backend's own customer <-> support threads. The member sees\n * one merged inbox; everything below routes each operation to the right API\n * based on this discriminator, so the two never cross.\n */\nexport type ConversationSource = 'clinical' | 'support';\n\n/** Normalised conversation. The backend passes Apex's record through verbatim\n * (the-backend routes/messages.ts → apexMessaging.Conversation), which names\n * three of these fields differently; `normalizeConversation` reconciles them so\n * consumers only ever see this shape. Support threads are mapped onto the same\n * shape by `normalizeSupportThread`. */\nexport interface Conversation {\n id: string;\n source: ConversationSource;\n participantName?: string;\n participantRole?: string;\n lastMessage?: string;\n lastMessageAt?: string;\n unreadCount?: number;\n /** Support threads only — open | pending | closed. */\n status?: string;\n [key: string]: unknown;\n}\n\n/** Map the wire record onto the Conversation shape. Apex sends `prescriberName`,\n * `lastMessagePreview` and `unreadByMember`; prefer the canonical names when\n * present so this keeps working if the backend ever aligns. */\nfunction normalizeConversation(raw: Conversation): Conversation {\n return {\n ...raw,\n source: 'clinical',\n participantName: raw.participantName ?? (raw.prescriberName as string | undefined),\n lastMessage: raw.lastMessage ?? (raw.lastMessagePreview as string | undefined),\n unreadCount: raw.unreadCount ?? (raw.unreadByMember as number | undefined),\n };\n}\n\n/**\n * Map a support thread onto the shared Conversation shape.\n *\n * The counterparty is the support team rather than a named person, so the\n * subject carries the identifying detail — it lands in the preview line (where\n * a clinical conversation shows its last message) and in the thread header's\n * secondary line. Support has no per-message unread count, only a\n * \"there is an unread reply\" flag, so it contributes at most 1 to the badge.\n */\nfunction normalizeSupportThread(raw: SupportThread): Conversation {\n return {\n ...raw,\n source: 'support',\n participantName: 'Support',\n participantRole: raw.subject,\n lastMessage: raw.subject,\n lastMessageAt: raw.lastMessageAt,\n unreadCount: raw.customerUnread ? 1 : 0,\n status: raw.status,\n };\n}\n\n/** Map a support message onto the shared ThreadMessage shape. */\nfunction normalizeSupportMessage(raw: SupportMessage): ThreadMessage {\n const own = raw.sender === 'customer';\n return {\n ...raw,\n id: raw.id,\n senderId: own ? 'me' : 'support',\n // The bubble decides ownership from `senderRole === 'patient'`; reusing that\n // value keeps one rendering rule for both sources.\n senderRole: own ? 'patient' : 'support',\n senderName: own ? 'You' : 'Support',\n type: 'text',\n text: raw.body,\n createdAt: raw.createdAt,\n attachments: (raw.attachments ?? []).map((a) => ({\n id: a.id,\n filename: a.filename,\n mimeType: a.mimeType,\n sizeBytes: a.sizeBytes,\n // No url: support's bucket is private, so these are resolved on demand.\n })),\n };\n}\n\n/** Newest activity first, across both sources. Undated threads sort last. */\nfunction byMostRecent(a: Conversation, b: Conversation): number {\n const ta = a.lastMessageAt ? new Date(a.lastMessageAt).getTime() : 0;\n const tb = b.lastMessageAt ? new Date(b.lastMessageAt).getTime() : 0;\n return tb - ta;\n}\n\n/**\n * One attachment on a message, normalised across sources.\n *\n * `url` present means the source handed us a directly-usable link (Apex's\n * clinical messages do this). Absent means it must be exchanged for a\n * short-lived signed URL by id — how support attachments work, since their\n * bucket is private.\n */\nexport interface ThreadAttachment {\n id: string;\n filename: string;\n mimeType: string;\n sizeBytes: number;\n url?: string;\n}\n\nexport function isImageAttachment(a: ThreadAttachment): boolean {\n return a.mimeType.startsWith('image/');\n}\n\nexport interface ThreadMessage {\n id: string;\n senderId: string;\n senderRole: string;\n senderName?: string;\n type: 'text' | 'system' | 'html';\n text: string;\n content?: string;\n createdAt: string;\n /** Empty for sources that don't carry attachments. */\n attachments?: ThreadAttachment[];\n [key: string]: unknown;\n}\n\nconst DEFAULT_CONVERSATION_POLL_MS = 30_000;\nconst DEFAULT_MESSAGE_POLL_MS = 10_000;\n\n// ── Public helpers ──────────────────────────────────────────────────\n\nexport function formatConversationTime(iso: string | undefined): string {\n if (!iso) return '';\n const d = new Date(iso);\n const now = new Date();\n const diffMs = now.getTime() - d.getTime();\n const diffDays = Math.floor(diffMs / 86400000);\n\n if (diffDays === 0) {\n return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });\n }\n if (diffDays === 1) return 'Yesterday';\n if (diffDays < 7) {\n return d.toLocaleDateString('en-US', { weekday: 'short' });\n }\n return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });\n}\n\nexport function formatMessageTime(iso: string): string {\n const d = new Date(iso);\n return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport interface UseMessagesThreadOptions {\n /** Override poll intervals. Defaults: conversations 30s, messages 10s. */\n pollIntervalMs?: {\n conversations?: number;\n messages?: number;\n };\n /** When set to false, the hook does not auto-poll. Useful for tests or when the consumer wants to drive refresh manually. Default true. */\n autoPoll?: boolean;\n}\n\n/**\n * Outcome of opening a support thread. Two flags rather than a boolean because\n * \"the thread exists but the file didn't attach\" is a real, recoverable state\n * the UI must not report as outright failure — retrying the whole thing would\n * open a second thread.\n */\nexport interface StartThreadResult {\n created: boolean;\n attachmentFailed: boolean;\n}\n\nexport interface MessagesThread {\n // Conversation list state\n conversations: Accessor<Conversation[]>;\n loadingConversations: Accessor<boolean>;\n\n // Active thread state\n selectedId: Accessor<string | null>;\n messages: Accessor<ThreadMessage[]>;\n loadingMessages: Accessor<boolean>;\n\n // Compose state\n draft: Accessor<string>;\n setDraft: (v: string) => void;\n sending: Accessor<boolean>;\n /** True while a new support thread is being opened. */\n startingThread: Accessor<boolean>;\n /** Source of the open conversation, or null when none is selected. */\n selectedSource: Accessor<ConversationSource | null>;\n\n // Actions\n /** Select a conversation. Loads messages, marks as read, starts the message-poll loop. */\n selectConversation: (id: string) => Promise<void>;\n /** Clear the active selection (useful for \"back to list\" on mobile). */\n clearSelection: () => void;\n /** Send the current draft as a message. Optimistically appends; rolls back if the request fails. */\n send: () => Promise<void>;\n /** Manually refetch the conversation list. */\n refreshConversations: () => Promise<void>;\n /** Open a new support thread with a subject and first message, then select it.\n * Support-only — clinical conversations are started by the prescriber, never\n * the member. An optional file is uploaded as a follow-up request; see\n * StartThreadResult for the partial-success case. */\n startSupportThread: (subject: string, body: string, file?: File) => Promise<StartThreadResult>;\n /** Send a file to the open support thread, with optional accompanying text. */\n sendAttachment: (file: File, text?: string) => Promise<boolean>;\n /** Exchange an attachment id for a short-lived viewable URL, or null.\n * Pass force to bypass the cache after an expired-URL load failure. */\n resolveAttachmentUrl: (attachmentId: string, force?: boolean) => Promise<string | null>;\n}\n\n/**\n * Read a deep-linked conversation id from the URL (`?c=<id>`), as produced by a\n * `/messages/:conversationId` redirect or a shared link.\n *\n * This lived in truemeds' hand-rolled panel before messaging moved into the\n * portal. Porting it here rather than dropping it keeps those links working —\n * they are the target of \"you have a new message\" emails, so losing them would\n * silently strand patients on the wrong thread.\n */\nfunction readDeepLinkedConversationId(): string | null {\n if (typeof window === 'undefined') return null;\n try {\n return new URLSearchParams(window.location.search).get('c');\n } catch {\n return null;\n }\n}\n\n/**\n * Keep the URL in sync with the open conversation so it survives a reload and\n * stays shareable, without ever leaving the portal shell.\n *\n * Deliberately built from `window.location.pathname` rather than a hard-coded\n * route: the portal is mounted at `/members` on truemeds and `/dashboard` on\n * nextage, and the SDK must not assume either. The `#messages` hash is preserved\n * because MemberPortal resolves its initial tab from it.\n */\nfunction syncConversationUrl(conversationId: string | null): void {\n if (typeof window === 'undefined') return;\n try {\n const { pathname, hash } = window.location;\n const query = conversationId ? `?c=${encodeURIComponent(conversationId)}` : '';\n window.history.replaceState(null, '', `${pathname}${query}${hash || '#messages'}`);\n } catch {\n /* history is unavailable (sandboxed iframe, exotic browser) — non-fatal */\n }\n}\n\n/**\n * Conversation list + active-thread state with polling. Tier 2 hook —\n * sites compose their own split-pane / mobile UI on top.\n */\nexport function useMessagesThread(options: UseMessagesThreadOptions = {}): MessagesThread {\n const conversationPollMs =\n options.pollIntervalMs?.conversations ?? DEFAULT_CONVERSATION_POLL_MS;\n const messagePollMs = options.pollIntervalMs?.messages ?? DEFAULT_MESSAGE_POLL_MS;\n const autoPoll = options.autoPoll !== false;\n\n const [conversations, setConversations] = createSignal<Conversation[]>([]);\n const [selectedId, setSelectedId] = createSignal<string | null>(null);\n const [messages, setMessages] = createSignal<ThreadMessage[]>([]);\n const [draft, setDraft] = createSignal('');\n const [loadingConversations, setLoadingConversations] = createSignal(true);\n const [loadingMessages, setLoadingMessages] = createSignal(false);\n const [sending, setSending] = createSignal(false);\n const [startingThread, setStartingThread] = createSignal(false);\n\n // Captured at init, consumed once by the first successful conversation fetch.\n let pendingDeepLinkId: string | null = readDeepLinkedConversationId();\n\n let convoPollTimer: ReturnType<typeof setInterval> | undefined;\n let msgPollTimer: ReturnType<typeof setInterval> | undefined;\n\n // Live subscription for the open SUPPORT thread, when realtime is available.\n // Purely an accelerator — the message poll above keeps running either way, so\n // a dropped socket degrades to the same behaviour clinical threads already\n // have rather than stalling the thread.\n let realtimeSub: SupportRealtimeSubscription | null = null;\n // Guards against a slow subscribe resolving after the user left the thread.\n let realtimeSeq = 0;\n\n async function stopRealtime() {\n realtimeSeq++;\n const sub = realtimeSub;\n realtimeSub = null;\n if (sub) await sub.unsubscribe();\n }\n\n function startRealtime(threadId: string) {\n const seq = ++realtimeSeq;\n void (async () => {\n const sub = await subscribeToSupportTopic(`support:thread:${threadId}`, (ping) => {\n // Ping carries no content: refetch the transcript, and the list so the\n // row's preview and ordering follow.\n if (selectedId() === ping.threadId) void fetchMessages(ping.threadId);\n void fetchConversations();\n });\n // A newer selection (or a teardown) happened while we were connecting.\n if (!sub) return;\n if (seq !== realtimeSeq) {\n await sub.unsubscribe();\n return;\n }\n realtimeSub = sub;\n })();\n }\n\n // Idempotency key for the in-flight send. Reused only for a resend of the\n // exact same text IN THE SAME CONVERSATION (a retry after a lost response) so\n // the backend dedupes a message that may have committed; any edit to the text\n // — or a switch to a different conversation — starts a fresh op. Scoping on\n // convoId matters because the same draft text can be sent to two different\n // recipients: without it, B's send would reuse A's retained key and, under a\n // globally-scoped backend, dedupe to A's message and never post.\n let pendingSend: { convoId: string; text: string; key: string } | null = null;\n\n // Same retain-on-failure rule as pendingSend, for thread creation.\n let pendingThreadStart: { subject: string; body: string; key: string } | null = null;\n\n // ── Fetchers ─────────────────────────────────────────────────────\n\n /**\n * Fetch the clinical conversations. Returns null when the request fails, so\n * the caller can tell \"no data\" apart from \"an empty list\" and leave the\n * existing rows alone rather than blanking the inbox on a blip.\n */\n async function fetchClinical(): Promise<Conversation[] | null> {\n try {\n const res = (await messagesApi.listConversations()) as {\n conversations?: Conversation[];\n } & ApiResponse<{ conversations: Conversation[] }>;\n const convos = res.conversations || res.data?.conversations;\n return convos ? convos.map(normalizeConversation) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetch support threads. Also returns null on failure — and a deployment whose\n * backend predates /support answers 404, which lands here and simply means the\n * inbox shows clinical conversations only.\n */\n async function fetchSupport(): Promise<Conversation[] | null> {\n try {\n const res = (await supportApi.listThreads()) as {\n threads?: SupportThread[];\n } & ApiResponse<{ threads: SupportThread[] }>;\n const threads = res.threads || res.data?.threads;\n return threads ? threads.map(normalizeSupportThread) : null;\n } catch {\n return null;\n }\n }\n\n async function fetchConversations(showLoading = false) {\n if (showLoading) setLoadingConversations(true);\n try {\n // Both sources in parallel; one failing must not hide the other.\n const [clinical, support] = await Promise.all([fetchClinical(), fetchSupport()]);\n\n if (clinical || support) {\n // Keep whichever side failed at its previous contents rather than\n // dropping those rows out of the merged list.\n const keepPrevious = (src: ConversationSource) =>\n conversations().filter((c) => c.source === src);\n const convos = [\n ...(clinical ?? keepPrevious('clinical')),\n ...(support ?? keepPrevious('support')),\n ].sort(byMostRecent);\n\n setConversations(convos);\n // Honour a `?c=` deep link once, against the first list we successfully\n // load. Deferred to here rather than onMount because the id can't be\n // validated until the conversations are known — selecting an id the\n // member doesn't own would fetch an empty thread and read as data loss.\n // One-shot either way, so a stale link can't re-fire on every poll tick.\n if (pendingDeepLinkId) {\n const target = pendingDeepLinkId;\n pendingDeepLinkId = null;\n if (conversations().some((c) => c.id === target)) {\n void selectConversation(target);\n } else {\n syncConversationUrl(null); // stale or foreign id — drop the param\n }\n }\n }\n } catch {\n // silent — polling will retry\n } finally {\n if (showLoading) setLoadingConversations(false);\n }\n }\n\n /**\n * Which API owns a conversation id.\n *\n * Read from the loaded list rather than encoded into the id, so deep links\n * (`?c=<id>`) keep working unchanged for clinical conversations. Ids are\n * opaque and never compared across sources, and the deep-link path already\n * refuses to select an id absent from the list — so an unknown id defaulting\n * to 'clinical' here can only be an id the member does not own, which the\n * backend rejects anyway.\n */\n function sourceOf(id: string): ConversationSource {\n return conversations().find((c) => c.id === id)?.source ?? 'clinical';\n }\n\n // Monotonic fetch token: every fetchMessages claims the next number, and only\n // the LATEST claim may write. A slow response for an earlier fetch (or a\n // stale poll tick) can never clobber fresher data.\n let fetchSeq = 0;\n\n async function fetchMessages(convoId: string, showLoading = false) {\n const seq = ++fetchSeq;\n if (showLoading) setLoadingMessages(true);\n try {\n let msgs: ThreadMessage[] | undefined;\n\n if (sourceOf(convoId) === 'support') {\n // Support returns the thread and its transcript together.\n const res = (await supportApi.getThread(convoId)) as {\n messages?: SupportMessage[];\n } & ApiResponse<{ messages: SupportMessage[] }>;\n const raw = res.messages || res.data?.messages;\n msgs = raw?.map(normalizeSupportMessage);\n } else {\n const res = (await messagesApi.listMessages(convoId)) as {\n messages?: ThreadMessage[];\n } & ApiResponse<{ messages: ThreadMessage[] }>;\n msgs = res.messages || res.data?.messages;\n }\n // Write-gates, in order of what they defend against:\n // · selectedId — the user switched threads while this was in flight; a\n // stale conversation's messages must never render under the new header.\n // · seq — an older response racing a newer fetch of the same thread.\n // · sending — mid-send, the server hasn't indexed the optimistic message\n // yet; a poll write here would wipe the temp bubble and make the\n // send's reconcile find nothing (the confirmed message would vanish\n // until the next poll). The next tick after the send catches up.\n if (msgs && selectedId() === convoId && seq === fetchSeq && !sending()) {\n setMessages(msgs);\n }\n } catch {\n // silent\n } finally {\n if (showLoading) setLoadingMessages(false);\n }\n }\n\n // ── Selection + polling ──────────────────────────────────────────\n\n // Selection token: only the latest selectConversation call may install the\n // message poll after its await — an earlier call resuming late must not\n // resurrect a poll for a thread the user already left.\n let selectSeq = 0;\n\n async function selectConversation(id: string) {\n const seq = ++selectSeq;\n // Kill the previous thread's poll BEFORE any await: an interval firing\n // during the load below would race its stale thread into the new one.\n if (msgPollTimer) {\n clearInterval(msgPollTimer);\n msgPollTimer = undefined;\n }\n void stopRealtime();\n setSelectedId(id);\n setMessages([]);\n syncConversationUrl(id);\n await fetchMessages(id, true);\n const markRead =\n sourceOf(id) === 'support' ? supportApi.markAsRead(id) : messagesApi.markAsRead(id);\n Promise.resolve(markRead)\n .then(() => {\n // Clear the row's pip immediately rather than waiting for the next poll.\n setConversations((prev) =>\n prev.map((c) => (c.id === id ? { ...c, unreadCount: 0 } : c)),\n );\n })\n .catch(() => {\n // ignore\n });\n\n if (seq !== selectSeq) return; // a newer selection owns the poll now\n if (autoPoll) {\n msgPollTimer = setInterval(() => {\n if (typeof document !== 'undefined' && !document.hidden) fetchMessages(id);\n }, messagePollMs);\n // Support threads additionally get a live channel. Clinical messaging is\n // proxied from Apex and has nothing to subscribe to.\n if (sourceOf(id) === 'support') startRealtime(id);\n }\n }\n\n function clearSelection() {\n selectSeq++; // invalidate any in-flight selection's poll install\n setSelectedId(null);\n setMessages([]);\n syncConversationUrl(null);\n if (msgPollTimer) clearInterval(msgPollTimer);\n msgPollTimer = undefined;\n void stopRealtime();\n }\n\n // ── Send ─────────────────────────────────────────────────────────\n\n async function send() {\n const text = draft().trim();\n const convoId = selectedId();\n if (!text || !convoId) return;\n\n // Re-entrancy guard: don't let a double-click fire two sends of the same draft.\n if (sending()) return;\n\n // Reuse the key only when resending the identical text to the SAME\n // conversation after a failure; a changed draft or a different conversation\n // is a new message and gets a fresh key.\n if (!pendingSend || pendingSend.text !== text || pendingSend.convoId !== convoId) {\n pendingSend = { convoId, text, key: newIdempotencyKey() };\n }\n const idempotencyKey = pendingSend.key;\n\n setSending(true);\n setDraft('');\n\n const optimistic: ThreadMessage = {\n id: `temp-${Date.now()}`,\n senderId: 'me',\n senderRole: 'patient',\n senderName: 'You',\n type: 'text',\n text,\n createdAt: new Date().toISOString(),\n };\n setMessages((prev) => [...prev, optimistic]);\n\n try {\n let msg: ThreadMessage | undefined;\n\n if (sourceOf(convoId) === 'support') {\n // Support's field is `body`, not `text`.\n const res = (await supportApi.sendMessage(convoId, { body: text }, { idempotencyKey })) as {\n message?: SupportMessage;\n } & ApiResponse<{ message: SupportMessage }>;\n const raw = res.message || res.data?.message;\n msg = raw ? normalizeSupportMessage(raw) : undefined;\n } else {\n const res = (await messagesApi.sendMessage(convoId, { text }, { idempotencyKey })) as {\n message?: ThreadMessage;\n } & ApiResponse<{ message: ThreadMessage }>;\n msg = res.message || res.data?.message;\n }\n\n if (msg) {\n setMessages((prev) => prev.map((m) => (m.id === optimistic.id ? msg : m)));\n }\n pendingSend = null; // consumed — next message gets a fresh key\n } catch {\n // Roll the optimistic bubble back and restore the draft. Keep pendingSend\n // so an immediate resend of the same text reuses the key and the backend\n // dedupes a send that may actually have committed.\n setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));\n setDraft(text);\n } finally {\n setSending(false);\n }\n }\n\n // ── Attachments ──────────────────────────────────────────────────\n\n // Signed URLs live 5 minutes server-side. Cache them for less than that so a\n // thread left open doesn't hand out a link that expires mid-render, and so\n // re-rendering an image bubble doesn't re-request on every tick.\n const SIGNED_URL_CACHE_MS = 4 * 60 * 1000;\n const signedUrls = new Map<string, { url: string; fetchedAt: number }>();\n\n /**\n * Resolve an attachment to a viewable URL.\n *\n * `force` bypasses the cache — used when an <img> fails to load, which in\n * practice means the URL expired while the thread sat open.\n */\n async function resolveAttachmentUrl(\n attachmentId: string,\n force = false,\n ): Promise<string | null> {\n const hit = signedUrls.get(attachmentId);\n if (!force && hit && Date.now() - hit.fetchedAt < SIGNED_URL_CACHE_MS) {\n return hit.url;\n }\n try {\n const res = (await supportApi.getAttachmentUrl(attachmentId)) as {\n url?: string;\n } & ApiResponse<{ url: string }>;\n const url = res.url || res.data?.url;\n if (!url) return null;\n signedUrls.set(attachmentId, { url, fetchedAt: Date.now() });\n return url;\n } catch {\n return null;\n }\n }\n\n /**\n * Send a file to the open thread, with optional accompanying text.\n *\n * Note the upload endpoint is NOT idempotent (multipart can't be hashed the\n * way the JSON routes are), so the `sending` re-entrancy guard is the only\n * thing standing between a double-click and a duplicate attachment.\n */\n async function sendAttachment(file: File, text?: string): Promise<boolean> {\n const threadId = selectedId();\n if (!threadId || sending()) return false;\n if (sourceOf(threadId) !== 'support') return false;\n\n setSending(true);\n try {\n await supportApi.uploadAttachment(threadId, file, text?.trim() || undefined);\n setDraft('');\n // No optimistic bubble: we have no local URL for the stored object, so an\n // optimistic render would show a broken image. Refetch instead.\n await fetchMessages(threadId);\n await fetchConversations();\n return true;\n } catch {\n return false;\n } finally {\n setSending(false);\n }\n }\n\n // ── Start a support thread ───────────────────────────────────────\n\n /**\n * Open a new support thread and select it.\n *\n * Unlike a clinical conversation — which only ever exists because a\n * prescriber started it — the member creates these, and the backend requires\n * a subject. Carries its own idempotency key so a double-submit or a retry\n * after a lost response can't open two threads for one question.\n */\n async function startSupportThread(\n subject: string,\n body: string,\n file?: File,\n ): Promise<StartThreadResult> {\n const trimmedSubject = subject.trim();\n const trimmedBody = body.trim();\n if (!trimmedSubject || !trimmedBody || startingThread()) {\n return { created: false, attachmentFailed: false };\n }\n\n if (!pendingThreadStart || pendingThreadStart.subject !== trimmedSubject || pendingThreadStart.body !== trimmedBody) {\n pendingThreadStart = { subject: trimmedSubject, body: trimmedBody, key: newIdempotencyKey() };\n }\n\n setStartingThread(true);\n try {\n const res = (await supportApi.createThread(\n { subject: trimmedSubject, body: trimmedBody },\n { idempotencyKey: pendingThreadStart.key },\n )) as { thread?: SupportThread } & ApiResponse<{ thread: SupportThread }>;\n const thread = res.thread || res.data?.thread;\n pendingThreadStart = null;\n\n // The create endpoint is JSON-only, so a file is a SECOND request against\n // the thread we just made. That can fail on its own, and the caller has to\n // be able to say \"your message went, the file didn't\" rather than claim\n // the whole thing failed and invite a duplicate thread.\n let attachmentFailed = false;\n if (file && thread) {\n try {\n await supportApi.uploadAttachment(thread.id, file);\n } catch {\n attachmentFailed = true;\n }\n }\n\n // Refresh first so the new row exists before selection — selectConversation\n // resolves its source from the loaded list.\n await fetchConversations();\n if (thread) await selectConversation(thread.id);\n return { created: true, attachmentFailed };\n } catch {\n // Keep pendingThreadStart so an immediate retry reuses the key.\n return { created: false, attachmentFailed: false };\n } finally {\n setStartingThread(false);\n }\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────\n\n onMount(() => {\n fetchConversations(true);\n if (autoPoll) {\n convoPollTimer = setInterval(() => {\n if (typeof document !== 'undefined' && !document.hidden) fetchConversations();\n }, conversationPollMs);\n }\n });\n\n onCleanup(() => {\n if (convoPollTimer) clearInterval(convoPollTimer);\n if (msgPollTimer) clearInterval(msgPollTimer);\n void stopRealtime();\n });\n\n return {\n conversations,\n loadingConversations,\n selectedId,\n messages,\n loadingMessages,\n draft,\n setDraft,\n sending,\n startingThread,\n selectedSource: () => {\n const id = selectedId();\n return id ? sourceOf(id) : null;\n },\n selectConversation,\n clearSelection,\n send,\n refreshConversations: () => fetchConversations(false),\n startSupportThread,\n sendAttachment,\n resolveAttachmentUrl,\n };\n}\n","import { createResource, type Resource, type ResourceFetcherInfo } from 'solid-js';\nimport {\n affiliatePortalApi,\n type AffiliateConversion,\n type AffiliateDashboardLinks,\n type AffiliateDashboardStats,\n type AffiliateDownlineMember,\n} from '../api/client';\nimport affiliateAuthStore from '../stores/affiliateAuth';\n\nexport interface AffiliateStatsFlow {\n stats: Resource<AffiliateDashboardStats | null>;\n refetch: () => void;\n}\n\nexport interface AffiliateConversionsFlow {\n conversions: Resource<AffiliateConversion[]>;\n refetch: () => void;\n}\n\nexport interface AffiliateLinksFlow {\n links: Resource<AffiliateDashboardLinks | null>;\n refetch: () => void;\n}\n\nexport interface AffiliateDownlineFlow {\n downline: Resource<AffiliateDownlineMember[]>;\n refetch: () => void;\n}\n\n/**\n * Wraps GET /affiliates/dashboard/stats as a resource. Gated on the\n * affiliate auth store so the fetcher only fires when the affiliate is\n * authenticated; otherwise the resource resolves to `null`.\n */\nexport function useAffiliateStats(): AffiliateStatsFlow {\n const [stats, { refetch }] = createResource(\n () => affiliateAuthStore.isAuthenticated(),\n async (authed: boolean): Promise<AffiliateDashboardStats | null> => {\n if (!authed) return null;\n try {\n const res = await affiliatePortalApi.getStats();\n return res.stats;\n } catch {\n // Pending affiliates get 403 from this endpoint — surface null.\n return null;\n }\n },\n );\n return { stats, refetch: () => refetch() };\n}\n\nexport function useAffiliateConversions(opts?: { limit?: number }): AffiliateConversionsFlow {\n const [conversions, { refetch }] = createResource<AffiliateConversion[], boolean>(\n () => affiliateAuthStore.isAuthenticated(),\n async (\n authed: boolean,\n _info: ResourceFetcherInfo<AffiliateConversion[]>,\n ): Promise<AffiliateConversion[]> => {\n if (!authed) return [];\n try {\n const res = await affiliatePortalApi.listConversions(opts);\n return res.conversions;\n } catch {\n return [];\n }\n },\n );\n return { conversions, refetch: () => refetch() };\n}\n\nexport function useAffiliateDownline(): AffiliateDownlineFlow {\n const [downline, { refetch }] = createResource<AffiliateDownlineMember[], boolean>(\n () => affiliateAuthStore.isAuthenticated(),\n async (authed: boolean): Promise<AffiliateDownlineMember[]> => {\n if (!authed) return [];\n try {\n const res = await affiliatePortalApi.getDownline();\n return res.downline;\n } catch {\n // Pending affiliates get 403 from this endpoint — surface empty.\n return [];\n }\n },\n );\n return { downline, refetch: () => refetch() };\n}\n\nexport function useAffiliateLinks(): AffiliateLinksFlow {\n const [links, { refetch }] = createResource(\n () => affiliateAuthStore.isAuthenticated(),\n async (authed: boolean): Promise<AffiliateDashboardLinks | null> => {\n if (!authed) return null;\n try {\n return await affiliatePortalApi.getLinks();\n } catch {\n return null;\n }\n },\n );\n return { links, refetch: () => refetch() };\n}\n","import type { EmbedEvent } from '@apextelemed/survey-solid';\nimport type { Draft, DraftStore } from '@apextelemed/survey-core';\nimport { getConfig } from '../config';\nimport {\n fetchFunnelConfig,\n postFunnelEvent,\n saveFunnelDraft,\n fetchResumedDraft,\n readResumeToken,\n stripResumeToken,\n adoptFunnelSessionId,\n type ResumedDraft,\n} from '../api/funnel';\n\n// ── Funnel telemetry flow ───────────────────────────────────────────────────\n//\n// Bridges the survey engine's lifecycle events to the-backend's funnel sink.\n// Composed into `useSurveyV2Flow` so every consumer site reports drop-off data\n// with zero wiring — gated per tenant by features.funnelTelemetry, resolved\n// asynchronously from /config/funnel.\n\n/** Engine events worth a session update. qualification:checked is deliberately\n * excluded (fires on every Next; step:completed already carries position). */\nconst FORWARDED = new Set<EmbedEvent['type']>([\n 'survey:loaded',\n 'step:shown',\n 'step:completed',\n 'abandoned',\n 'submit:succeeded',\n]);\n\nexport interface FunnelTelemetry {\n /** Forward an engine event (no-op until config resolves; drops if disabled). */\n onEvent: (e: EmbedEvent) => void;\n}\n\n/**\n * Create a telemetry forwarder. Events arriving before the tenant's funnel\n * config resolves are buffered (bounded) and flushed once it does; if the\n * tenant never enabled telemetry the buffer is discarded.\n */\nexport function createFunnelTelemetry(): FunnelTelemetry {\n let enabled: boolean | null = null;\n let buffer: EmbedEvent[] = [];\n\n void fetchFunnelConfig().then((cfg) => {\n enabled = cfg.telemetry;\n const pending = buffer;\n buffer = [];\n if (enabled) for (const e of pending) forward(e);\n });\n\n function forward(e: EmbedEvent): void {\n postFunnelEvent(e.type, (e.data ?? undefined) as Record<string, unknown> | undefined);\n }\n\n return {\n onEvent(e: EmbedEvent): void {\n if (!FORWARDED.has(e.type)) return;\n if (enabled === null) {\n // Config still in flight — remember a handful, never unboundedly.\n if (buffer.length < 50) buffer.push(e);\n return;\n }\n if (enabled) forward(e);\n },\n };\n}\n\n/**\n * Post the pre-survey email gate's captured address into the session.\n * Rides the telemetry endpoint (email:captured), so it requires\n * features.funnelTelemetry on the backend as well as funnelEmailGate.\n */\nexport function captureFunnelEmail(email: string): void {\n postFunnelEvent('email:captured', { email });\n}\n\nconst emailGateDoneKey = () => `${getConfig().storagePrefix}-funnel-email-done`;\n\n/** True once the visitor has answered (or skipped) the email gate. */\nexport function emailGateAnswered(): boolean {\n try {\n return localStorage.getItem(emailGateDoneKey()) === '1';\n } catch {\n return true; // no storage → never gate\n }\n}\n\nexport function markEmailGateAnswered(): void {\n try {\n localStorage.setItem(emailGateDoneKey(), '1');\n } catch {\n /* ignore */\n }\n}\n\n// ── Resume-link redemption ──────────────────────────────────────────────────\n\nlet redemption: Promise<ResumedDraft | null> | null = null;\n\n/**\n * Redeem the `?resume=` token in the URL — at most once per page load, no\n * matter how many callers ask.\n *\n * Two things need the answer and they run in the wrong order: the email gate\n * decides whether to render BEFORE the survey mounts, and the draft store only\n * loads once it has. Leaving the exchange inside the draft store meant the gate\n * couldn't see it, so a patient following a recovery email on a new device was\n * asked for the address we had already emailed — and, worse, answered it under\n * a freshly minted session id, forking their row and earning a second reminder\n * chain. Both now await this, so the session is adopted before anything can be\n * posted under the wrong one.\n *\n * Resolves null instantly when there is no token, so it is safe to call\n * unconditionally.\n */\nexport function redeemResumeLink(): Promise<ResumedDraft | null> {\n if (!redemption) {\n redemption = (async () => {\n const token = readResumeToken();\n if (!token) return null;\n const resumed = await fetchResumedDraft(token);\n // Strip either way: a dead token that stays in the URL is a bearer token\n // for clinical answers with nothing left to authorize.\n stripResumeToken();\n if (!resumed) return null;\n // Keep writing to the session the email was about, not the one this\n // browser just minted, so the reminder history and the conversion land on\n // one row.\n if (resumed.sessionId) adoptFunnelSessionId(resumed.sessionId);\n // We mailed this person — their address is already on the session. Asking\n // again is pure friction, and for a tenant with the gate set to required\n // it is a wall in front of the answers they came back to finish.\n markEmailGateAnswered();\n return resumed;\n })();\n }\n return redemption;\n}\n\n/** Test seam: forget the redemption so the next call re-reads the URL. */\nexport function resetResumeRedemption(): void {\n redemption = null;\n}\n\n// ── Cross-device draft store ────────────────────────────────────────────────\n\n/**\n * A `DraftStore` that keeps survey progress in BOTH places:\n *\n * - localStorage, written synchronously, so refresh-resume stays instant and\n * survives an offline moment (unchanged from the engine's default);\n * - Apex, written debounced through the-backend, so the patient can resume on\n * a different device from the link in a recovery email.\n *\n * The answers go to the clinical system; the partner backend is told only the\n * resulting draft id. Every remote call is best-effort — a failed save costs a\n * cross-device resume, never the survey in front of the patient.\n */\nexport interface FunnelDraftStoreOptions {\n /** Local store to wrap (the engine's localStorage default). */\n local: DraftStore;\n /** Survey identity, stored with the draft so a resume re-composes the same survey. */\n drugIds?: string[];\n templateId?: string;\n mode?: string;\n /** Debounce for remote writes. Answers change on every keystroke. */\n remoteDebounceMs?: number;\n}\n\nexport function createFunnelDraftStore(opts: FunnelDraftStoreOptions): DraftStore {\n const debounceMs = opts.remoteDebounceMs ?? 2000;\n let draftId: string | undefined;\n let pending: Omit<Draft, 'savedAt'> | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let enabled: boolean | null = null;\n\n void fetchFunnelConfig().then((cfg) => {\n // Drafts ride the same per-tenant opt-in as the rest of funnel capture.\n enabled = cfg.telemetry;\n if (enabled && pending) scheduleFlush(0);\n });\n\n async function flush(): Promise<void> {\n const draft = pending;\n if (!draft || enabled !== true) return;\n pending = null;\n const saved = await saveFunnelDraft({\n draftId,\n answers: draft.answers,\n stepIndex: draft.stepIndex,\n drugIds: opts.drugIds,\n templateId: opts.templateId,\n mode: opts.mode,\n });\n if (!saved) return;\n const isNew = saved !== draftId;\n draftId = saved;\n // Tell the partner backend WHICH draft this session owns — the pointer\n // only. It never receives the answers.\n if (isNew) postFunnelEvent('draft:saved', { draftId: saved });\n }\n\n function scheduleFlush(ms: number): void {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), ms);\n }\n\n // A patient leaving mid-survey is exactly who this feature is for, so don't\n // let a pending debounce die with the page.\n if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {\n window.addEventListener('pagehide', () => void flush());\n }\n\n return {\n async load() {\n // Shared with the email gate, which may already have redeemed the link\n // before this store existed — hence the memo rather than a second read.\n const resumed = await redeemResumeLink();\n if (resumed) {\n draftId = resumed.draftId;\n const draft = { answers: resumed.answers as Draft['answers'], stepIndex: resumed.stepIndex };\n // Mirror into local storage so a refresh on THIS device now resumes\n // without needing the link again.\n opts.local.save(draft);\n return { ...draft, savedAt: Date.now() };\n }\n // No token, or it expired/consumed — fall through to this device's copy.\n return opts.local.load();\n },\n save(draft) {\n opts.local.save(draft);\n pending = draft;\n scheduleFlush(debounceMs);\n },\n clear() {\n pending = null;\n if (timer) clearTimeout(timer);\n opts.local.clear();\n // The Apex draft is left to expire: the partner backend refuses resume\n // for a session that submitted or converted, so a stale draft is\n // unreachable long before it expires.\n },\n };\n}\n","import {\n useSurveyV2Flow as usePackageSurveyV2Flow,\n type SurveyV2Flow,\n type EmbedEvent,\n} from '@apextelemed/survey-solid';\nimport { createLocalDraftStore, draftKey } from '@apextelemed/survey-core';\nimport type { PatientInfo } from '../api/apexV2';\nimport { getConfig } from '../config';\nimport cartStore from '../stores/cart';\nimport medicationStore from '../stores/medication';\nimport { createFunnelTelemetry, createFunnelDraftStore } from './funnel';\n\n// ── Public surface ──────────────────────────────────────────────────────────\n//\n// The survey engine + Solid adapter now live in `@apextelemed/survey-solid`\n// (apex-survey-helper). This module is a thin partner-core seam over that\n// package: it injects portal config (apexEmbedApiBase / keys / tenant) and\n// keeps the cart/medication-store drug-intent resolver — both partner-core\n// concerns the headless package deliberately does not own.\n\n/** Re-exported so consumers keep pattern-matching on `outcome.kind`. */\nexport type { SurveyV2Flow, SurveyV2Outcome } from '@apextelemed/survey-solid';\n\n/**\n * Options the partner-core hook accepts. Mirrors the package's option shape\n * minus the connection params (apiBaseUrl / publishableKey / tenantKey), which\n * partner-core injects from `getConfig()`.\n */\nexport interface UseSurveyV2FlowOptions {\n drugIds?: string[];\n templateId?: string;\n mode?: 'initial' | 'refill';\n token?: string;\n /**\n * Opt-in: auto-submit at the end of the questionnaire (skipping the\n * patient-info step) when a returning/known member's identity is already\n * complete. Default OFF. Pair with `knownPatientInfo`. See the engine docs.\n */\n skipPatientInfoWhenComplete?: boolean;\n /**\n * Known identity for a returning member on the `drugIds` path. Seeds the\n * engine so the skip guard can pass and the patient-info step is prefilled.\n * Resolve it BEFORE this hook runs — the engine is built once, from the\n * options passed at that time.\n */\n knownPatientInfo?: Partial<PatientInfo>;\n /**\n * Widen the fields required for the skip to fire (default: the engine's\n * firstName/lastName/email/dob/state). Add any your downstream needs (e.g. a\n * shipping address) so the skip never drops them.\n */\n requiredPatientInfoFields?: Array<keyof PatientInfo>;\n /** Override the storage TTL (default 24h). */\n draftTtlMs?: number;\n /** Lifecycle events from the engine. */\n onEvent?: (e: EmbedEvent) => void;\n /** Load/submit failures from the engine (mirrors the package hook's option). */\n onError?: (error: Error) => void;\n}\n\n// ── Drug-intent resolver ────────────────────────────────────────────────────\n\n/**\n * Resolves the survey's compose target (\"what drugs do we ask about?\") from\n * the inputs the consumer supplied, with fallbacks to module-level state for\n * cases where the wrapper didn't pass anything explicit.\n *\n * Precedence:\n * 1. token (returning-member flow, drugs come from the token's response)\n * 2. explicit drugIds (URL-driven flow)\n * 3. cart contents — items() with non-null `drugId`\n * 4. medicationStore.selected() — single drug\n * 5. nothing — caller should render a \"pick a medication\" affordance\n *\n * Exposed so callers / tests can verify the chain. SurveyV2Page uses the\n * result to decide whether to construct the engine at all.\n */\nexport interface ResolvedSurveyV2Intent {\n /** True iff we have something to compose against. */\n resolved: boolean;\n drugIds?: string[];\n token?: string;\n}\n\nexport function resolveSurveyV2DrugIntent(opts: {\n drugIds?: string[];\n token?: string;\n}): ResolvedSurveyV2Intent {\n if (opts.token) return { resolved: true, token: opts.token };\n if (opts.drugIds && opts.drugIds.length > 0) {\n return { resolved: true, drugIds: opts.drugIds };\n }\n\n const cartDrugIds = cartStore\n .items()\n .map((i) => i.drugId)\n .filter((id): id is string => !!id);\n if (cartDrugIds.length > 0) return { resolved: true, drugIds: cartDrugIds };\n\n const selectedDrugId = medicationStore.selected()?.drugId;\n if (selectedDrugId) return { resolved: true, drugIds: [selectedDrugId] };\n\n return { resolved: false };\n}\n\n// ── Hook ────────────────────────────────────────────────────────────────────\n\n/**\n * partner-core wrapper over `@apextelemed/survey-solid`'s `useSurveyV2Flow`.\n * Reads the Apex embed connection details from portal config and forwards the\n * survey scope unchanged. Throws early if the host never called `configure()`\n * with `apexEmbedApiBase`.\n */\nexport function useSurveyV2Flow(opts: UseSurveyV2FlowOptions): SurveyV2Flow {\n const cfg = getConfig();\n if (!cfg.apexEmbedApiBase) {\n throw new Error('apex-partner-core: apexEmbedApiBase is not configured.');\n }\n // apexPublishableKey is optional: omit it when proxying through a partner\n // backend that injects its own server-side credentials (e.g. the-backend's\n // /apex/v2/embed/* mount). Required for browser-direct embeds against\n // Apex's /api/v2/embed/*.\n\n // Funnel telemetry composes UNDER the caller's onEvent so every consumer\n // site reports drop-off data with zero wiring. Server-gated per tenant\n // (features.funnelTelemetry) — for tenants that never opted in, the\n // forwarder resolves to disabled and drops everything.\n const telemetry = createFunnelTelemetry();\n\n // Drafts go to Apex as well as localStorage, so a patient who abandons the\n // questionnaire can resume it from the link in a recovery email on ANY\n // device. Wraps (never replaces) the engine's local store, so refresh-resume\n // stays instant and keeps working offline; the remote half is best-effort and\n // no-ops entirely for tenants without funnel capture enabled.\n const draftStore = createFunnelDraftStore({\n local: createLocalDraftStore(\n draftKey({\n publishableKey: cfg.apexPublishableKey,\n tenantKey: cfg.tenantKey,\n token: opts.token,\n drugIds: opts.drugIds,\n templateId: opts.templateId,\n mode: opts.mode,\n }),\n { ttlMs: opts.draftTtlMs },\n ),\n drugIds: opts.drugIds,\n templateId: opts.templateId,\n mode: opts.mode,\n });\n\n return usePackageSurveyV2Flow({\n apiBaseUrl: cfg.apexEmbedApiBase,\n publishableKey: cfg.apexPublishableKey,\n tenantKey: cfg.tenantKey,\n drugIds: opts.drugIds,\n templateId: opts.templateId,\n mode: opts.mode,\n token: opts.token,\n skipPatientInfoWhenComplete: opts.skipPatientInfoWhenComplete,\n knownPatientInfo: opts.knownPatientInfo,\n requiredPatientInfoFields: opts.requiredPatientInfoFields,\n draftTtlMs: opts.draftTtlMs,\n draftStore,\n onEvent: (e) => {\n telemetry.onEvent(e);\n opts.onEvent?.(e);\n },\n onError: opts.onError,\n });\n}\n\n// Re-export the SurveyV2State type for consumer convenience. (FlatStep,\n// PatientInfo, V2*Result are already exported via `./api/apexV2`.)\nexport type { SurveyV2State } from '@apextelemed/survey-core';\n\n// ── Prescription photo upload ───────────────────────────────────────────────\n\nexport const PRESCRIPTION_PHOTO_MAX_BYTES = 10 * 1024 * 1024;\n\n/**\n * Upload one pill-bottle photo mid-survey. Bytes go out-of-band through the\n * partner backend's anonymous v2-embed relay (the-backend\n * `/apex/v2/embed/surveys/prescription-photos`) into Apex's private bucket;\n * only the returned `photoId` enters the survey answer. Never put image bytes\n * in an answer — answers are re-POSTed on every step and written to the\n * localStorage draft.\n */\nexport async function uploadPrescriptionPhoto(file: File): Promise<{ photoId: string }> {\n const cfg = getConfig();\n if (!cfg.apexEmbedApiBase) {\n throw new Error('apex-partner-core: apexEmbedApiBase is not configured.');\n }\n if (file.size > PRESCRIPTION_PHOTO_MAX_BYTES) {\n throw new Error('That photo is larger than 10MB. Please retake it at a lower resolution.');\n }\n\n const formData = new FormData();\n formData.append('photo', file);\n\n // Same auth headers as survey-core's embed client; Content-Type is left to\n // fetch so it can set the multipart boundary.\n const res = await fetch(`${cfg.apexEmbedApiBase}/surveys/prescription-photos`, {\n method: 'POST',\n headers: {\n ...(cfg.apexPublishableKey ? { 'x-apex-publishable-key': cfg.apexPublishableKey } : {}),\n ...(cfg.tenantKey ? { 'X-Tenant-Key': cfg.tenantKey } : {}),\n },\n body: formData,\n });\n\n let parsed: { photoId?: string; error?: string } | null = null;\n try {\n parsed = (await res.json()) as { photoId?: string; error?: string };\n } catch {\n /* non-JSON body */\n }\n if (!res.ok || !parsed?.photoId) {\n throw new Error(parsed?.error || `Photo upload failed (HTTP ${res.status})`);\n }\n return { photoId: parsed.photoId };\n}\n"]}