@apextelemed/partner-core 0.19.0-dev.61 → 0.19.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 (51) hide show
  1. package/dist/api/index.d.ts +23 -2
  2. package/dist/api/index.js +4 -4
  3. package/dist/api/index.jsx +8 -4
  4. package/dist/chunk/{HEQLEGHI.js → BTDK3J34.js} +51 -3
  5. package/dist/chunk/BTDK3J34.js.map +1 -0
  6. package/dist/chunk/ESNAWOHG.jsx +1 -0
  7. package/dist/chunk/{TFJKTKZ3.jsx → FKEDRIA7.jsx} +2986 -2099
  8. package/dist/chunk/{CDRUVUTJ.js → FZ4LIOG2.js} +18 -8
  9. package/dist/chunk/FZ4LIOG2.js.map +1 -0
  10. package/dist/chunk/{OZHJ5IGL.jsx → HEXXZYK4.jsx} +370 -131
  11. package/dist/chunk/{ZWAZNB4Y.jsx → HSBATWVL.jsx} +2 -2
  12. package/dist/chunk/{WTHAR2P2.js → LJAMZMRF.js} +3 -3
  13. package/dist/chunk/{WTHAR2P2.js.map → LJAMZMRF.js.map} +1 -1
  14. package/dist/chunk/{33BDC6MT.jsx → MVWCKLRH.jsx} +2 -2
  15. package/dist/chunk/{GJSE37VN.js → O2VF7KNG.js} +3 -3
  16. package/dist/chunk/{GJSE37VN.js.map → O2VF7KNG.js.map} +1 -1
  17. package/dist/chunk/{UZ2K7HBG.js → P6YCW73X.js} +2475 -1202
  18. package/dist/chunk/P6YCW73X.js.map +1 -0
  19. package/dist/chunk/{X6WJQ47H.jsx → PZ4BRSEK.jsx} +50 -2
  20. package/dist/chunk/{EED3KNR7.jsx → UAZK2UTR.jsx} +41 -3
  21. package/dist/chunk/{VGF2LLAD.js → WM5KNUNX.js} +240 -14
  22. package/dist/chunk/WM5KNUNX.js.map +1 -0
  23. package/dist/chunk/{OOMMZESR.js → WUVYCWKW.js} +40 -4
  24. package/dist/chunk/WUVYCWKW.js.map +1 -0
  25. package/dist/chunk/XZVVZIRZ.js +3 -0
  26. package/dist/chunk/XZVVZIRZ.js.map +1 -0
  27. package/dist/chunk/{LA6F37YV.jsx → ZEQ5TNDM.jsx} +20 -7
  28. package/dist/{client-CMbSYUam.d.ts → client-C0MG1mOg.d.ts} +178 -2
  29. package/dist/flows/index.d.ts +113 -2
  30. package/dist/flows/index.js +6 -6
  31. package/dist/flows/index.jsx +14 -6
  32. package/dist/index/index.d.ts +26 -5
  33. package/dist/index/index.js +8 -8
  34. package/dist/index/index.jsx +22 -8
  35. package/dist/pages/index.d.ts +2 -2
  36. package/dist/pages/index.js +5 -5
  37. package/dist/pages/index.jsx +5 -5
  38. package/dist/stores/index.d.ts +1 -1
  39. package/dist/stores/index.js +2 -2
  40. package/dist/stores/index.jsx +2 -2
  41. package/dist/theme/admin.css +3 -0
  42. package/dist/theme/member-portal.css +43 -0
  43. package/package.json +1 -1
  44. package/dist/chunk/ACE7M2YA.jsx +0 -1
  45. package/dist/chunk/CDRUVUTJ.js.map +0 -1
  46. package/dist/chunk/HEQLEGHI.js.map +0 -1
  47. package/dist/chunk/JSHO46VZ.js +0 -3
  48. package/dist/chunk/JSHO46VZ.js.map +0 -1
  49. package/dist/chunk/OOMMZESR.js.map +0 -1
  50. package/dist/chunk/UZ2K7HBG.js.map +0 -1
  51. package/dist/chunk/VGF2LLAD.js.map +0 -1
@@ -292,6 +292,9 @@ var ApiError = class extends Error {
292
292
  /** The response body's `details`, untouched, for the few refusals whose
293
293
  * specifics a caller acts on (e.g. which prices are missing). Never shown as prose. */
294
294
  details;
295
+ /** The response body's `reason`, when the endpoint names why it refused (e.g.
296
+ * `stale_text` on a text-message consent). Branch on this, never on message. */
297
+ reason;
295
298
  constructor(message, opts = {}) {
296
299
  super(message);
297
300
  this.name = "ApiError";
@@ -299,6 +302,7 @@ var ApiError = class extends Error {
299
302
  this.ambiguous = opts.ambiguous ?? false;
300
303
  this.code = opts.code;
301
304
  this.details = opts.details;
305
+ this.reason = opts.reason;
302
306
  if (opts.cause !== void 0) this.cause = opts.cause;
303
307
  }
304
308
  };
@@ -376,11 +380,13 @@ async function coreFetch(endpoint, fetchOpts, track, call = {}) {
376
380
  let errorMsg = `Request failed: ${res.status}`;
377
381
  let errorCode;
378
382
  let errorDetails;
383
+ let errorReason;
379
384
  try {
380
385
  const body = await res.json();
381
386
  errorMsg = body.error || body.message || errorMsg;
382
387
  errorCode = typeof body.code === "string" ? body.code : void 0;
383
388
  errorDetails = body.details;
389
+ errorReason = typeof body.reason === "string" ? body.reason : void 0;
384
390
  if (track.enrichErrorDetails && Array.isArray(body.details) && body.details.length > 0) {
385
391
  const lines = body.details.map(
386
392
  (d) => typeof d === "string" ? d : d?.message
@@ -396,7 +402,8 @@ async function coreFetch(endpoint, fetchOpts, track, call = {}) {
396
402
  status: res.status,
397
403
  ambiguous: res.status >= 500,
398
404
  code: errorCode,
399
- ...errorDetails !== void 0 ? { details: errorDetails } : {}
405
+ ...errorDetails !== void 0 ? { details: errorDetails } : {},
406
+ ...errorReason !== void 0 ? { reason: errorReason } : {}
400
407
  });
401
408
  }
402
409
  if (res.status === 204) return void 0;
@@ -835,6 +842,13 @@ var usersApi = {
835
842
  },
836
843
  updateProfile(payload) {
837
844
  return patch("/users/me", payload);
845
+ },
846
+ getSmsState() {
847
+ return apiFetch("/users/me/sms");
848
+ },
849
+ /** Only the named events change; the reply is the full state again. */
850
+ setSmsEvents(events) {
851
+ return put("/users/me/sms/preferences", { events });
838
852
  }
839
853
  };
840
854
  var membersApi = {
@@ -980,6 +994,14 @@ var adminApi = {
980
994
  getRecurringRevenue() {
981
995
  return apiFetch("/admin/dashboard/recurring-revenue");
982
996
  },
997
+ /**
998
+ * Charges due on each of the next `days` days (1–92, default 31), bucketed by
999
+ * calendar day in `timeZone` (an IANA zone; default the browser's).
1000
+ */
1001
+ getBillingForecast(days = 31, timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone) {
1002
+ const q = new URLSearchParams({ days: String(days), tz: timeZone || "UTC" });
1003
+ return apiFetch(`/admin/dashboard/billing-forecast?${q}`);
1004
+ },
983
1005
  getCustomers(params) {
984
1006
  const query = params ? { ...params, facets: params.facets ? 1 : void 0 } : void 0;
985
1007
  return apiFetch(`/admin/customers${qs(query)}`);
@@ -1140,6 +1162,32 @@ var adminApi = {
1140
1162
  note ? { note } : {}
1141
1163
  );
1142
1164
  },
1165
+ // ── Text messages (settings.write / emailTemplates.write / patient.support) ──
1166
+ /** Is this site set up to text customers, and from what number. Needs `settings.write`. */
1167
+ getSmsSettings() {
1168
+ return apiFetch("/admin/sms/settings");
1169
+ },
1170
+ /** Every event's text, as saved. Needs `emailTemplates.write`. */
1171
+ getSmsTemplates() {
1172
+ return apiFetch("/admin/sms/templates");
1173
+ },
1174
+ /**
1175
+ * Change some events' texts. Send ONLY what changed: a missing event or field
1176
+ * is kept, `null` resets to the default. Rejects (400) with the server's
1177
+ * reason when a body doesn't start with `{{siteName}}`, runs past 300
1178
+ * characters, or uses a token the event doesn't have. Returns the full list.
1179
+ */
1180
+ saveSmsTemplates(templates) {
1181
+ return put("/admin/sms/templates", { templates });
1182
+ },
1183
+ /** Text the SAVED version of an event to the signed-in admin's own phone. */
1184
+ sendSmsTemplateTest(key) {
1185
+ return post(`/admin/sms/templates/${encodeURIComponent(key)}/test`);
1186
+ },
1187
+ /** The send log, newest first. Needs `patient.support`. Page with `nextBefore`. */
1188
+ listSmsMessages(params) {
1189
+ return apiFetch(`/admin/sms/messages${qs(params)}`);
1190
+ },
1143
1191
  getEmailNotifications() {
1144
1192
  return apiFetch("/admin/settings/email-notifications");
1145
1193
  },
@@ -1605,4 +1653,4 @@ export {
1605
1653
  clearAffiliateTokens,
1606
1654
  affiliatePortalApi
1607
1655
  };
1608
- //# sourceMappingURL=X6WJQ47H.jsx.map
1656
+ //# sourceMappingURL=PZ4BRSEK.jsx.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getTokens
3
- } from "./X6WJQ47H.jsx";
3
+ } from "./PZ4BRSEK.jsx";
4
4
  import {
5
5
  getConfig
6
6
  } from "./QVZ7BRNO.jsx";
@@ -141,6 +141,42 @@ function stripResumeToken() {
141
141
  }
142
142
  }
143
143
 
144
+ // src/api/sms.ts
145
+ var DISABLED2 = { enabled: false };
146
+ var str = (v) => typeof v === "string" && v.trim() ? v : void 0;
147
+ var configPromise2 = null;
148
+ function fetchSmsConfig() {
149
+ if (!configPromise2) {
150
+ configPromise2 = (async () => {
151
+ try {
152
+ const cfg = getConfig();
153
+ const res = await fetch(`${cfg.apiBase}/config/sms`, {
154
+ headers: { "X-Tenant-Key": cfg.tenantKey }
155
+ });
156
+ if (!res.ok) return DISABLED2;
157
+ const body = await res.json();
158
+ const consentText = str(body.consentText);
159
+ const consentTextVersion = str(body.consentTextVersion);
160
+ if (body.enabled !== true || !consentText || !consentTextVersion) return DISABLED2;
161
+ return {
162
+ enabled: true,
163
+ brandName: str(body.brandName),
164
+ consentText,
165
+ consentTextVersion,
166
+ termsUrl: str(body.termsUrl),
167
+ privacyUrl: str(body.privacyUrl)
168
+ };
169
+ } catch {
170
+ return DISABLED2;
171
+ }
172
+ })();
173
+ }
174
+ return configPromise2;
175
+ }
176
+ function resetSmsConfigCache() {
177
+ configPromise2 = null;
178
+ }
179
+
144
180
  export {
145
181
  fetchFunnelConfig,
146
182
  adoptFunnelSessionId,
@@ -152,6 +188,8 @@ export {
152
188
  saveFunnelDraft,
153
189
  fetchResumedDraft,
154
190
  readResumeToken,
155
- stripResumeToken
191
+ stripResumeToken,
192
+ fetchSmsConfig,
193
+ resetSmsConfigCache
156
194
  };
157
- //# sourceMappingURL=EED3KNR7.jsx.map
195
+ //# sourceMappingURL=UAZK2UTR.jsx.map
@@ -1,6 +1,6 @@
1
- import { fetchFunnelConfig, postFunnelEvent, readResumeToken, fetchResumedDraft, stripResumeToken, adoptFunnelSessionId, saveFunnelDraft } from './OOMMZESR.js';
2
- import { cart_default, medication_default, auth_default, affiliateAuth_default } from './GJSE37VN.js';
3
- import { newIdempotencyKey, apexApi, usersApi, addressesApi, catalogApi, paymentsApi, subscriptionsApi, membersApi, supportApi, productsApi, affiliatePortalApi, adminApi, adminCatalogApi, adminProductPharmaciesApi, ApiError, ordersApi, adminCatalogConversionApi, messagesApi, authApi } from './HEQLEGHI.js';
1
+ import { fetchSmsConfig, fetchFunnelConfig, postFunnelEvent, readResumeToken, fetchResumedDraft, stripResumeToken, adoptFunnelSessionId, saveFunnelDraft, resetSmsConfigCache } from './WUVYCWKW.js';
2
+ import { cart_default, medication_default, auth_default, affiliateAuth_default } from './O2VF7KNG.js';
3
+ import { newIdempotencyKey, apexApi, usersApi, addressesApi, catalogApi, paymentsApi, subscriptionsApi, membersApi, supportApi, productsApi, affiliatePortalApi, adminApi, adminCatalogApi, adminProductPharmaciesApi, ApiError, ordersApi, adminCatalogConversionApi, messagesApi, authApi } from './BTDK3J34.js';
4
4
  import { getConfig } from './2IFPDU4D.js';
5
5
  import { createSignal, onMount, createEffect, on, onCleanup, createResource, createMemo } from 'solid-js';
6
6
  import { useSurveyV2Flow as useSurveyV2Flow$1 } from '@apextelemed/survey-solid';
@@ -1512,6 +1512,83 @@ function useCartCheckoutFlow() {
1512
1512
  submit
1513
1513
  };
1514
1514
  }
1515
+
1516
+ // src/flows/phone.ts
1517
+ var PHONE_ERROR = "Enter a valid 10-digit US phone number.";
1518
+ function isValidUsPhone(raw) {
1519
+ const digits = raw.replace(/\D/g, "");
1520
+ return digits.length === 10 || digits.length === 11 && digits.startsWith("1");
1521
+ }
1522
+ function formatUsPhone(raw) {
1523
+ const digits = raw.replace(/\D/g, "");
1524
+ const ten = digits.length === 11 && digits.startsWith("1") ? digits.slice(1) : digits;
1525
+ if (ten.length !== 10) return raw;
1526
+ return `(${ten.slice(0, 3)}) ${ten.slice(3, 6)}-${ten.slice(6)}`;
1527
+ }
1528
+ function offerFromConfig(cfg) {
1529
+ if (!cfg.enabled || !cfg.consentText || !cfg.consentTextVersion) return null;
1530
+ return {
1531
+ text: cfg.consentText,
1532
+ textVersion: cfg.consentTextVersion,
1533
+ brandName: cfg.brandName,
1534
+ termsUrl: cfg.termsUrl,
1535
+ privacyUrl: cfg.privacyUrl
1536
+ };
1537
+ }
1538
+ var SMS_CONSENT_PHONE_HINT = "Enter a valid mobile number above to turn this on.";
1539
+ function useSmsConsent(phone, restoredVersion) {
1540
+ const [offer, setOffer] = createSignal(null);
1541
+ const [loaded, setLoaded] = createSignal(false);
1542
+ const [raw, setRaw] = createSignal(false);
1543
+ const phoneOk = () => isValidUsPhone(phone());
1544
+ const enabled = () => offer() !== null && phoneOk();
1545
+ onMount(() => {
1546
+ let alive = true;
1547
+ onCleanup(() => {
1548
+ alive = false;
1549
+ });
1550
+ void fetchSmsConfig().then((cfg) => {
1551
+ if (!alive) return;
1552
+ const next = offerFromConfig(cfg);
1553
+ if (next) {
1554
+ setOffer(next);
1555
+ if (restoredVersion && restoredVersion === next.textVersion && phoneOk()) setRaw(true);
1556
+ }
1557
+ setLoaded(true);
1558
+ });
1559
+ });
1560
+ createEffect(
1561
+ on(
1562
+ phoneOk,
1563
+ (ok) => {
1564
+ if (!ok) setRaw(false);
1565
+ },
1566
+ { defer: true }
1567
+ )
1568
+ );
1569
+ const checked = () => raw() && enabled();
1570
+ return {
1571
+ offer,
1572
+ checked,
1573
+ setChecked: (v) => {
1574
+ if (v && !enabled()) return;
1575
+ setRaw(v);
1576
+ },
1577
+ enabled,
1578
+ hint: () => offer() && !phoneOk() ? SMS_CONSENT_PHONE_HINT : null,
1579
+ grant: () => {
1580
+ const o = offer();
1581
+ return o && checked() ? { granted: true, textVersion: o.textVersion } : void 0;
1582
+ },
1583
+ draftVersion: () => {
1584
+ if (!loaded()) return restoredVersion;
1585
+ const o = offer();
1586
+ return o && checked() ? o.textVersion : void 0;
1587
+ }
1588
+ };
1589
+ }
1590
+
1591
+ // src/flows/signup.ts
1515
1592
  var DRAFT_TTL_MS = 7 * 24 * 3600 * 1e3;
1516
1593
  var MAX_RESTORABLE_STEP = 2;
1517
1594
  function draftKey() {
@@ -1558,6 +1635,7 @@ function useSignupFlow(options) {
1558
1635
  const [password, setPassword] = createSignal("");
1559
1636
  const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? "");
1560
1637
  const [phone, setPhone] = createSignal(restored.phone ?? "");
1638
+ const smsConsent = useSmsConsent(phone, restored.smsConsentVersion);
1561
1639
  const [street, setStreet] = createSignal(restored.street ?? "");
1562
1640
  const [city, setCity] = createSignal(restored.city ?? "");
1563
1641
  const [state, setState] = createSignal(restored.state ?? "");
@@ -1584,7 +1662,8 @@ function useSignupFlow(options) {
1584
1662
  street: street(),
1585
1663
  city: city(),
1586
1664
  state: state(),
1587
- zip: zip()
1665
+ zip: zip(),
1666
+ smsConsentVersion: smsConsent.draftVersion()
1588
1667
  });
1589
1668
  });
1590
1669
  });
@@ -1597,6 +1676,7 @@ function useSignupFlow(options) {
1597
1676
  if (!password().trim()) return "Password is required.";
1598
1677
  if (password().length < 8) return "Password must be at least 8 characters.";
1599
1678
  if (!phone().trim()) return "Phone number is required.";
1679
+ if (!isValidUsPhone(phone())) return PHONE_ERROR;
1600
1680
  if (!/^\d{4}-\d{2}-\d{2}$/.test(dateOfBirth())) return "Enter a valid date of birth.";
1601
1681
  const dob = /* @__PURE__ */ new Date(dateOfBirth() + "T00:00:00");
1602
1682
  if (Number.isNaN(dob.getTime())) return "Enter a valid date of birth.";
@@ -1699,6 +1779,7 @@ function useSignupFlow(options) {
1699
1779
  dosage: i.dosage
1700
1780
  })) : void 0;
1701
1781
  const savingsMemberId = options.savingsMemberId?.() || void 0;
1782
+ const smsGrant = smsConsent.grant();
1702
1783
  await auth_default.signupAndSubscribe(
1703
1784
  {
1704
1785
  email: email().trim(),
@@ -1725,7 +1806,8 @@ function useSignupFlow(options) {
1725
1806
  zip: zip().trim()
1726
1807
  },
1727
1808
  promoCode: promoCode().trim() || void 0,
1728
- ...savingsMemberId ? { savingsMemberId } : {}
1809
+ ...savingsMemberId ? { savingsMemberId } : {},
1810
+ ...smsGrant ? { smsConsent: smsGrant } : {}
1729
1811
  },
1730
1812
  { idempotencyKey: idempotencyKey() }
1731
1813
  );
@@ -1785,6 +1867,7 @@ function useSignupFlow(options) {
1785
1867
  setDateOfBirth,
1786
1868
  phone,
1787
1869
  setPhone,
1870
+ smsConsent,
1788
1871
  street,
1789
1872
  setStreet,
1790
1873
  city,
@@ -1848,6 +1931,7 @@ function useRegisterFlow() {
1848
1931
  const [password, setPassword] = createSignal("");
1849
1932
  const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? "");
1850
1933
  const [phone, setPhone] = createSignal(restored.phone ?? "");
1934
+ const smsConsent = useSmsConsent(phone, restored.smsConsentVersion);
1851
1935
  const [street, setStreet] = createSignal(restored.street ?? "");
1852
1936
  const [city, setCity] = createSignal(restored.city ?? "");
1853
1937
  const [state, setState] = createSignal(restored.state ?? "");
@@ -1868,7 +1952,8 @@ function useRegisterFlow() {
1868
1952
  street: street(),
1869
1953
  city: city(),
1870
1954
  state: state(),
1871
- zip: zip()
1955
+ zip: zip(),
1956
+ smsConsentVersion: smsConsent.draftVersion()
1872
1957
  });
1873
1958
  });
1874
1959
  });
@@ -1881,6 +1966,7 @@ function useRegisterFlow() {
1881
1966
  if (!password().trim()) return "Password is required.";
1882
1967
  if (password().length < 8) return "Password must be at least 8 characters.";
1883
1968
  if (!phone().trim()) return "Phone number is required.";
1969
+ if (!isValidUsPhone(phone())) return PHONE_ERROR;
1884
1970
  if (!/^\d{4}-\d{2}-\d{2}$/.test(dateOfBirth())) return "Enter a valid date of birth.";
1885
1971
  const dob = /* @__PURE__ */ new Date(dateOfBirth() + "T00:00:00");
1886
1972
  if (Number.isNaN(dob.getTime())) return "Enter a valid date of birth.";
@@ -1953,6 +2039,7 @@ function useRegisterFlow() {
1953
2039
  setSubmitting(true);
1954
2040
  setOutcome({ kind: "submitting" });
1955
2041
  try {
2042
+ const smsGrant = smsConsent.grant();
1956
2043
  await auth_default.signup({
1957
2044
  email: email().trim(),
1958
2045
  password: password(),
@@ -1965,7 +2052,8 @@ function useRegisterFlow() {
1965
2052
  city: city().trim(),
1966
2053
  state: state(),
1967
2054
  zip: zip().trim()
1968
- }
2055
+ },
2056
+ ...smsGrant ? { smsConsent: smsGrant } : {}
1969
2057
  });
1970
2058
  if (finishIfAuthenticated()) return;
1971
2059
  if (await reconcileViaLogin()) return;
@@ -2015,6 +2103,7 @@ function useRegisterFlow() {
2015
2103
  setDateOfBirth,
2016
2104
  phone,
2017
2105
  setPhone,
2106
+ smsConsent,
2018
2107
  street,
2019
2108
  setStreet,
2020
2109
  city,
@@ -5428,7 +5517,7 @@ var REVIEW_STAGES = ["ready_to_commit", "active_not_committed"];
5428
5517
  function useCatalogConversion(opts) {
5429
5518
  const [preview, setPreview] = createSignal(null);
5430
5519
  const [phase, setPhase] = createSignal({ kind: "rest" });
5431
- const [notice, setNotice] = createSignal(null);
5520
+ const [notice2, setNotice] = createSignal(null);
5432
5521
  const [matches, setMatches] = createSignal({});
5433
5522
  const [matchesPlan, setMatchesPlan] = createSignal(void 0);
5434
5523
  const [confirming, setConfirming] = createSignal(false);
@@ -5843,7 +5932,7 @@ function useCatalogConversion(opts) {
5843
5932
  return {
5844
5933
  state,
5845
5934
  preview,
5846
- notice,
5935
+ notice: notice2,
5847
5936
  dismissNotice: () => setNotice(null),
5848
5937
  busy,
5849
5938
  reload,
@@ -5967,7 +6056,7 @@ function classifyAddPharmacyError(err) {
5967
6056
  }
5968
6057
  function useAddPharmacy(opts) {
5969
6058
  const [state, setState] = createSignal({ kind: "idle" });
5970
- const [notice, setNotice] = createSignal(null);
6059
+ const [notice2, setNotice] = createSignal(null);
5971
6060
  const [drugs, setDrugs] = createSignal([]);
5972
6061
  const [drugsStatus, setDrugsStatus] = createSignal("idle");
5973
6062
  const [selected, setSelected] = createSignal("");
@@ -6241,7 +6330,7 @@ function useAddPharmacy(opts) {
6241
6330
  return {
6242
6331
  state,
6243
6332
  busy,
6244
- notice,
6333
+ notice: notice2,
6245
6334
  dismissNotice: () => setNotice(null),
6246
6335
  drugs,
6247
6336
  drugsStatus,
@@ -6275,7 +6364,144 @@ function useAddPharmacy(opts) {
6275
6364
  startOver
6276
6365
  };
6277
6366
  }
6367
+ var NOTICES = {
6368
+ needs_consent: "Your number was updated. Texts are off for the new number until you turn them on again.",
6369
+ stale_text: "Our text-message terms were updated. Please read the new wording and turn texts on again.",
6370
+ no_phone: "Add a mobile number before turning on texts.",
6371
+ unavailable: "Text messages are not available right now."
6372
+ };
6373
+ var notice = (kind) => ({ kind, message: NOTICES[kind] });
6374
+ function useSmsPreferences() {
6375
+ const [state, setState] = createSignal(null);
6376
+ const [offer, setOffer] = createSignal(null);
6377
+ const [loading, setLoading] = createSignal(true);
6378
+ const [busy, setBusy] = createSignal(false);
6379
+ const [error, setError] = createSignal(null);
6380
+ const [currentNotice, setNotice] = createSignal(null);
6381
+ let alive = true;
6382
+ onCleanup(() => {
6383
+ alive = false;
6384
+ });
6385
+ async function refresh() {
6386
+ const next = await usersApi.getSmsState();
6387
+ if (alive) setState(next);
6388
+ }
6389
+ async function reload() {
6390
+ setLoading(true);
6391
+ try {
6392
+ const [next, cfg] = await Promise.all([usersApi.getSmsState(), fetchSmsConfig()]);
6393
+ if (!alive) return;
6394
+ setState(next);
6395
+ setOffer(offerFromConfig(cfg));
6396
+ } catch {
6397
+ if (alive) setState(null);
6398
+ } finally {
6399
+ if (alive) setLoading(false);
6400
+ }
6401
+ }
6402
+ onMount(() => void reload());
6403
+ async function run(fn) {
6404
+ if (busy()) return false;
6405
+ setBusy(true);
6406
+ setError(null);
6407
+ setNotice(null);
6408
+ try {
6409
+ return await fn() !== false;
6410
+ } catch (err) {
6411
+ setError(err instanceof Error ? err.message : "Something went wrong. Please try again.");
6412
+ return false;
6413
+ } finally {
6414
+ if (alive) setBusy(false);
6415
+ }
6416
+ }
6417
+ async function refused(reason) {
6418
+ if (reason === "stale_text") {
6419
+ resetSmsConfigCache();
6420
+ const cfg = await fetchSmsConfig();
6421
+ if (alive) setOffer(offerFromConfig(cfg));
6422
+ setNotice(notice("stale_text"));
6423
+ } else if (reason === "no_phone") {
6424
+ setNotice(notice("no_phone"));
6425
+ } else {
6426
+ setNotice(notice("unavailable"));
6427
+ await refresh().catch(() => {
6428
+ });
6429
+ }
6430
+ }
6431
+ async function setPhone(raw) {
6432
+ const phone = raw.trim();
6433
+ if (busy()) return false;
6434
+ if (!isValidUsPhone(phone)) {
6435
+ setNotice(null);
6436
+ setError(PHONE_ERROR);
6437
+ return false;
6438
+ }
6439
+ return run(async () => {
6440
+ const hadConsent = state()?.consented === true;
6441
+ await usersApi.updateProfile({ phone });
6442
+ await refresh();
6443
+ if (hadConsent && state()?.consented !== true) setNotice(notice("needs_consent"));
6444
+ });
6445
+ }
6446
+ async function optIn() {
6447
+ return run(async () => {
6448
+ const shown = offer();
6449
+ if (!shown) {
6450
+ setNotice(notice("unavailable"));
6451
+ return false;
6452
+ }
6453
+ try {
6454
+ const res = await usersApi.updateProfile({
6455
+ smsConsent: { granted: true, textVersion: shown.textVersion, source: "profile" }
6456
+ });
6457
+ if (res?.smsConsent?.status === "refused") {
6458
+ await refused(res.smsConsent.reason);
6459
+ return false;
6460
+ }
6461
+ } catch (err) {
6462
+ if (err instanceof ApiError && err.status === 409) {
6463
+ await refused(err.reason);
6464
+ return false;
6465
+ }
6466
+ throw err;
6467
+ }
6468
+ await refresh();
6469
+ });
6470
+ }
6471
+ async function optOut() {
6472
+ return run(async () => {
6473
+ await usersApi.updateProfile({ smsConsent: { granted: false } });
6474
+ await refresh();
6475
+ });
6476
+ }
6477
+ async function setEvent(key, enabled) {
6478
+ return run(async () => {
6479
+ const next = await usersApi.setSmsEvents({ [key]: enabled });
6480
+ if (alive) setState(next);
6481
+ });
6482
+ }
6483
+ return {
6484
+ loading,
6485
+ state,
6486
+ available: () => state()?.available === true,
6487
+ phone: () => state()?.phone ?? null,
6488
+ consented: () => state()?.consented === true,
6489
+ optedOutByStop: () => state()?.optedOutByStop === true,
6490
+ fromNumber: () => state()?.fromNumber,
6491
+ events: () => state()?.events ?? [],
6492
+ showEvents: () => state()?.consented === true && state()?.optedOutByStop !== true,
6493
+ consentOffer: offer,
6494
+ busy,
6495
+ error,
6496
+ notice: currentNotice,
6497
+ reload,
6498
+ setPhone,
6499
+ optIn,
6500
+ optOut,
6501
+ setEvent
6502
+ };
6503
+ }
6278
6504
 
6279
- export { ACCOUNT_SOURCE_LABEL, DEFAULT_COLOR_PALETTE, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MATCH_DEPENDENT_WARNINGS, MATCH_HOW_LABEL, ORPHAN_REASON, READINESS_LABEL, SOURCE_FIELD_NOTE, SUPPORT_CATEGORIES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, addCatalogItemAsProduct, applyPriceDrafts, availableStateOptions, availableStates, bestOfferDiscount, buildFulfillmentRows, buildMatrixView, buildRefillView, buildSaveBody, buildStrengthRows, buildTimeline, buildTrackerView, buildTrackingUrl, canLeaveUnmatched, canOfferConversion, captureFunnelEmail, catalogUnavailableMessage, categoryColor, categoryLabel, classifyAddPharmacyError, classifyCatalogError, classifyConversionError, compareStrengths, createCatalogProduct, createFunnelTelemetry, deriveAttention, deriveCatalogAvailabilityDecision, deriveJourney, describeConversion, emailGateAnswered, explainFinding, findStoredDosePrice, firstAddressError, flaggedSubscribers, fmtDay, formatCalendarDate, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, groupDrugsByPharmacy, hasBlockers, hasConversion, hasErrors, hasStateRestrictions, initialMatches, intakeEvidence, invalidDraftKeys, isCatalogItemId, isCssColorValue, isImageAttachment, isLive, isQuestionVisible, isReconcilable, lifecycleReason, liveDoses, lowestPrice, lowestSalePrice, markEmailGateAnswered, matchKey, matchProblem, matchesComplete, missingPrices, moveInOrder, needsReview, normalizeState, normalizeStates, offerBeatsPromo, offerDurationText, offerSummaryText, orphanKey, parseMoney, pharmacyIsOnProduct, pharmacyLabel, primarySubscription, readinessStatus, reconcileCartAgainstCatalog, reconcileCartLines, redeemResumeLink, removeStoredDosePrice, resetResumeRedemption, resolveCategoryColor, resolveStrengthPrices, resolveSurveyV2DrugIntent, salePriceForBase, skuBindingModeFor, sourceKey, sourceLabel, stateAvailabilityNote, strengthsChanged, subscribeToSupportTopic, toChoices, toTrackerRequest, uploadPrescriptionPhoto, upsertDosePrice, useAddPharmacy, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCardTokenizer, useCartCheckoutFlow, useCartReconcile, useCatalog, useCatalogAvailability, useCatalogConversion, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductCatalogEditor, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress, visibleWarnings };
6280
- //# sourceMappingURL=VGF2LLAD.js.map
6281
- //# sourceMappingURL=VGF2LLAD.js.map
6505
+ export { ACCOUNT_SOURCE_LABEL, DEFAULT_COLOR_PALETTE, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MATCH_DEPENDENT_WARNINGS, MATCH_HOW_LABEL, ORPHAN_REASON, PHONE_ERROR, READINESS_LABEL, SOURCE_FIELD_NOTE, SUPPORT_CATEGORIES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, addCatalogItemAsProduct, applyPriceDrafts, availableStateOptions, availableStates, bestOfferDiscount, buildFulfillmentRows, buildMatrixView, buildRefillView, buildSaveBody, buildStrengthRows, buildTimeline, buildTrackerView, buildTrackingUrl, canLeaveUnmatched, canOfferConversion, captureFunnelEmail, catalogUnavailableMessage, categoryColor, categoryLabel, classifyAddPharmacyError, classifyCatalogError, classifyConversionError, compareStrengths, createCatalogProduct, createFunnelTelemetry, deriveAttention, deriveCatalogAvailabilityDecision, deriveJourney, describeConversion, emailGateAnswered, explainFinding, findStoredDosePrice, firstAddressError, flaggedSubscribers, fmtDay, formatCalendarDate, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, formatUsPhone, groupDrugsByPharmacy, hasBlockers, hasConversion, hasErrors, hasStateRestrictions, initialMatches, intakeEvidence, invalidDraftKeys, isCatalogItemId, isCssColorValue, isImageAttachment, isLive, isQuestionVisible, isReconcilable, isValidUsPhone, lifecycleReason, liveDoses, lowestPrice, lowestSalePrice, markEmailGateAnswered, matchKey, matchProblem, matchesComplete, missingPrices, moveInOrder, needsReview, normalizeState, normalizeStates, offerBeatsPromo, offerDurationText, offerSummaryText, orphanKey, parseMoney, pharmacyIsOnProduct, pharmacyLabel, primarySubscription, readinessStatus, reconcileCartAgainstCatalog, reconcileCartLines, redeemResumeLink, removeStoredDosePrice, resetResumeRedemption, resolveCategoryColor, resolveStrengthPrices, resolveSurveyV2DrugIntent, salePriceForBase, skuBindingModeFor, sourceKey, sourceLabel, stateAvailabilityNote, strengthsChanged, subscribeToSupportTopic, toChoices, toTrackerRequest, uploadPrescriptionPhoto, upsertDosePrice, useAddPharmacy, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCardTokenizer, useCartCheckoutFlow, useCartReconcile, useCatalog, useCatalogAvailability, useCatalogConversion, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductCatalogEditor, useProductDetail, useRegisterFlow, useSignupFlow, useSmsConsent, useSmsPreferences, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress, visibleWarnings };
6506
+ //# sourceMappingURL=WM5KNUNX.js.map
6507
+ //# sourceMappingURL=WM5KNUNX.js.map