@apextelemed/partner-core 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/api/index.d.ts +14 -1
  2. package/dist/api/index.js +2 -2
  3. package/dist/api/index.jsx +8 -2
  4. package/dist/chunk/{SNAV6DII.jsx → 2EVGOW2Z.jsx} +26 -4
  5. package/dist/chunk/{KFJXIKD4.js → 5RQ4ZIYB.js} +48 -9
  6. package/dist/chunk/5RQ4ZIYB.js.map +1 -0
  7. package/dist/chunk/{FJZHH5T4.jsx → AC7FFU4J.jsx} +312 -6
  8. package/dist/chunk/ACE7M2YA.jsx +1 -0
  9. package/dist/chunk/{EIXV4DCU.js → D6GCJFQD.js} +26 -6
  10. package/dist/chunk/D6GCJFQD.js.map +1 -0
  11. package/dist/chunk/{OEXSGX5F.js → J4G52ET6.js} +665 -337
  12. package/dist/chunk/J4G52ET6.js.map +1 -0
  13. package/dist/chunk/JSHO46VZ.js +3 -0
  14. package/dist/chunk/JSHO46VZ.js.map +1 -0
  15. package/dist/chunk/{MEWFN6IW.jsx → M6DZVPYZ.jsx} +49 -8
  16. package/dist/chunk/{6TFBQECC.jsx → NP4CMOLW.jsx} +41 -1
  17. package/dist/chunk/{J6KNY37T.js → XMYPS7PT.js} +40 -3
  18. package/dist/chunk/XMYPS7PT.js.map +1 -0
  19. package/dist/flows/index.js +3 -3
  20. package/dist/flows/index.jsx +3 -3
  21. package/dist/index/index.d.ts +1 -1
  22. package/dist/index/index.js +5 -5
  23. package/dist/index/index.jsx +11 -5
  24. package/dist/pages/index.js +2 -2
  25. package/dist/pages/index.jsx +2 -2
  26. package/dist/testing/storage.d.ts +1 -1
  27. package/dist/testing/storage.d.ts.map +1 -1
  28. package/dist/testing/storage.js +1 -0
  29. package/dist/testing/storage.js.map +1 -1
  30. package/package.json +1 -1
  31. package/dist/chunk/AN3WPMEP.js +0 -3
  32. package/dist/chunk/AN3WPMEP.js.map +0 -1
  33. package/dist/chunk/EIXV4DCU.js.map +0 -1
  34. package/dist/chunk/J6KNY37T.js.map +0 -1
  35. package/dist/chunk/KFJXIKD4.js.map +0 -1
  36. package/dist/chunk/O3QK7YZR.jsx +0 -1
  37. package/dist/chunk/OEXSGX5F.js.map +0 -1
@@ -9,6 +9,7 @@ import {
9
9
  buildTrackerView,
10
10
  captureFunnelEmail,
11
11
  emailGateAnswered,
12
+ formatCalendarDate,
12
13
  formatConversationTime,
13
14
  formatEventDate,
14
15
  formatMessageTime,
@@ -19,6 +20,7 @@ import {
19
20
  redeemResumeLink,
20
21
  resolveSurveyV2DrugIntent,
21
22
  stateAvailabilityNote,
23
+ uploadPrescriptionPhoto,
22
24
  useAffiliateConversions,
23
25
  useAffiliateDownline,
24
26
  useAffiliateLinks,
@@ -34,7 +36,7 @@ import {
34
36
  useSurveyFlow,
35
37
  useSurveyV2Flow,
36
38
  useUpdatePaymentMethodFlow
37
- } from "./MEWFN6IW.jsx";
39
+ } from "./M6DZVPYZ.jsx";
38
40
  import {
39
41
  fetchFunnelConfig
40
42
  } from "./I46Y2J5W.jsx";
@@ -1633,6 +1635,305 @@ function MultiSelectQuestion(props) {
1633
1635
  </div>
1634
1636
  </Show3>;
1635
1637
  }
1638
+ var PHOTO_CHECKLIST_ITEMS = [
1639
+ { key: "drugName", label: "Drug name" },
1640
+ { key: "dosageSchedule", label: "Dosage & schedule" },
1641
+ { key: "expiration", label: "Expiration date" },
1642
+ { key: "prescriber", label: "Prescriber" },
1643
+ { key: "refillsLeft", label: "Refills left" },
1644
+ { key: "rxNumber", label: "Prescription number" },
1645
+ { key: "pharmacy", label: "Pharmacy" },
1646
+ { key: "phone", label: "Pharmacy phone" }
1647
+ ];
1648
+ function emptyChecklist() {
1649
+ return {
1650
+ drugName: false,
1651
+ dosageSchedule: false,
1652
+ expiration: false,
1653
+ prescriber: false,
1654
+ refillsLeft: false,
1655
+ rxNumber: false,
1656
+ pharmacy: false,
1657
+ phone: false
1658
+ };
1659
+ }
1660
+ function PrescriptionPhotosQuestion(props) {
1661
+ const { Button, Banner, Spinner, Textarea } = usePrimitives();
1662
+ const initial = props.value;
1663
+ const restoredPhotos = initial && "photos" in initial && Array.isArray(initial.photos) ? initial.photos.map((p) => ({
1664
+ photoId: p.photoId,
1665
+ checklist: { ...emptyChecklist(), ...p.checklist }
1666
+ })) : [];
1667
+ const [entries, setEntries] = createSignal(restoredPhotos);
1668
+ const [done, setDone] = createSignal(restoredPhotos.length > 0);
1669
+ const [none, setNone] = createSignal(!!initial && "none" in initial && initial.none === true);
1670
+ const [manual, setManual] = createSignal(
1671
+ !!initial && "manual" in initial && typeof initial.manual === "string"
1672
+ );
1673
+ const [manualText, setManualText] = createSignal(
1674
+ initial && "manual" in initial && typeof initial.manual === "string" ? initial.manual : ""
1675
+ );
1676
+ const [uploading, setUploading] = createSignal(false);
1677
+ const [error, setError] = createSignal(null);
1678
+ let fileInput;
1679
+ const allChecked = (e) => PHOTO_CHECKLIST_ITEMS.every((i) => e.checklist[i.key]);
1680
+ function emit() {
1681
+ if (none()) return props.onChange({ version: 1, none: true });
1682
+ if (manual()) {
1683
+ const text = manualText().trim();
1684
+ return props.onChange(text ? { version: 1, manual: manualText() } : void 0);
1685
+ }
1686
+ const list = entries();
1687
+ if (list.length > 0 && done() && list.every(allChecked)) {
1688
+ return props.onChange({
1689
+ version: 1,
1690
+ photos: list.map((e) => ({ photoId: e.photoId, checklist: e.checklist }))
1691
+ });
1692
+ }
1693
+ props.onChange(void 0);
1694
+ }
1695
+ async function handleFile(file) {
1696
+ if (!file) return;
1697
+ setError(null);
1698
+ setUploading(true);
1699
+ try {
1700
+ const { photoId } = await uploadPrescriptionPhoto(file);
1701
+ setEntries((prev) => [
1702
+ ...prev,
1703
+ { photoId, checklist: emptyChecklist(), objectUrl: URL.createObjectURL(file) }
1704
+ ]);
1705
+ setDone(false);
1706
+ emit();
1707
+ } catch (err) {
1708
+ setError(err instanceof Error ? err.message : "Photo upload failed. Please try again.");
1709
+ } finally {
1710
+ setUploading(false);
1711
+ if (fileInput) fileInput.value = "";
1712
+ }
1713
+ }
1714
+ function removeEntry(photoId) {
1715
+ const entry = entries().find((e) => e.photoId === photoId);
1716
+ if (entry?.objectUrl) URL.revokeObjectURL(entry.objectUrl);
1717
+ setEntries((prev) => prev.filter((e) => e.photoId !== photoId));
1718
+ emit();
1719
+ }
1720
+ function toggleCheck(photoId, key, checked) {
1721
+ setEntries(
1722
+ (prev) => prev.map(
1723
+ (e) => e.photoId === photoId ? { ...e, checklist: { ...e.checklist, [key]: checked } } : e
1724
+ )
1725
+ );
1726
+ emit();
1727
+ }
1728
+ const blockedHint = () => {
1729
+ if (none() || manual() && manualText().trim()) return null;
1730
+ const list = entries();
1731
+ if (list.length === 0 && !manual()) {
1732
+ return "Add at least one prescription photo \u2014 or choose an option below if you have none or can\u2019t upload.";
1733
+ }
1734
+ if (manual()) return "Enter your prescription information to continue.";
1735
+ if (!list.every(allChecked)) {
1736
+ return "Confirm each item is visible in every photo (retake the photo if something isn\u2019t).";
1737
+ }
1738
+ if (!done()) return 'Check "I\u2019ve added all my prescriptions" when you\u2019re finished.';
1739
+ return null;
1740
+ };
1741
+ return <div style={{ display: "flex", "flex-direction": "column", gap: "0.75rem" }}>
1742
+ <div>
1743
+ <div style={{ "font-size": "0.875rem", "font-weight": 500 }}>{props.label}</div>
1744
+ <Show3 when={props.helpText}>
1745
+ <div style={{ "font-size": "0.8125rem", opacity: 0.65, "margin-top": "0.25rem" }}>
1746
+ {props.helpText}
1747
+ </div>
1748
+ </Show3>
1749
+ </div>
1750
+
1751
+ <Show3 when={error()}>
1752
+ <Banner variant="error">{error()}</Banner>
1753
+ </Show3>
1754
+
1755
+ {
1756
+ /* Uploaded photos, each with its visibility checklist. */
1757
+ }
1758
+ <For2 each={entries()}>
1759
+ {(entry, i) => <div
1760
+ style={{
1761
+ border: "1px solid rgba(128,128,128,0.25)",
1762
+ "border-radius": "0.5rem",
1763
+ padding: "0.75rem",
1764
+ display: "flex",
1765
+ "flex-direction": "column",
1766
+ gap: "0.5rem"
1767
+ }}
1768
+ >
1769
+ <div style={{ display: "flex", gap: "0.75rem", "align-items": "flex-start" }}>
1770
+ <Show3
1771
+ when={entry.objectUrl}
1772
+ fallback={<div
1773
+ style={{
1774
+ width: "72px",
1775
+ height: "72px",
1776
+ "border-radius": "0.375rem",
1777
+ background: "rgba(128,128,128,0.12)",
1778
+ display: "flex",
1779
+ "align-items": "center",
1780
+ "justify-content": "center",
1781
+ "font-size": "0.6875rem",
1782
+ opacity: 0.7,
1783
+ "text-align": "center",
1784
+ "flex-shrink": 0
1785
+ }}
1786
+ >
1787
+ Photo uploaded
1788
+ </div>}
1789
+ >
1790
+ <img
1791
+ src={entry.objectUrl}
1792
+ alt={`Prescription photo ${i() + 1}`}
1793
+ style={{
1794
+ width: "72px",
1795
+ height: "72px",
1796
+ "object-fit": "cover",
1797
+ "border-radius": "0.375rem",
1798
+ "flex-shrink": 0
1799
+ }}
1800
+ />
1801
+ </Show3>
1802
+ <div style={{ flex: 1 }}>
1803
+ <div style={{ "font-size": "0.8125rem", "font-weight": 500, "margin-bottom": "0.25rem" }}>
1804
+ Prescription {i() + 1} — confirm these are visible:
1805
+ </div>
1806
+ <div
1807
+ style={{
1808
+ display: "grid",
1809
+ "grid-template-columns": "repeat(auto-fill, minmax(10rem, 1fr))",
1810
+ gap: "0.25rem 0.75rem"
1811
+ }}
1812
+ >
1813
+ <For2 each={PHOTO_CHECKLIST_ITEMS}>
1814
+ {(item) => <label
1815
+ style={{
1816
+ display: "flex",
1817
+ gap: "0.375rem",
1818
+ "align-items": "center",
1819
+ "font-size": "0.8125rem",
1820
+ cursor: "pointer"
1821
+ }}
1822
+ >
1823
+ <input
1824
+ type="checkbox"
1825
+ checked={entry.checklist[item.key]}
1826
+ onChange={(e) => toggleCheck(entry.photoId, item.key, e.currentTarget.checked)}
1827
+ />
1828
+ {item.label}
1829
+ </label>}
1830
+ </For2>
1831
+ </div>
1832
+ </div>
1833
+ </div>
1834
+ <div>
1835
+ <Button variant="ghost" size="sm" onClick={() => removeEntry(entry.photoId)}>
1836
+ Remove photo
1837
+ </Button>
1838
+ </div>
1839
+ </div>}
1840
+ </For2>
1841
+
1842
+ {
1843
+ /* Camera on mobile (capture), file picker on desktop. */
1844
+ }
1845
+ <input
1846
+ ref={fileInput}
1847
+ type="file"
1848
+ accept="image/*"
1849
+ capture="environment"
1850
+ hidden
1851
+ onChange={(e) => void handleFile(e.currentTarget.files?.[0] ?? void 0)}
1852
+ />
1853
+ <Show3 when={!none() && !manual()}>
1854
+ <div style={{ display: "flex", gap: "0.5rem", "align-items": "center" }}>
1855
+ <Button
1856
+ variant="secondary"
1857
+ disabled={uploading()}
1858
+ onClick={() => fileInput?.click()}
1859
+ >
1860
+ {entries().length === 0 ? "Take or upload a photo" : "Add another prescription"}
1861
+ </Button>
1862
+ <Show3 when={uploading()}>
1863
+ <Spinner size="sm" />
1864
+ </Show3>
1865
+ </div>
1866
+ </Show3>
1867
+
1868
+ <Show3 when={entries().length > 0}>
1869
+ <label
1870
+ style={{ display: "flex", gap: "0.5rem", "align-items": "center", "font-size": "0.875rem", cursor: "pointer" }}
1871
+ >
1872
+ <input
1873
+ type="checkbox"
1874
+ checked={done()}
1875
+ onChange={(e) => {
1876
+ setDone(e.currentTarget.checked);
1877
+ emit();
1878
+ }}
1879
+ />
1880
+ I&rsquo;ve added all my prescriptions
1881
+ </label>
1882
+ </Show3>
1883
+
1884
+ {
1885
+ /* The no-photo paths, mutually exclusive with photos and each other. */
1886
+ }
1887
+ <Show3 when={entries().length === 0}>
1888
+ <div style={{ display: "flex", "flex-direction": "column", gap: "0.375rem" }}>
1889
+ <label
1890
+ style={{ display: "flex", gap: "0.5rem", "align-items": "center", "font-size": "0.875rem", cursor: "pointer" }}
1891
+ >
1892
+ <input
1893
+ type="checkbox"
1894
+ checked={none()}
1895
+ onChange={(e) => {
1896
+ setNone(e.currentTarget.checked);
1897
+ if (e.currentTarget.checked) setManual(false);
1898
+ emit();
1899
+ }}
1900
+ />
1901
+ I have no current prescriptions
1902
+ </label>
1903
+ <label
1904
+ style={{ display: "flex", gap: "0.5rem", "align-items": "center", "font-size": "0.875rem", cursor: "pointer" }}
1905
+ >
1906
+ <input
1907
+ type="checkbox"
1908
+ checked={manual()}
1909
+ onChange={(e) => {
1910
+ setManual(e.currentTarget.checked);
1911
+ if (e.currentTarget.checked) setNone(false);
1912
+ emit();
1913
+ }}
1914
+ />
1915
+ I can&rsquo;t upload a photo. I will enter my prescription information manually.
1916
+ </label>
1917
+ </div>
1918
+ </Show3>
1919
+
1920
+ <Show3 when={manual() && entries().length === 0}>
1921
+ <Textarea
1922
+ value={manualText()}
1923
+ onInput={(v) => {
1924
+ setManualText(v);
1925
+ emit();
1926
+ }}
1927
+ rows={4}
1928
+ placeholder="For each prescription: drug name, dosage & schedule, prescriber, refills left, prescription number, pharmacy and phone"
1929
+ />
1930
+ </Show3>
1931
+
1932
+ <Show3 when={blockedHint()}>
1933
+ <div style={{ "font-size": "0.8125rem", opacity: 0.7 }}>{blockedHint()}</div>
1934
+ </Show3>
1935
+ </div>;
1936
+ }
1636
1937
  function QuestionField2(props) {
1637
1938
  const { TextField, Textarea, Select, RadioGroup, CheckboxGroup } = usePrimitives();
1638
1939
  const q = () => props.question;
@@ -1742,6 +2043,14 @@ function QuestionField2(props) {
1742
2043
  </div>
1743
2044
  </div>;
1744
2045
  })()}
2046
+ </Show3>
2047
+ <Show3 when={q().type === "prescription_photos"}>
2048
+ <PrescriptionPhotosQuestion
2049
+ label={lbl()}
2050
+ helpText={q().helpText}
2051
+ value={val()}
2052
+ onChange={(v) => props.onChange(v)}
2053
+ />
1745
2054
  </Show3>
1746
2055
  <Show3 when={q().type === "address"}>
1747
2056
  {(() => {
@@ -13756,10 +14065,7 @@ function pick(member, ...keys) {
13756
14065
  return "";
13757
14066
  }
13758
14067
  function formatDob(value) {
13759
- if (!value) return "";
13760
- const d = new Date(value);
13761
- if (Number.isNaN(d.getTime())) return value;
13762
- return d.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
14068
+ return formatCalendarDate(value);
13763
14069
  }
13764
14070
  function AccountPanel(props) {
13765
14071
  const m = () => props.member;
@@ -16692,4 +16998,4 @@ export {
16692
16998
  AffiliateForgotPassword,
16693
16999
  AffiliateResetPassword
16694
17000
  };
16695
- //# sourceMappingURL=FJZHH5T4.jsx.map
17001
+ //# sourceMappingURL=AC7FFU4J.jsx.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=ACE7M2YA.jsx.map
@@ -1,7 +1,7 @@
1
- import { readCartToken, fetchResumedCart, stripCartToken, adoptCartId, fetchCartConfig, postCartSnapshot, resetCartId } from './J6KNY37T.js';
2
- import { useCardTokenizer, useAddressPair, isLive, formatCvv, formatExpiry, formatCardNumber, firstAddressError, validateAddress } from './KFJXIKD4.js';
1
+ import { readPromoCode, clearPromoCode, readCartToken, fetchResumedCart, stripCartToken, adoptCartId, fetchCartConfig, postCartSnapshot, resetCartId } from './XMYPS7PT.js';
2
+ import { useCardTokenizer, useAddressPair, isLive, formatCvv, formatExpiry, formatCardNumber, firstAddressError, validateAddress } from './5RQ4ZIYB.js';
3
3
  import { cart_default, auth_default, medication_default } from './FWUBNK42.js';
4
- import { productsApi, subscriptionsApi, promoCodesApi, newIdempotencyKey, usersApi, ApiError } from './UNAI6NBV.js';
4
+ import { productsApi, promoCodesApi, subscriptionsApi, newIdempotencyKey, usersApi, ApiError } from './UNAI6NBV.js';
5
5
  import { getConfig } from './5XGPFYIJ.js';
6
6
  import { createResource, createMemo, createSignal, onMount, createEffect, createRoot, on } from 'solid-js';
7
7
 
@@ -255,6 +255,20 @@ function useSubscriptionIntakeFlow(options) {
255
255
  const [promoValidating, setPromoValidating] = createSignal(false);
256
256
  const [promoError, setPromoError] = createSignal(null);
257
257
  const [promoApplied, setPromoApplied] = createSignal(null);
258
+ onMount(async () => {
259
+ if (promoCode().trim()) return;
260
+ const stashed = readPromoCode();
261
+ if (!stashed) return;
262
+ try {
263
+ const res = await promoCodesApi.validate(stashed, {
264
+ productIds: [options.pricing.productId],
265
+ subtotalCents: savingsBaseCents()
266
+ });
267
+ if (res.valid) setPromoCode(stashed);
268
+ else clearPromoCode();
269
+ } catch {
270
+ }
271
+ });
258
272
  const [idemKey, setIdemKey] = createSignal(restored.idempotencyKey ?? "");
259
273
  onMount(() => {
260
274
  createEffect(() => {
@@ -319,7 +333,13 @@ function useSubscriptionIntakeFlow(options) {
319
333
  try {
320
334
  const res = await promoCodesApi.validate(code, {
321
335
  productIds: [options.pricing.productId],
322
- subtotalCents: options.pricing.priceCents
336
+ // The base the promo will actually be applied to. For a savings member
337
+ // that is the savings price, not list: the server discounts the
338
+ // savings-substituted subtotal at checkout, so quoting off list would
339
+ // show a percentage promo as a bigger saving than it is (10% of $399
340
+ // displayed, 10% of $280 charged). Same rule as savingsBaseCents — keep
341
+ // the two in step.
342
+ subtotalCents: savingsBaseCents()
323
343
  });
324
344
  if (!res.valid) {
325
345
  setPromoError(res.error ?? "Invalid promo code.");
@@ -682,5 +702,5 @@ function startCartCapture(opts = {}) {
682
702
  }
683
703
 
684
704
  export { DEFAULT_COLOR_PALETTE, categoryColor, lowestPrice, lowestSalePrice, restoreCartFromLink, startCartCapture, useCatalog, useMedicationSelect, useProductDetail, useSubscriptionIntakeFlow };
685
- //# sourceMappingURL=EIXV4DCU.js.map
686
- //# sourceMappingURL=EIXV4DCU.js.map
705
+ //# sourceMappingURL=D6GCJFQD.js.map
706
+ //# sourceMappingURL=D6GCJFQD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/flows/products.ts","../../src/flows/categoryVisual.ts","../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createSignal","createEffect"],"mappings":";;;;;;;AAWO,SAAS,cAAA,CAAe,SAAyB,MAAA,EAA+B;AACrF,EAAA,MAAM,OAAA,GAAA,CAAW,OAAA,CAAQ,aAAA,IAAiB,EAAC,EAA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AAI,KAAA,eAAoB,KAAK,CAAA;AAC7B,IAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,MAAA,CAAO,wBAAwB,UAAA,EAAY;AACrF,MAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AAAA,IACnD;AACA,IAAA,OAAA,EAAQ;AACR,IAAA,OAAA,GAAU,KAAA;AAAA,EACZ,CAAA;AACF","file":"D6GCJFQD.js","sourcesContent":["import { createMemo, createResource, createSignal, type Accessor, type Resource } from 'solid-js';\nimport { productsApi, type CatalogProduct } from '../api/client';\nimport cartStore from '../stores/cart';\nimport medicationStore from '../stores/medication';\n\nexport type { CatalogProduct } from '../api/client';\n\n// ── Pricing helpers (pure) ──────────────────────────────────────────\n\n/** Effective price for a single dose: the overlay price if present, else the\n * product's base price (null when neither is set — dose not purchasable). */\nexport function priceForDosage(product: CatalogProduct, dosage: string): number | null {\n const overlay = (product.dosage_prices ?? []).find((d) => d.dosage === dosage);\n if (overlay && overlay.price != null) return overlay.price;\n return product.price;\n}\n\n/** Lowest price across the product's available doses (overlay-or-base each),\n * falling back to the product-level price. Returns null for free / unpriced products. */\nexport function lowestPrice(product: CatalogProduct): number | null {\n const available = product.available_dosages ?? [];\n if (available.length === 0) return product.price;\n let min: number | null = null;\n for (const dose of available) {\n const p = priceForDosage(product, dose);\n if (p != null && (min == null || p < min)) min = p;\n }\n return min ?? product.price;\n}\n\n/**\n * Lowest sale price for a tiered product, computed by re-deriving the same\n * percent/fixed discount the backend applied at the product level. Used so\n * the strikethrough lands on the displayed (lowest-tier) value.\n *\n * Returns null when no active sale, no discount, or insufficient data.\n */\nexport function lowestSalePrice(product: CatalogProduct, basePrice: number | null): number | null {\n if (basePrice == null || !product.activeSale) return null;\n const sale = product.activeSale;\n const baseCents = Math.round(basePrice * 100);\n if (sale.discountCents <= 0) return null;\n if (\n product.salePriceCents != null &&\n product.price != null &&\n Math.abs(product.price - basePrice) < 0.001\n ) {\n return product.salePriceCents / 100;\n }\n if (product.price != null && product.salePriceCents != null && product.price > 0) {\n const ratio = product.salePriceCents / Math.round(product.price * 100);\n return Math.max(0, basePrice * ratio);\n }\n return Math.max(0, (baseCents - sale.discountCents) / 100);\n}\n\n// ── useCatalog ──────────────────────────────────────────────────────\n\nexport interface CatalogFlow {\n products: Resource<CatalogProduct[]>;\n /** Products in the \"weight-loss\" category. */\n weightLoss: Accessor<CatalogProduct[]>;\n /** Products NOT in \"weight-loss\" (peptides, recovery, etc). */\n peptides: Accessor<CatalogProduct[]>;\n /** Filter products by an arbitrary category slug. */\n filterByCategory: (slug: string) => CatalogProduct[];\n}\n\n/** Fetches the product catalog and exposes a couple of common derivations. */\nexport function useCatalog(): CatalogFlow {\n const [products] = createResource<CatalogProduct[]>(async () => {\n try {\n const res = await productsApi.list();\n return res.products;\n } catch {\n return [];\n }\n });\n\n const weightLoss = () =>\n (products() ?? []).filter((p) => (p.categories ?? []).includes('weight-loss'));\n const peptides = () =>\n (products() ?? []).filter((p) => !(p.categories ?? []).includes('weight-loss'));\n const filterByCategory = (slug: string) =>\n (products() ?? []).filter((p) => (p.categories ?? []).includes(slug));\n\n return { products, weightLoss, peptides, filterByCategory };\n}\n\n// ── useProductDetail ────────────────────────────────────────────────\n\nexport interface ProductDetailFlow {\n product: Resource<CatalogProduct | null>;\n dosageOptions: Accessor<Array<{ dosage: string; price: number; savingsPrice: number | null }>>;\n selectedDosage: Accessor<string>;\n setSelectedDosage: (v: string) => void;\n /** Effective base price for the currently-selected dosage. */\n selectedPrice: Accessor<number | null>;\n /** Sale price for the selected dosage, if a sale is active. */\n selectedSalePrice: Accessor<number | null>;\n /** 'per_dose' (default) or 'flat_fee'. When 'flat_fee', `dosageOptions` is\n * collapsed to a single entry and consumer UI should hide the dose picker. */\n pricingMode: Accessor<'per_dose' | 'flat_fee'>;\n /** True if the product+dosage combination is already in cart. */\n inCart: Accessor<boolean>;\n addToCart: () => void;\n}\n\n/**\n * Single-product page state. Loads the catalog and finds the product by id.\n * Tracks dosage selection, derives current/sale price, exposes addToCart.\n */\nexport function useProductDetail(productId: Accessor<string>): ProductDetailFlow {\n const [product] = createResource<CatalogProduct | null, string>(productId, async (id) => {\n if (!id) return null;\n try {\n const res = await productsApi.list();\n return res.products.find((p) => p.id === id) ?? null;\n } catch {\n return null;\n }\n });\n\n const pricingMode = createMemo<'per_dose' | 'flat_fee'>(\n () => product()?.pricing_mode ?? 'per_dose',\n );\n\n const dosageOptions = createMemo(() => {\n const p = product();\n if (!p) return [];\n // Doses come from the linked Apex drug (available_dosages); dosage_prices is\n // only a price overlay. A dose with no resolvable price (no overlay + no\n // base price) is dropped — it isn't purchasable.\n const all = (p.available_dosages ?? [])\n .map((dosage) => {\n const overlay = (p.dosage_prices ?? []).find((d) => d.dosage === dosage);\n const price = overlay && overlay.price != null ? overlay.price : p.price;\n return { dosage, price, savingsPrice: overlay?.savingsPrice ?? null };\n })\n .filter((o): o is { dosage: string; price: number; savingsPrice: number | null } => o.price != null);\n if (pricingMode() !== 'flat_fee' || all.length === 0) return all;\n // flat_fee: collapse to a single entry — prefer dosage_override, else first.\n const override = p.dosage_override;\n const chosen = (override && all.find((d) => d.dosage === override)) || all[0];\n return [chosen];\n });\n const [selectedDosage, setSelectedDosage] = createSignal<string>('');\n\n // Auto-select the first dosage once options arrive\n createMemo(() => {\n const opts = dosageOptions();\n if (opts.length > 0 && !selectedDosage()) setSelectedDosage(opts[0].dosage);\n });\n\n const selectedPrice = createMemo<number | null>(() => {\n const opts = dosageOptions();\n const chosen = opts.find((d) => d.dosage === selectedDosage());\n if (chosen) return chosen.price;\n return product()?.price ?? null;\n });\n\n const selectedSalePrice = createMemo<number | null>(() => {\n const p = product();\n const base = selectedPrice();\n if (!p || base == null || !p.activeSale) return null;\n if (p.salePriceCents != null && p.price != null && p.price > 0) {\n const ratio = p.salePriceCents / Math.round(p.price * 100);\n return Math.max(0, base * ratio);\n }\n return Math.max(0, base - p.activeSale.discountCents / 100);\n });\n\n const inCart = createMemo(() => {\n const p = product();\n if (!p) return false;\n const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? '');\n const key = cartStore.itemKey(p.id, dosage);\n return cartStore.items().some((i) => cartStore.itemKey(i.productId, i.dosage) === key);\n });\n\n function addToCart() {\n const p = product();\n if (!p) return;\n const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? '');\n const effective = selectedSalePrice() ?? selectedPrice() ?? 0;\n const priceCents = Math.round(effective * 100);\n cartStore.add({\n productId: p.id,\n productName: p.name,\n dosage,\n quantity: 1,\n priceCents,\n drugId: p.id,\n apexDrugId: p.apex_drug_id ?? null,\n categories: p.categories ?? [],\n thumbnailUrl: p.thumbnail_url ?? undefined,\n hideDoseLabel: pricingMode() === 'flat_fee' ? true : undefined,\n isSubscription: p.is_subscription ? true : undefined,\n });\n cartStore.open();\n }\n\n return {\n product,\n dosageOptions,\n selectedDosage,\n setSelectedDosage,\n selectedPrice,\n selectedSalePrice,\n pricingMode,\n inCart,\n addToCart,\n };\n}\n\n// ── useMedicationSelect ─────────────────────────────────────────────\n\nexport interface MedicationSelectFlow {\n products: Resource<CatalogProduct[]>;\n weightLoss: Accessor<CatalogProduct[]>;\n peptides: Accessor<CatalogProduct[]>;\n /** Pick a specific product as the patient's selected medication and proceed. The site fires the navigation in the optional `onSelected` callback. */\n selectMedication: (product: CatalogProduct) => void;\n /** Pick \"general consultation\" — a null drugId, indicating no pre-selected drug. */\n selectGeneralConsultation: () => void;\n}\n\nexport interface UseMedicationSelectOptions {\n /** Called after a selection is made. Sites typically navigate to their survey route. */\n onSelected?: () => void;\n /** Override the label used for the general-consultation selection. Default \"General Consultation\". */\n generalConsultationLabel?: string;\n}\n\n/**\n * Catalog browse + select-for-survey. The selection is written to\n * medicationStore (legacy single-item flow); the site navigates afterward\n * via the onSelected callback.\n */\nexport function useMedicationSelect(\n options: UseMedicationSelectOptions = {},\n): MedicationSelectFlow {\n const catalog = useCatalog();\n\n function selectMedication(product: CatalogProduct) {\n medicationStore.select({ drugId: product.id, drugName: product.name });\n options.onSelected?.();\n }\n\n function selectGeneralConsultation() {\n medicationStore.select({\n drugId: null,\n drugName: options.generalConsultationLabel ?? 'General Consultation',\n });\n options.onSelected?.();\n }\n\n return {\n products: catalog.products,\n weightLoss: catalog.weightLoss,\n peptides: catalog.peptides,\n selectMedication,\n selectGeneralConsultation,\n };\n}\n","/**\n * Deterministic procedural color for product categories.\n *\n * Sites want a stable color per category id without curating maps. The hash\n * is stable across reloads, so the same id always picks the same slot. Sites\n * override the palette to brand-align — default palette works out of the box.\n */\n\nfunction hashId(id: string): number {\n let h = 5381;\n for (let i = 0; i < id.length; i++) h = ((h << 5) + h + id.charCodeAt(i)) | 0;\n return Math.abs(h);\n}\n\n/** Default palette. Reads on light or dark; sites that want brand alignment\n * pass their own array (e.g. CSS var refs). */\nexport const DEFAULT_COLOR_PALETTE: readonly string[] = [\n '#4f46e5', // indigo\n '#0891b2', // cyan\n '#0d9488', // teal\n '#f59e0b', // amber\n '#e11d48', // rose\n '#10b981', // emerald\n '#8b5cf6', // violet\n '#f97316', // orange\n];\n\nexport interface CategoryColorOpts {\n palette?: readonly string[];\n}\n\nexport function categoryColor(id: string, opts: CategoryColorOpts = {}): string {\n const palette = opts.palette ?? DEFAULT_COLOR_PALETTE;\n if (palette.length === 0) return 'currentColor';\n return palette[hashId(id) % palette.length];\n}\n","import { createEffect, createSignal, onMount, type Accessor } from 'solid-js';\nimport {\n promoCodesApi,\n subscriptionsApi,\n usersApi,\n newIdempotencyKey,\n ApiError,\n type PromoValidationResponse,\n type ApiResponse,\n} from '../api/client';\nimport { readPromoCode, clearPromoCode } from '../api/promoRef';\nimport authStore from '../stores/auth';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\n\n// ── Draft persistence ───────────────────────────────────────────────\n\nconst DRAFT_TTL_MS = 7 * 24 * 3600 * 1000;\nconst MAX_RESTORABLE_STEP = 1; // Account + Address only; never restore into Payment\n\ninterface IntakeDraft {\n step?: number;\n firstName?: string;\n lastName?: string;\n dateOfBirth?: string;\n email?: string;\n phone?: string;\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n /** Idempotency key for THIS draft's create/signup attempt. Persisted so a\n * refresh mid-submit retries with the SAME key and the backend dedupes\n * instead of double-charging; rotated after a definitive rejection. */\n idempotencyKey?: string;\n savedAt?: number;\n}\n\nfunction draftKey(): string {\n return `${getConfig().storagePrefix}-subscription-intake-draft`;\n}\n\nfunction loadDraft(): IntakeDraft {\n try {\n const raw = localStorage.getItem(draftKey());\n if (!raw) return {};\n const parsed = JSON.parse(raw) as IntakeDraft;\n if (parsed.savedAt && Date.now() - parsed.savedAt > DRAFT_TTL_MS) {\n localStorage.removeItem(draftKey());\n return {};\n }\n return parsed ?? {};\n } catch {\n return {};\n }\n}\n\nfunction saveDraft(draft: IntakeDraft) {\n try {\n localStorage.setItem(draftKey(), JSON.stringify({ ...draft, savedAt: Date.now() }));\n } catch {\n // noop\n }\n}\n\nfunction clearDraft() {\n try {\n localStorage.removeItem(draftKey());\n } catch {\n // noop\n }\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface SurveyResult {\n surveyResponseId: string;\n /**\n * v2 survey response id. When set, the Rx is linked to the Apex survey\n * snapshot and Apex generates the prescriber case notes from it (no local\n * caseNotes synthesis). Leave unset for the legacy v1 flow.\n */\n v2SurveyResponseId?: string;\n caseNotes?: string;\n drugId: string;\n drugName: string;\n dosage: string;\n}\n\nexport interface MedicationPricing {\n productId: string;\n productName: string;\n priceCents: number;\n savingsPriceCents?: number | null;\n}\n\nexport type SubscriptionIntakeOutcome =\n | { kind: 'in_progress' }\n | { kind: 'tokenizing' }\n | { kind: 'submitting' }\n /**\n * The member already holds a live subscription, so this intake must not create\n * a second one. Emitted ONLY under `singleSubscription` — without that option\n * the flow behaves exactly as before, so existing consumers that switch on\n * 'completed' alone are unaffected.\n *\n * Deliberately NOT 'completed': that kind means *this* purchase succeeded, and\n * hosts navigate onward celebrating it. This one means the member arrived\n * already subscribed and needs telling, not congratulating.\n */\n | { kind: 'already_subscribed'; productId?: string }\n | { kind: 'completed' };\n\nexport interface UseSubscriptionIntakeFlowOptions {\n surveyResult: SurveyResult;\n pricing: MedicationPricing;\n intervalDays?: number;\n /**\n * Whether the member is enrolled in the savings program — read reactively, so\n * a verification that completes mid-intake re-quotes. When true and the\n * product defines `savingsPriceCents`, that rate is quoted instead of list.\n *\n * Must track the same member the SERVER will resolve at charge time (the\n * persisted savings link), or the quote and the charge disagree.\n */\n isSavingsMember?: () => boolean;\n /**\n * Single-subscription tenants: the site sells ONE subscription program, so a\n * member may hold at most one live subscription — of ANY product.\n *\n * Widens the mount reconcile below from \"already subscribed to THIS product\"\n * to \"already subscribed to anything\", and turns the server's\n * `SUBSCRIPTION_EXISTS` rejection into an `already_subscribed` outcome instead\n * of a raw error banner. Mirrors `features.singleSubscription` on the tenant;\n * setting it here without the tenant flag still guards the common paths, but\n * the server is what actually enforces it.\n */\n singleSubscription?: boolean;\n}\n\nexport interface PromoPricing {\n baseCents: number;\n discountCents: number;\n finalCents: number;\n promoCode?: string;\n}\n\nexport interface SubscriptionIntakeFlow {\n // Step 0 = Account, 1 = Address, 2 = Payment\n step: Accessor<number>;\n stepCount: 3;\n next: () => Promise<void>;\n back: () => void;\n\n outcome: Accessor<SubscriptionIntakeOutcome>;\n error: Accessor<string | null>;\n submitting: Accessor<boolean>;\n tokenizing: Accessor<boolean>;\n /** True once the card tokenizer is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */\n tokenizerReady: Accessor<boolean>;\n /** @deprecated alias of tokenizerReady (pre-rename name). */\n acceptJsReady: Accessor<boolean>;\n /** Non-null when payment setup failed to initialize — render as a banner. */\n /** Tokenizer init failure, or null. */\n tokenizerError: Accessor<string | null>;\n /** @deprecated alias of tokenizerError (pre-rename name). */\n acceptJsError: Accessor<string | null>;\n\n // Step 0 — Account\n firstName: Accessor<string>; setFirstName: (v: string) => void;\n lastName: Accessor<string>; setLastName: (v: string) => void;\n email: Accessor<string>; setEmail: (v: string) => void;\n password: Accessor<string>; setPassword: (v: string) => void;\n dateOfBirth: Accessor<string>; setDateOfBirth: (v: string) => void;\n phone: Accessor<string>; setPhone: (v: string) => void;\n\n // Step 1 — Address (delivery + billing override; see AddressPair).\n // `address.billingSameAsShipping` is this flow's \"billing same as delivery\".\n address: AddressPair;\n\n // Step 2 — Payment\n cardNumber: Accessor<string>; setCardNumber: (v: string) => void;\n expiry: Accessor<string>; setExpiry: (v: string) => void;\n cvv: Accessor<string>; setCvv: (v: string) => void;\n\n // Promo\n promoCode: Accessor<string>; setPromoCode: (v: string) => void;\n promoValidating: Accessor<boolean>;\n promoError: Accessor<string | null>;\n promoApplied: Accessor<PromoValidationResponse | null>;\n applyPromo: () => Promise<void>;\n clearPromo: () => void;\n\n // Pricing (reflects applied promo)\n pricing: Accessor<PromoPricing>;\n\n // Context (read-only, from options)\n surveyResult: SurveyResult;\n medication: MedicationPricing;\n\n submit: () => Promise<void>;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport function useSubscriptionIntakeFlow(\n options: UseSubscriptionIntakeFlowOptions,\n): SubscriptionIntakeFlow {\n const accept = useCardTokenizer();\n\n let restored: IntakeDraft = {};\n if (typeof window !== 'undefined') restored = loadDraft();\n\n const [step, setStep] = createSignal(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));\n const [error, setError] = createSignal<string | null>(null);\n const [tokenizing, setTokenizing] = createSignal(false);\n const [submitting, setSubmitting] = createSignal(false);\n const [outcome, setOutcome] = createSignal<SubscriptionIntakeOutcome>({ kind: 'in_progress' });\n\n // Account\n const [firstName, setFirstName] = createSignal(restored.firstName ?? '');\n const [lastName, setLastName] = createSignal(restored.lastName ?? '');\n const [email, setEmail] = createSignal(restored.email ?? '');\n const [password, setPassword] = createSignal('');\n const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? '');\n const [phone, setPhone] = createSignal(restored.phone ?? '');\n\n // Address (delivery/shipping + billing override), backed by the shared\n // useAddressPair so validation and the same-as / copy-on-uncheck behavior\n // match the checkout flow. The individual accessors below keep this flow's\n // public interface stable for consuming storefronts (no breaking change).\n const addr = useAddressPair({\n initialShipping: {\n street: restored.street ?? '',\n city: restored.city ?? '',\n state: restored.state ?? '',\n zip: restored.zip ?? '',\n },\n });\n\n // Internal shipping getters for draft persistence + payload building; the full\n // read/write surface (incl. billing override) is exposed as `address` below.\n const street = () => addr.shipping().street;\n const city = () => addr.shipping().city;\n const state = () => addr.shipping().state;\n const zip = () => addr.shipping().zip;\n\n // Effective billing address sent as the charge's billTo.\n const effectiveBillingAddress = () => {\n const b = addr.effectiveBilling();\n return { street: b.street.trim(), city: b.city.trim(), state: b.state, zip: b.zip.trim() };\n };\n\n // Payment\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n\n // Promo\n const [promoCode, setPromoCode] = createSignal('');\n const [promoValidating, setPromoValidating] = createSignal(false);\n const [promoError, setPromoError] = createSignal<string | null>(null);\n const [promoApplied, setPromoApplied] = createSignal<PromoValidationResponse | null>(null);\n\n // ── Pre-fill from a `?promo=` landing ───────────────────────────\n //\n // A campaign link stashes its code (see api/promoRef). Being inside the\n // storage window says nothing about the CODE still being live — a sale can end\n // while the stash is fresh — so re-validate before showing it to anyone, and\n // drop it silently when the server says no. An expired or withdrawn code must\n // not greet a member with an error they did nothing to cause.\n //\n // Pre-fills ONLY: the member still presses Apply. Auto-applying would put a\n // discount on screen before they asked for it and, for a savings member handed\n // an exclusive code, would surface a refusal on arrival.\n //\n // Yields to anything already in the field. Nothing sets it before mount today\n // (the draft does not persist a promo), but a member's own entry must never be\n // overwritten by a stale link if that changes.\n onMount(async () => {\n if (promoCode().trim()) return;\n const stashed = readPromoCode();\n if (!stashed) return;\n try {\n const res = await promoCodesApi.validate(stashed, {\n productIds: [options.pricing.productId],\n subtotalCents: savingsBaseCents(),\n });\n if (res.valid) setPromoCode(stashed);\n else clearPromoCode();\n } catch {\n // Network/-server blip: leave the stash for the next visit rather than\n // discarding a code that may be perfectly good.\n }\n });\n\n // Idempotency key for the create/signup POST — restored with the draft so a\n // retry after a refresh presents the same key (see IntakeDraft.idempotencyKey).\n const [idemKey, setIdemKey] = createSignal(restored.idempotencyKey ?? '');\n\n // ── Auto-save draft ─────────────────────────────────────────────\n\n onMount(() => {\n createEffect(() => {\n saveDraft({\n step: step(),\n firstName: firstName(),\n lastName: lastName(),\n dateOfBirth: dateOfBirth(),\n email: email(),\n phone: phone(),\n street: street(),\n city: city(),\n state: state(),\n zip: zip(),\n idempotencyKey: idemKey() || undefined,\n });\n });\n });\n\n // ── Mount reconcile (authenticated re-subscribe path) ───────────\n //\n // The restored draft re-arms submit with no memory of a create that already\n // committed: if the subscription landed server-side but this client never saw\n // the response (refresh mid-submit, dropped connection), the user is invited\n // to subscribe — and be charged — again. Ask the server before offering the\n // form.\n //\n // Scope depends on the tenant's model:\n // default → THIS product only. A subscription to a different\n // medication is a legitimate separate purchase and\n // must not block this intake.\n // singleSubscription → any live subscription. The program IS the\n // subscription, so a second one of any product is a\n // double charge, not a second purchase.\n //\n // The unauthenticated path needs no reconcile (a committed signup makes the\n // email taken, so a re-submit fails instead of double-charging). Fails open —\n // the server refuses the duplicate regardless, and blocking a real intake on a\n // lookup blip costs a customer.\n onMount(async () => {\n if (!authStore.isAuthenticated()) return;\n try {\n const res = (await subscriptionsApi.list()) as {\n subscriptions?: Array<{ productId?: string; status?: string }>;\n } | null;\n const existing = res?.subscriptions?.find(\n (s) =>\n isLive(s.status) &&\n (options.singleSubscription || s.productId === options.pricing.productId),\n );\n if (existing) {\n clearDraft();\n // Same-product is the ambiguous-retry case this reconcile was built for:\n // the purchase this very flow was configured for already exists, so the\n // member is done. A DIFFERENT product means they came back to buy\n // something they can't have alongside what they hold — a distinct\n // outcome, and only reachable under singleSubscription.\n setOutcome(\n existing.productId === options.pricing.productId\n ? { kind: 'completed' }\n : { kind: 'already_subscribed', productId: existing.productId },\n );\n }\n } catch {\n // Reconcile is a guard, not a gate — never block intake on a lookup blip.\n }\n });\n\n // ── Pricing ─────────────────────────────────────────────────────\n\n /**\n * The base price to quote: the product's savings rate for an enrolled member,\n * otherwise list.\n *\n * `savingsPriceCents` was carried on MedicationPricing but never actually\n * read, so enrolled members were quoted (and charged) list price. This mirrors\n * the SERVER rule exactly — `resolveProductPricing` in the-backend keys off\n * the member's savings link and treats a null savings price as \"no savings\n * rate for this item\", never as free — because the server re-derives the\n * charge from the DB and ignores the amount posted here. If the two rules ever\n * disagree, the member sees one number and is charged another; that mismatch\n * is the whole reason this exists, so keep them in step.\n */\n const savingsBaseCents = (): number => {\n const list = options.pricing.priceCents;\n const savings = options.pricing.savingsPriceCents;\n return options.isSavingsMember?.() && savings != null ? savings : list;\n };\n\n const pricing = (): PromoPricing => {\n const baseCents = savingsBaseCents();\n const promo = promoApplied();\n if (!promo?.valid || !promo.discountCents) {\n return { baseCents, discountCents: 0, finalCents: baseCents };\n }\n const discountCents = Math.min(baseCents, promo.discountCents);\n return {\n baseCents,\n discountCents,\n finalCents: promo.finalCents ?? Math.max(0, baseCents - discountCents),\n promoCode: promo.promoCode?.code,\n };\n };\n\n // ── Promo code ──────────────────────────────────────────────────\n\n async function applyPromo() {\n const code = promoCode().trim();\n if (!code) {\n setPromoError('Enter a promo code.');\n return;\n }\n setPromoError(null);\n setPromoValidating(true);\n try {\n const res = await promoCodesApi.validate(code, {\n productIds: [options.pricing.productId],\n // The base the promo will actually be applied to. For a savings member\n // that is the savings price, not list: the server discounts the\n // savings-substituted subtotal at checkout, so quoting off list would\n // show a percentage promo as a bigger saving than it is (10% of $399\n // displayed, 10% of $280 charged). Same rule as savingsBaseCents — keep\n // the two in step.\n subtotalCents: savingsBaseCents(),\n });\n if (!res.valid) {\n setPromoError(res.error ?? 'Invalid promo code.');\n setPromoApplied(null);\n } else {\n setPromoApplied(res);\n setPromoError(null);\n }\n } catch {\n setPromoError('Could not validate promo code. Please try again.');\n setPromoApplied(null);\n } finally {\n setPromoValidating(false);\n }\n }\n\n function clearPromo() {\n setPromoCode('');\n setPromoApplied(null);\n setPromoError(null);\n }\n\n // ── Validation per step ─────────────────────────────────────────\n\n function validateStep(s: number): string | null {\n if (s === 0) {\n if (!firstName().trim()) return 'First name is required.';\n if (!lastName().trim()) return 'Last name is required.';\n // Authenticated members already have an account — they don't re-enter\n // credentials; submit() subscribes their existing account instead.\n if (!authStore.isAuthenticated()) {\n if (!email().trim()) return 'Email is required.';\n if (!password().trim()) return 'Password is required.';\n if (password().length < 8) return 'Password must be at least 8 characters.';\n }\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateOfBirth())) return 'Enter a valid date of birth.';\n const dob = new Date(dateOfBirth() + 'T00:00:00');\n if (Number.isNaN(dob.getTime())) return 'Enter a valid date of birth.';\n const age = (Date.now() - dob.getTime()) / (365.25 * 24 * 3600 * 1000);\n if (age < 18) return 'You must be at least 18 to register.';\n if (age > 120) return 'Enter a valid date of birth.';\n } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n if (!cardNumberRaw().trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n }\n return null;\n }\n\n // ── Navigation ───────────────────────────────────────────────────\n\n async function next() {\n const err = validateStep(step());\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n setStep((s) => s + 1);\n }\n\n function back() {\n setError(null);\n if (step() > 0) setStep((s) => s - 1);\n }\n\n // ── Submit (from Payment step) ──────────────────────────────────\n\n async function submit() {\n const finalPricing = pricing();\n const isFree = finalPricing.finalCents === 0;\n\n if (!isFree) {\n const cardErr = validateStep(2);\n if (cardErr) {\n setError(cardErr);\n return;\n }\n if (addr.billingIsOverride()) {\n const bErr = firstAddressError(validateAddress(addr.billing(), 'Billing'));\n if (bErr) { setError(bErr); return; }\n }\n }\n\n setError(null);\n\n let opaque: Record<string, unknown> | undefined;\n if (!isFree) {\n setTokenizing(true);\n setOutcome({ kind: 'tokenizing' });\n try {\n opaque = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Card tokenization failed.');\n setTokenizing(false);\n setOutcome({ kind: 'in_progress' });\n return;\n }\n setTokenizing(false);\n }\n\n setSubmitting(true);\n setOutcome({ kind: 'submitting' });\n\n // One key per logical purchase attempt: minted on first submit, persisted in\n // the draft (the auto-save effect tracks it), reused verbatim on retries so\n // the backend's idempotency middleware can collapse a replay of a create\n // that already committed.\n let idempotencyKey = idemKey();\n if (!idempotencyKey) {\n idempotencyKey = newIdempotencyKey();\n setIdemKey(idempotencyKey);\n }\n\n try {\n const promo = promoApplied();\n\n if (authStore.isAuthenticated()) {\n // Logged-in member (e.g. a savings member who created an account first):\n // subscribe their EXISTING account instead of creating a second one. The\n // account may be name-only, so first persist the profile entered during\n // intake, then create the subscription + Apex Rx on that account.\n await usersApi.updateProfile({\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n });\n\n const res = await subscriptionsApi.create({\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n billingAddress: effectiveBillingAddress(),\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n productId: options.pricing.productId,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n metadata: {\n drugId: options.surveyResult.drugId,\n selectedDosage: options.surveyResult.dosage,\n caseNotes: options.surveyResult.caseNotes,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n },\n }, { idempotencyKey });\n if ((res as ApiResponse).error) {\n throw new Error((res as ApiResponse).error || 'Subscription failed. Please try again.');\n }\n } else {\n await authStore.signupAndSubscribe({\n email: email().trim(),\n password: password(),\n member: {\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n medication: options.surveyResult.drugId,\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n billingAddress: effectiveBillingAddress(),\n surveyResponseId: options.surveyResult.surveyResponseId,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n caseNotes: options.surveyResult.caseNotes,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n }, { idempotencyKey });\n }\n\n clearDraft();\n setOutcome({ kind: 'completed' });\n } catch (err) {\n // The server refused because this member already holds a live\n // subscription. Not an error the member can act on by retrying — nothing\n // is wrong with what they typed — so surface it as its own outcome and\n // let the host explain, rather than as a red banner over a form that will\n // never succeed. Draft cleared so a later legitimate intake (after a\n // cancellation) starts clean.\n if (err instanceof ApiError && err.code === 'SUBSCRIPTION_EXISTS') {\n clearDraft();\n setOutcome({ kind: 'already_subscribed' });\n return;\n }\n\n // A definitive rejection (4xx: decline, validation) means nothing was\n // committed — the next attempt is a NEW operation and must not be\n // deduped against this one, so rotate the key. An AMBIGUOUS failure\n // (connection dropped, 5xx) may have committed server-side: keep the key\n // so the retry collapses into the original instead of charging twice.\n const maybeCommitted = err instanceof ApiError && err.ambiguous;\n if (!maybeCommitted) setIdemKey(newIdempotencyKey());\n\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n step,\n stepCount: 3,\n next,\n back,\n\n outcome,\n error,\n submitting,\n tokenizing,\n tokenizerReady: accept.ready,\n acceptJsReady: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\n\n firstName, setFirstName,\n lastName, setLastName,\n email, setEmail,\n password, setPassword,\n dateOfBirth, setDateOfBirth,\n phone, setPhone,\n\n address: addr,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n\n pricing,\n\n surveyResult: options.surveyResult,\n medication: options.pricing,\n\n submit,\n };\n}\n","import { createEffect, createRoot, on } from 'solid-js';\nimport cartStore, { type CartItem } from '../stores/cart';\nimport { promoCodesApi } from '../api/client';\nimport {\n adoptCartId,\n fetchCartConfig,\n fetchResumedCart,\n postCartSnapshot,\n readCartToken,\n resetCartId,\n stripCartToken,\n type CartSnapshotLine,\n type ResumedCart,\n} from '../api/cart';\n\n// Abandoned-cart capture, wired to the cart store.\n//\n// Two halves, both best-effort:\n//\n// - SNAPSHOT: every cart change is mirrored to the-backend (debounced, plus a\n// flush on pagehide — a shopper leaving is exactly the moment this exists\n// for). Identity only; the server re-prices.\n// - RESTORE: a `?cart=` token in the URL is traded for the saved cart and\n// rebuilt locally, so a recovery email opened on a phone brings the basket\n// with it.\n//\n// Nothing here may block, slow or break shopping. Every failure path ends in\n// \"carry on with the cart this browser already had\".\n\nexport interface CartCaptureOptions {\n /** Debounce for snapshot writes. Quantity steppers fire fast. */\n debounceMs?: number;\n /**\n * Address for an anonymous shopper, if the site collected one outside the\n * survey's email gate (e.g. checkout step 1). Logged-in shoppers need\n * nothing here — the backend reads their email off the token.\n */\n email?: () => string | null | undefined;\n}\n\nfunction toSnapshotLines(items: CartItem[]): CartSnapshotLine[] {\n return items.map((i) => ({\n productId: i.productId,\n ...(i.dosage ? { dosage: i.dosage } : {}),\n quantity: i.quantity || 1,\n }));\n}\n\n/** Rebuild the local cart from a resumed one, replacing whatever was there. */\nfunction applyResumedCart(resumed: ResumedCart): void {\n cartStore.clear();\n for (const line of resumed.items) {\n cartStore.add({\n productId: line.productId,\n productName: line.name,\n dosage: line.dosage ?? '',\n quantity: 1,\n // The sale price when one is running — same figure the catalog shows.\n priceCents: line.salePriceCents ?? line.priceCents,\n drugId: line.productId,\n apexDrugId: line.apexDrugId,\n categories: line.categories,\n thumbnailUrl: line.thumbnailUrl ?? undefined,\n hideDoseLabel: line.hideDoseLabel || undefined,\n isSubscription: line.isSubscription || undefined,\n });\n if (line.quantity > 1) {\n cartStore.setQuantity(cartStore.itemKey(line.productId, line.dosage ?? ''), line.quantity);\n }\n }\n}\n\n/**\n * Re-apply the promo code the cart was carrying when it was abandoned.\n *\n * Re-VALIDATED, never trusted: a code can expire, get revoked, or stop\n * covering the products still in the cart between abandonment and return, and\n * showing a discount the checkout won't honour is worse than showing none.\n */\nasync function restorePromo(resumed: ResumedCart): Promise<void> {\n if (!resumed.promoCode) return;\n try {\n const res = await promoCodesApi.validate(resumed.promoCode, {\n productIds: resumed.items.map((i) => i.productId),\n subtotalCents: resumed.subtotalCents,\n });\n if (!res.valid || !res.promoCode) return;\n cartStore.setPromo({\n code: res.promoCode.code,\n discountType: res.promoCode.discountType,\n discountValueCents: res.promoCode.discountValueCents,\n discountCents: res.discountCents ?? 0,\n });\n } catch {\n /* the cart is restored either way — the code is a bonus */\n }\n}\n\nlet restoreInFlight: Promise<ResumedCart | null> | null = null;\n\n/**\n * Redeem a `?cart=` token if the URL carries one.\n *\n * Exported for sites that want to act on the restore — opening their cart\n * drawer on arrival, say, or waiting for their catalog first.\n *\n * Single-flight: `startCartCapture()` restores on its own, so a site calling\n * this directly would otherwise race it — both read the token before either\n * strips it, and the cart gets rebuilt twice. Concurrent callers share one\n * restore and one result.\n */\nexport function restoreCartFromLink(): Promise<ResumedCart | null> {\n if (!restoreInFlight) {\n restoreInFlight = runRestore().finally(() => {\n restoreInFlight = null;\n });\n }\n return restoreInFlight;\n}\n\nasync function runRestore(): Promise<ResumedCart | null> {\n const token = readCartToken();\n if (!token) return null;\n\n const resumed = await fetchResumedCart(token);\n // Strip either way: a dead token that stays in the URL re-fires this on\n // every navigation and, worse, gets shared or bookmarked.\n stripCartToken();\n if (!resumed) return null;\n\n // Keep writing to the cart the email was about, not the one this browser\n // happened to mint — otherwise the reminder history and the conversion land\n // on different rows.\n adoptCartId(resumed.cartId);\n applyResumedCart(resumed);\n void restorePromo(resumed);\n return resumed;\n}\n\nlet running = false;\n\n/**\n * Start mirroring the cart. Call once at app boot; returns a disposer.\n *\n * No-ops for tenants that never opted in (`GET /config/cart`), so it is safe to\n * call unconditionally from shared site scaffolding.\n */\nexport function startCartCapture(opts: CartCaptureOptions = {}): () => void {\n if (running) return () => {};\n running = true;\n\n const debounceMs = opts.debounceMs ?? 2000;\n let enabled: boolean | null = null;\n let pending: CartItem[] | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lastSentEmpty = true;\n\n function flush(): void {\n if (timer) clearTimeout(timer);\n timer = undefined;\n const items = pending;\n pending = null;\n if (!items || enabled !== true) return;\n\n // An empty cart is not an abandoned one: the snapshot deletes the row, and\n // the id is retired so the next basket starts a clean one. This is also the\n // post-purchase path — checkout clears the cart — which is why converting\n // doesn't need its own wiring here.\n if (items.length === 0) {\n if (lastSentEmpty) return;\n postCartSnapshot({ items: [], promoCode: null });\n resetCartId();\n lastSentEmpty = true;\n return;\n }\n\n postCartSnapshot({\n items: toSnapshotLines(items),\n promoCode: cartStore.appliedPromo()?.code ?? null,\n email: opts.email?.() ?? null,\n });\n lastSentEmpty = false;\n }\n\n function schedule(ms: number): void {\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, ms);\n }\n\n const dispose = createRoot((disposeRoot) => {\n // `defer` so merely starting capture doesn't post the cart the shopper\n // hasn't touched; the first real change schedules the first write.\n createEffect(\n on(\n cartStore.items,\n (items) => {\n pending = items;\n if (enabled === true) schedule(debounceMs);\n },\n { defer: true },\n ),\n );\n return disposeRoot;\n });\n\n void fetchCartConfig().then((cfg) => {\n enabled = cfg.snapshot;\n if (!enabled) return;\n void restoreCartFromLink();\n if (pending) schedule(0);\n });\n\n // The shopper leaving with items in the cart is the whole point; don't let a\n // pending debounce die with the page.\n const onPageHide = () => flush();\n if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {\n window.addEventListener('pagehide', onPageHide);\n }\n\n return () => {\n if (timer) clearTimeout(timer);\n if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {\n window.removeEventListener('pagehide', onPageHide);\n }\n dispose();\n running = false;\n };\n}\n"]}