@apextelemed/partner-core 0.6.4 → 0.8.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 (54) hide show
  1. package/README.md +2 -2
  2. package/dist/api/index.d.ts +1 -1
  3. package/dist/api/index.js +3 -3
  4. package/dist/api/index.jsx +5 -3
  5. package/dist/{cart-D4mVX_zx.d.ts → cart-o6DpAu5y.d.ts} +1 -0
  6. package/dist/chunk/{4ZSZHZQV.jsx → 2OOCTPLG.jsx} +2 -2
  7. package/dist/chunk/{MLXPHJLR.js → 4HOG2LES.js} +7 -3
  8. package/dist/chunk/4HOG2LES.js.map +1 -0
  9. package/dist/chunk/{5HNZ7SEM.jsx → 6UXFHBE2.jsx} +45 -219
  10. package/dist/chunk/{HXMLRDIJ.jsx → AW6DQGQR.jsx} +647 -122
  11. package/dist/chunk/{NSRQXBHK.js → EHKYRS2R.js} +25 -189
  12. package/dist/chunk/EHKYRS2R.js.map +1 -0
  13. package/dist/chunk/{YJEHCCLY.js → EXXI5Y7I.js} +4 -3
  14. package/dist/chunk/EXXI5Y7I.js.map +1 -0
  15. package/dist/chunk/{WLEIDQ5M.jsx → GL3OY7W5.jsx} +6 -2
  16. package/dist/chunk/{ZDBW3JDO.jsx → GNPMRN6O.jsx} +3348 -1428
  17. package/dist/chunk/{QTGJY3YQ.js → HEQMD3X4.js} +3 -3
  18. package/dist/chunk/{QTGJY3YQ.js.map → HEQMD3X4.js.map} +1 -1
  19. package/dist/chunk/{WUE4VQBA.js → HKXDH266.js} +520 -23
  20. package/dist/chunk/HKXDH266.js.map +1 -0
  21. package/dist/chunk/{MTCQREMZ.js → HYLIHVIE.js} +4176 -2111
  22. package/dist/chunk/HYLIHVIE.js.map +1 -0
  23. package/dist/chunk/{EVCGDF5D.jsx → JF2KCOOX.jsx} +18 -1
  24. package/dist/chunk/{NBB2VTQK.jsx → QAFLR3EN.jsx} +2 -2
  25. package/dist/chunk/{2OXI5TKO.jsx → RSMUKR4J.jsx} +3 -2
  26. package/dist/chunk/{BEDW4XUM.js → RUA3XYFO.js} +19 -3
  27. package/dist/chunk/RUA3XYFO.js.map +1 -0
  28. package/dist/chunk/{BVLA7ATM.js → ZOZBYBNI.js} +3 -3
  29. package/dist/chunk/{BVLA7ATM.js.map → ZOZBYBNI.js.map} +1 -1
  30. package/dist/{client-B6Kt7LWo.d.ts → client-ZnA3JEbd.d.ts} +91 -8
  31. package/dist/flows/index.d.ts +246 -13
  32. package/dist/flows/index.js +6 -6
  33. package/dist/flows/index.jsx +31 -13
  34. package/dist/index/index.d.ts +4 -4
  35. package/dist/index/index.js +8 -8
  36. package/dist/index/index.jsx +48 -16
  37. package/dist/pages/index.d.ts +41 -6
  38. package/dist/pages/index.js +5 -5
  39. package/dist/pages/index.jsx +19 -7
  40. package/dist/primitives/default/index.js +1 -1
  41. package/dist/primitives/default/index.jsx +1 -1
  42. package/dist/stores/index.d.ts +2 -2
  43. package/dist/stores/index.js +2 -2
  44. package/dist/stores/index.jsx +2 -2
  45. package/dist/testing/seam-suite.js +1 -1
  46. package/dist/theme/admin.css +406 -1
  47. package/dist/theme/member-portal.css +5 -5
  48. package/package.json +1 -1
  49. package/dist/chunk/BEDW4XUM.js.map +0 -1
  50. package/dist/chunk/MLXPHJLR.js.map +0 -1
  51. package/dist/chunk/MTCQREMZ.js.map +0 -1
  52. package/dist/chunk/NSRQXBHK.js.map +0 -1
  53. package/dist/chunk/WUE4VQBA.js.map +0 -1
  54. package/dist/chunk/YJEHCCLY.js.map +0 -1
@@ -6,28 +6,30 @@ import {
6
6
  readResumeToken,
7
7
  saveFunnelDraft,
8
8
  stripResumeToken
9
- } from "./NBB2VTQK.jsx";
9
+ } from "./QAFLR3EN.jsx";
10
10
  import {
11
11
  affiliateAuth_default,
12
12
  auth_default,
13
13
  cart_default,
14
14
  medication_default
15
- } from "./WLEIDQ5M.jsx";
15
+ } from "./GL3OY7W5.jsx";
16
16
  import {
17
17
  ApiError,
18
18
  addressesApi,
19
19
  affiliatePortalApi,
20
20
  apexApi,
21
21
  authApi,
22
+ catalogApi,
22
23
  membersApi,
23
24
  messagesApi,
24
25
  newIdempotencyKey,
25
26
  ordersApi,
26
27
  paymentsApi,
28
+ productsApi,
27
29
  subscriptionsApi,
28
30
  supportApi,
29
31
  usersApi
30
- } from "./EVCGDF5D.jsx";
32
+ } from "./JF2KCOOX.jsx";
31
33
  import {
32
34
  getConfig
33
35
  } from "./LDZIUFDM.jsx";
@@ -144,13 +146,23 @@ function useSurveyFlow(options = {}) {
144
146
  const [createRequestKey, setCreateRequestKey] = createSignal(newIdempotencyKey());
145
147
  const [hydrated, setHydrated] = createSignal(false);
146
148
  const totalSteps = () => steps().length;
147
- const isLastStep = () => currentStep() >= totalSteps() - 1;
148
149
  const step2 = () => steps()[currentStep()] ?? null;
149
150
  const visibleQuestions = () => {
150
151
  const s = step2();
151
152
  if (!s) return [];
152
153
  return s.questions.filter((q) => isQuestionVisible(q, answers()));
153
154
  };
155
+ const stepHasVisibleQuestions = (i) => {
156
+ const s = steps()[i];
157
+ return !!s && s.questions.some((q) => isQuestionVisible(q, answers()));
158
+ };
159
+ const nearestVisibleStep = (from, dir) => {
160
+ for (let i = from + dir; i >= 0 && i < steps().length; i += dir) {
161
+ if (stepHasVisibleQuestions(i)) return i;
162
+ }
163
+ return -1;
164
+ };
165
+ const isLastStep = () => nearestVisibleStep(currentStep(), 1) === -1;
154
166
  onMount(async () => {
155
167
  const cartItems = cart_default.items();
156
168
  const hasCart = cartItems.length > 0;
@@ -212,7 +224,12 @@ function useSurveyFlow(options = {}) {
212
224
  const draft = loadSurveyDraft();
213
225
  if (draft.surveyId === sid) {
214
226
  if (draft.answers) setAnswers(draft.answers);
215
- setCurrentStep(Math.min(Math.max(draft.currentStep ?? 0, 0), Math.max(flat.length - 1, 0)));
227
+ const restoredStep = Math.min(Math.max(draft.currentStep ?? 0, 0), Math.max(flat.length - 1, 0));
228
+ setCurrentStep(restoredStep);
229
+ if (!stepHasVisibleQuestions(restoredStep)) {
230
+ const fwd = nearestVisibleStep(restoredStep, 1);
231
+ setCurrentStep(fwd !== -1 ? fwd : Math.max(nearestVisibleStep(restoredStep, -1), 0));
232
+ }
216
233
  if (draft.responseId) setResponseId(draft.responseId);
217
234
  if (draft.submitSurveyKey) setSubmitSurveyKey(draft.submitSurveyKey);
218
235
  if (draft.createRequestKey) setCreateRequestKey(draft.createRequestKey);
@@ -447,11 +464,13 @@ function useSurveyFlow(options = {}) {
447
464
  } finally {
448
465
  setSubmitting(false);
449
466
  }
450
- setCurrentStep((s) => s + 1);
467
+ const nextStep = nearestVisibleStep(currentStep(), 1);
468
+ if (nextStep !== -1) setCurrentStep(nextStep);
451
469
  }
452
470
  function back() {
453
471
  setValidationError(null);
454
- if (currentStep() > 0) setCurrentStep((s) => s - 1);
472
+ const prev = nearestVisibleStep(currentStep(), -1);
473
+ if (prev !== -1) setCurrentStep(prev);
455
474
  }
456
475
  async function confirmDrugSelection() {
457
476
  if (!selectedDrugId()) {
@@ -740,15 +759,97 @@ function useAddressPair(options = {}) {
740
759
  };
741
760
  }
742
761
 
762
+ // src/flows/catalogAvailability.ts
763
+ import { createEffect as createEffect2, createSignal as createSignal3, on, onCleanup } from "solid-js";
764
+ var DEBOUNCE_MS = 300;
765
+ var STATE_RE = /^[A-Za-z]{2}$/;
766
+ var INERT_DECISION = {
767
+ unavailableIds: [],
768
+ blocking: false,
769
+ degraded: false
770
+ };
771
+ function deriveCatalogAvailabilityDecision(result) {
772
+ if (!result) return INERT_DECISION;
773
+ if (result.degraded === true) return { ...INERT_DECISION, degraded: true };
774
+ const unavailableIds = result.items.filter((item) => item.checked && item.available === false).map((item) => item.id);
775
+ return { unavailableIds, blocking: unavailableIds.length > 0, degraded: false };
776
+ }
777
+ function useCatalogAvailability(ids, state) {
778
+ const [loading, setLoading] = createSignal3(false);
779
+ const [unavailableIds, setUnavailableIds] = createSignal3([]);
780
+ const [degraded, setDegraded] = createSignal3(false);
781
+ let generation = 0;
782
+ let timer;
783
+ let pending = null;
784
+ function markPending() {
785
+ if (pending) return;
786
+ let resolve;
787
+ const promise = new Promise((r) => resolve = r);
788
+ pending = { promise, resolve };
789
+ }
790
+ function markSettled() {
791
+ pending?.resolve();
792
+ pending = null;
793
+ }
794
+ function settleInert() {
795
+ setLoading(false);
796
+ setUnavailableIds([]);
797
+ setDegraded(false);
798
+ markSettled();
799
+ }
800
+ createEffect2(
801
+ on([ids, state], ([currentIds, currentState]) => {
802
+ if (timer) clearTimeout(timer);
803
+ const requestedIds = [...new Set(currentIds.map((id) => id.trim()).filter(Boolean))];
804
+ const normalizedState = (currentState ?? "").trim().toUpperCase();
805
+ const gen = ++generation;
806
+ if (requestedIds.length === 0 || !STATE_RE.test(normalizedState)) {
807
+ settleInert();
808
+ return;
809
+ }
810
+ setLoading(true);
811
+ markPending();
812
+ timer = setTimeout(() => {
813
+ catalogApi.availability(requestedIds, normalizedState).then((result) => {
814
+ if (gen !== generation) return;
815
+ const decision = deriveCatalogAvailabilityDecision(result);
816
+ setUnavailableIds(decision.unavailableIds);
817
+ setDegraded(decision.degraded);
818
+ }).catch(() => {
819
+ if (gen !== generation) return;
820
+ setUnavailableIds([]);
821
+ setDegraded(false);
822
+ }).finally(() => {
823
+ if (gen !== generation) return;
824
+ setLoading(false);
825
+ markSettled();
826
+ });
827
+ }, DEBOUNCE_MS);
828
+ })
829
+ );
830
+ onCleanup(() => {
831
+ if (timer) clearTimeout(timer);
832
+ generation++;
833
+ markSettled();
834
+ });
835
+ const blocking = () => !degraded() && unavailableIds().length > 0;
836
+ const isUnavailable = (id) => unavailableIds().includes(id);
837
+ const settled = () => pending?.promise ?? Promise.resolve();
838
+ return { loading, blocking, degraded, unavailableIds, isUnavailable, settled };
839
+ }
840
+ function catalogUnavailableMessage(itemName, state) {
841
+ return `${itemName} isn\u2019t available for delivery to ${stateLabel(state)}.`;
842
+ }
843
+
743
844
  // src/flows/checkout.ts
744
- import { createSignal as createSignal4, createEffect as createEffect2, onMount as onMount3 } from "solid-js";
845
+ import { createSignal as createSignal5, createEffect as createEffect3, onMount as onMount3 } from "solid-js";
745
846
 
746
847
  // src/flows/_internal/cardTokenizer.ts
747
- import { createSignal as createSignal3, onMount as onMount2, onCleanup } from "solid-js";
848
+ import { createSignal as createSignal4, onMount as onMount2, onCleanup as onCleanup2 } from "solid-js";
748
849
  function useCardTokenizer() {
749
- const [config, setConfig] = createSignal3(null);
750
- const [scriptLoaded, setScriptLoaded] = createSignal3(false);
751
- const [error, setError] = createSignal3(null);
850
+ const [config, setConfig] = createSignal4(null);
851
+ const [scriptLoaded, setScriptLoaded] = createSignal4(false);
852
+ const [error, setError] = createSignal4(null);
752
853
  const ready = () => {
753
854
  const cfg = config();
754
855
  if (!cfg) return false;
@@ -801,7 +902,7 @@ function useCardTokenizer() {
801
902
  "The secure payment library could not load. Check your connection (or ad blocker) and refresh the page."
802
903
  );
803
904
  document.head.appendChild(script);
804
- onCleanup(() => {
905
+ onCleanup2(() => {
805
906
  script.onload = null;
806
907
  script.onerror = null;
807
908
  });
@@ -900,17 +1001,17 @@ function formatCvv(raw) {
900
1001
  function useCheckoutFlow(options = {}) {
901
1002
  const accept = useCardTokenizer();
902
1003
  const address = useAddressPair();
903
- const [outcome, setOutcome] = createSignal4({ kind: "loading" });
904
- const [profile, setProfile] = createSignal4(null);
905
- const [prescription, setPrescription] = createSignal4(null);
906
- const [hasPaymentMethod, setHasPaymentMethod] = createSignal4(false);
907
- const [cardNumberRaw, setCardNumberRaw] = createSignal4("", { equals: false });
908
- const [expiryRaw, setExpiryRaw] = createSignal4("", { equals: false });
909
- const [cvvRaw, setCvvRaw] = createSignal4("", { equals: false });
910
- const [paymentError, setPaymentError] = createSignal4(null);
911
- const [processing, setProcessing] = createSignal4(false);
912
- const [correctionAcknowledged, setCorrectionAcknowledged] = createSignal4(false);
913
- createEffect2(() => {
1004
+ const [outcome, setOutcome] = createSignal5({ kind: "loading" });
1005
+ const [profile, setProfile] = createSignal5(null);
1006
+ const [prescription, setPrescription] = createSignal5(null);
1007
+ const [hasPaymentMethod, setHasPaymentMethod] = createSignal5(false);
1008
+ const [cardNumberRaw, setCardNumberRaw] = createSignal5("", { equals: false });
1009
+ const [expiryRaw, setExpiryRaw] = createSignal5("", { equals: false });
1010
+ const [cvvRaw, setCvvRaw] = createSignal5("", { equals: false });
1011
+ const [paymentError, setPaymentError] = createSignal5(null);
1012
+ const [processing, setProcessing] = createSignal5(false);
1013
+ const [correctionAcknowledged, setCorrectionAcknowledged] = createSignal5(false);
1014
+ createEffect3(() => {
914
1015
  address.shipping();
915
1016
  setCorrectionAcknowledged(false);
916
1017
  });
@@ -947,7 +1048,14 @@ function useCheckoutFlow(options = {}) {
947
1048
  promoCode: cart_default.appliedPromo()?.code
948
1049
  };
949
1050
  };
950
- const canSubmit = () => hasPaymentMethod() || accept.ready();
1051
+ const availability = useCatalogAvailability(
1052
+ () => {
1053
+ const drugId = prescription()?.drugId;
1054
+ return drugId ? [drugId] : [];
1055
+ },
1056
+ () => address.shipping().state
1057
+ );
1058
+ const canSubmit = () => (hasPaymentMethod() || accept.ready()) && !availability.blocking();
951
1059
  onMount3(async () => {
952
1060
  try {
953
1061
  const [profileRes, subsRes] = await Promise.all([
@@ -1022,6 +1130,11 @@ function useCheckoutFlow(options = {}) {
1022
1130
  setPaymentError("Missing medication details.");
1023
1131
  return;
1024
1132
  }
1133
+ await availability.settled();
1134
+ if (availability.blocking()) {
1135
+ setPaymentError(catalogUnavailableMessage(rx.drugName || "This medication", address.shipping().state));
1136
+ return;
1137
+ }
1025
1138
  if (!address.validate()) {
1026
1139
  const badShipping = hasErrors(address.shippingErrors());
1027
1140
  const badBilling = hasErrors(address.billingErrors());
@@ -1101,6 +1214,7 @@ function useCheckoutFlow(options = {}) {
1101
1214
  outcome,
1102
1215
  profile,
1103
1216
  address,
1217
+ availability,
1104
1218
  pricing,
1105
1219
  hasPaymentMethod,
1106
1220
  tokenizerReady: accept.ready,
@@ -1121,7 +1235,7 @@ function useCheckoutFlow(options = {}) {
1121
1235
  }
1122
1236
 
1123
1237
  // src/flows/cartCheckout.ts
1124
- import { createSignal as createSignal5, createEffect as createEffect3, onMount as onMount4 } from "solid-js";
1238
+ import { createSignal as createSignal6, createEffect as createEffect4, onMount as onMount4 } from "solid-js";
1125
1239
  var memoryKeys = /* @__PURE__ */ new Map();
1126
1240
  var ATTEMPT_SCOPE = "cart";
1127
1241
  function keyStorageKey(scope) {
@@ -1151,20 +1265,24 @@ function clearAttemptKey(scope) {
1151
1265
  function useCartCheckoutFlow() {
1152
1266
  const accept = useCardTokenizer();
1153
1267
  const address = useAddressPair();
1154
- const [outcome, setOutcome] = createSignal5({ kind: "loading" });
1155
- const [profile, setProfile] = createSignal5(null);
1156
- const [cardNumberRaw, setCardNumberRaw] = createSignal5("", { equals: false });
1157
- const [expiryRaw, setExpiryRaw] = createSignal5("", { equals: false });
1158
- const [cvvRaw, setCvvRaw] = createSignal5("", { equals: false });
1159
- const [paymentError, setPaymentError] = createSignal5(null);
1160
- const [processing, setProcessing] = createSignal5(false);
1161
- const [correctionAcknowledged, setCorrectionAcknowledged] = createSignal5(false);
1162
- createEffect3(() => {
1268
+ const [outcome, setOutcome] = createSignal6({ kind: "loading" });
1269
+ const [profile, setProfile] = createSignal6(null);
1270
+ const [cardNumberRaw, setCardNumberRaw] = createSignal6("", { equals: false });
1271
+ const [expiryRaw, setExpiryRaw] = createSignal6("", { equals: false });
1272
+ const [cvvRaw, setCvvRaw] = createSignal6("", { equals: false });
1273
+ const [paymentError, setPaymentError] = createSignal6(null);
1274
+ const [processing, setProcessing] = createSignal6(false);
1275
+ const [correctionAcknowledged, setCorrectionAcknowledged] = createSignal6(false);
1276
+ createEffect4(() => {
1163
1277
  address.shipping();
1164
1278
  setCorrectionAcknowledged(false);
1165
1279
  });
1166
1280
  const items = () => cart_default.items().filter((i) => i.isSubscription !== true);
1167
1281
  const skippedSubscriptionItems = () => cart_default.items().filter((i) => i.isSubscription === true);
1282
+ const availability = useCatalogAvailability(
1283
+ () => items().map((i) => i.productId),
1284
+ () => address.shipping().state
1285
+ );
1168
1286
  const pricing = () => {
1169
1287
  const subtotalCents = items().reduce((sum, i) => sum + i.priceCents * (i.quantity || 1), 0);
1170
1288
  const promo = cart_default.appliedPromo();
@@ -1182,7 +1300,7 @@ function useCartCheckoutFlow() {
1182
1300
  promoCode: promo?.code
1183
1301
  };
1184
1302
  };
1185
- const canSubmit = () => accept.ready();
1303
+ const canSubmit = () => accept.ready() && !availability.blocking();
1186
1304
  onMount4(async () => {
1187
1305
  if (!auth_default.isAuthenticated()) {
1188
1306
  setOutcome({ kind: "needs_auth" });
@@ -1251,6 +1369,13 @@ function useCartCheckoutFlow() {
1251
1369
  setOutcome({ kind: "needs_cart" });
1252
1370
  return;
1253
1371
  }
1372
+ await availability.settled();
1373
+ if (availability.blocking()) {
1374
+ setPaymentError(
1375
+ "One or more items in your cart aren\u2019t available for delivery to your address. Please remove them or update your shipping state."
1376
+ );
1377
+ return;
1378
+ }
1254
1379
  if (!address.validate()) {
1255
1380
  const badShipping = hasErrors(address.shippingErrors());
1256
1381
  const badBilling = hasErrors(address.billingErrors());
@@ -1349,6 +1474,7 @@ function useCartCheckoutFlow() {
1349
1474
  address,
1350
1475
  items,
1351
1476
  skippedSubscriptionItems,
1477
+ availability,
1352
1478
  pricing,
1353
1479
  tokenizerReady: accept.ready,
1354
1480
  acceptJsLoaded: accept.ready,
@@ -1368,7 +1494,7 @@ function useCartCheckoutFlow() {
1368
1494
  }
1369
1495
 
1370
1496
  // src/flows/signup.ts
1371
- import { createEffect as createEffect4, createSignal as createSignal6, onMount as onMount5 } from "solid-js";
1497
+ import { createEffect as createEffect5, createSignal as createSignal7, onMount as onMount5 } from "solid-js";
1372
1498
  var DRAFT_TTL_MS = 7 * 24 * 3600 * 1e3;
1373
1499
  var MAX_RESTORABLE_STEP = 2;
1374
1500
  function draftKey() {
@@ -1404,29 +1530,33 @@ function useSignupFlow(options) {
1404
1530
  const accept = useCardTokenizer();
1405
1531
  let restored = {};
1406
1532
  if (typeof window !== "undefined") restored = loadDraft();
1407
- const [step2, setStep] = createSignal6(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));
1408
- const [error, setError] = createSignal6(null);
1409
- const [tokenizing, setTokenizing] = createSignal6(false);
1410
- const [submitting, setSubmitting] = createSignal6(false);
1411
- const [outcome, setOutcome] = createSignal6({ kind: "in_progress" });
1412
- const [firstName, setFirstName] = createSignal6(restored.firstName ?? "");
1413
- const [lastName, setLastName] = createSignal6(restored.lastName ?? "");
1414
- const [email, setEmail] = createSignal6(restored.email ?? "");
1415
- const [password, setPassword] = createSignal6("");
1416
- const [dateOfBirth, setDateOfBirth] = createSignal6(restored.dateOfBirth ?? "");
1417
- const [phone, setPhone] = createSignal6(restored.phone ?? "");
1418
- const [street, setStreet] = createSignal6(restored.street ?? "");
1419
- const [city, setCity] = createSignal6(restored.city ?? "");
1420
- const [state, setState] = createSignal6(restored.state ?? "");
1421
- const [zip, setZip] = createSignal6(restored.zip ?? "");
1422
- const [cardNumberRaw, setCardNumberRaw] = createSignal6("", { equals: false });
1423
- const [expiryRaw, setExpiryRaw] = createSignal6("", { equals: false });
1424
- const [cvvRaw, setCvvRaw] = createSignal6("", { equals: false });
1425
- const [tokenizedData, setTokenizedData] = createSignal6(null);
1426
- const [promoCode, setPromoCode] = createSignal6("");
1427
- const [idempotencyKey, setIdempotencyKey] = createSignal6(newIdempotencyKey());
1533
+ const [step2, setStep] = createSignal7(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));
1534
+ const [error, setError] = createSignal7(null);
1535
+ const [tokenizing, setTokenizing] = createSignal7(false);
1536
+ const [submitting, setSubmitting] = createSignal7(false);
1537
+ const [outcome, setOutcome] = createSignal7({ kind: "in_progress" });
1538
+ const [firstName, setFirstName] = createSignal7(restored.firstName ?? "");
1539
+ const [lastName, setLastName] = createSignal7(restored.lastName ?? "");
1540
+ const [email, setEmail] = createSignal7(restored.email ?? "");
1541
+ const [password, setPassword] = createSignal7("");
1542
+ const [dateOfBirth, setDateOfBirth] = createSignal7(restored.dateOfBirth ?? "");
1543
+ const [phone, setPhone] = createSignal7(restored.phone ?? "");
1544
+ const [street, setStreet] = createSignal7(restored.street ?? "");
1545
+ const [city, setCity] = createSignal7(restored.city ?? "");
1546
+ const [state, setState] = createSignal7(restored.state ?? "");
1547
+ const [zip, setZip] = createSignal7(restored.zip ?? "");
1548
+ const [cardNumberRaw, setCardNumberRaw] = createSignal7("", { equals: false });
1549
+ const [expiryRaw, setExpiryRaw] = createSignal7("", { equals: false });
1550
+ const [cvvRaw, setCvvRaw] = createSignal7("", { equals: false });
1551
+ const [tokenizedData, setTokenizedData] = createSignal7(null);
1552
+ const [promoCode, setPromoCode] = createSignal7("");
1553
+ const [idempotencyKey, setIdempotencyKey] = createSignal7(newIdempotencyKey());
1554
+ const cartIsEmpty = () => cart_default.items().length === 0;
1555
+ onMount5(() => {
1556
+ if (options.requireCart && cartIsEmpty()) setOutcome({ kind: "needs_cart" });
1557
+ });
1428
1558
  onMount5(() => {
1429
- createEffect4(() => {
1559
+ createEffect5(() => {
1430
1560
  saveDraft({
1431
1561
  step: step2(),
1432
1562
  firstName: firstName(),
@@ -1530,6 +1660,10 @@ function useSignupFlow(options) {
1530
1660
  }
1531
1661
  async function submit() {
1532
1662
  if (submitting()) return;
1663
+ if (options.requireCart && cartIsEmpty()) {
1664
+ setOutcome({ kind: "needs_cart" });
1665
+ return;
1666
+ }
1533
1667
  const opaque = tokenizedData();
1534
1668
  if (!opaque) {
1535
1669
  setError("Card not tokenized. Please go back and re-enter your card details.");
@@ -1654,7 +1788,7 @@ function useSignupFlow(options) {
1654
1788
  }
1655
1789
 
1656
1790
  // src/flows/register.ts
1657
- import { createEffect as createEffect5, createSignal as createSignal7, onMount as onMount6 } from "solid-js";
1791
+ import { createEffect as createEffect6, createSignal as createSignal8, onMount as onMount6 } from "solid-js";
1658
1792
  var DRAFT_TTL_MS2 = 7 * 24 * 3600 * 1e3;
1659
1793
  var MAX_RESTORABLE_STEP2 = 1;
1660
1794
  function draftKey2() {
@@ -1689,26 +1823,26 @@ function clearDraft2() {
1689
1823
  function useRegisterFlow() {
1690
1824
  let restored = {};
1691
1825
  if (typeof window !== "undefined") restored = loadDraft2();
1692
- const [step2, setStep] = createSignal7(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP2));
1693
- const [error, setError] = createSignal7(null);
1694
- const [submitting, setSubmitting] = createSignal7(false);
1695
- const [outcome, setOutcome] = createSignal7({ kind: "in_progress" });
1696
- const [firstName, setFirstName] = createSignal7(restored.firstName ?? "");
1697
- const [lastName, setLastName] = createSignal7(restored.lastName ?? "");
1698
- const [email, setEmail] = createSignal7(restored.email ?? "");
1699
- const [password, setPassword] = createSignal7("");
1700
- const [dateOfBirth, setDateOfBirth] = createSignal7(restored.dateOfBirth ?? "");
1701
- const [phone, setPhone] = createSignal7(restored.phone ?? "");
1702
- const [street, setStreet] = createSignal7(restored.street ?? "");
1703
- const [city, setCity] = createSignal7(restored.city ?? "");
1704
- const [state, setState] = createSignal7(restored.state ?? "");
1705
- const [zip, setZip] = createSignal7(restored.zip ?? "");
1826
+ const [step2, setStep] = createSignal8(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP2));
1827
+ const [error, setError] = createSignal8(null);
1828
+ const [submitting, setSubmitting] = createSignal8(false);
1829
+ const [outcome, setOutcome] = createSignal8({ kind: "in_progress" });
1830
+ const [firstName, setFirstName] = createSignal8(restored.firstName ?? "");
1831
+ const [lastName, setLastName] = createSignal8(restored.lastName ?? "");
1832
+ const [email, setEmail] = createSignal8(restored.email ?? "");
1833
+ const [password, setPassword] = createSignal8("");
1834
+ const [dateOfBirth, setDateOfBirth] = createSignal8(restored.dateOfBirth ?? "");
1835
+ const [phone, setPhone] = createSignal8(restored.phone ?? "");
1836
+ const [street, setStreet] = createSignal8(restored.street ?? "");
1837
+ const [city, setCity] = createSignal8(restored.city ?? "");
1838
+ const [state, setState] = createSignal8(restored.state ?? "");
1839
+ const [zip, setZip] = createSignal8(restored.zip ?? "");
1706
1840
  onMount6(() => {
1707
1841
  if (auth_default.isAuthenticated()) {
1708
1842
  setOutcome({ kind: "already_authenticated" });
1709
1843
  return;
1710
1844
  }
1711
- createEffect5(() => {
1845
+ createEffect6(() => {
1712
1846
  saveDraft2({
1713
1847
  step: step2(),
1714
1848
  firstName: firstName(),
@@ -1901,7 +2035,7 @@ function isLive(status) {
1901
2035
  }
1902
2036
 
1903
2037
  // src/flows/subscribe.ts
1904
- import { createSignal as createSignal8, onMount as onMount7 } from "solid-js";
2038
+ import { createEffect as createEffect7, createSignal as createSignal9, on as on2, onMount as onMount7 } from "solid-js";
1905
2039
  async function hasActiveSubscription() {
1906
2040
  const subsRes = await subscriptionsApi.list();
1907
2041
  return (subsRes?.subscriptions ?? []).some((s) => s.status === "active");
@@ -1912,17 +2046,25 @@ async function hasReconcilableSubscription() {
1912
2046
  }
1913
2047
  function useSubscribeFlow(options) {
1914
2048
  const accept = useCardTokenizer();
1915
- const [outcome, setOutcome] = createSignal8({ kind: "loading" });
1916
- const [error, setError] = createSignal8(null);
1917
- const [submitting, setSubmitting] = createSignal8(false);
1918
- const [street, setStreet] = createSignal8("");
1919
- const [city, setCity] = createSignal8("");
1920
- const [state, setState] = createSignal8("");
1921
- const [zip, setZip] = createSignal8("");
1922
- const [cardNumberRaw, setCardNumberRaw] = createSignal8("", { equals: false });
1923
- const [expiryRaw, setExpiryRaw] = createSignal8("", { equals: false });
1924
- const [cvvRaw, setCvvRaw] = createSignal8("", { equals: false });
1925
- const [idempotencyKey, setIdempotencyKey] = createSignal8(newIdempotencyKey());
2049
+ const [outcome, setOutcome] = createSignal9({ kind: "loading" });
2050
+ const [error, setError] = createSignal9(null);
2051
+ const [submitting, setSubmitting] = createSignal9(false);
2052
+ const [quote, setQuote] = createSignal9(null);
2053
+ const [quoteError, setQuoteError] = createSignal9(null);
2054
+ const [street, setStreet] = createSignal9("");
2055
+ const [city, setCity] = createSignal9("");
2056
+ const [state, setState] = createSignal9("");
2057
+ const [zip, setZip] = createSignal9("");
2058
+ const [profileState, setProfileState] = createSignal9("");
2059
+ const shipState = () => profileState() || state();
2060
+ const availability = useCatalogAvailability(
2061
+ () => cart_default.items().map((i) => i.productId),
2062
+ shipState
2063
+ );
2064
+ const [cardNumberRaw, setCardNumberRaw] = createSignal9("", { equals: false });
2065
+ const [expiryRaw, setExpiryRaw] = createSignal9("", { equals: false });
2066
+ const [cvvRaw, setCvvRaw] = createSignal9("", { equals: false });
2067
+ const [idempotencyKey, setIdempotencyKey] = createSignal9(newIdempotencyKey());
1926
2068
  onMount7(async () => {
1927
2069
  if (!auth_default.isAuthenticated()) {
1928
2070
  setOutcome({ kind: "needs_auth" });
@@ -1946,12 +2088,90 @@ function useSubscribeFlow(options) {
1946
2088
  setStreet(p.address1 || p.street || "");
1947
2089
  setCity(p.city || "");
1948
2090
  setState(normalizeState(p.state || ""));
2091
+ setProfileState(normalizeState(p.state || ""));
1949
2092
  setZip(p.zip || "");
1950
2093
  }
1951
2094
  } catch {
1952
2095
  }
1953
2096
  setOutcome({ kind: "in_progress" });
1954
2097
  });
2098
+ const cartProducts = () => cart_default.items().map((i) => ({
2099
+ productId: i.productId,
2100
+ productName: i.productName,
2101
+ quantity: i.quantity,
2102
+ dosage: i.dosage
2103
+ }));
2104
+ function estimateFromCart() {
2105
+ const lines = cart_default.items().map((i) => ({
2106
+ productId: i.productId,
2107
+ productName: i.productName,
2108
+ dosage: i.dosage || null,
2109
+ quantity: i.quantity || 1,
2110
+ amountCents: i.priceCents * (i.quantity || 1)
2111
+ }));
2112
+ let subtotalCents = lines.reduce((s, l) => s + l.amountCents, 0);
2113
+ if (subtotalCents === 0 && lines.length === 0) subtotalCents = options.membershipAmountCents;
2114
+ const discountCents = Math.min(subtotalCents, cart_default.appliedPromo()?.discountCents ?? 0);
2115
+ return {
2116
+ source: "estimate",
2117
+ model: "per_product",
2118
+ intervalDays: options.membershipIntervalDays ?? 30,
2119
+ lines,
2120
+ subtotalCents,
2121
+ discountCents,
2122
+ totalCents: subtotalCents - discountCents
2123
+ };
2124
+ }
2125
+ let quoteSeq = 0;
2126
+ async function refreshQuote() {
2127
+ const seq = ++quoteSeq;
2128
+ setQuoteError(null);
2129
+ try {
2130
+ const p = await subscriptionsApi.preview({
2131
+ products: cartProducts(),
2132
+ productId: cartProducts()[0]?.productId,
2133
+ promoCode: cart_default.appliedPromo()?.code,
2134
+ intervalDays: options.membershipIntervalDays
2135
+ });
2136
+ if (seq !== quoteSeq) return;
2137
+ if (p.alreadySubscribed) {
2138
+ setOutcome({ kind: "already_subscribed" });
2139
+ return;
2140
+ }
2141
+ setQuote({
2142
+ source: "server",
2143
+ model: p.model,
2144
+ intervalDays: p.intervalDays,
2145
+ lines: (p.lines ?? []).map((l) => ({
2146
+ productId: l.productId,
2147
+ productName: l.productName,
2148
+ dosage: l.dosage ?? null,
2149
+ quantity: l.quantity,
2150
+ amountCents: l.amountCents
2151
+ })),
2152
+ subtotalCents: p.subtotalCents,
2153
+ discountCents: p.discountCents,
2154
+ totalCents: p.totalCents
2155
+ });
2156
+ } catch (e) {
2157
+ if (seq !== quoteSeq) return;
2158
+ const status = e instanceof ApiError ? e.status : void 0;
2159
+ if (status && status >= 400 && status < 500 && status !== 404 && status !== 405) {
2160
+ setQuote(null);
2161
+ setQuoteError(e instanceof Error ? e.message : "This order cannot be priced right now.");
2162
+ return;
2163
+ }
2164
+ setQuote(estimateFromCart());
2165
+ }
2166
+ }
2167
+ createEffect7(
2168
+ on2(
2169
+ () => [outcome().kind, cart_default.items(), cart_default.appliedPromo()],
2170
+ ([kind]) => {
2171
+ if (kind === "in_progress") void refreshQuote();
2172
+ }
2173
+ )
2174
+ );
1955
2175
  function validate() {
1956
2176
  const a = validateAddress(
1957
2177
  { street: street(), city: city(), state: state(), zip: zip() },
@@ -1965,6 +2185,7 @@ function useSubscribeFlow(options) {
1965
2185
  if (!cvvRaw().trim()) return "CVV is required.";
1966
2186
  return null;
1967
2187
  }
2188
+ let awaitingAvailability = false;
1968
2189
  async function submit() {
1969
2190
  if (submitting()) return;
1970
2191
  if (!auth_default.isAuthenticated()) {
@@ -1975,6 +2196,22 @@ function useSubscribeFlow(options) {
1975
2196
  setOutcome({ kind: "needs_cart" });
1976
2197
  return;
1977
2198
  }
2199
+ if (quoteError()) {
2200
+ setError(quoteError());
2201
+ return;
2202
+ }
2203
+ if (awaitingAvailability) return;
2204
+ awaitingAvailability = true;
2205
+ try {
2206
+ await availability.settled();
2207
+ } finally {
2208
+ awaitingAvailability = false;
2209
+ }
2210
+ if (availability.blocking()) {
2211
+ const unavailableItem = cart_default.items().find((i) => availability.isUnavailable(i.productId));
2212
+ setError(catalogUnavailableMessage(unavailableItem?.productName ?? "One of your items", shipState()));
2213
+ return;
2214
+ }
1978
2215
  const err = validate();
1979
2216
  if (err) {
1980
2217
  setError(err);
@@ -1998,7 +2235,9 @@ function useSubscribeFlow(options) {
1998
2235
  const res = await subscriptionsApi.create(
1999
2236
  {
2000
2237
  opaqueData: opaque,
2001
- amountCents: options.membershipAmountCents,
2238
+ // Informational only — the backend prices the cart itself. Send what
2239
+ // the customer was shown so the two are auditable together.
2240
+ amountCents: quote()?.totalCents ?? options.membershipAmountCents,
2002
2241
  intervalDays: options.membershipIntervalDays ?? 30,
2003
2242
  billingAddress: {
2004
2243
  street: street().trim(),
@@ -2046,6 +2285,8 @@ function useSubscribeFlow(options) {
2046
2285
  acceptJsError: accept.error,
2047
2286
  error,
2048
2287
  submitting,
2288
+ quote,
2289
+ quoteError,
2049
2290
  street,
2050
2291
  setStreet,
2051
2292
  city,
@@ -2054,6 +2295,8 @@ function useSubscribeFlow(options) {
2054
2295
  setState,
2055
2296
  zip,
2056
2297
  setZip,
2298
+ availability,
2299
+ shipState,
2057
2300
  cardNumber: cardNumberRaw,
2058
2301
  setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),
2059
2302
  expiry: expiryRaw,
@@ -2426,7 +2669,7 @@ var LIFECYCLE_LABEL = {
2426
2669
  past_due: "Past due",
2427
2670
  paused: "Paused",
2428
2671
  incomplete: "Incomplete signup",
2429
- cancelled: "Cancelled",
2672
+ cancelled: "Canceled",
2430
2673
  card_declined: "Card declined",
2431
2674
  awaiting_prescriber: "Awaiting prescriber",
2432
2675
  never_subscribed: "Never subscribed"
@@ -2580,12 +2823,12 @@ function lifecycleReason(o) {
2580
2823
  o.subscriptions.filter((x) => x.status === "cancelled"),
2581
2824
  (x) => x.cancelledAt
2582
2825
  )[0] ?? sub;
2583
- if (!s) return "Subscription cancelled.";
2826
+ if (!s) return "Subscription canceled.";
2584
2827
  const started = ms(s.createdAt);
2585
2828
  const ended = ms(s.cancelledAt);
2586
2829
  const months = started !== null && ended !== null ? Math.max(0, Math.round((ended - started) / (30 * DAY_MS2))) : null;
2587
2830
  const tenure = months !== null && months > 0 ? ` after ${months} month${months === 1 ? "" : "s"}` : "";
2588
- return `Cancelled on ${fmtDay(s.cancelledAt)}${tenure}.`;
2831
+ return `Canceled on ${fmtDay(s.cancelledAt)}${tenure}.`;
2589
2832
  }
2590
2833
  default:
2591
2834
  return o.lifecycle.label || "";
@@ -2711,7 +2954,7 @@ function deriveAttention(o, now = /* @__PURE__ */ new Date()) {
2711
2954
  id: "cancelled-with-pending",
2712
2955
  severity: "warning",
2713
2956
  title: `${pending.length} unapproved prescription request${pending.length === 1 ? " is" : "s are"} still in the prescriber queue after cancellation`,
2714
- detail: "A cancelled customer should not be prescribed. Cancel the pending requests.",
2957
+ detail: "A canceled customer should not be prescribed. Cancel the pending requests.",
2715
2958
  action: { kind: "cancel_unapproved", label: "Cancel unapproved requests" }
2716
2959
  });
2717
2960
  }
@@ -2737,8 +2980,8 @@ var JOURNEY_LABEL = {
2737
2980
  shipped: "Shipped",
2738
2981
  renewing: "Renewing"
2739
2982
  };
2740
- function step(key, state, date = null, detail = null) {
2741
- return { key, label: JOURNEY_LABEL[key], state, date, detail };
2983
+ function step(key, state, date = null, detail = null, label = JOURNEY_LABEL[key]) {
2984
+ return { key, label, state, date, detail };
2742
2985
  }
2743
2986
  function deriveJourney(o) {
2744
2987
  const steps = [];
@@ -2870,7 +3113,7 @@ function deriveJourney(o) {
2870
3113
  }
2871
3114
  } else if (subs.some((s) => s.status === "cancelled")) {
2872
3115
  const c = newestFirst(subs.filter((s) => s.status === "cancelled"), (s) => s.cancelledAt)[0];
2873
- steps.push(step("renewing", "blocked", c?.cancelledAt ?? null, "Cancelled"));
3116
+ steps.push(step("renewing", "blocked", c?.cancelledAt ?? null, "Subscription ended", "Canceled"));
2874
3117
  } else {
2875
3118
  steps.push(step("renewing", "upcoming"));
2876
3119
  }
@@ -2970,7 +3213,7 @@ function buildTimeline(o, limit = 200) {
2970
3213
  ev.push({ id: `sub-paused-${s.id}`, at: s.pausedAt, kind: "subscription", title: "Subscription paused", tone: "neutral" });
2971
3214
  }
2972
3215
  if (s.cancelledAt) {
2973
- ev.push({ id: `sub-cancelled-${s.id}`, at: s.cancelledAt, kind: "subscription", title: "Subscription cancelled", tone: "danger" });
3216
+ ev.push({ id: `sub-cancelled-${s.id}`, at: s.cancelledAt, kind: "subscription", title: "Subscription canceled", tone: "danger" });
2974
3217
  }
2975
3218
  for (const a of s.billingAttempts ?? []) {
2976
3219
  if (a.status === "succeeded") continue;
@@ -3170,17 +3413,17 @@ function useMemberPortalData() {
3170
3413
  }
3171
3414
 
3172
3415
  // src/flows/updatePaymentMethod.ts
3173
- import { createEffect as createEffect6, createSignal as createSignal9 } from "solid-js";
3416
+ import { createEffect as createEffect8, createSignal as createSignal10 } from "solid-js";
3174
3417
  function useUpdatePaymentMethodFlow(subscriptionId) {
3175
3418
  const accept = useCardTokenizer();
3176
- const [cardNumber, setCardNumberRaw] = createSignal9("");
3177
- const [expiry, setExpiryRaw] = createSignal9("");
3178
- const [cvv, setCvvRaw] = createSignal9("");
3179
- const [submitting, setSubmitting] = createSignal9(false);
3180
- const [error, setError] = createSignal9(null);
3419
+ const [cardNumber, setCardNumberRaw] = createSignal10("");
3420
+ const [expiry, setExpiryRaw] = createSignal10("");
3421
+ const [cvv, setCvvRaw] = createSignal10("");
3422
+ const [submitting, setSubmitting] = createSignal10(false);
3423
+ const [error, setError] = createSignal10(null);
3181
3424
  const billing = useAddressPair();
3182
- const [billingLoaded, setBillingLoaded] = createSignal9(false);
3183
- createEffect6(() => {
3425
+ const [billingLoaded, setBillingLoaded] = createSignal10(false);
3426
+ createEffect8(() => {
3184
3427
  const id = subscriptionId();
3185
3428
  if (!id || billingLoaded()) return;
3186
3429
  void (async () => {
@@ -3255,7 +3498,7 @@ function useUpdatePaymentMethodFlow(subscriptionId) {
3255
3498
  }
3256
3499
 
3257
3500
  // src/flows/messages.ts
3258
- import { createSignal as createSignal10, onMount as onMount8, onCleanup as onCleanup2 } from "solid-js";
3501
+ import { createSignal as createSignal11, onMount as onMount8, onCleanup as onCleanup3 } from "solid-js";
3259
3502
 
3260
3503
  // src/flows/supportRealtime.ts
3261
3504
  var TOKEN_REFRESH_MS = 4 * 60 * 1e3;
@@ -3264,10 +3507,12 @@ async function subscribeToSupportTopic(topic, onPing) {
3264
3507
  try {
3265
3508
  const config = await supportApi.getRealtimeToken();
3266
3509
  if (!config?.token || !config.url || !config.anonKey) return null;
3510
+ const topicName = typeof topic === "string" ? topic : config.topics ? topic(config.topics) : void 0;
3511
+ if (!topicName) return null;
3267
3512
  const { createClient } = await import("@supabase/supabase-js");
3268
3513
  const client = createClient(config.url, config.anonKey);
3269
3514
  await client.realtime.setAuth(config.token);
3270
- const channel = client.channel(topic, {
3515
+ const channel = client.channel(topicName, {
3271
3516
  config: { private: true }
3272
3517
  });
3273
3518
  channel.on("broadcast", { event: "thread_updated" }, (message) => {
@@ -3424,15 +3669,15 @@ function useMessagesThread(options = {}) {
3424
3669
  const conversationPollMs = options.pollIntervalMs?.conversations ?? DEFAULT_CONVERSATION_POLL_MS;
3425
3670
  const messagePollMs = options.pollIntervalMs?.messages ?? DEFAULT_MESSAGE_POLL_MS;
3426
3671
  const autoPoll = options.autoPoll !== false;
3427
- const [conversations, setConversations] = createSignal10([]);
3428
- const [selectedId, setSelectedId] = createSignal10(null);
3429
- const [messages, setMessages] = createSignal10([]);
3430
- const [draft, setDraft] = createSignal10("");
3431
- const [loadingConversations, setLoadingConversations] = createSignal10(true);
3432
- const [loadingMessages, setLoadingMessages] = createSignal10(false);
3433
- const [sending, setSending] = createSignal10(false);
3434
- const [startingThread, setStartingThread] = createSignal10(false);
3435
- const [startingCareTeamThread, setStartingCareTeamThread] = createSignal10(false);
3672
+ const [conversations, setConversations] = createSignal11([]);
3673
+ const [selectedId, setSelectedId] = createSignal11(null);
3674
+ const [messages, setMessages] = createSignal11([]);
3675
+ const [draft, setDraft] = createSignal11("");
3676
+ const [loadingConversations, setLoadingConversations] = createSignal11(true);
3677
+ const [loadingMessages, setLoadingMessages] = createSignal11(false);
3678
+ const [sending, setSending] = createSignal11(false);
3679
+ const [startingThread, setStartingThread] = createSignal11(false);
3680
+ const [startingCareTeamThread, setStartingCareTeamThread] = createSignal11(false);
3436
3681
  let pendingDeepLinkId = readDeepLinkedConversationId();
3437
3682
  let convoPollTimer;
3438
3683
  let msgPollTimer;
@@ -3732,7 +3977,7 @@ function useMessagesThread(options = {}) {
3732
3977
  }, conversationPollMs);
3733
3978
  }
3734
3979
  });
3735
- onCleanup2(() => {
3980
+ onCleanup3(() => {
3736
3981
  if (convoPollTimer) clearInterval(convoPollTimer);
3737
3982
  if (msgPollTimer) clearInterval(msgPollTimer);
3738
3983
  void stopRealtime();
@@ -3763,10 +4008,234 @@ function useMessagesThread(options = {}) {
3763
4008
  };
3764
4009
  }
3765
4010
 
4011
+ // src/flows/products.ts
4012
+ import { createMemo, createResource as createResource3, createSignal as createSignal12 } from "solid-js";
4013
+ function priceForDosage(product, dosage) {
4014
+ const overlay = (product.dosage_prices ?? []).find((d) => d.dosage === dosage);
4015
+ if (overlay && overlay.price != null) return overlay.price;
4016
+ return product.price;
4017
+ }
4018
+ function lowestPrice(product) {
4019
+ const available = product.available_dosages ?? [];
4020
+ if (available.length === 0) return product.price;
4021
+ let min = null;
4022
+ for (const dose of available) {
4023
+ const p = priceForDosage(product, dose);
4024
+ if (p != null && (min == null || p < min)) min = p;
4025
+ }
4026
+ return min ?? product.price;
4027
+ }
4028
+ function salePriceForBase(product, basePrice) {
4029
+ if (basePrice == null || !product.activeSale) return null;
4030
+ const sale = product.activeSale;
4031
+ const baseCents = Math.round(basePrice * 100);
4032
+ if (sale.discountCents <= 0) return null;
4033
+ if (product.salePriceCents != null && product.price != null && Math.abs(product.price - basePrice) < 1e-3) {
4034
+ return product.salePriceCents / 100;
4035
+ }
4036
+ if (product.price != null && product.salePriceCents != null && product.price > 0) {
4037
+ const ratio = product.salePriceCents / Math.round(product.price * 100);
4038
+ return Math.max(0, basePrice * ratio);
4039
+ }
4040
+ return Math.max(0, (baseCents - sale.discountCents) / 100);
4041
+ }
4042
+ function lowestSalePrice(product, basePrice) {
4043
+ return salePriceForBase(product, basePrice);
4044
+ }
4045
+ function useCatalog() {
4046
+ const [products] = createResource3(async () => {
4047
+ try {
4048
+ const res = await productsApi.list();
4049
+ return res.products;
4050
+ } catch {
4051
+ return [];
4052
+ }
4053
+ });
4054
+ const weightLoss = () => (products() ?? []).filter((p) => (p.categories ?? []).includes("weight-loss"));
4055
+ const peptides = () => (products() ?? []).filter((p) => !(p.categories ?? []).includes("weight-loss"));
4056
+ const filterByCategory = (slug) => (products() ?? []).filter((p) => (p.categories ?? []).includes(slug));
4057
+ return { products, weightLoss, peptides, filterByCategory };
4058
+ }
4059
+ function useProductDetail(productId) {
4060
+ const [product] = createResource3(productId, async (id) => {
4061
+ if (!id) return null;
4062
+ try {
4063
+ const res = await productsApi.list();
4064
+ return res.products.find((p) => p.id === id) ?? null;
4065
+ } catch {
4066
+ return null;
4067
+ }
4068
+ });
4069
+ const pricingMode = createMemo(
4070
+ () => product()?.pricing_mode ?? "per_dose"
4071
+ );
4072
+ const dosageOptions = createMemo(() => {
4073
+ const p = product();
4074
+ if (!p) return [];
4075
+ const all = (p.available_dosages ?? []).map((dosage) => {
4076
+ const overlay = (p.dosage_prices ?? []).find((d) => d.dosage === dosage);
4077
+ const price = overlay && overlay.price != null ? overlay.price : p.price;
4078
+ return { dosage, price, savingsPrice: overlay?.savingsPrice ?? null };
4079
+ }).filter((o) => o.price != null);
4080
+ if (pricingMode() !== "flat_fee" || all.length === 0) return all;
4081
+ const override = p.dosage_override;
4082
+ const chosen = override && all.find((d) => d.dosage === override) || all[0];
4083
+ return [chosen];
4084
+ });
4085
+ const [selectedDosage, setSelectedDosage] = createSignal12("");
4086
+ createMemo(() => {
4087
+ const opts = dosageOptions();
4088
+ if (opts.length > 0 && !selectedDosage()) setSelectedDosage(opts[0].dosage);
4089
+ });
4090
+ const selectedPrice = createMemo(() => {
4091
+ const opts = dosageOptions();
4092
+ const chosen = opts.find((d) => d.dosage === selectedDosage());
4093
+ if (chosen) return chosen.price;
4094
+ return product()?.price ?? null;
4095
+ });
4096
+ const selectedSalePrice = createMemo(() => {
4097
+ const p = product();
4098
+ const base = selectedPrice();
4099
+ if (!p || base == null || !p.activeSale) return null;
4100
+ if (p.salePriceCents != null && p.price != null && p.price > 0) {
4101
+ const ratio = p.salePriceCents / Math.round(p.price * 100);
4102
+ return Math.max(0, base * ratio);
4103
+ }
4104
+ return Math.max(0, base - p.activeSale.discountCents / 100);
4105
+ });
4106
+ const inCart = createMemo(() => {
4107
+ const p = product();
4108
+ if (!p) return false;
4109
+ const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? "");
4110
+ const key = cart_default.itemKey(p.id, dosage);
4111
+ return cart_default.items().some((i) => cart_default.itemKey(i.productId, i.dosage) === key);
4112
+ });
4113
+ function addToCart() {
4114
+ const p = product();
4115
+ if (!p) return;
4116
+ const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? "");
4117
+ const effective = selectedSalePrice() ?? selectedPrice() ?? 0;
4118
+ const priceCents = Math.round(effective * 100);
4119
+ cart_default.add({
4120
+ productId: p.id,
4121
+ productName: p.name,
4122
+ dosage,
4123
+ quantity: 1,
4124
+ priceCents,
4125
+ drugId: p.id,
4126
+ apexDrugId: p.apex_drug_id ?? null,
4127
+ categories: p.categories ?? [],
4128
+ thumbnailUrl: p.thumbnail_url ?? void 0,
4129
+ hideDoseLabel: pricingMode() === "flat_fee" ? true : void 0,
4130
+ isSubscription: p.is_subscription ? true : void 0
4131
+ });
4132
+ cart_default.open();
4133
+ }
4134
+ return {
4135
+ product,
4136
+ dosageOptions,
4137
+ selectedDosage,
4138
+ setSelectedDosage,
4139
+ selectedPrice,
4140
+ selectedSalePrice,
4141
+ pricingMode,
4142
+ inCart,
4143
+ addToCart
4144
+ };
4145
+ }
4146
+ function useMedicationSelect(options = {}) {
4147
+ const catalog = useCatalog();
4148
+ function selectMedication(product) {
4149
+ medication_default.select({ drugId: product.id, drugName: product.name });
4150
+ options.onSelected?.();
4151
+ }
4152
+ function selectGeneralConsultation() {
4153
+ medication_default.select({
4154
+ drugId: null,
4155
+ drugName: options.generalConsultationLabel ?? "General Consultation"
4156
+ });
4157
+ options.onSelected?.();
4158
+ }
4159
+ return {
4160
+ products: catalog.products,
4161
+ weightLoss: catalog.weightLoss,
4162
+ peptides: catalog.peptides,
4163
+ selectMedication,
4164
+ selectGeneralConsultation
4165
+ };
4166
+ }
4167
+
4168
+ // src/flows/cartReconcile.ts
4169
+ import { createResource as createResource4 } from "solid-js";
4170
+ function snapshotChanged(before, after) {
4171
+ return before.productName !== after.productName || before.priceCents !== after.priceCents || (before.apexDrugId ?? null) !== (after.apexDrugId ?? null) || !!before.isSubscription !== !!after.isSubscription || !!before.hideDoseLabel !== !!after.hideDoseLabel;
4172
+ }
4173
+ function reconcileCartLines(items, products, opts = {}) {
4174
+ const byId = new Map(products.map((p) => [p.id, p]));
4175
+ const kept = [];
4176
+ const dropped = [];
4177
+ const refreshed = [];
4178
+ for (const item of items) {
4179
+ const product = byId.get(item.productId);
4180
+ if (!product) {
4181
+ dropped.push({ item, reason: "unavailable" });
4182
+ continue;
4183
+ }
4184
+ if (opts.requireApexDrug && !product.apex_drug_id) {
4185
+ dropped.push({ item, reason: "not_prescribable" });
4186
+ continue;
4187
+ }
4188
+ const base = priceForDosage(product, item.dosage);
4189
+ if (base == null) {
4190
+ dropped.push({ item, reason: "unpriced" });
4191
+ continue;
4192
+ }
4193
+ const effective = salePriceForBase(product, base) ?? base;
4194
+ const next = {
4195
+ ...item,
4196
+ productName: product.name,
4197
+ priceCents: Math.round(effective * 100),
4198
+ apexDrugId: product.apex_drug_id ?? null,
4199
+ categories: product.categories ?? [],
4200
+ thumbnailUrl: product.thumbnail_url ?? void 0,
4201
+ hideDoseLabel: product.pricing_mode === "flat_fee" ? true : void 0,
4202
+ isSubscription: product.is_subscription ? true : void 0
4203
+ };
4204
+ if (snapshotChanged(item, next)) refreshed.push(next);
4205
+ kept.push(next);
4206
+ }
4207
+ return { items: kept, dropped, refreshed, checked: true };
4208
+ }
4209
+ var UNCHECKED = { items: [], dropped: [], refreshed: [], checked: false };
4210
+ async function reconcileCartAgainstCatalog(opts = {}) {
4211
+ const items = cart_default.items();
4212
+ if (items.length === 0) return { ...UNCHECKED, checked: true };
4213
+ let products;
4214
+ try {
4215
+ products = (await productsApi.list()).products ?? [];
4216
+ } catch {
4217
+ return UNCHECKED;
4218
+ }
4219
+ if (products.length === 0) return UNCHECKED;
4220
+ const result = reconcileCartLines(items, products, opts);
4221
+ if (result.dropped.length > 0 || result.refreshed.length > 0) {
4222
+ cart_default.replace(result.items);
4223
+ }
4224
+ return result;
4225
+ }
4226
+ function useCartReconcile(opts = {}) {
4227
+ const [result] = createResource4(() => reconcileCartAgainstCatalog(opts));
4228
+ return {
4229
+ dropped: () => result()?.dropped ?? [],
4230
+ refreshed: () => result()?.refreshed ?? [],
4231
+ pending: () => result.loading
4232
+ };
4233
+ }
4234
+
3766
4235
  // src/flows/affiliate.ts
3767
- import { createResource as createResource3 } from "solid-js";
4236
+ import { createResource as createResource5 } from "solid-js";
3768
4237
  function useAffiliateStats() {
3769
- const [stats, { refetch }] = createResource3(
4238
+ const [stats, { refetch }] = createResource5(
3770
4239
  () => affiliateAuth_default.isAuthenticated(),
3771
4240
  async (authed) => {
3772
4241
  if (!authed) return null;
@@ -3781,7 +4250,7 @@ function useAffiliateStats() {
3781
4250
  return { stats, refetch: () => refetch() };
3782
4251
  }
3783
4252
  function useAffiliateConversions(opts) {
3784
- const [conversions, { refetch }] = createResource3(
4253
+ const [conversions, { refetch }] = createResource5(
3785
4254
  () => affiliateAuth_default.isAuthenticated(),
3786
4255
  async (authed, _info) => {
3787
4256
  if (!authed) return [];
@@ -3796,7 +4265,7 @@ function useAffiliateConversions(opts) {
3796
4265
  return { conversions, refetch: () => refetch() };
3797
4266
  }
3798
4267
  function useAffiliateDownline() {
3799
- const [downline, { refetch }] = createResource3(
4268
+ const [downline, { refetch }] = createResource5(
3800
4269
  () => affiliateAuth_default.isAuthenticated(),
3801
4270
  async (authed) => {
3802
4271
  if (!authed) return [];
@@ -3811,7 +4280,7 @@ function useAffiliateDownline() {
3811
4280
  return { downline, refetch: () => refetch() };
3812
4281
  }
3813
4282
  function useAffiliateLinks() {
3814
- const [links, { refetch }] = createResource3(
4283
+ const [links, { refetch }] = createResource5(
3815
4284
  () => affiliateAuth_default.isAuthenticated(),
3816
4285
  async (authed) => {
3817
4286
  if (!authed) return null;
@@ -3825,6 +4294,45 @@ function useAffiliateLinks() {
3825
4294
  return { links, refetch: () => refetch() };
3826
4295
  }
3827
4296
 
4297
+ // src/flows/categoryVisual.ts
4298
+ function hashId(id) {
4299
+ let h = 5381;
4300
+ for (let i = 0; i < id.length; i++) h = (h << 5) + h + id.charCodeAt(i) | 0;
4301
+ return Math.abs(h);
4302
+ }
4303
+ var DEFAULT_COLOR_PALETTE = [
4304
+ "#4f46e5",
4305
+ // indigo
4306
+ "#0891b2",
4307
+ // cyan
4308
+ "#0d9488",
4309
+ // teal
4310
+ "#f59e0b",
4311
+ // amber
4312
+ "#e11d48",
4313
+ // rose
4314
+ "#10b981",
4315
+ // emerald
4316
+ "#8b5cf6",
4317
+ // violet
4318
+ "#f97316"
4319
+ // orange
4320
+ ];
4321
+ function categoryColor(id, opts = {}) {
4322
+ const palette = opts.palette ?? DEFAULT_COLOR_PALETTE;
4323
+ if (palette.length === 0) return "currentColor";
4324
+ return palette[hashId(id) % palette.length];
4325
+ }
4326
+ function isCssColorValue(value) {
4327
+ return /^(#[0-9a-f]{3,8}|(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([^;{}()]*\)|var\(--[\w-]+\))$/i.test(
4328
+ value.trim()
4329
+ );
4330
+ }
4331
+ function resolveCategoryColor(category, opts = {}) {
4332
+ const set = category.color?.trim();
4333
+ return set && isCssColorValue(set) ? set : categoryColor(category.id, opts);
4334
+ }
4335
+
3828
4336
  // src/flows/funnel.ts
3829
4337
  var FORWARDED = /* @__PURE__ */ new Set([
3830
4338
  "survey:loaded",
@@ -4053,6 +4561,9 @@ export {
4053
4561
  hasErrors,
4054
4562
  firstAddressError,
4055
4563
  useAddressPair,
4564
+ deriveCatalogAvailabilityDecision,
4565
+ useCatalogAvailability,
4566
+ catalogUnavailableMessage,
4056
4567
  formatCardNumber,
4057
4568
  formatExpiry,
4058
4569
  formatCvv,
@@ -4087,16 +4598,30 @@ export {
4087
4598
  buildTimeline,
4088
4599
  useMemberPortalData,
4089
4600
  useUpdatePaymentMethodFlow,
4601
+ subscribeToSupportTopic,
4090
4602
  SUPPORT_CATEGORIES,
4091
4603
  categoryLabel,
4092
4604
  isImageAttachment,
4093
4605
  formatConversationTime,
4094
4606
  formatMessageTime,
4095
4607
  useMessagesThread,
4608
+ lowestPrice,
4609
+ salePriceForBase,
4610
+ lowestSalePrice,
4611
+ useCatalog,
4612
+ useProductDetail,
4613
+ useMedicationSelect,
4614
+ reconcileCartLines,
4615
+ reconcileCartAgainstCatalog,
4616
+ useCartReconcile,
4096
4617
  useAffiliateStats,
4097
4618
  useAffiliateConversions,
4098
4619
  useAffiliateDownline,
4099
4620
  useAffiliateLinks,
4621
+ DEFAULT_COLOR_PALETTE,
4622
+ categoryColor,
4623
+ isCssColorValue,
4624
+ resolveCategoryColor,
4100
4625
  createFunnelTelemetry,
4101
4626
  captureFunnelEmail,
4102
4627
  emailGateAnswered,
@@ -4107,4 +4632,4 @@ export {
4107
4632
  useSurveyV2Flow,
4108
4633
  uploadPrescriptionPhoto
4109
4634
  };
4110
- //# sourceMappingURL=HXMLRDIJ.jsx.map
4635
+ //# sourceMappingURL=AW6DQGQR.jsx.map