@apextelemed/partner-core 0.15.0 → 0.16.0-dev.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/api/index.d.ts +1 -1
- package/dist/api/index.js +3 -3
- package/dist/api/index.jsx +5 -3
- package/dist/chunk/{JOPX73FC.jsx → 2RWPQQ4A.jsx} +5 -5
- package/dist/chunk/{WDB3G3X3.js → 46MIDHRD.js} +3 -3
- package/dist/chunk/{WDB3G3X3.js.map → 46MIDHRD.js.map} +1 -1
- package/dist/chunk/{DLP3Q3AT.js → AM5HSKWG.js} +6 -6
- package/dist/chunk/{DLP3Q3AT.js.map → AM5HSKWG.js.map} +1 -1
- package/dist/chunk/{OLSTMCLZ.jsx → AO3N6VTS.jsx} +24 -1
- package/dist/chunk/{YYWHDAAF.js → CXMAV5SC.js} +3 -3
- package/dist/chunk/{YYWHDAAF.js.map → CXMAV5SC.js.map} +1 -1
- package/dist/chunk/{CWPXPAUD.js → E6KLEFN3.js} +586 -6
- package/dist/chunk/E6KLEFN3.js.map +1 -0
- package/dist/chunk/{5ZJ7NC4S.jsx → HYN2BVTH.jsx} +2225 -1352
- package/dist/chunk/{CCRVBJ6A.jsx → KK36ZETG.jsx} +2 -2
- package/dist/chunk/{NCK4UJHA.jsx → MMPKHKIU.jsx} +2 -2
- package/dist/chunk/{NSWRAFQE.js → MPW4IVPB.js} +2533 -1132
- package/dist/chunk/MPW4IVPB.js.map +1 -0
- package/dist/chunk/{ZYHXLSJA.js → NEV5KNPS.js} +25 -3
- package/dist/chunk/NEV5KNPS.js.map +1 -0
- package/dist/chunk/{VECSCRAK.jsx → ONYGQYUN.jsx} +608 -5
- package/dist/chunk/{2LWM2YSR.jsx → RF6RWN3P.jsx} +2 -2
- package/dist/chunk/{IBGYHU26.js → RGFD2T3K.js} +3 -3
- package/dist/chunk/{IBGYHU26.js.map → RGFD2T3K.js.map} +1 -1
- package/dist/{client-B07yeMS8.d.ts → client-oZcZn-HB.d.ts} +178 -1
- package/dist/flows/index.d.ts +300 -2
- package/dist/flows/index.js +6 -6
- package/dist/flows/index.jsx +44 -6
- package/dist/index/index.d.ts +2 -2
- package/dist/index/index.js +7 -7
- package/dist/index/index.jsx +47 -7
- package/dist/pages/index.d.ts +1 -1
- package/dist/pages/index.js +5 -5
- package/dist/pages/index.jsx +5 -5
- package/dist/stores/index.d.ts +1 -1
- package/dist/stores/index.js +2 -2
- package/dist/stores/index.jsx +2 -2
- package/dist/theme/admin.css +95 -0
- package/package.json +1 -1
- package/dist/chunk/CWPXPAUD.js.map +0 -1
- package/dist/chunk/NSWRAFQE.js.map +0 -1
- package/dist/chunk/ZYHXLSJA.js.map +0 -1
|
@@ -914,6 +914,28 @@ var adminCatalogApi = {
|
|
|
914
914
|
);
|
|
915
915
|
}
|
|
916
916
|
};
|
|
917
|
+
var conversionPath = (productId) => `/admin/products/${encodeURIComponent(productId)}/catalog-conversion`;
|
|
918
|
+
var adminCatalogConversionApi = {
|
|
919
|
+
/** Where the product stands and what the next step would do. Read-only; safe to repeat. */
|
|
920
|
+
preview(productId) {
|
|
921
|
+
return apiFetch(conversionPath(productId));
|
|
922
|
+
},
|
|
923
|
+
/** Creates the catalog item INACTIVE (nothing is sold from it). Idempotent server-side. */
|
|
924
|
+
prepare(productId, planHash) {
|
|
925
|
+
return post(`${conversionPath(productId)}/prepare`, { planHash });
|
|
926
|
+
},
|
|
927
|
+
/**
|
|
928
|
+
* Activates the item and re-points the product. Takes about 35 seconds; never
|
|
929
|
+
* retry it blindly — re-read the preview first.
|
|
930
|
+
*/
|
|
931
|
+
commit(productId, body) {
|
|
932
|
+
return post(conversionPath(productId), body);
|
|
933
|
+
},
|
|
934
|
+
/** Puts a converted product back as it was. Does not undo everything — read `notUndone`. */
|
|
935
|
+
undo(productId, options = {}) {
|
|
936
|
+
return post(`${conversionPath(productId)}/undo`, options);
|
|
937
|
+
}
|
|
938
|
+
};
|
|
917
939
|
var adminApi = {
|
|
918
940
|
getDashboard() {
|
|
919
941
|
return apiFetch("/admin/dashboard/stats");
|
|
@@ -1472,6 +1494,6 @@ var affiliatePortalApi = {
|
|
|
1472
1494
|
}
|
|
1473
1495
|
};
|
|
1474
1496
|
|
|
1475
|
-
export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, adminCatalogApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, catalogApi, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, offersApi, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi };
|
|
1476
|
-
//# sourceMappingURL=
|
|
1477
|
-
//# sourceMappingURL=
|
|
1497
|
+
export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, adminCatalogApi, adminCatalogConversionApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, catalogApi, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, offersApi, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi };
|
|
1498
|
+
//# sourceMappingURL=NEV5KNPS.js.map
|
|
1499
|
+
//# sourceMappingURL=NEV5KNPS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/api/affiliateRef.ts","../../src/api/recaptcha.ts","../../src/api/client.ts"],"names":["storageKey"],"mappings":";;;AAiBA,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA,G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,CAAA;AAAA,EACA,QAAA,GAA6C;AAC3C,IAAA,OAAO,eAAwC,6BAA6B,CAAA;AAAA,EAC9E,CAAA;AAAA,EACA,aAAA,GAA2D;AACzD,IAAA,OAAO,eAAiD,mCAAmC,CAAA;AAAA,EAC7F,CAAA;AAAA,EACA,WAAA,GAAgE;AAC9D,IAAA,OAAO,eAAwD,gCAAgC,CAAA;AAAA,EACjG,CAAA;AAAA;AAAA;AAAA,EAGA,KAAA,CAAM,SAAiB,WAAA,EAAuD;AAC5E,IAAA,MAAM,SAAS,IAAI,eAAA,CAAgB,EAAE,GAAA,EAAK,SAAS,CAAA;AACnD,IAAA,IAAI,WAAA,EAAa,MAAA,CAAO,GAAA,CAAI,SAAA,EAAW,WAAW,CAAA;AAClD,IAAA,OAAO,cAAA;AAAA,MACL,CAAA,kBAAA,EAAqB,MAAA,CAAO,QAAA,EAAU,CAAA,CAAA;AAAA,MACtC,EAAE,MAAA,EAAQ,KAAA,EAAO,QAAA,EAAU,IAAA;AAAK,KAClC;AAAA,EACF;AACF","file":"NEV5KNPS.js","sourcesContent":["// ── First-party affiliate referral capture ──────────────────────────\n//\n// Attribution must survive from a `?ref=CODE` landing through signup to the\n// eventual checkout. The legacy carrier is the cross-site `affiliate_ref`\n// cookie set by /affiliates/track, but that cookie is third-party relative to\n// the storefront origin (frontend on *.web.app, API on *.run.app) and is\n// dropped by Safari, incognito, and third-party-cookie blocking.\n//\n// So we also stash the code in the storefront's own first-party localStorage\n// and send it back explicitly as `affiliateRef` on the attributable checkout\n// requests (see client.ts). The backend prefers it over the cookie and still\n// validates it server-side (code → active affiliate → program).\n\nimport { getConfig } from '../config';\n\n// Mirrors the default program cookie window so a stored ref expires like the\n// cookie would, rather than lingering forever.\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst storageKey = () => `${getConfig().storagePrefix}-affiliate-ref`;\n\ninterface StoredRef {\n code: string;\n ts: number;\n}\n\n/** Persist a referral code from a `?ref=` landing. No-op for empty input. */\nexport function captureAffiliateRef(code: string): void {\n if (typeof localStorage === 'undefined') return;\n const trimmed = code.trim();\n if (!trimmed) return;\n try {\n const entry: StoredRef = { code: trimmed, ts: Date.now() };\n localStorage.setItem(storageKey(), JSON.stringify(entry));\n } catch {\n // storage unavailable (private mode / quota) — non-fatal\n }\n}\n\n/** Read the stored referral code, or null if absent/expired. */\nexport function readAffiliateRef(): string | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(storageKey());\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredRef>;\n if (!parsed.code || typeof parsed.ts !== 'number') return null;\n if (Date.now() - parsed.ts > TTL_MS) {\n localStorage.removeItem(storageKey());\n return null;\n }\n return parsed.code;\n } catch {\n return null;\n }\n}\n\n/** Drop the stored referral code. */\nexport function clearAffiliateRef(): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(storageKey());\n } catch {\n // non-fatal\n }\n}\n","// ── reCAPTCHA v3 ────────────────────────────────────────────────────\n//\n// Per-tenant, data-driven bot protection on auth + payment surfaces. The\n// backend tells us — via GET /config/recaptcha, reachable pre-login — whether\n// this tenant has reCAPTCHA enabled and which site key to use. Only then do we\n// load Google's v3 script and mint tokens; tenants without it pay nothing.\n//\n// `executeRecaptcha()` is called by the api-client interceptor (see client.ts)\n// for whitelisted requests, which attaches the token as `X-Recaptcha-Token`.\n// It returns null whenever a token can't be produced (tenant disabled, script\n// blocked, execute failed) — the backend tolerates that in `monitor` mode and\n// rejects it only once a tenant flips to `enforce`.\n\nimport { getConfig } from '../config';\n\ninterface RecaptchaPublicConfig {\n enabled: boolean;\n version?: string;\n siteKey?: string;\n action?: string;\n /** Tenant enforcement posture from GET /config/recaptcha. In 'enforce' the\n * backend 403s a missing/failed token; in 'monitor' (or when absent) it\n * verifies-and-continues. Drives how patiently we wait for a slow mint. */\n mode?: 'monitor' | 'enforce';\n}\n\ndeclare global {\n interface Window {\n grecaptcha?: {\n ready: (cb: () => void) => void;\n execute: (siteKey: string, opts: { action: string }) => Promise<string>;\n };\n }\n}\n\nlet configPromise: Promise<RecaptchaPublicConfig> | null = null;\nlet scriptPromise: Promise<void> | null = null;\n\n/**\n * Bounds on the token mint. reCAPTCHA sits inline on the login/checkout/subscribe\n * critical path, so the mint is always bounded — a stalled Google api.js must not\n * hang those flows for the tens of seconds the browser takes to fire `onerror`.\n * But the bound is posture-aware (see RecaptchaPublicConfig.mode):\n * - 'monitor' / unknown: the backend verifies-and-continues without a token, so\n * a null token is harmless — fail open FAST to keep the UI snappy.\n * - 'enforce': a null token is a guaranteed 403, so a valid-but-slow cold mint\n * (poor connection, cold cache) must not be clipped — wait patiently.\n * Either way a truly dead api.js is bounded and, via loadScript, retried on the\n * next action.\n */\nconst MINT_TIMEOUT_MS: Record<'monitor' | 'enforce', number> = { monitor: 5000, enforce: 15000 };\n/** Bound on the pre-mint config fetch, so an unreachable /config/recaptcha can't\n * hang the flow before we even know the posture. */\nconst CONFIG_TIMEOUT_MS = 5000;\n\n/**\n * Resolve `null` if `p` doesn't settle within `ms` (fail-open: a null token\n * just omits the header, which the backend tolerates outside `enforce` mode).\n * Never rejects.\n */\nfunction withTimeout<T>(p: Promise<T>, ms: number): Promise<T | null> {\n return new Promise<T | null>((resolve) => {\n let done = false;\n const timer = setTimeout(() => {\n if (done) return;\n done = true;\n console.warn(`[recaptcha] timed out after ${ms}ms; proceeding without a token`);\n resolve(null);\n }, ms);\n p.then(\n (v) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n resolve(v);\n },\n () => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n resolve(null);\n },\n );\n });\n}\n\nasync function fetchRecaptchaConfig(): Promise<RecaptchaPublicConfig> {\n const cfg = getConfig();\n try {\n const res = await fetch(`${cfg.apiBase}/config/recaptcha`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return { enabled: false };\n return (await res.json()) as RecaptchaPublicConfig;\n } catch {\n return { enabled: false };\n }\n}\n\n/** Memoized public config — fetched at most once per session. */\nfunction getRecaptchaConfig(): Promise<RecaptchaPublicConfig> {\n if (!configPromise) configPromise = fetchRecaptchaConfig();\n return configPromise;\n}\n\n/** Inject Google's v3 script once, keyed to the tenant's site key. A failed or\n * stalled load is NOT memoized: if `onload`/`onerror` never fire (api.js\n * swallowed by a middlebox / captive portal) a timeout rejects and drops the\n * memo, so a later gated action retries the injection instead of re-awaiting a\n * permanently-pending promise (and re-paying the executeRecaptcha timeout each\n * time). A successful load stays memoized. */\nfunction loadScript(siteKey: string, timeoutMs: number): Promise<void> {\n if (scriptPromise) return scriptPromise;\n scriptPromise = new Promise<void>((resolve, reject) => {\n if (typeof window === 'undefined') {\n resolve();\n return;\n }\n if (window.grecaptcha) {\n resolve();\n return;\n }\n const script = document.createElement('script');\n script.src = `https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}`;\n script.async = true;\n const timer = setTimeout(\n () => reject(new Error('reCAPTCHA script load timed out')),\n timeoutMs,\n );\n script.onload = () => {\n clearTimeout(timer);\n resolve();\n };\n script.onerror = () => {\n clearTimeout(timer);\n reject(new Error('Failed to load reCAPTCHA'));\n };\n document.head.appendChild(script);\n }).catch((err) => {\n scriptPromise = null;\n throw err;\n });\n return scriptPromise;\n}\n\n/**\n * Mint a v3 token for `action`, or null if reCAPTCHA is not enabled for this\n * tenant or a token can't be produced. Never throws.\n */\nexport async function executeRecaptcha(action: string): Promise<string | null> {\n // Resolve config first (bounded) so the mint timeout can be posture-aware: a\n // timed-out config just yields no token, same as a disabled tenant.\n const cfg = await withTimeout(getRecaptchaConfig(), CONFIG_TIMEOUT_MS);\n if (!cfg?.enabled || !cfg.siteKey) return null;\n const bound = cfg.mode === 'enforce' ? MINT_TIMEOUT_MS.enforce : MINT_TIMEOUT_MS.monitor;\n return withTimeout(mintToken(cfg.siteKey, action, bound), bound);\n}\n\n/** Unbounded token mint for a known-enabled tenant; `executeRecaptcha` wraps it\n * in the posture-aware timeout and passes that same bound to the script load. */\nasync function mintToken(siteKey: string, action: string, timeoutMs: number): Promise<string | null> {\n try {\n await loadScript(siteKey, timeoutMs);\n const grecaptcha = window.grecaptcha;\n if (!grecaptcha) return null;\n return await new Promise<string>((resolve, reject) => {\n grecaptcha.ready(() => {\n grecaptcha.execute(siteKey, { action }).then(resolve).catch(reject);\n });\n });\n } catch (err) {\n console.warn('[recaptcha] execute failed:', err);\n return null;\n }\n}\n\n/** Test/HMR hook — drop memoized config + script promises. */\nexport function __resetRecaptchaForTests(): void {\n configPromise = null;\n scriptPromise = null;\n}\n","// ── Config ──────────────────────────────────────────────────────────\n//\n// API base, tenant key, and auth storage key are pulled from runtime config\n// (see `../config.ts`). Sites must call `configure()` at boot before any of\n// these helpers run.\n\nimport { getConfig } from '../config';\nimport { executeRecaptcha } from './recaptcha';\nimport { readAffiliateRef } from './affiliateRef';\n\nexport const authStorageKey = () => `${getConfig().storagePrefix}-auth`;\n\n// ── reCAPTCHA interceptor ───────────────────────────────────────────\n//\n// Single choke point: for the auth + payment surfaces Intuit's questionnaire\n// covers, mint a v3 token and attach it as `X-Recaptcha-Token`. Keeps the flow\n// hooks and pages free of any reCAPTCHA code. Keyed by `METHOD path`; both\n// apiFetch and affiliateFetch pass full endpoint paths, so one table serves\n// both. No-op for tenants without reCAPTCHA (executeRecaptcha returns null).\nconst RECAPTCHA_ACTIONS: Record<string, string> = {\n 'POST /auth/login': 'login',\n 'POST /auth/register': 'register',\n 'POST /auth/register-member': 'register_member',\n 'POST /auth/register-and-subscribe': 'register_subscribe',\n 'POST /auth/check-email': 'check_email',\n 'POST /auth/request-password-reset': 'password_reset_request',\n 'POST /auth/reset-password': 'password_reset',\n 'POST /payments/checkout': 'checkout',\n 'POST /payments/prescription-checkout': 'prescription_checkout',\n 'POST /subscriptions': 'subscribe',\n 'POST /affiliates/login': 'affiliate_login',\n 'POST /affiliates/register': 'affiliate_register',\n 'POST /affiliates/request-password-reset': 'affiliate_password_reset_request',\n 'POST /affiliates/reset-password': 'affiliate_password_reset',\n};\n\nfunction recaptchaActionFor(method: string | undefined, endpoint: string): string | null {\n const path = endpoint.split('?')[0];\n return RECAPTCHA_ACTIONS[`${(method ?? 'GET').toUpperCase()} ${path}`] ?? null;\n}\n\n/** Attach X-Recaptcha-Token to `headers` if this request is a gated surface. */\nasync function applyRecaptcha(headers: Headers, method: string | undefined, endpoint: string): Promise<void> {\n const action = recaptchaActionFor(method, endpoint);\n if (!action) return;\n const token = await executeRecaptcha(action);\n if (token) headers.set('X-Recaptcha-Token', token);\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface AuthTokens {\n accessToken: string;\n refreshToken: string;\n userId: string;\n}\n\nexport interface User {\n id: string;\n email: string;\n firstName: string;\n lastName: string;\n role: string;\n [key: string]: unknown;\n}\n\nexport interface LoginPayload {\n email: string;\n password: string;\n}\n\nexport interface RegisterPayload {\n email: string;\n password: string;\n member: {\n firstName: string;\n lastName: string;\n dateOfBirth: string;\n phone?: string;\n address1: string;\n city: string;\n state: string;\n zip: string;\n };\n}\n\nexport interface RegisterAndSubscribePayload extends RegisterPayload {\n opaqueData?: Record<string, unknown>;\n amountCents: number;\n intervalDays?: number;\n medication?: string;\n products?: Array<{ productId: string; productName: string; quantity?: number; dosage?: string }>;\n /** v1 survey response id (legacy, the-backend formats caseNotes locally). */\n surveyResponseId?: string;\n /** v2 survey response id (Apex formats caseNotes from the survey snapshot). */\n v2SurveyResponseId?: string;\n caseNotes?: string;\n billingAddress?: { street: string; city: string; state: string; zip: string };\n promoCode?: string;\n /**\n * Verified savings-program member id. The backend re-verifies it, links it\n * to the NEW account and prices the charge at the savings rate; an id already\n * linked to another account is refused (409) before any charge.\n */\n savingsMemberId?: string;\n}\n\n/** Item in a cart-style order/checkout. Mirrors the live backend contract:\n * POST /orders and POST /payments/checkout both read `item.productId`;\n * quantity defaults to 1 server-side; dosage is required only for per-dose\n * products carrying an Apex clinical dose. */\nexport interface OrderItemInput {\n productId: string;\n quantity?: number;\n dosage?: string;\n}\n\n/** A US postal address on the checkout wire (shipping or billing). Structurally\n * matches the flows' `AddressValue`. */\nexport interface CheckoutAddress {\n street: string;\n street2?: string;\n city: string;\n state: string;\n zip: string;\n}\n\nexport interface CheckoutPayload {\n items: OrderItemInput[];\n /** Pinned to `CheckoutAddress` (`street`, not `street1`): the backend stores\n * checkout shipping verbatim today, its only shipping-address parser\n * (`sanitizeCheckoutAddress`, on the prescription-checkout route) reads\n * `street`, and the AuthNet billTo mapping reads `billingAddress.street/\n * city/state/zip` — so `street` is the wire canon for both addresses. */\n shippingAddress: CheckoutAddress;\n /** Provider-neutral tokenized card from useCardTokenizer().tokenize() — AuthNet\n * ships `{ dataDescriptor, dataValue }`, QuickBooks `{ token }`. REQUIRED —\n * POST /payments/checkout 400s when absent (it charges the raw token; there\n * is no card-on-file path on this route). */\n opaqueData: Record<string, unknown>;\n billingAddress?: CheckoutAddress;\n promoCode?: string;\n}\n\n/** Response envelope of POST /payments/checkout. 201 carries the succeeded\n * charge; a declined card comes back as a 400 with `success: false` and the\n * gateway's `error`/`errorCode` (surfaced to the caller as an ApiError). */\nexport interface CheckoutResult {\n success: boolean;\n status?: 'succeeded' | 'failed';\n orderId?: string;\n paymentId?: string;\n transactionId?: string;\n amountCents?: number;\n error?: string;\n errorCode?: string;\n}\n\n/** A one-time order row as returned by GET /orders and GET /orders/:id.\n * `items[].priceAtPurchase` is the per-unit price snapshot in cents; `delivery`\n * is joined from the linked prescription request and is null for plain\n * cart purchases. */\nexport interface Order {\n id: string;\n status: string;\n total_cents: number;\n items: Array<{\n productId: string;\n name: string;\n quantity: number;\n priceAtPurchase: number;\n dosage?: string;\n }>;\n created_at?: string;\n delivery?: {\n status: string;\n trackingNumber?: string;\n shipCarrier?: string;\n trackingUrl?: string;\n } | null;\n}\n\nexport interface PaymentInitiatePayload {\n amount: number;\n currency?: string;\n paymentMethodToken?: string;\n}\n\nexport interface PaymentCallbackPayload {\n transactionId: string;\n status: string;\n [key: string]: unknown;\n}\n\nexport interface SendMessagePayload {\n text: string;\n}\n\nexport interface CreateOrderPayload {\n items: OrderItemInput[];\n shippingAddress: Record<string, string>;\n}\n\nexport interface UpdateProfilePayload {\n firstName?: string;\n lastName?: string;\n phone?: string;\n dateOfBirth?: string;\n gender?: string;\n address1?: string;\n address2?: string;\n city?: string;\n state?: string;\n zip?: string;\n /** Last-entered survey vitals, persisted for cross-device carry-over. */\n heightIn?: number;\n weightLb?: number;\n}\n\nexport interface UpdatePaymentMethodPayload {\n /** Provider-neutral tokenized card from useCardTokenizer().tokenize() (AuthNet\n * {dataDescriptor,dataValue}, QuickBooks {token}). Sent to the backend as\n * `opaqueData`; PUT /subscriptions/:id/payment-method 400s when absent. */\n opaqueData: Record<string, unknown>;\n /** The card's billTo. Omit to keep the backend's per-field fallback to the\n * member's profile address. Sending it lets a member whose card bills\n * somewhere other than where they ship actually save that card — the\n * gateway validates live on update, so a wrong billTo fails AVS. */\n billingAddress?: { street?: string; city?: string; state?: string; zip?: string };\n}\n\n/**\n * An email's editable copy. `body` is HTML limited to what the backend's\n * sanitizer keeps: `<p>`, `<h2>`, `<ul>`/`<ol>`/`<li>`, `<strong>`, `<em>`,\n * `<u>`, `<br>`, `<a href>`, and a top-level `<a data-button href>` button.\n * Placeholders are literal `{{name}}` text, or lead an `href`.\n */\nexport interface TemplateText {\n subject: string;\n body: string;\n}\n\nexport interface EmailTemplatesMap {\n [key: string]: TemplateText;\n}\n\n/**\n * How a placeholder's value may be used. `text`: a plain value. `url`: a bare\n * URL, meant as the target of a link or button. `html`: a ready-made link\n * whose wording the backend fixes (e.g. `{{unsubscribeLink}}`).\n */\nexport type PlaceholderKind = 'text' | 'url' | 'html';\n\nexport interface Placeholder {\n /** Including the braces: `{{firstName}}`. */\n token: string;\n description: string;\n kind: PlaceholderKind;\n}\n\n/** Per-template placeholder tokens, keyed by template key. */\nexport interface TemplatePlaceholdersMap {\n [key: string]: Placeholder[];\n}\n\n/**\n * An admin-authored email, as opposed to the fixed transactional set. This is\n * the only place marketing copy lives: a sequence step points at one by id\n * and carries no text of its own.\n */\nexport interface CustomTemplate extends TemplateText {\n id: string;\n name: string;\n createdAt: string;\n updatedAt: string;\n /** Sequences with a step on this template. Non-empty blocks deletion (409). */\n usedBy: Array<{ sequenceId: string; sequenceName: string }>;\n}\n\n/** What create/update take: the whole template, every time. */\nexport type CustomTemplateInput = TemplateText & { name: string };\n\n/** Admin copies of customer emails: who gets them, and for which events. */\nexport interface EmailNotificationSettings {\n recipientEmails: string[];\n /** Keyed by template key; the backend returns every event it knows. */\n enabledEvents: Record<string, boolean>;\n}\n\n/** `self_serve`: the admin switches it. `request`: the platform team turns it on when asked. */\nexport type TenantFeatureAccess = 'self_serve' | 'request';\n\n/** One optional feature of the tenant, as the backend describes it. */\nexport interface TenantFeature {\n key: string;\n label: string;\n description: string;\n access: TenantFeatureAccess;\n enabled: boolean;\n /** Self-serve only: the feature that has to be on before this one can be. */\n requires?: { key: string; label: string; enabled: boolean };\n /** Request only: present while an ask is pending. */\n request?: { requestedAt: string; requestedBy: string; note?: string };\n}\n\nexport interface BillingReminderSettings {\n renewalReminder: { enabled: boolean; daysBefore: number[] };\n cardExpiring: { enabled: boolean; daysBeforeExpiry: number };\n pastDueNudge: { enabled: boolean; intervalDays: number; maxNudges: number };\n}\n\nexport interface ApiResponse<T = unknown> {\n data?: T;\n error?: string;\n message?: string;\n}\n\nexport interface PaginationParams {\n page?: number;\n limit?: number;\n [key: string]: unknown;\n}\n\nexport interface SurveySubmitPayload {\n surveyId: string;\n answers: Array<{ questionId: string; value: unknown }>;\n patientInfo: {\n firstName: string;\n lastName: string;\n email: string;\n dob: string;\n state: string;\n street1: string;\n city: string;\n zipCode: string;\n phone?: string;\n street2?: string;\n };\n}\n\nexport interface SelectDrugPayload {\n surveyId: string;\n responseId: string;\n drugId: string;\n}\n\nexport interface CreateRequestPayload {\n drugId?: string;\n dosage?: string;\n /** Dose redesign (Phase 8): optional intake hints forwarded to Apex via the-backend\n * for the single-drug (drugId) path. `requestedSku` is binding (patient-bought SKU);\n * `requestedClinicalDose` is advisory. Both optional — absent => unchanged payload. */\n requestedSku?: string;\n /** SKU identity S4: the stable, opaque `skus[].id` form of `requestedSku` (from\n * Apex's /v1/drugs catalog). Preferred over the free-text label — it survives a\n * relabel. Additive alongside `requestedSku`; absent => unchanged payload. */\n requestedSkuId?: string;\n requestedClinicalDose?: { value: number; unit: string };\n /** v1 survey response id (legacy, the-backend formats caseNotes locally). */\n surveyResponseId?: string;\n /** v2 survey response id (Apex formats caseNotes from the snapshot). */\n v2SurveyResponseId?: string;\n caseNotes?: string;\n promoCode?: string;\n medications?: Array<{ productId: string; productName: string; quantity?: number; dosage?: string; requestedSku?: string; requestedSkuId?: string; requestedClinicalDose?: { value: number; unit: string } }>;\n patientInfo?: {\n firstName: string;\n lastName: string;\n email: string;\n phone?: string;\n dob: string;\n street1: string;\n street2?: string;\n city: string;\n state: string;\n zipCode: string;\n };\n}\n\nexport interface CreateSubscriptionPayload {\n opaqueData?: Record<string, unknown>;\n amountCents: number;\n intervalDays?: number;\n billingAddress?: { street: string; city: string; state: string; zip: string; country?: string };\n products?: Array<{ productId: string; productName: string; quantity?: number; dosage?: string }>;\n metadata?: Record<string, unknown>;\n productId?: string;\n promoCode?: string;\n}\n\n/** What POST /subscriptions/preview says the subscribe call would charge. */\nexport interface SubscriptionPreviewLine {\n productId: string;\n productName: string;\n quantity: number;\n dosage: string | null;\n baseAmountCents: number;\n amountCents: number;\n}\nexport interface SubscriptionPreview {\n /** 'membership': one membership line regardless of the cart; 'per_product': one line per cart product. */\n model: 'membership' | 'per_product';\n createsRx: boolean;\n intervalDays: number;\n lines: SubscriptionPreviewLine[];\n subtotalCents: number;\n discountCents: number;\n totalCents: number;\n promoApplied: boolean;\n /** The buyer's own offer, when it is what priced this cart (an offer and a\n * promo code compete for one slot). Absent on backends that predate offers. */\n offerApplied?: { label: string; amountText: string; recurringIndefinite: boolean } | null;\n savingsApplied: boolean;\n /** The member already holds this subscription, so the charge would return\n * it unchanged and charge nothing (lines empty, totals 0). Absent on\n * backends that predate the existing-subscription guards on the preview. */\n alreadySubscribed?: boolean;\n subscriptionId?: string;\n}\nexport type SubscriptionPreviewPayload = Pick<CreateSubscriptionPayload, 'products' | 'productId' | 'promoCode' | 'intervalDays'>;\n\nexport interface SendToPharmacyPayload {\n requestId: string;\n pharmacyId: string;\n}\n\n// ── Shipping / Renewal types ───────────────────────────────────────\n\nexport interface DeliveryInfo {\n status: string | null;\n trackingNumber: string;\n shipCarrier: string;\n trackingUrl: string | null;\n}\n\nexport type RenewalStatus =\n | 'awaiting_fill'\n | 'scheduled'\n | 'survey_sent'\n | 'survey_completed'\n | 'request_created'\n | 'request_failed'\n | 'canceled';\n\nexport interface MemberPrescriptionRequest {\n requestId: string;\n status: 'pending' | 'approved' | 'denied' | 'call_requested' | 'shipped';\n drugId?: string;\n drugName?: string;\n productId?: string;\n dosage?: string;\n priceCents?: number;\n /** The patient has already paid for this request (prescription_requests.payment_confirmed).\n * In the pay-before-review flow a request can be paid while still pending, so consumers\n * must not assume \"unpaid until approved\". */\n paymentConfirmed?: boolean;\n createdAt: string;\n updatedAt?: string;\n delivery: DeliveryInfo | null;\n /** The day an approved-and-waiting Rx is due at the pharmacy (`YYYY-MM-DD`).\n * Null once it has been transmitted, and null for a date already past — the\n * backend withholds a slipped schedule rather than render it as a plan. */\n pharmacySendDate?: string | null;\n renewal?: {\n renewalId: string;\n cycleNumber: number;\n status: RenewalStatus;\n pharmacyFillDate: string | null;\n triggerAt: string | null;\n } | null;\n}\n\nexport interface PendingRenewalSurvey {\n renewalId: string;\n cycleNumber: number;\n prescriptionRequestId: string;\n drugId?: string;\n drugName?: string;\n dosage?: string;\n pharmacyFillDate: string | null;\n surveyId: string;\n}\n\n/**\n * Body for `completeSurvey`. A renewal check-in ends one of two ways:\n * - the member re-qualifies → `{ surveyResponseId }` (the Apex response id links\n * the survey snapshot to the renewal so the next Rx carries case notes), or\n * - the member no longer qualifies → `{ disqualified: true, reason? }` (the\n * backend moves the renewal to terminal `declined`; no Rx is created).\n */\nexport type CompleteSurveyPayload =\n | { surveyResponseId: string }\n | { disqualified: true; reason?: string };\n\nexport interface MembersMeResponse {\n member: Record<string, unknown>;\n orders?: Array<Record<string, unknown>>;\n subscriptions?: Array<{\n id: string;\n productId: string;\n /** Apex drug id (a code). */\n medication: string;\n /** Friendly product name resolved server-side; absent when unresolved. */\n medicationName?: string;\n dosage: string;\n status: string;\n amountCents: number;\n intervalDays: number;\n /** Billing mirror — advances only on a successful charge. Not a fill date. */\n currentPeriodEnd: string;\n /**\n * The real next-fill date (`YYYY-MM-DD`) from the member's live renewal row.\n * Null while a cycle awaits its fill (the pharmacy has not shipped, so the\n * date is unknown) and on partners without renewals.\n */\n nextFillDate?: string | null;\n /** When the check-in opens, from the same renewal row. */\n checkInDueAt?: string | null;\n /** The live renewal's status, or null when no cycle is running. */\n checkInStatus?: string | null;\n createdAt: string;\n }>;\n /** The member's prescription requests. `/members/me` no longer emits a single\n * \"current\" request — that field was dropped in the backend's single-drug\n * migration; consumers use this list (or `membersApi.getRequests()` for the\n * paginated list with renewal metadata). */\n prescriptionRequests?: MemberPrescriptionRequest[];\n}\n\n// ── Token management ────────────────────────────────────────────────\n\n// Token-cleared notification: clearTokens()/clearAffiliateTokens() run from\n// deep inside the transport (refresh failure, post-refresh 401) — out of band\n// of the auth stores, whose isAuthenticated() only flips via their own\n// syncTokens(). Without a signal the chrome keeps rendering an authenticated\n// shell whose every request 401s until a hard reload. Stores register here to\n// learn the moment their token family is wiped, whoever wiped it. Same-tab\n// only by design: cross-tab convergence is the stores' `storage` listener,\n// which the browser never fires in the tab that did the clearing.\n\nexport type TokenTrackName = 'patient' | 'affiliate';\n\nconst tokensClearedListeners: Record<TokenTrackName, Set<() => void>> = {\n patient: new Set(),\n affiliate: new Set(),\n};\n\n/** Subscribe to same-tab wipes of a track's tokens. Listeners must not write\n * token storage (a re-clear would re-notify). Returns an unsubscribe. */\nexport function onTokensCleared(track: TokenTrackName, cb: () => void): () => void {\n tokensClearedListeners[track].add(cb);\n return () => tokensClearedListeners[track].delete(cb);\n}\n\nfunction notifyTokensCleared(track: TokenTrackName): void {\n for (const cb of tokensClearedListeners[track]) {\n try {\n cb();\n } catch {\n // A listener error must never break the clearing path itself.\n }\n }\n}\n\nexport function getTokens(): AuthTokens | null {\n try {\n const raw = localStorage.getItem(authStorageKey());\n if (!raw) return null;\n return JSON.parse(raw) as AuthTokens;\n } catch {\n return null;\n }\n}\n\nexport function setTokens(tokens: AuthTokens): void {\n localStorage.setItem(authStorageKey(), JSON.stringify(tokens));\n}\n\nexport function clearTokens(): void {\n localStorage.removeItem(authStorageKey());\n notifyTokensCleared('patient');\n}\n\n// ── Refresh queue ───────────────────────────────────────────────────\n//\n// Two layers of dedup keep a token refresh from racing itself into a logout:\n// 1. `refreshPromise` — a per-tab in-memory single-flight, so several 401s in\n// one tab share one refresh.\n// 2. `withRefreshLock` — a cross-tab single-flight via the Web Locks API. The\n// backend rotates the refresh token on EVERY refresh and revokes the whole\n// token family if a spent token is replayed (reuse detection), so two tabs\n// must not both POST the same token. The tab that loses the lock re-reads\n// storage: if a peer already wrote a fresh token it ADOPTS it (no network,\n// no replay); only a genuinely expired token with no peer rotation clears\n// the session.\n\nlet refreshPromise: Promise<AuthTokens | null> | null = null;\n\n/** `<storageKey>-refresh` — the cross-tab Web Lock name for a token family. */\nconst refreshLockName = (storageKey: string) => `${storageKey}-refresh`;\nconst patientRefreshLockName = () => refreshLockName(authStorageKey());\n\n/** Run `fn` under a named cross-tab lock when the Web Locks API is available;\n * otherwise run it directly (older browsers keep the per-tab single-flight). */\nfunction withRefreshLock<T>(name: string, fn: () => Promise<T>): Promise<T> {\n const lockManager = typeof navigator !== 'undefined' ? navigator.locks : undefined;\n if (!lockManager?.request) return fn();\n // navigator.locks.request can reject before it ever runs our callback: in\n // partitioned/cross-origin iframes or non-fully-active documents\n // (SecurityError/InvalidStateError), or on a reserved lock name (a leading\n // '-', which an empty storagePrefix would produce). If acquisition fails\n // before `run` started, fall back to a direct single-flight run so a 401 still\n // refreshes instead of surfacing a raw DOMException out of the fetch path. If\n // `run` DID start, propagate its own outcome unchanged (never double-run it).\n let started = false;\n const run = () => {\n started = true;\n return fn();\n };\n try {\n return (lockManager.request(name, run) as Promise<T>).catch((err) => {\n if (!started) return fn();\n throw err;\n });\n } catch {\n return fn();\n }\n}\n\n/** Adopt-vs-replay: if the store already holds a fresh token a peer tab rotated\n * to (its refreshToken differs from the one we were about to present) AND it\n * still belongs to the same account, return it so the caller adopts it instead\n * of replaying a now-spent token. Else null. The `sameOwner` identity check\n * stops a peer tab that logged in as a DIFFERENT user (same browser profile,\n * shared storage key) from having its tokens adopted and the original request\n * retried under the wrong session. Parameterized by the token getter so the\n * patient and affiliate refresh queues share one condition, not two hand-synced\n * copies. */\nfunction adoptRotatedTokens<T extends { accessToken?: string; refreshToken?: string }>(\n getLatest: () => T | null,\n presented: T,\n sameOwner: (latest: T) => boolean,\n): T | null {\n const latest = getLatest();\n if (\n latest?.accessToken &&\n latest.refreshToken &&\n latest.refreshToken !== presented.refreshToken &&\n sameOwner(latest)\n ) {\n return latest;\n }\n return null;\n}\n\nconst adoptPatientTokens = (presented: AuthTokens): AuthTokens | null =>\n adoptRotatedTokens(getTokens, presented, (latest) => latest.userId === presented.userId);\n\n/** Upper bound on a single refresh POST. The refresh runs while holding the\n * cross-tab Web Lock (see withRefreshLock); an unbounded POST that stalls on a\n * flaky network would hold that lock — blocking every other tab's 401 recovery\n * — until the socket eventually gave up. On abort the fetch rejects, the\n * caller's catch adopts a peer's rotated token or clears the session, and the\n * lock is released. */\nconst REFRESH_TIMEOUT_MS = 10000;\n\nfunction fetchWithTimeout(input: string, init: RequestInit, ms: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), ms);\n return fetch(input, { ...init, signal: controller.signal }).finally(() => clearTimeout(timer));\n}\n\nasync function refreshAccessToken(): Promise<AuthTokens | null> {\n if (refreshPromise) return refreshPromise;\n\n // Capture the token we intend to present BEFORE contending for the lock, so\n // that once we hold it we can detect a peer tab having rotated in the interim.\n const presented = getTokens();\n if (!presented?.refreshToken || !presented?.userId) return null;\n\n refreshPromise = withRefreshLock(patientRefreshLockName(), async () => {\n // A peer rotated while we waited on the lock → adopt, never replay.\n const adopted = adoptPatientTokens(presented);\n if (adopted) return adopted;\n\n try {\n const cfg = getConfig();\n const res = await fetchWithTimeout(\n `${cfg.apiBase}/auth/refresh`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n },\n body: JSON.stringify({\n refreshToken: presented.refreshToken,\n userId: presented.userId,\n }),\n },\n REFRESH_TIMEOUT_MS,\n );\n\n if (!res.ok) {\n // Losing tab of a race that skipped the lock: adopt a peer's fresh\n // token if one appeared.\n const raced = adoptPatientTokens(presented);\n if (raced) return raced;\n // Only a definitive rejection of the presented refresh token ends the\n // session. A 5xx/gateway blip on the refresh endpoint says nothing\n // about the token — clearing here deleted a valid refresh token from\n // shared storage and logged out every tab over a transient outage.\n if (res.status === 401 || res.status === 403) clearTokens();\n return null;\n }\n\n const data = (await res.json()) as {\n uid: string;\n idToken: string;\n refreshToken: string;\n };\n const newTokens: AuthTokens = {\n accessToken: data.idToken,\n refreshToken: data.refreshToken,\n userId: data.uid,\n };\n setTokens(newTokens);\n return newTokens;\n } catch {\n const raced = adoptPatientTokens(presented);\n if (raced) return raced;\n // Network drop / timeout: the token is most likely still valid — keep it\n // so a later attempt can retry instead of force-logging the user out.\n return null;\n }\n }).finally(() => {\n refreshPromise = null;\n });\n\n return refreshPromise;\n}\n\n// ── Errors + idempotency ────────────────────────────────────────────\n\n/**\n * Error thrown by {@link apiFetch}. `ambiguous` means the request's outcome is\n * UNKNOWN to the client — the server may have committed the mutation even\n * though we never saw a success response (connection dropped mid-flight, or a\n * 5xx that could be post-commit). Callers of charge/create flows must treat an\n * ambiguous failure as \"maybe it worked\": reconcile against server state before\n * offering a retry, and reuse the same idempotency key if they do retry. A\n * non-ambiguous error (4xx, declined card, validation) is a definitive \"it did\n * not happen\" and is safe to retry with a fresh key.\n */\nexport class ApiError extends Error {\n readonly status?: number;\n readonly ambiguous: boolean;\n /** Machine-readable error code from the response body, when the endpoint\n * sends one (e.g. `SUBSCRIPTION_EXISTS`). Branch on this, never on message. */\n readonly code?: string;\n\n constructor(\n message: string,\n opts: { status?: number; ambiguous?: boolean; cause?: unknown; code?: string } = {},\n ) {\n super(message);\n this.name = 'ApiError';\n this.status = opts.status;\n this.ambiguous = opts.ambiguous ?? false;\n this.code = opts.code;\n if (opts.cause !== undefined) (this as { cause?: unknown }).cause = opts.cause;\n }\n}\n\n/**\n * Generate a client-side idempotency key (RFC 4122 v4). Persist it across\n * retries of the SAME logical operation so the backend dedupes; mint a fresh\n * one only for a genuinely new operation.\n */\nexport function newIdempotencyKey(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n // fall through to manual construction\n }\n const bytes = new Uint8Array(16);\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10\n const h = Array.from(bytes, (b) => b.toString(16).padStart(2, '0'));\n return `${h[0]}${h[1]}${h[2]}${h[3]}-${h[4]}${h[5]}-${h[6]}${h[7]}-${h[8]}${h[9]}-${h[10]}${h[11]}${h[12]}${h[13]}${h[14]}${h[15]}`;\n}\n\n// ── Core fetch ──────────────────────────────────────────────────────\n//\n// One transport pipeline (tenant header, content-type, bearer, reCAPTCHA,\n// 401-refresh-and-retry, error parsing) shared by the patient and affiliate\n// clients. Per-client differences live in a `TransportTrack`: which token\n// store to read/clear, which single-flight refresh to run, the credentials\n// policy (patient omits it → same-origin; affiliate forces `include` for its\n// cross-site refresh cookie), the session-expired copy, and whether to append\n// backend `details[]` to error messages (patient surface only).\n\ninterface TransportTrack {\n getAccessToken: () => string | undefined;\n clear: () => void;\n /** Single-flight refresh for this track (the item-21 cross-tab seam). */\n refresh: () => Promise<{ accessToken: string } | null>;\n /** Omitted (undefined) → browser default (same-origin); 'include' for the\n * affiliate cross-site refresh cookie. Never overrides a caller's value. */\n credentials?: RequestCredentials;\n sessionExpiredMessage: string;\n /** Append backend `details[]` to the thrown error message (patient surface). */\n enrichErrorDetails: boolean;\n}\n\nasync function coreFetch<T = unknown>(\n endpoint: string,\n fetchOpts: RequestInit,\n track: TransportTrack,\n call: { skipAuth?: boolean; authTokenOverride?: string; idempotencyKey?: string } = {},\n): Promise<T> {\n const { skipAuth, authTokenOverride, idempotencyKey } = call;\n\n const cfg = getConfig();\n const headers = new Headers(fetchOpts.headers);\n headers.set('X-Tenant-Key', cfg.tenantKey);\n\n if (!headers.has('Content-Type') && fetchOpts.body && typeof fetchOpts.body === 'string') {\n headers.set('Content-Type', 'application/json');\n }\n\n // Only send the custom Idempotency-Key header when the tenant's backend is\n // known to CORS-allow-list AND honor it (see PortalConfig.idempotencyKeys).\n // Sending it before the backend allow-lists it would fail CORS preflight and\n // block the request outright.\n if (idempotencyKey && cfg.idempotencyKeys) {\n headers.set('Idempotency-Key', idempotencyKey);\n }\n\n // A per-call override token (e.g. an admin \"view as customer\" impersonation\n // token) authenticates this single request WITHOUT touching the token store,\n // and never triggers the 401-refresh path below — an expired impersonated\n // read just throws, it can never refresh or overwrite the caller's session.\n if (authTokenOverride) {\n headers.set('Authorization', `Bearer ${authTokenOverride}`);\n } else if (!skipAuth) {\n const token = track.getAccessToken();\n if (token) headers.set('Authorization', `Bearer ${token}`);\n }\n\n await applyRecaptcha(headers, fetchOpts.method, endpoint);\n\n const url = `${cfg.apiBase}${endpoint}`;\n // Apply the track's credentials policy. When the track sets one it WINS: the\n // affiliate cross-site refresh cookie must always be sent, and a caller must\n // not be able to suppress it by passing its own `credentials`. The patient\n // track leaves it undefined, so the caller's value (or the same-origin\n // default) stands.\n const build = (): RequestInit =>\n track.credentials !== undefined\n ? { ...fetchOpts, headers, credentials: track.credentials }\n : { ...fetchOpts, headers };\n\n // A rejected fetch() (dropped connection, DNS, CORS) means the request may or\n // may not have reached the server — the outcome is ambiguous. Surface that so\n // charge/create callers reconcile instead of blindly retrying (double-charge).\n const doFetch = async (): Promise<Response> => {\n try {\n return await fetch(url, build());\n } catch (e) {\n throw new ApiError('Network error — your connection dropped mid-request. Please try again.', {\n ambiguous: true,\n cause: e,\n });\n }\n };\n\n let res = await doFetch();\n\n // Refresh-and-retry on 401 (never for a per-call impersonation override).\n if (res.status === 401 && !skipAuth && !authTokenOverride) {\n const refreshed = await track.refresh();\n if (refreshed) {\n headers.set('Authorization', `Bearer ${refreshed.accessToken}`);\n // The original attempt consumed its single-use reCAPTCHA v3 token (one\n // verify per token); replaying it on the retry would fail enforce-mode\n // verification with a bogus \"verify you're human\". Drop the stale header\n // and mint a fresh token for gated surfaces.\n headers.delete('X-Recaptcha-Token');\n await applyRecaptcha(headers, fetchOpts.method, endpoint);\n res = await doFetch();\n if (res.status === 401) {\n // The backend rejected a freshly-minted token: the session is dead in a\n // way refresh can't cure (secret rotation, revoked account, auth\n // regression). Without clearing here the store keeps presenting the\n // tokens and every action loops refresh→retry→401, rotating the\n // refresh-token family each time — parity with the refresh-failed\n // branch below.\n track.clear();\n throw new ApiError(track.sessionExpiredMessage, { status: 401 });\n }\n } else {\n // Refresh yielded no token. If the refresh path cleared storage, the\n // session is definitively over. If the tokens SURVIVED, the refresh only\n // hit a transient failure (5xx/network) — clearing here would delete a\n // valid refresh token across every tab over a blip. Throw a retryable\n // error instead, deliberately WITHOUT a 401 status: the auth stores end\n // the session on a definitive 401/403 from a profile fetch, and this\n // isn't one.\n if (track.getAccessToken()) {\n throw new ApiError(\n 'We couldn’t reach the server to refresh your session. Please try again.',\n );\n }\n track.clear();\n throw new ApiError(track.sessionExpiredMessage, { status: 401 });\n }\n }\n\n if (!res.ok) {\n let errorMsg = `Request failed: ${res.status}`;\n let errorCode: string | undefined;\n try {\n const body = (await res.json()) as {\n error?: string;\n message?: string;\n details?: unknown[];\n code?: string;\n };\n errorMsg = body.error || body.message || errorMsg;\n // Machine-readable discriminator (e.g. SUBSCRIPTION_EXISTS) for the few\n // rejections a caller must BRANCH on rather than merely display. Matching\n // the prose instead is a trap — the copy is tuned per tenant and changes.\n errorCode = typeof body.code === 'string' ? body.code : undefined;\n // Append per-item details (e.g. which product failed mapping) so callers\n // can surface specifics rather than just a generic top-level error.\n if (track.enrichErrorDetails && Array.isArray(body.details) && body.details.length > 0) {\n // Zod-style details arrive as `{ message }` objects (the catalog\n // authoring routes forward them); a bare join would print \"[object Object]\".\n const lines = body.details\n .map((d: unknown) =>\n typeof d === 'string' ? d : (d as { message?: unknown } | null)?.message,\n )\n .filter((d): d is string => typeof d === 'string' && d.length > 0);\n if (lines.length > 0) errorMsg += `: ${lines.join('; ')}`;\n }\n } catch {\n // ignore parse failure\n }\n if (res.status === 403 && /recaptcha/i.test(errorMsg)) {\n errorMsg = 'We couldn’t verify you’re human. Please refresh the page and try again.';\n }\n // 5xx may be raised AFTER the server committed the mutation, so its outcome\n // is ambiguous too; 4xx is a definitive rejection (nothing happened).\n throw new ApiError(errorMsg, { status: res.status, ambiguous: res.status >= 500, code: errorCode });\n }\n\n // Handle 204 No Content\n if (res.status === 204) return undefined as T;\n\n return (await res.json()) as T;\n}\n\nconst PATIENT_TRACK: TransportTrack = {\n getAccessToken: () => getTokens()?.accessToken,\n clear: clearTokens,\n refresh: () => refreshAccessToken(),\n credentials: undefined,\n sessionExpiredMessage: 'Session expired. Please log in again.',\n enrichErrorDetails: true,\n};\n\nexport async function apiFetch<T = unknown>(\n endpoint: string,\n options: RequestInit & { skipAuth?: boolean; authToken?: string; idempotencyKey?: string } = {},\n): Promise<T> {\n const { skipAuth, authToken, idempotencyKey, ...fetchOpts } = options;\n return coreFetch<T>(endpoint, fetchOpts, PATIENT_TRACK, {\n skipAuth,\n authTokenOverride: authToken,\n idempotencyKey,\n });\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nfunction qs(params?: Record<string, unknown>): string {\n if (!params) return '';\n const p = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== null) p.set(k, String(v));\n }\n const s = p.toString();\n return s ? `?${s}` : '';\n}\n\nfunction post<T = unknown>(\n endpoint: string,\n body?: unknown,\n opts?: { skipAuth?: boolean; idempotencyKey?: string },\n) {\n return apiFetch<T>(endpoint, {\n method: 'POST',\n body: body !== undefined ? JSON.stringify(body) : undefined,\n skipAuth: opts?.skipAuth,\n idempotencyKey: opts?.idempotencyKey,\n });\n}\n\nfunction put<T = unknown>(endpoint: string, body?: unknown) {\n return apiFetch<T>(endpoint, {\n method: 'PUT',\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n}\n\nfunction patch<T = unknown>(endpoint: string, body?: unknown) {\n return apiFetch<T>(endpoint, {\n method: 'PATCH',\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n}\n\nfunction del(endpoint: string) {\n return apiFetch(endpoint, { method: 'DELETE' });\n}\n\n// ── Backend auth response type (flat, no data wrapper) ──────────────\n\ninterface BackendAuthResponse {\n uid: string;\n idToken: string;\n refreshToken: string;\n expiresIn: number;\n paymentToken?: string;\n subscriptionId?: string;\n [key: string]: unknown;\n}\n\n/** Normalize backend auth response into the shape the app expects. */\nfunction normalizeAuthResponse(raw: BackendAuthResponse): {\n user: User;\n accessToken: string;\n refreshToken: string;\n userId: string;\n subscriptionId?: string;\n} {\n return {\n user: {\n id: raw.uid,\n email: '', // Not returned by login/register — fetchProfile fills this in\n firstName: '',\n lastName: '',\n role: 'user',\n },\n accessToken: raw.idToken,\n refreshToken: raw.refreshToken,\n userId: raw.uid,\n subscriptionId: raw.subscriptionId,\n };\n}\n\n// ── API modules ─────────────────────────────────────────────────────\n\nexport const authApi = {\n async login(payload: LoginPayload) {\n const raw = await post<BackendAuthResponse>('/auth/login', payload, { skipAuth: true });\n const normalized = normalizeAuthResponse(raw);\n return { data: normalized } as ApiResponse<typeof normalized>;\n },\n\n async register(payload: RegisterPayload) {\n const raw = await post<BackendAuthResponse>('/auth/register', payload, { skipAuth: true });\n const normalized = normalizeAuthResponse(raw);\n return { data: normalized } as ApiResponse<typeof normalized>;\n },\n\n async refresh(refreshToken: string, userId: string) {\n const raw = await post<BackendAuthResponse>('/auth/refresh', { refreshToken, userId }, { skipAuth: true });\n const normalized = normalizeAuthResponse(raw);\n return { data: normalized } as ApiResponse<typeof normalized>;\n },\n\n async registerAndSubscribe(\n payload: RegisterAndSubscribePayload,\n opts?: { idempotencyKey?: string },\n ) {\n // Send the first-party referral code so the conversion attributes even when\n // the cross-site affiliate_ref cookie is blocked (Safari/incognito).\n const raw = await post<BackendAuthResponse>(\n '/auth/register-and-subscribe',\n { ...payload, affiliateRef: readAffiliateRef() ?? undefined },\n { skipAuth: true, idempotencyKey: opts?.idempotencyKey },\n );\n const normalized = normalizeAuthResponse(raw);\n return { data: normalized } as ApiResponse<typeof normalized>;\n },\n\n checkEmail(email: string) {\n return post<{ exists: boolean }>('/auth/check-email', { email }, { skipAuth: true });\n },\n\n // Self-serve password reset. Both endpoints are unauthenticated (skipAuth) and\n // reCAPTCHA-gated (see RECAPTCHA_ACTIONS). `requestPasswordReset` always 200s\n // for anti-enumeration; the returned `message` is generic success copy.\n requestPasswordReset(params: { email: string; redirectUrl: string }) {\n return post<{ message: string }>('/auth/request-password-reset', params, { skipAuth: true });\n },\n\n resetPassword(params: { email: string; token: string; newPassword: string }) {\n return post<{ message: string }>('/auth/reset-password', params, { skipAuth: true });\n },\n};\n\nexport const apexApi = {\n getConfig(surveyType?: 'glp1' | 'generic') {\n const params = surveyType ? `?surveyType=${surveyType}` : '';\n return apiFetch<ApiResponse>(`/apex/config${params}`, { skipAuth: true });\n },\n\n getSurvey(surveyId: string) {\n return apiFetch<ApiResponse>(`/apex/surveys/${surveyId}`, { skipAuth: true });\n },\n\n getSurveyForDrug(drugId: string) {\n return apiFetch<{ surveyId: string; name: string; description: string | null; drugIds: string[] }>(\n `/apex/surveys/by-drug/${encodeURIComponent(drugId)}`,\n { skipAuth: true },\n );\n },\n\n async getSurveyByType(type: 'glp1' | 'generic') {\n const cfgRes = await apiFetch<ApiResponse<{ surveyId?: string }>>(`/apex/config?surveyType=${type}`, { skipAuth: true });\n const surveyId = (cfgRes.data as { surveyId?: string } | undefined)?.surveyId;\n if (!surveyId) throw new Error(`No ${type} survey configured for this tenant`);\n return apiFetch<ApiResponse>(`/apex/surveys/${surveyId}`, { skipAuth: true });\n },\n\n submitSurvey(payload: SurveySubmitPayload, opts?: { idempotencyKey?: string }) {\n return post(\n `/apex/surveys/${payload.surveyId}/submit`,\n {\n answers: payload.answers,\n patientInfo: payload.patientInfo,\n },\n { idempotencyKey: opts?.idempotencyKey },\n );\n },\n\n checkQualification(surveyId: string, answers: Array<{ questionId: string; value: unknown }>) {\n return post<ApiResponse>(`/apex/surveys/${surveyId}/check-qualification`, { answers });\n },\n\n selectDrug(payload: SelectDrugPayload) {\n return post(`/apex/surveys/${payload.surveyId}/select-drug`, {\n responseId: payload.responseId,\n drugId: payload.drugId,\n });\n },\n\n getPreviousAnswers(surveyId: string) {\n return apiFetch<ApiResponse>(`/apex/surveys/${surveyId}/previous-answers`);\n },\n\n getRequestStatus(requestId: string, drugId?: string, opts?: { authToken?: string }) {\n const q = drugId ? `?drugId=${encodeURIComponent(drugId)}` : '';\n return apiFetch<ApiResponse>(`/apex/requests/${requestId}${q}`, { authToken: opts?.authToken });\n },\n\n listRequests() {\n return apiFetch<{ requests: Array<{\n requestId: string;\n status: 'pending' | 'approved' | 'denied' | 'new' | 'processing' | 'completed';\n drugId?: string;\n drugName?: string;\n dosage?: string;\n priceCents?: number;\n paymentConfirmed?: boolean;\n pharmacySent?: boolean;\n createdAt: string;\n items?: Array<{ drugId?: string; productId?: string; dosage?: string }>;\n }> }>('/apex/requests');\n },\n\n sendToPharmacy(payload: SendToPharmacyPayload) {\n return post(`/apex/requests/${payload.requestId}/send-to-pharmacy`);\n },\n\n createRequest(payload: CreateRequestPayload, opts?: { idempotencyKey?: string }) {\n return post('/apex/requests', payload, { idempotencyKey: opts?.idempotencyKey });\n },\n};\n\n// ── Catalog availability ────────────────────────────────────────────\n//\n// GET /apex/catalog/availability?ids=…&state=XX — per-item deliverability for\n// a set of cart lines (product ids, same ids the site puts in the cart and\n// passes to the v2 survey as drugIds) in a given ship-to state. Apex partners\n// can route one catalog item to several pharmacies serving different states,\n// so this is per-ITEM on top of the tenant-level `unavailableStates` gating\n// in flows/address.ts. Anonymous (works pre-login, same as the rest of the\n// `/apex/*` catalog surface) and ADVISORY ONLY — Apex re-checks at\n// prescriber approval, so a \"true\" here is never a guarantee. See\n// flows/catalogAvailability.ts for the debounced hook that wraps this and the\n// fail-open contract a caller must honor.\n\nexport interface CatalogAvailabilityReason {\n code: string;\n}\n\nexport interface CatalogAvailabilityItem {\n /** Echoes the id as sent (never the backend's resolved Apex id), so a\n * caller can match the result back to its own cart line. */\n id: string;\n available: boolean;\n /** False when the backend never actually asked Apex about this id (a\n * legacy/non-catalog item, or a fail-open answer) — treat as available. */\n checked: boolean;\n /** Present only when unavailable. Codes come from Apex's resolver\n * (`state_not_served`, `unknown_item`, others) — don't branch on a closed\n * list; show generic copy for any unavailable item. */\n reasons?: CatalogAvailabilityReason[];\n}\n\nexport interface CatalogAvailabilityResult {\n state: string;\n /** In request order. */\n items: CatalogAvailabilityItem[];\n /** Present (true) only when Apex was unreachable and every id was answered\n * fail-open. Never a reason to block checkout. */\n degraded?: true;\n}\n\nexport const catalogApi = {\n availability(ids: string[], state: string) {\n return apiFetch<CatalogAvailabilityResult>(\n `/apex/catalog/availability${qs({ ids: ids.join(','), state })}`,\n { skipAuth: true },\n );\n },\n};\n\nexport interface AddressVerifyResult {\n status: 'verified' | 'corrected' | 'undeliverable' | 'unchecked';\n /** Standardized address from the verifier (present on verified/corrected). */\n normalized?: CheckoutAddress;\n /** True when `normalized` differs from the input — the user should confirm it. */\n corrected: boolean;\n messages: string[];\n}\n\nexport const addressesApi = {\n /** Server-side US address deliverability check (Shippo). Fails open: the\n * backend returns `unchecked` when unconfigured/unreachable, never an error. */\n verify(address: CheckoutAddress) {\n return post<AddressVerifyResult>('/addresses/verify', address);\n },\n};\n\nexport const paymentsApi = {\n getConfig() {\n return apiFetch<ApiResponse>('/config/payment');\n },\n\n /** One-time cart charge. The Idempotency-Key header is only sent when the\n * tenant enables `idempotencyKeys` in PortalConfig, and the backend does NOT\n * yet run its idempotency middleware on POST /payments/checkout (unlike\n * prescription-checkout) — the key is best-effort future-proofing and never\n * a license to auto-retry an ambiguous failure: a replay is a possible\n * second real charge until the backend adds the middleware. */\n checkout(payload: CheckoutPayload, opts?: { idempotencyKey?: string }) {\n // Send the first-party referral code (see prescriptionCheckout) so a\n // referred cart checkout attributes even when the affiliate_ref cookie is\n // blocked. POST /payments/checkout reads affiliateRef.\n return post<CheckoutResult>('/payments/checkout', {\n ...payload,\n affiliateRef: readAffiliateRef() ?? undefined,\n }, { idempotencyKey: opts?.idempotencyKey });\n },\n\n prescriptionCheckout(\n payload: {\n drugId: string;\n prescriptionRequestId?: string;\n opaqueData?: Record<string, unknown>;\n promoCode?: string;\n /** Per-order delivery address; backend falls back to the member profile when omitted. */\n shippingAddress?: CheckoutAddress;\n /** Charge billTo; backend falls back to the member profile when omitted. */\n billingAddress?: CheckoutAddress;\n },\n opts?: { idempotencyKey?: string },\n ) {\n // Send the first-party referral code so a referred one-time purchase\n // attributes even when the cross-site affiliate_ref cookie is blocked.\n return post('/payments/prescription-checkout', {\n ...payload,\n affiliateRef: readAffiliateRef() ?? undefined,\n }, { idempotencyKey: opts?.idempotencyKey });\n },\n\n initiate(payload: PaymentInitiatePayload) {\n return post('/payments/initiate', payload);\n },\n\n callback(payload: PaymentCallbackPayload) {\n return post('/payments/callback', payload);\n },\n};\n\nexport const subscriptionsApi = {\n list(params?: PaginationParams, opts?: { authToken?: string }) {\n return apiFetch<ApiResponse>(`/subscriptions${qs(params)}`, { authToken: opts?.authToken });\n },\n\n create(payload: CreateSubscriptionPayload, opts?: { idempotencyKey?: string }) {\n // Attach the first-party referral code (see registerAndSubscribe) so\n // existing-user subscribes attribute without relying on the cookie.\n return post<ApiResponse>(\n '/subscriptions',\n {\n ...payload,\n affiliateRef: readAffiliateRef() ?? undefined,\n },\n { idempotencyKey: opts?.idempotencyKey },\n );\n },\n\n /** Server-priced quote for `create(payload)` — same model, guards and pricing\n * as the charge, nothing charged. 404 on a backend that predates it. */\n preview(payload: SubscriptionPreviewPayload) {\n return post<SubscriptionPreview>('/subscriptions/preview', {\n ...payload,\n affiliateRef: readAffiliateRef() ?? undefined,\n });\n },\n\n get(id: string) {\n return apiFetch<ApiResponse>(`/subscriptions/${id}`);\n },\n\n cancel(id: string) {\n return post(`/subscriptions/${id}/cancel`);\n },\n\n pause(id: string) {\n return post(`/subscriptions/${id}/pause`);\n },\n\n resume(id: string) {\n return post(`/subscriptions/${id}/resume`);\n },\n\n getPaymentMethod(id: string) {\n return apiFetch<ApiResponse>(`/subscriptions/${id}/payment-method`);\n },\n\n updatePaymentMethod(id: string, payload: UpdatePaymentMethodPayload) {\n return put(`/subscriptions/${id}/payment-method`, payload);\n },\n};\n\nexport const messagesApi = {\n listConversations(params?: PaginationParams) {\n return apiFetch<ApiResponse>(`/messages/conversations${qs(params)}`);\n },\n\n getConversation(id: string) {\n return apiFetch<ApiResponse>(`/messages/conversations/${id}`);\n },\n\n listMessages(conversationId: string, params?: PaginationParams) {\n return apiFetch<ApiResponse>(`/messages/conversations/${conversationId}/messages${qs(params)}`);\n },\n\n /**\n * Start (or reuse) the member's care-team conversation with an opening\n * message (1..5000 chars). Answers `{ conversation, message, created }`.\n * 409 `{ error: 'no_care_team' }` means the member has never had a\n * prescriber assigned — there is nothing to route the message to. Loosely\n * typed like the rest of this object: the raw conversation/message shapes\n * are reconciled onto `Conversation`/`ThreadMessage` in flows/messages.ts,\n * which already owns that normalization for every other clinical response.\n */\n start(payload: { text: string }, opts?: { idempotencyKey?: string }) {\n return post<ApiResponse>('/messages/conversations/start', payload, {\n idempotencyKey: opts?.idempotencyKey,\n });\n },\n\n sendMessage(\n conversationId: string,\n payload: SendMessagePayload,\n opts?: { idempotencyKey?: string },\n ) {\n return post(`/messages/conversations/${conversationId}/messages`, payload, {\n idempotencyKey: opts?.idempotencyKey,\n });\n },\n\n markAsRead(conversationId: string) {\n return post(`/messages/conversations/${conversationId}/read`);\n },\n\n uploadAttachment(conversationId: string, file: File) {\n const formData = new FormData();\n formData.append('file', file);\n return apiFetch<ApiResponse>(`/messages/conversations/${conversationId}/attachments`, {\n method: 'POST',\n body: formData,\n });\n },\n\n // Backend answers `{ unreadCount }` at the top level, not `{ count }`.\n getUnreadCount() {\n return apiFetch<ApiResponse<{ unreadCount: number }>>('/messages/unread-count');\n },\n};\n\n// ── Support messaging ───────────────────────────────────────────────\n//\n// Customer <-> support threads, distinct from `messagesApi` above: that one\n// proxies Apex's clinical patient<->prescriber conversations, this one is the\n// backend's own `/support` surface. Two different counterparties, two different\n// systems of record — the member portal merges them into one inbox for display.\n\nexport type SupportThreadStatus = 'open' | 'pending' | 'closed' | 'transferred';\n\n/** Optional customer-picked category, set at thread creation. Routes the\n * question to the right destination (billing/orders/account/technical land\n * with support; medical questions never carry a category — those go to the\n * care team via a different flow entirely). Mirrors the-backend's allowlist. */\nexport type SupportThreadCategory = 'billing' | 'orders' | 'account' | 'technical' | 'other';\n\n/**\n * Mirrors the backend's allowlist so a rejected file fails instantly instead of\n * round-tripping to a 415. The server remains the authority — this is UX, not\n * enforcement. Keep in step with services/supportAttachments.ts in the-backend.\n */\nexport const SUPPORT_ATTACHMENT_MIME_TYPES = [\n 'image/jpeg',\n 'image/png',\n 'image/webp',\n 'image/gif',\n 'image/heic',\n 'application/pdf',\n 'text/plain',\n];\n\n/** 10MB, matching the server's multer cap and the bucket's own limit. */\nexport const SUPPORT_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;\n\n/**\n * How a tenant answers customer support (the-backend's `supportChannel`\n * setting). `portal` is the two-way conversation view. `email` bypasses it: the\n * customer sees only the Support form, each submission is emailed to the\n * tenant's support inbox, and the reply comes back by email — no thread exists\n * on either side. Support only — care-team conversations are never affected.\n */\nexport type SupportChannel = 'portal' | 'email';\n\n/** Tenant setting behind `SupportChannel` (admin only — customers see just the mode). */\nexport interface SupportChannelSettings {\n mode: SupportChannel;\n /** Inbox that receives messages in `email` mode. Kept while in `portal` mode. */\n email: string | null;\n}\n\nexport interface SupportThread {\n id: string;\n subject: string;\n status: SupportThreadStatus;\n lastMessageAt: string;\n lastSender: 'customer' | 'support';\n /** True when the customer has not read the latest support reply. */\n customerUnread: boolean;\n createdAt: string;\n updatedAt: string;\n /** Set by the customer at creation; null when they skipped it. */\n category?: SupportThreadCategory | null;\n}\n\nexport interface SupportAttachment {\n id: string;\n messageId: string;\n filename: string;\n mimeType: string;\n sizeBytes: number;\n createdAt: string;\n}\n\nexport interface SupportMessage {\n id: string;\n threadId: string;\n sender: 'customer' | 'support';\n body: string;\n createdAt: string;\n attachments: SupportAttachment[];\n}\n\n/** Credentials for subscribing to live thread updates. 503 when unconfigured. */\nexport interface SupportRealtimeToken {\n token: string;\n expiresAt: string;\n url: string;\n anonKey: string;\n topics: { tenant: string; threadPrefix: string };\n}\n\nexport const supportApi = {\n listThreads() {\n return apiFetch<\n ApiResponse<{ threads: SupportThread[]; channel?: SupportChannel }> & {\n threads?: SupportThread[];\n /** How this tenant answers support. Absent on an older backend (= portal). */\n channel?: SupportChannel;\n }\n >('/support/threads');\n },\n\n getThread(id: string) {\n return apiFetch<\n ApiResponse<{ thread: SupportThread; messages: SupportMessage[] }> & {\n thread?: SupportThread;\n messages?: SupportMessage[];\n }\n >(`/support/threads/${id}`);\n },\n\n /** Open a new thread. Unlike a clinical conversation this needs a subject. */\n createThread(\n payload: { subject: string; body: string; category?: SupportThreadCategory | null },\n opts?: { idempotencyKey?: string },\n ) {\n return post<\n ApiResponse<{ thread: SupportThread; message: SupportMessage }> & {\n thread?: SupportThread;\n message?: SupportMessage;\n }\n >('/support/threads', payload, { idempotencyKey: opts?.idempotencyKey });\n },\n\n sendMessage(threadId: string, payload: { body: string }, opts?: { idempotencyKey?: string }) {\n return post<ApiResponse<{ message: SupportMessage }> & { message?: SupportMessage }>(\n `/support/threads/${threadId}/messages`,\n payload,\n { idempotencyKey: opts?.idempotencyKey },\n );\n },\n\n markAsRead(threadId: string) {\n return post(`/support/threads/${threadId}/read`);\n },\n\n /**\n * Send the Support form on a tenant whose `SupportChannel` is `email`. One\n * multipart request (the file rides along), nothing is stored, and there is\n * no thread to come back to — the tenant replies by email. Rejects if the\n * email could not be sent, so the form can keep the draft for a retry.\n */\n sendEmail(\n payload: { subject: string; body: string; category?: SupportThreadCategory | null },\n file?: File,\n ) {\n const formData = new FormData();\n formData.append('subject', payload.subject);\n formData.append('body', payload.body);\n if (payload.category) formData.append('category', payload.category);\n if (file) formData.append('file', file);\n return apiFetch<{ sent: boolean }>('/support/email', { method: 'POST', body: formData });\n },\n\n uploadAttachment(threadId: string, file: File, body?: string) {\n const formData = new FormData();\n formData.append('file', file);\n if (body) formData.append('body', body);\n return apiFetch<ApiResponse>(`/support/threads/${threadId}/attachments`, {\n method: 'POST',\n body: formData,\n });\n },\n\n /** Short-lived signed URL for a stored attachment. */\n getAttachmentUrl(attachmentId: string) {\n return apiFetch<ApiResponse<{ url: string }> & { url?: string }>(\n `/support/attachments/${attachmentId}`,\n );\n },\n\n /** Threads (not messages) carrying an unread reply. */\n getUnreadCount() {\n return apiFetch<ApiResponse<{ unreadCount: number }> & { unreadCount?: number }>(\n '/support/unread-count',\n );\n },\n\n /**\n * Realtime credentials. Answers 503 when the deployment has no anon key\n * configured, which callers should treat as \"stay on polling\", not an error.\n */\n getRealtimeToken() {\n return apiFetch<SupportRealtimeToken>('/support/realtime-token');\n },\n};\n\nexport interface ProductSaleSummary {\n saleIds: string[];\n primaryLabel: string;\n endDate?: string;\n discountCents: number;\n finalCents: number;\n}\n\nexport interface CatalogProduct {\n id: string;\n name: string;\n description: string | null;\n price: number | null;\n categories: string[];\n is_subscription: boolean;\n /** Subscription billing cycle as stored on the product. The backend has\n * always sent this on `GET /products` — it was just missing from the type.\n * Sites needing a period in days derive it from here instead of assuming 30.\n * Absent/null on non-subscription products. */\n billing_interval?: { unit: string; length: number } | null;\n benefits: string[];\n metadata: Record<string, unknown> | null;\n /** Available doses for this product, from the linked Apex drug (the source of\n * truth for what's offered). The backend derives this; an empty/absent list\n * means no Apex-backed doses (a plain, dose-less product). */\n available_dosages?: string[];\n /** Optional price overlay keyed by dosage: a dose listed here uses this price,\n * any other available dose falls back to the product's base `price`. */\n dosage_prices: Array<{ dosage: string; price: number; savingsPrice: number | null }>;\n /** When 'flat_fee', the base `price` applies to any dose and the customer-facing\n * UI is expected to hide the variant picker. `dosage_override` (or the first\n * active dose) is the hidden dose used for prescriptions. Defaults to 'per_dose'. */\n pricing_mode?: 'per_dose' | 'flat_fee';\n dosage_override?: string | null;\n /** The linked Apex drug id (the id the survey qualification verdict is keyed\n * on). Carried onto the cart item so request creation can drop drugs the\n * survey marked ineligible. Null for products with no Apex link. */\n apex_drug_id?: string | null;\n /** Merchandising flag set in the admin product editor — featured products are\n * surfaced prominently (e.g. the storefront landing page / a \"Featured\"\n * filter). Absent on older payloads; treat missing as not featured. */\n featured?: boolean;\n thumbnail_url: string | null;\n salePriceCents?: number | null;\n activeSale?: ProductSaleSummary | null;\n}\n\n/**\n * Presentation metadata an admin sets on a category (the-backend `categories`\n * row). The backend-owned replacement for per-site hardcoded `CATEGORY_META`\n * maps keyed by category id.\n *\n * Every field is optional on the wire: a backend deploy that predates the\n * columns simply omits them, and `null` means \"not set — use the site\n * default\". `color` and `icon` are free strings the site interprets (a hex\n * value, a Tailwind class, an icon name); the backend does not validate them.\n */\nexport interface CategoryMetadata {\n /** Short marketing line under the category name. */\n tagline?: string | null;\n /** Longer copy for a category page or hero. */\n description?: string | null;\n imageUrl?: string | null;\n color?: string | null;\n icon?: string | null;\n /** Short chip label, e.g. \"New\" or \"Coming soon\". */\n badge?: string | null;\n /**\n * Hide from storefront indexes. The public list still returns hidden\n * categories (with the flag) so deep links keep working — sites filter.\n */\n hidden?: boolean;\n}\n\nexport interface PublicCategory extends CategoryMetadata {\n id: string;\n name: string;\n order: number;\n}\n\nexport const productsApi = {\n list(category?: string) {\n const params: Record<string, unknown> = {};\n if (category) params.category = category;\n return apiFetch<{ products: CatalogProduct[] }>(`/products${qs(params)}`);\n },\n\n categories() {\n return apiFetch<{ categories: PublicCategory[] }>('/products/categories');\n },\n};\n\nexport interface PromoValidationResponse {\n valid: boolean;\n error?: string;\n promoCode?: {\n id: string;\n code: string;\n discountType: 'percent' | 'fixed';\n discountValueCents: number;\n productIds: string[];\n isExclusive: boolean;\n affiliateId?: string;\n };\n discountCents?: number;\n finalCents?: number;\n}\n\nexport const promoCodesApi = {\n validate(code: string, opts: { productIds?: string[]; subtotalCents?: number } = {}) {\n const params: Record<string, unknown> = { code };\n if (opts.productIds && opts.productIds.length > 0) params.productIds = opts.productIds.join(',');\n if (typeof opts.subtotalCents === 'number') params.subtotalCents = opts.subtotalCents;\n return apiFetch<PromoValidationResponse>(`/promo-codes/validate${qs(params)}`);\n },\n};\n\n/**\n * An offer the signed-in member holds and has not claimed yet: a discount that\n * is theirs if they subscribe by its deadline. Display only — checkout looks\n * the buyer's offers up server-side and never takes one from the client.\n */\nexport interface MemberOffer {\n id: string;\n label: string;\n discountType: 'percent' | 'fixed';\n /** percent: 1–100. fixed: cents. */\n discountValueCents: number;\n /** \"$10\" / \"15%\". */\n amountText: string;\n recurringIndefinite: boolean;\n /** Rebills after the first charge that carry the discount; ignored when indefinite. */\n recurringCharges: number;\n /** Empty = any product. */\n productIds: string[];\n expiresAt: string;\n /** The last full day to claim it, as the member was told (\"November 11, 2026\").\n * Print this; do not format `expiresAt`, which is hours into the next day. */\n deadlineText: string;\n}\n\nexport const offersApi = {\n /** The signed-in member's unclaimed offers (member JWT). */\n mine() {\n return apiFetch<{ offers: MemberOffer[] }>('/offers/mine');\n },\n /**\n * The offers waiting for someone with no account yet, by the address they\n * are registering with — so a guest is shown the price they will be charged.\n * Empty for an address that already has an account. POST: the address never\n * goes in a URL.\n */\n forEmail(email: string) {\n return post<{ offers: MemberOffer[] }>('/offers/for-email', { email });\n },\n};\n\nexport const ordersApi = {\n create(payload: CreateOrderPayload) {\n return post<{ order: Order }>('/orders', payload);\n },\n\n list(params?: PaginationParams) {\n return apiFetch<{ orders: Order[] }>(`/orders${qs(params)}`);\n },\n\n get(id: string) {\n return apiFetch<{ order: Order }>(`/orders/${id}`);\n },\n};\n\nexport const usersApi = {\n async getProfile(opts?: { authToken?: string }) {\n // Backend returns { user: { ... } } at /users/me\n const raw = await apiFetch<{ user: User }>('/users/me', { authToken: opts?.authToken });\n // Normalize snake_case fields from backend\n const u = raw.user;\n const normalized: User = {\n ...u,\n id: u.id,\n email: u.email || (u as Record<string, unknown>).email as string || '',\n firstName: u.firstName || (u as Record<string, unknown>).first_name as string || '',\n lastName: u.lastName || (u as Record<string, unknown>).last_name as string || '',\n role: u.role || 'user',\n };\n return { data: normalized } as ApiResponse<User>;\n },\n\n updateProfile(payload: UpdateProfilePayload) {\n return patch('/users/me', payload);\n },\n};\n\n// ── Members API (shipping, renewals, surveys) ─────────────────────\n\nexport type MemberSurveyMode = 'initial' | 'refill';\n\n/** List entry for a member's own submitted surveys — served from the backend's\n * local ownership records, no Apex round-trip. */\nexport interface MemberSurveyResponseSummary {\n id: string;\n mode: MemberSurveyMode;\n submittedAt: string;\n}\n\nexport interface MemberSurveyTranscriptItem {\n questionId: string;\n question: string;\n answer: string;\n}\n\nexport interface MemberSurveyTranscriptSection {\n sectionId: string;\n title: string;\n items: MemberSurveyTranscriptItem[];\n}\n\n/** Structured transcript of a submitted survey, exactly as asked at submit time\n * (Apex renders from the stored composedSurvey — never recomposed against the\n * current catalog). */\nexport interface MemberSurveyTranscript {\n id: string;\n mode: MemberSurveyMode;\n createdAt: string | null;\n completedAt: string | null;\n drugIds: string[];\n selectedDrugId: string | null;\n patientName: string | null;\n sections: MemberSurveyTranscriptSection[];\n}\n\nexport const membersApi = {\n getMe() {\n return apiFetch<MembersMeResponse>('/members/me');\n },\n\n /** The member's own submitted intake/refill surveys (newest first). */\n getSurveyResponses() {\n return apiFetch<{ responses: MemberSurveyResponseSummary[] }>('/apex/surveys/responses');\n },\n\n getSurveyResponse(responseId: string) {\n return apiFetch<MemberSurveyTranscript>(\n `/apex/surveys/responses/${encodeURIComponent(responseId)}`,\n );\n },\n\n getRequests(opts?: { authToken?: string }) {\n return apiFetch<{ requests: MemberPrescriptionRequest[] }>('/members/me/requests', {\n authToken: opts?.authToken,\n });\n },\n\n /** Cancel a still-under-review request (pending/new only). */\n cancelRequest(requestId: string) {\n return del(`/members/me/requests/${requestId}`);\n },\n\n getPendingSurveys(opts?: { authToken?: string }) {\n return apiFetch<{ surveys: PendingRenewalSurvey[] }>('/members/me/surveys', {\n authToken: opts?.authToken,\n });\n },\n\n completeSurvey(renewalId: string, payload: CompleteSurveyPayload) {\n // `newRequestId` is present only when this cycle's rebill was already\n // observed (charge-first): otherwise the Rx is minted later by the rebill\n // webhook / cron backstop. `declined` is returned on a disqualification.\n return post<{ success: boolean; newRequestId?: string; declined?: boolean }>(\n `/members/me/renewals/${renewalId}/complete-survey`,\n payload,\n );\n },\n};\n\n// ── Admin response types ───────────────────────────────────────────\n\nexport interface AdminDashboardStats {\n totalCustomers: number;\n activeSubscriptions: number;\n totalRevenueCents: number;\n failedPayments30d: number;\n}\n\n/** One price point in the recurring-revenue breakdown: everyone on the same\n * charge amount and billing cycle. */\nexport interface AdminRecurringPricePoint {\n /** What each of them is charged per cycle now (after any discount). */\n amountCents: number;\n intervalDays: number;\n subscribers: number;\n /** Their combined charge brought to a 30-day month. */\n monthlyCents: number;\n}\n\nexport interface AdminRecurringRevenue {\n activeSubscriptions: number;\n monthlyCents: number;\n /** monthlyCents × 12. */\n annualCents: number;\n averageMonthlyCents: number;\n /** Largest share of monthlyCents first. */\n pricePoints: AdminRecurringPricePoint[];\n}\n\nexport interface AdminCustomer {\n uid: string;\n email: string;\n firstName: string;\n lastName: string;\n createdAt: string;\n subscriptionStatus: string;\n status: string;\n}\n\nexport interface AdminPayment {\n id: string;\n date: string;\n amountCents: number;\n status: string;\n customerEmail: string;\n customerUid: string;\n transactionId: string;\n /** Additive fields from the partial-refund ledger; absent on older backends. */\n refundedAmountCents?: number;\n /** Reserved by refunds waiting for the charge to settle; not refundable again. */\n scheduledRefundCents?: number;\n /** A scheduled refund that didn't go out and hasn't been dismissed. */\n scheduledRefundProblem?: AdminScheduledRefundProblem | null;\n failureReason?: string | null;\n type?: string | null;\n customerFirstName?: string;\n customerLastName?: string;\n}\n\nexport interface AdminSubscription {\n id: string;\n medication: string;\n /** Product name resolved server-side (by the row's product, then by Apex drug id).\n * `medication` is free text that on older rows holds an internal code, so prefer\n * this and fall back to `medication` only when absent (older backends). */\n medicationName?: string | null;\n dosage: string;\n status: string;\n amountCents: number;\n intervalDays: number;\n currentPeriodEnd: string;\n createdAt: string;\n customerEmail: string;\n customerUid: string;\n authnetSubscriptionId: string;\n}\n\nexport interface AdminWebhookEvent {\n id: string;\n date: string;\n event_type: string;\n provider: string;\n status: string;\n payload: unknown;\n [key: string]: unknown;\n}\n\nexport interface AdminProduct {\n id: string;\n name: string;\n description: string | null;\n price: number | null;\n savingsPrice: number | null;\n categories: string[];\n isSubscription: boolean;\n billingInterval: { unit: string; length: number } | null;\n benefits: string[];\n metadata: Record<string, unknown> | null;\n apexDrugId: string | null;\n dosageOverride: string | null;\n /** A per-dose price overlay that now also carries the SKU identity binding.\n * `price` is null for a dose that is SKU-bound but charges the product base\n * price (binding is independent of pricing). `apexSkuId` is the drug's stable\n * `skus[].id` this dose maps to. See sku-identity-backend-product-config.md. */\n dosagePrices: Array<{ dosage: string; price: number | null; savingsPrice: number | null; apexSkuId?: string | null }>;\n /** 'per_dose' (default) lets each dose have its own price; 'flat_fee' uses the\n * top-level `price` for any dose and hides the variant picker on storefronts. */\n pricingMode: 'per_dose' | 'flat_fee';\n /** SKU identity (id-native product config): product-level bound SKU id for a\n * single-dose / flat-fee product (per-dose ids live on dosagePrices above). */\n apexSkuId: string | null;\n /** 'bound' = forward the bound apexSkuId; 'prescriber_picks' = forward drugId\n * only (titration / no fixed SKU at order time); null = un-migrated (legacy\n * fuzzy path). */\n skuBindingMode: 'bound' | 'prescriber_picks' | null;\n active: boolean;\n /** Merchandising flag — marks the product for prominent placement (e.g. a\n * \"Featured\" badge or row) on storefronts that choose to surface it. */\n featured: boolean;\n thumbnailUrl: string | null;\n createdAt: string;\n updatedAt: string;\n /** True when `apexDrugId` is a partner catalog item (`cat_…`): the product is\n * pricing + storefront metadata laid over ONE Apex item whose structure\n * (strengths, pharmacy drugs, preference order) Apex owns. The overlay fields\n * below are absent from a backend that predates the unified catalog, so read\n * them as optional. */\n catalogOverlay?: boolean;\n /** `ok` Apex lists the item; `missing` it no longer does; `unavailable` Apex\n * could not be asked (strengths unknown, nothing flagged); `none` the product\n * has no Apex pointer (not prescribed). */\n apexItemStatus?: AdminApexItemStatus;\n /** Apex's current dose ladder with the price a customer would pay for each\n * dose. Fresh from Apex on every read; never a stored copy. */\n strengths?: AdminProductStrength[];\n /** Stored prices whose dose Apex stopped offering. They stay inside\n * `dosagePrices` (never sold) until an admin removes them. */\n orphanedDosePrices?: AdminOrphanedDosePrice[];\n /** Something the product offers cannot be sold for want of a price. */\n needsPrice?: boolean;\n}\n\n/** Read-only fields the backend derives from Apex; never sent on a write. */\nexport type AdminProductOverlayField =\n | 'catalogOverlay'\n | 'apexItemStatus'\n | 'strengths'\n | 'orphanedDosePrices'\n | 'needsPrice';\n\nexport type AdminApexItemStatus = 'ok' | 'missing' | 'unavailable' | 'none';\n\nexport interface AdminProductStrength {\n dosage: string;\n /** The Apex dose id (`cdose_…`) the price hangs on. */\n apexSkuId: string | null;\n price: number | null;\n savingsPrice: number | null;\n priceSource: 'dose' | 'base' | null;\n needsPrice: boolean;\n}\n\nexport type AdminOrphanReason = 'dose_not_listed' | 'dose_inactive' | 'item_not_listed';\n\nexport interface AdminOrphanedDosePrice {\n dosage: string;\n apexSkuId: string | null;\n price: number | null;\n savingsPrice: number | null;\n reason: AdminOrphanReason;\n}\n\nexport interface AdminCategory extends CategoryMetadata {\n id: string;\n name: string;\n order: number;\n}\n\n/** Create payload. Metadata fields are optional; `null` (or empty string) clears. */\nexport interface AdminCategoryInput extends CategoryMetadata {\n id: string;\n name: string;\n order?: number;\n}\n\n/** Update payload — only provided fields change; id is immutable. */\nexport type AdminCategoryUpdate = Partial<Omit<AdminCategoryInput, 'id'>>;\n\nexport interface AdminApexDrug {\n id: string;\n name: string;\n dosages: string[];\n /** SKU identity: the drug's stable, opaque SKUs (partner-safe — no pharmacy\n * productId/internalName). Powers the dose→SKU picker in the product editor.\n * Empty for an un-migrated Apex drug. */\n skus: Array<{ id: string; label: string; active?: boolean }>;\n defaultAdCopy: string | null;\n imported: boolean;\n productId: string | null;\n}\n\nexport interface AdminListParams {\n limit?: number;\n offset?: number;\n search?: string;\n [key: string]: unknown;\n}\n\n// ── Customer 360 (admin) ─────────────────────────────────────────────\n//\n// The customer list and the per-customer overview are served by the-backend's\n// `admin_customer_summary` view plus `GET /admin/customers/:uid/overview`. The\n// lifecycle bucket is derived server-side by ONE rule table that also drives the\n// list's server-side filter, so a row's label and the filter that returned it\n// can never disagree. The package only turns bucket + facts into sentences.\n\nexport type AdminLifecycleBucket =\n | 'active'\n | 'past_due'\n | 'paused'\n | 'incomplete'\n | 'cancelled'\n | 'card_declined'\n | 'awaiting_prescriber'\n | 'never_subscribed';\n\nexport interface AdminLifecycle {\n bucket: AdminLifecycleBucket;\n label: string;\n}\n\n/** Raw per-customer facts from the summary view (the inputs to the bucket). */\nexport interface AdminCustomerFacts {\n subscriptionCount: number;\n liveSubscriptionCount: number;\n latestSubscriptionStatus: string | null;\n nextChargeAt: string | null;\n lastPaymentAt: string | null;\n lastPaymentStatus: string | null;\n /** True when the most recent payment is a rolled-back checkout decline; null with no payments. */\n lastPaymentDetached: boolean | null;\n pendingRequestCount: number;\n latestRequestApexStatus: string | null;\n isSavingsMember: boolean;\n /** An Apex survey.completed capture exists for this email. */\n hasFunnelCapture: boolean;\n hasOpenCart: boolean;\n}\n\n/** A customer list row: the legacy keys plus lifecycle + facts. */\nexport interface AdminCustomerRow extends AdminCustomer {\n lifecycle?: AdminLifecycle;\n facts?: AdminCustomerFacts;\n}\n\nexport interface AdminCustomerListParams {\n limit?: number;\n offset?: number;\n /** Matches email OR name (single escaped ilike server-side). */\n search?: string;\n lifecycle?: AdminLifecycleBucket;\n savingsMember?: boolean;\n hasFunnelCapture?: boolean;\n sort?: 'createdAt' | 'email' | 'lastPaymentAt';\n /** Ask for per-bucket counts. Costs one count query per bucket — request once per visit, not per keystroke. */\n facets?: boolean;\n}\n\nexport interface AdminCustomerProfile {\n uid: string;\n email: string;\n firstName: string;\n lastName: string;\n phone: string;\n createdAt: string;\n /** Account status (`users.status`: active / disabled), not the legacy conflated value. */\n status: string | null;\n paymentStatus: string | null;\n apexMemberId: string | null;\n savingsMemberId: string | null;\n address: {\n address1: string | null;\n address2: string | null;\n city: string | null;\n state: string | null;\n zip: string | null;\n };\n}\n\n// The three \"view\" shapes below mirror the-backend's adminOps billing views\n// (SubscriptionView / PaymentView / BillingAttemptView), which null-fill every\n// column rather than omitting keys. Columns that are NOT NULL in the schema\n// (amount_cents, created_at) are still typed nullable here to match the wire.\n\nexport interface AdminBillingAttempt {\n id: string;\n subscriptionId?: string | null;\n billingPeriod: number | null;\n attemptNo: number | null;\n status: 'pending' | 'indeterminate' | 'succeeded' | 'failed' | string;\n amountCents: number | null;\n transactionId: string | null;\n errorCode: string | null;\n errorMessage: string | null;\n createdAt: string | null;\n updatedAt?: string | null;\n}\n\nexport interface AdminSubscriptionDetail {\n id: string;\n memberUid: string | null;\n customerEmail?: string;\n status: string;\n medication: string | null;\n /** Product name resolved server-side (by the row's product, then by Apex drug id).\n * `medication` is free text that on older rows holds an internal code, so prefer\n * this and fall back to `medication` only when absent (older backends). */\n medicationName?: string | null;\n dosage: string | null;\n productId: string | null;\n amountCents: number | null;\n baseAmountCents: number | null;\n intervalDays: number | null;\n currentPeriodStart: string | null;\n currentPeriodEnd: string | null;\n /** 'gateway' (schedule lives at Authorize.Net) or 'platform' (billing engine). */\n billingMode: 'gateway' | 'platform' | string | null;\n nextChargeAt: string | null;\n billingPeriod: number | null;\n retryCount: number;\n lastAttemptAt: string | null;\n discountRecurringRemaining: number | null;\n discountRecurringIndefinite: boolean;\n gatewaySubscriptionId: string | null;\n provider?: string | null;\n promoCodeId?: string | null;\n /** The promo code text behind `promoCodeId`, resolved server-side; absent on older backends. */\n promoCode?: string | null;\n saleId?: string | null;\n /** The sale name behind `saleId`, resolved server-side; absent on older backends. */\n saleName?: string | null;\n /** What the billing engine will charge next period: the discounted amount while a\n * recurring discount runs, the base amount once it has ended. Absent on older\n * backends — fall back to `amountCents`. */\n nextChargeCents?: number | null;\n affiliateId?: string | null;\n cancelledAt: string | null;\n pausedAt: string | null;\n createdAt: string | null;\n updatedAt?: string | null;\n billingAttempts: AdminBillingAttempt[];\n}\n\nexport interface AdminPaymentDetail {\n id: string;\n memberUid?: string | null;\n createdAt: string | null;\n amountCents: number | null;\n currency?: string | null;\n status: string;\n type: string | null;\n transactionId: string | null;\n failureReason: string | null;\n responseCode?: number | null;\n provider?: string | null;\n refundedAmountCents: number;\n /** Reserved by refunds waiting for the charge to settle; absent on older backends. */\n scheduledRefundCents?: number;\n /** A scheduled refund that didn't go out and hasn't been dismissed. */\n scheduledRefundProblem?: AdminScheduledRefundProblem | null;\n refundTransactionId?: string | null;\n refundReason?: string | null;\n refundedAt: string | null;\n voidedAt: string | null;\n source?: string | null;\n subscriptionId: string | null;\n orderId: string | null;\n /** True for a checkout decline whose subscription was rolled back. */\n detached: boolean;\n rolledBackFrom: { subscriptionId: string | null; productId: string | null; email: string | null } | null;\n}\n\n/** `items` is the order's raw JSONB; the fields below are what checkout writes. */\nexport interface AdminOrderSummary {\n id: string;\n status: string;\n totalCents: number;\n items: Array<{ productId?: string; name?: string; quantity?: number; priceAtPurchase?: number; dosage?: string }>;\n shippingAddress?: unknown;\n subscriptionId: string | null;\n prescriptionRequestId: string | null;\n paymentId: string | null;\n createdAt: string | null;\n}\n\nexport interface AdminCustomerRequest {\n requestId: string;\n productId: string | null;\n drugId: string | null;\n drugName: string | null;\n /** Dashboard status: pending | approved | denied | call_requested | pharmacy | processing | completed | shipped */\n status: string;\n apexStatusLocal: string | null;\n paymentConfirmed: boolean;\n pharmacySent: boolean;\n dosage: string | null;\n createdAt: string | null;\n updatedAt: string | null;\n delivery: DeliveryInfo | null;\n /** The row's own shipping columns; always present, fields null until shipped. */\n tracking: {\n trackingNumber: string | null;\n shipCarrier: string | null;\n deliveryStatus: string | null;\n shippedAt: string | null;\n } | null;\n renewal: {\n id: string;\n status: string;\n cycleNumber: number | null;\n pharmacyFillDate: string | null;\n triggerAt: string | null;\n needsReviewAt?: string | null;\n reviewReason?: string | null;\n } | null;\n /**\n * The assigned pharmacy and its own order number (null until transmitted).\n * Live-read only: null when `live` is false. Optional so an older backend\n * that doesn't send it still type-checks.\n */\n pharmacy?: {\n pharmacyId: string | null;\n pharmacyName: string | null;\n orderNumber: string | null;\n } | null;\n /** False when Apex could not be reached (or the row is past the live cap) and it was built from local columns. */\n live: boolean;\n}\n\nexport interface AdminCustomerSupportThread {\n id: string;\n subject: string | null;\n status: SupportThreadStatus | string;\n lastMessageAt: string | null;\n lastSender: 'customer' | 'support' | string | null;\n adminUnread: boolean;\n /** Optional: present only if the customer-360 summary endpoint includes it. */\n category?: SupportThreadCategory | null;\n}\n\nexport interface AdminCustomerSupport {\n threadCount: number;\n openCount: number;\n adminUnreadCount: number;\n lastMessageAt: string | null;\n threads: AdminCustomerSupportThread[];\n}\n\nexport interface AdminCustomerFunnel {\n telemetryEnabled: boolean;\n cartRecoveryEnabled: boolean;\n /** Each list holds the 20 most recent rows. */\n captures: Array<{\n responseId: string;\n qualified: boolean;\n mode: string | null;\n drugIds: string[];\n capturedAt: string | null;\n convertedAt: string | null;\n remindersSent: number;\n }>;\n sessions: Array<{\n sessionId: string;\n lastStep: number | null;\n stepCount: number | null;\n phase: string | null;\n startedAt: string | null;\n lastSeenAt: string | null;\n convertedAt: string | null;\n remindersSent: number;\n }>;\n carts: Array<{\n cartId: string;\n itemCount: number;\n subtotalCents: number;\n promoCode: string | null;\n updatedAt: string | null;\n convertedAt: string | null;\n recoveredAt: string | null;\n remindersSent: number;\n }>;\n}\n\nexport interface AdminCustomerOverview {\n customer: AdminCustomerProfile;\n lifecycle: AdminLifecycle & { facts: AdminCustomerFacts };\n subscriptions: AdminSubscriptionDetail[];\n payments: AdminPaymentDetail[];\n orders: AdminOrderSummary[];\n requests: { capped: boolean; items: AdminCustomerRequest[] };\n support: AdminCustomerSupport;\n funnel: AdminCustomerFunnel;\n tenant: {\n requirePaidSubscription: boolean;\n fulfillmentMode: 'auto' | 'deferred' | null;\n singleSubscription: boolean;\n savingsProgram: boolean;\n /** The backend can build a reset link itself (tenant domains configured). */\n passwordResetAvailable: boolean;\n };\n /** Sections that failed to load and came back empty (e.g. 'support', 'funnel'). */\n partial: string[];\n}\n\nexport interface AdminSubscriptionPatch {\n amountCents?: number;\n nextChargeAt?: string | null;\n currentPeriodStart?: string;\n currentPeriodEnd?: string;\n}\n\nexport interface AdminSubscriptionWriteResult {\n subscription: AdminSubscriptionDetail;\n before: AdminSubscriptionDetail;\n warnings?: string[];\n}\n\nexport interface AdminRefundResult {\n success: boolean;\n refundId?: string;\n refundedAmountCents?: number;\n remainingCents?: number;\n status?: string;\n error?: string;\n code?: string;\n /**\n * True when the charge hadn't settled, so the (partial) refund was queued\n * instead of issued: no money has moved yet, the backend retries hourly and\n * emails the customer when it goes out. `remainingCents` already excludes it.\n */\n scheduled?: boolean;\n scheduledRefund?: AdminScheduledRefund;\n}\n\n/**\n * A scheduled refund that did NOT go out (gave up waiting for settlement, or\n * the gateway declined). The customer was not refunded or told. Shown until an\n * admin dismisses it or refunds the payment again.\n */\nexport interface AdminScheduledRefundProblem {\n id: string;\n amountCents: number;\n reason: string;\n at: string;\n}\n\n/** A refund queued until its charge settles (`/admin/payments/:id/scheduled-refunds`). */\nexport interface AdminScheduledRefund {\n id: string;\n paymentId: string;\n amountCents: number;\n status: 'scheduled' | 'processing' | 'completed' | 'failed' | 'cancelled';\n reason: string;\n note: string | null;\n requestedBy: string | null;\n attempts: number;\n lastError: string | null;\n nextAttemptAt: string;\n giveUpAt: string;\n refundTransactionId: string | null;\n completedAt: string | null;\n orderId?: string | null;\n createdAt: string;\n}\n\n// ── Catalog authoring (admin) ────────────────────────────────────────\n//\n// `/admin/catalog/*` is a pass-through to the tenant's own Apex partner catalog.\n// Apex OWNS this structure — items, dose ladders, the pharmacy drug that fills\n// an item at each pharmacy, and the pharmacies' preference order — and the\n// backend keeps no copy of it. Apex's own validation (classification must\n// agree, one fulfillment per pharmacy, …) answers in `error` and is meant to be\n// shown to the admin verbatim. Failures reach callers as `ApiError`:\n// 4xx Apex rejected the write; `message` is Apex's.\n// 502/504 code `apex_unavailable` — Apex could not be asked.\n// 502 code `apex_credentials_rejected` — our key was refused.\n// 409 code `apex_not_configured` — the tenant has no Apex link.\n// See `flows/productCatalog.ts` for how the editor reacts to each.\n\nexport type CatalogClassification = 'controlled' | 'non-controlled';\nexport type CatalogDoseModel = 'clinical' | 'sku';\n\nexport interface CatalogItem {\n /** `cat_…` — the id a product's `apexDrugId` points at. */\n id: string;\n partnerId?: string;\n name: string;\n description?: string | null;\n classification: CatalogClassification;\n /** 'clinical' doses carry a value + unit and are portable across pharmacies;\n * 'sku' doses are the routed pharmacy's own labels. Fixed after creation. */\n doseModel: CatalogDoseModel;\n active: boolean;\n createdAt?: string;\n updatedAt?: string | null;\n}\n\nexport interface CatalogDose {\n /** `cdose_…` — the id a product's price for this strength hangs on. */\n id: string;\n itemId: string;\n label: string;\n value?: number | null;\n unit?: string | null;\n displayOrder: number;\n active: boolean;\n}\n\nexport interface CatalogFulfillment {\n id: string;\n itemId: string;\n pharmacyId: string;\n /** The pharmacy drug that fills the item at that pharmacy. */\n drugId: string;\n /** Lower wins. */\n preferenceRank: number;\n enabled: boolean;\n /** Where this product may not go though the pharmacy serves the state. */\n excludedStates: string[];\n}\n\nexport interface CatalogMatrixCell {\n producible: boolean;\n /** Operator-readable; present only when it can't be made. */\n detail?: string;\n}\n\n/** An item with its ladder, its mappings and whether each rung can be produced\n * at each pharmacy. Apex answers this after every write too. */\nexport interface CatalogReadiness {\n item: CatalogItem;\n doses: CatalogDose[];\n fulfillments: CatalogFulfillment[];\n /** doseId → fulfillmentId → cell. */\n matrix: Record<string, Record<string, CatalogMatrixCell>>;\n /** fulfillmentId → setup problems that block the whole mapping. */\n fulfillmentProblems: Record<string, string[]>;\n warnings: string[];\n}\n\n/** A pharmacy drug the partner may map (\"pick a pharmacy drug\"). */\nexport interface CatalogMappableDrug {\n id: string;\n name: string;\n pharmacyId: string | null;\n pharmacyName: string | null;\n classification: CatalogClassification;\n}\n\nexport interface CatalogEquivalentSuggestions {\n suggestion: true;\n drugId: string;\n activesKey: string | null;\n matches: Array<{\n drugId: string;\n name: string;\n pharmacyId: string | null;\n classification: string;\n }>;\n note: string;\n}\n\nexport interface CatalogDoseSuggestion {\n label: string;\n value: number | null;\n unit: string | null;\n /** Which mapped drugs carry this rung. */\n fromDrugIds: string[];\n}\n\nexport interface CatalogDoseSuggestions {\n doseModel: CatalogDoseModel;\n suggestions: CatalogDoseSuggestion[];\n}\n\nexport interface CatalogItemInput {\n name: string;\n classification: CatalogClassification;\n doseModel: CatalogDoseModel;\n description?: string;\n active?: boolean;\n}\n\nexport interface CatalogDoseInput {\n label: string;\n value?: number;\n unit?: string;\n displayOrder?: number;\n active?: boolean;\n}\n\nexport interface CatalogFulfillmentInput {\n pharmacyId: string;\n drugId: string;\n preferenceRank?: number;\n enabled?: boolean;\n /** A write REPLACES the list: send the full set you want, omit to keep. */\n excludedStates?: string[];\n}\n\nconst catalogPath = (itemId: string) => `/admin/catalog/${encodeURIComponent(itemId)}`;\n\n/** The 17 `/admin/catalog` routes, one method each. Admin-only. */\nexport const adminCatalogApi = {\n /** Same-actives drugs at OTHER pharmacies — advisory, a human decides. */\n suggestEquivalents(drugId: string) {\n return apiFetch<CatalogEquivalentSuggestions>(`/admin/catalog/suggest${qs({ drugId })}`);\n },\n\n /** The pharmacy drugs this tenant may map to a catalog item. */\n listDrugs() {\n return apiFetch<{ drugs: CatalogMappableDrug[] }>('/admin/catalog/drugs');\n },\n\n /** Seeds an item, its dose ladder and its first fulfillment from a drug. */\n createItemFromDrug(drugId: string) {\n return post<CatalogReadiness>('/admin/catalog/from-drug', { drugId });\n },\n\n listItems() {\n return apiFetch<{ items: CatalogReadiness[] }>('/admin/catalog');\n },\n\n createItem(input: CatalogItemInput) {\n return post<CatalogItem>('/admin/catalog', input);\n },\n\n getItem(itemId: string) {\n return apiFetch<CatalogReadiness>(catalogPath(itemId));\n },\n\n updateItem(itemId: string, patch_: Partial<CatalogItemInput>) {\n return patch<CatalogItem>(catalogPath(itemId), patch_);\n },\n\n deleteItem(itemId: string) {\n return apiFetch<{ success: boolean }>(catalogPath(itemId), { method: 'DELETE' });\n },\n\n getMatrix(itemId: string) {\n return apiFetch<CatalogReadiness>(`${catalogPath(itemId)}/matrix`);\n },\n\n getSuggestedDoses(itemId: string) {\n return apiFetch<CatalogDoseSuggestions>(`${catalogPath(itemId)}/suggested-doses`);\n },\n\n createDose(itemId: string, input: CatalogDoseInput) {\n return post<CatalogDose>(`${catalogPath(itemId)}/doses`, input);\n },\n\n updateDose(itemId: string, doseId: string, patch_: Partial<CatalogDoseInput>) {\n return patch<CatalogDose>(`${catalogPath(itemId)}/doses/${encodeURIComponent(doseId)}`, patch_);\n },\n\n deleteDose(itemId: string, doseId: string) {\n return apiFetch<{ success: boolean }>(`${catalogPath(itemId)}/doses/${encodeURIComponent(doseId)}`, {\n method: 'DELETE',\n });\n },\n\n /** Renumbers the item's fulfillments 1..n in the order given. */\n setFulfillmentOrder(itemId: string, orderedIds: string[]) {\n return put<{ fulfillments: CatalogFulfillment[] }>(`${catalogPath(itemId)}/fulfillments/order`, {\n orderedIds,\n });\n },\n\n createFulfillment(itemId: string, input: CatalogFulfillmentInput) {\n return post<CatalogFulfillment>(`${catalogPath(itemId)}/fulfillments`, input);\n },\n\n updateFulfillment(\n itemId: string,\n fulfillmentId: string,\n patch_: Partial<Pick<CatalogFulfillmentInput, 'preferenceRank' | 'enabled' | 'excludedStates'>>,\n ) {\n return patch<CatalogFulfillment>(\n `${catalogPath(itemId)}/fulfillments/${encodeURIComponent(fulfillmentId)}`,\n patch_,\n );\n },\n\n deleteFulfillment(itemId: string, fulfillmentId: string) {\n return apiFetch<{ success: boolean }>(\n `${catalogPath(itemId)}/fulfillments/${encodeURIComponent(fulfillmentId)}`,\n { method: 'DELETE' },\n );\n },\n};\n\n// ── Per-product catalog conversion (admin) ───────────────────────────\n//\n// Move ONE legacy prescribed product (`apexDrugId` is a pharmacy drug id) onto a\n// partner catalog item, and back. The server owns the state machine; every\n// answer carries the stage the product is in, and that stage — not anything the\n// client remembers — decides what is offered next. See `flows/catalogConversion.ts`.\n//\n// GET /admin/products/:id/catalog-conversion preview (read-only)\n// POST …/catalog-conversion/prepare { planHash } create the item, INACTIVE\n// POST …/catalog-conversion { planHash, doseMatches } activate + re-point\n// POST …/catalog-conversion/undo { deactivateItem?, force? }\n//\n// The commit waits for the backend's other instances' caches to catch up and\n// takes about 35 seconds. NOTHING in this client times a request out on its own\n// (the only timeout in this file bounds a token refresh), so a commit is never\n// cut short here; a proxy in between might, which reaches callers as an\n// ambiguous failure and is reconciled by re-reading the preview.\n//\n// A refusal is `{ error, code, details?, preview? }` and surfaces as an\n// `ApiError` carrying the backend's own `message` and `code`. The codes callers\n// branch on: 409 `blocked`, `plan_changed`, `prepare_first`, `edited_since`,\n// `renewal_in_flight`, `conversion_in_progress`; 400 `invalid_dose_matches`;\n// 502 for an Apex failure (`apex_refused`, `activation_failed`, `repoint_failed`).\n// The refusal's own `preview` is not kept on the error: callers re-read the\n// preview, which is also how they learn the outcome of a request whose answer\n// never arrived.\n\nexport type CatalogConversionStage =\n | 'not_started'\n | 'ready_to_commit'\n | 'active_not_committed'\n | 'committed_not_active'\n | 'converted'\n | 'not_convertible';\n\n/** One blocker / warning / note. `rows` is evidence for support, not for display. */\nexport interface CatalogConversionFinding {\n /** Stable machine code, e.g. `renewal_in_flight`. Branch on this, never on the prose. */\n code: string;\n check: string;\n /** The backend's explanation, in plain English. */\n message: string;\n rowCount: number;\n rows: unknown[];\n truncated: boolean;\n}\n\n/** The three product fields a conversion changes, and nothing else. */\nexport interface CatalogConversionPointers {\n apex_drug_id: string | null;\n apex_sku_id: string | null;\n dosage_prices: unknown[];\n}\n\nexport type CatalogConversionTarget =\n | {\n kind: 'existing';\n itemId: string;\n itemName: string;\n doseModel: string | null;\n active: boolean;\n /** An earlier `prepare` of this product created it. */\n createdByConversion: boolean;\n }\n | { kind: 'create_from_drug'; drugId: string; doseModel: null };\n\n/** A stored value the conversion must decide for. */\nexport interface CatalogConversionSource {\n /** A price entry, the single-dose binding, or a label only subscribers hold. */\n field: 'dosage_prices' | 'apex_sku_id' | 'subscriber_dose';\n dosage: string | null;\n apexSkuId: string | null;\n price: number | null;\n savingsPrice: number | null;\n /** Open renewal cycles of this product stored on this label. */\n subscriberCount: number;\n /** A price entry bound to the same id as the single-dose binding: its match re-keys both. */\n alsoKeysApexSkuId?: boolean;\n}\n\nexport interface CatalogConversionDoseMatch {\n source: CatalogConversionSource;\n suggestedDoseId: string | null;\n /** How the suggestion was found; null when there is none. */\n how: 'source_sku' | 'exact_label' | 'already_bound' | null;\n}\n\nexport interface CatalogConversionDose {\n id: string;\n label: string;\n active: boolean;\n /** Offered right now: the only doses a match may name. */\n live: boolean;\n sourceSkuId: string | null;\n}\n\nexport interface CatalogConversionRun {\n runId: string;\n planHash: string | null;\n itemId: string;\n appliedAt: string;\n actor: string;\n activated: boolean;\n}\n\nexport interface CatalogConversionPreview {\n tenantId: string;\n productId: string;\n generatedAt: string;\n stage: CatalogConversionStage;\n /** No blockers, and a step is available. */\n eligible: boolean;\n nextStep: 'prepare' | 'commit' | 'none';\n nextStepDescription: string;\n drugListMode: { header: string | null; effective: 'mixed' | 'catalog_only' } | null;\n product: { id: string; name: string; pricingMode: string; current: CatalogConversionPointers };\n target: CatalogConversionTarget | null;\n /** False until the target item exists (create-from-drug): suggestions are all null then. */\n dosesKnown: boolean;\n doses: CatalogConversionDose[];\n doseMatches: CatalogConversionDoseMatch[];\n plannedAfter: CatalogConversionPointers | null;\n strengthsAfter: Array<{\n dosage: string;\n apexSkuId: string | null;\n price: number | null;\n priceSource: string | null;\n needsPrice: boolean;\n }>;\n blockers: CatalogConversionFinding[];\n warnings: CatalogConversionFinding[];\n info: CatalogConversionFinding[];\n /** The conversion currently in force for this product, if any. */\n conversion: CatalogConversionRun | null;\n /** Fingerprint of everything the next step acts on; null when nothing can be planned. */\n planHash: string | null;\n /** Operator-facing text; the editor renders the structured fields instead. */\n summary: string;\n}\n\nexport interface CatalogConversionPrepareResult {\n status: 'prepared' | 'already_prepared';\n itemId: string;\n correctedActive?: boolean;\n preview: CatalogConversionPreview;\n message: string;\n}\n\n/** The admin's choice for one source: a live dose of the item, or `null` = not carried over. */\nexport interface CatalogConversionChoice {\n source: { dosage: string | null; apexSkuId: string | null };\n doseId: string | null;\n}\n\nexport interface CatalogConversionCommitResult {\n status: 'converted' | 'already_converted';\n runId: string;\n itemId: string;\n before: CatalogConversionPointers;\n after: CatalogConversionPointers;\n activatedNow: boolean;\n warnings: CatalogConversionFinding[];\n preview: CatalogConversionPreview;\n message: string;\n}\n\nexport interface CatalogConversionUndoOptions {\n /** Also switch the catalog item off. The backend refuses when something else still needs it. */\n deactivateItem?: boolean;\n /** Overwrite edits made to the product's pointers since the conversion. */\n force?: boolean;\n}\n\nexport interface CatalogConversionUndoResult {\n status: 'undone';\n runId: string;\n itemId: string;\n restored: CatalogConversionPointers;\n overwrittenEdit: CatalogConversionPointers | null;\n otherProductsOnItem: string[];\n item: { id: string; deactivated: boolean; stillActive: boolean | null; deactivationRefused: string[] };\n requestsOnCatalogId: { count: number; rows: unknown[] };\n /** Plainly: what this did NOT undo. */\n notUndone: string[];\n message: string;\n}\n\nconst conversionPath = (productId: string) => `/admin/products/${encodeURIComponent(productId)}/catalog-conversion`;\n\nexport const adminCatalogConversionApi = {\n /** Where the product stands and what the next step would do. Read-only; safe to repeat. */\n preview(productId: string) {\n return apiFetch<CatalogConversionPreview>(conversionPath(productId));\n },\n\n /** Creates the catalog item INACTIVE (nothing is sold from it). Idempotent server-side. */\n prepare(productId: string, planHash: string) {\n return post<CatalogConversionPrepareResult>(`${conversionPath(productId)}/prepare`, { planHash });\n },\n\n /**\n * Activates the item and re-points the product. Takes about 35 seconds; never\n * retry it blindly — re-read the preview first.\n */\n commit(productId: string, body: { planHash: string; doseMatches: CatalogConversionChoice[] }) {\n return post<CatalogConversionCommitResult>(conversionPath(productId), body);\n },\n\n /** Puts a converted product back as it was. Does not undo everything — read `notUndone`. */\n undo(productId: string, options: CatalogConversionUndoOptions = {}) {\n return post<CatalogConversionUndoResult>(`${conversionPath(productId)}/undo`, options);\n },\n};\n\nexport const adminApi = {\n getDashboard() {\n return apiFetch<AdminDashboardStats>('/admin/dashboard/stats');\n },\n\n getRecurringRevenue() {\n return apiFetch<AdminRecurringRevenue>('/admin/dashboard/recurring-revenue');\n },\n\n getCustomers(params?: AdminCustomerListParams & AdminListParams) {\n // `facets` is a flag, not a value: send it as `1` and drop it when false so\n // the URL stays stable for the common no-facets fetch.\n const query = params\n ? { ...params, facets: params.facets ? 1 : undefined }\n : undefined;\n return apiFetch<{\n customers: AdminCustomerRow[];\n hasMore: boolean;\n facets?: Partial<Record<AdminLifecycleBucket, number>>;\n }>(`/admin/customers${qs(query)}`);\n },\n\n getCustomer(id: string) {\n return apiFetch<{ customer: AdminCustomer; subscriptions: AdminSubscription[]; recentPayments: AdminPayment[] }>(`/admin/customers/${id}`);\n },\n\n /** The customer 360: every per-customer record the support view renders, in one call. */\n getCustomerOverview(uid: string) {\n return apiFetch<AdminCustomerOverview>(`/admin/customers/${uid}/overview`);\n },\n\n /**\n * Edit a subscription's price and/or schedule. Amount edits are refused (409)\n * for gateway-billed subscriptions — their schedule lives at Authorize.Net.\n */\n updateSubscription(id: string, body: AdminSubscriptionPatch) {\n return patch<AdminSubscriptionWriteResult>(`/admin/subscriptions/${id}`, body);\n },\n\n pauseSubscription(id: string) {\n return post<AdminSubscriptionWriteResult>(`/admin/subscriptions/${id}/pause`, {});\n },\n\n resumeSubscription(id: string) {\n return post<AdminSubscriptionWriteResult>(`/admin/subscriptions/${id}/resume`, {});\n },\n\n /** Close a pending/indeterminate billing attempt so the engine can move on. */\n resolveBillingAttempt(subscriptionId: string, attemptId: string, resolution: 'failed' | 'succeeded') {\n return post<{ before: AdminBillingAttempt; after: AdminBillingAttempt }>(\n `/admin/subscriptions/${subscriptionId}/billing-attempts/${attemptId}/resolve`,\n { resolution },\n );\n },\n\n /**\n * Mint a short-lived (15-min) impersonation token to preview the patient\n * dashboard as this customer, read-only. The returned token authenticates\n * GET reads only; any write with it is rejected 403 by the backend.\n */\n impersonateCustomer(uid: string) {\n return post<{ token: string; expiresAt: string; customer: AdminCustomer }>(\n `/admin/customers/${uid}/impersonate`,\n {},\n );\n },\n\n updateCustomerEmail(uid: string, email: string) {\n return patch<{ customer: AdminCustomer }>(`/admin/customers/${uid}/email`, { email });\n },\n\n /** Edit the name on the account. Email has its own endpoint (it notifies both addresses). */\n updateCustomerName(uid: string, name: { firstName: string; lastName: string }) {\n return patch<{ customer: AdminCustomer }>(`/admin/customers/${uid}`, {\n first_name: name.firstName,\n last_name: name.lastName,\n });\n },\n\n // `redirectUrl` is the absolute URL of the host site's password-reset page;\n // the backend appends `?token=…&email=…` before emailing the customer. When\n // omitted, the backend builds the link from the tenant's configured domains\n // (see the overview's `tenant.passwordResetAvailable`).\n sendPasswordReset(uid: string, redirectUrl?: string) {\n return post<{ ok: true }>(\n `/admin/customers/${uid}/send-password-reset`,\n redirectUrl ? { redirectUrl } : {},\n );\n },\n\n getPayments(params?: AdminListParams) {\n return apiFetch<{ payments: AdminPayment[]; hasMore: boolean }>(`/admin/payments${qs(params)}`);\n },\n\n /**\n * Refund a payment, in full (no amount) or in part. Partial refunds\n * accumulate on the row; the backend answers 409 `unsettled_requires_void`\n * when a partial is requested against a charge the gateway has not settled.\n */\n refundPayment(id: string, opts?: number | { amountCents?: number; reason?: string }) {\n const body =\n typeof opts === 'number'\n ? { amountCents: opts }\n : opts\n ? { ...(opts.amountCents ? { amountCents: opts.amountCents } : {}), ...(opts.reason ? { reason: opts.reason } : {}) }\n : {};\n return post<AdminRefundResult>(`/admin/payments/${id}/refund`, body);\n },\n\n getScheduledRefunds(paymentId: string) {\n return apiFetch<{ scheduledRefunds: AdminScheduledRefund[] }>(`/admin/payments/${paymentId}/scheduled-refunds`);\n },\n\n /** Stop flagging this payment's failed scheduled refund(s). */\n dismissScheduledRefundProblem(paymentId: string) {\n return post<{ dismissed: number }>(`/admin/payments/${paymentId}/scheduled-refunds/dismiss`);\n },\n\n /** Cancel every still-waiting scheduled refund on a payment. 409 while one is being issued. */\n cancelScheduledRefunds(paymentId: string) {\n return del(`/admin/payments/${paymentId}/scheduled-refunds`) as Promise<{ cancelled: AdminScheduledRefund[]; busy: number }>;\n },\n\n // QuickBooks self-service connect (tenant admin).\n quickbooksStatus() {\n return apiFetch<{ provider: string | null; connected: boolean; realmId?: string; environment: string }>('/admin/quickbooks/status');\n },\n\n connectQuickBooks(returnUrl: string) {\n return post<{ authUrl: string }>('/admin/quickbooks/connect', { returnUrl });\n },\n\n getSubscriptions(params?: AdminListParams) {\n return apiFetch<{ subscriptions: AdminSubscription[]; hasMore: boolean }>(`/admin/subscriptions${qs(params)}`);\n },\n\n cancelSubscription(id: string) {\n return post<{\n success: boolean;\n // Canceling cascades to the member's still-unapproved Apex requests when\n // this was their last live plan; the route reports what it touched.\n requestsCancelled?: string[];\n requestsSkipped?: Array<{ requestId: string; status: string }>;\n requestsFailed?: Array<{ requestId: string; error: string }>;\n }>(`/admin/subscriptions/${id}/cancel`);\n },\n\n /**\n * Cancel a customer's still-unapproved Apex requests without touching billing.\n * Backfill for members cancelled before the on-cancel cascade existed, whose\n * requests are still sitting in the prescriber queue. Idempotent; 409s while\n * the customer has a live subscription unless `force` is set.\n */\n cancelUnapprovedRequests(uid: string, opts?: { force?: boolean }) {\n return post<{\n success: boolean;\n cancelled: string[];\n skipped: Array<{ requestId: string; status: string }>;\n failed: Array<{ requestId: string; error: string }>;\n }>(`/admin/customers/${uid}/cancel-unapproved-requests`, opts?.force ? { force: true } : {});\n },\n\n getWebhookEvents(params?: AdminListParams) {\n return apiFetch<{ events: AdminWebhookEvent[]; hasMore: boolean }>(`/admin/webhook-events${qs(params)}`);\n },\n\n // The email-template calls use the backend's `format=body` shape: one HTML\n // `body` per template rather than greeting / paragraphs / closing.\n getEmailTemplates() {\n return apiFetch<{\n templates: EmailTemplatesMap;\n placeholders: TemplatePlaceholdersMap;\n customTemplates: CustomTemplate[];\n /** Tokens every custom template may use (rendered through the sequence mailer). */\n customPlaceholders: Placeholder[];\n }>('/admin/settings/email-templates?format=body');\n },\n\n createCustomTemplate(input: CustomTemplateInput) {\n return post<CustomTemplate>('/admin/settings/email-templates/custom?format=body', input);\n },\n\n updateCustomTemplate(id: string, input: CustomTemplateInput) {\n return put<CustomTemplate>(`/admin/settings/email-templates/custom/${id}?format=body`, input);\n },\n\n /** Rejects with the server's message (409) while a sequence still uses it. */\n deleteCustomTemplate(id: string) {\n return apiFetch<{ success: boolean }>(`/admin/settings/email-templates/custom/${id}`, { method: 'DELETE' });\n },\n\n sendCustomTemplateTest(id: string) {\n return post<{ success: boolean; sentTo: string }>(`/admin/settings/email-templates/custom/${id}/test`);\n },\n\n saveEmailTemplates(templates: EmailTemplatesMap) {\n return put<{ success: boolean }>('/admin/settings/email-templates', { templates });\n },\n\n resetEmailTemplate(templateKey: string) {\n return post<{ success: boolean; template: TemplateText }>('/admin/settings/email-templates/reset?format=body', { templateKey });\n },\n\n sendTestEmail(templateKey: string) {\n return post<{ success: boolean; sentTo?: string; error?: string }>('/admin/settings/email-templates/test', { templateKey });\n },\n\n /** Every optional feature of this tenant, with its state and any pending request. */\n getFeatures() {\n return apiFetch<{ features: TenantFeature[] }>('/admin/features');\n },\n\n /** Switch a self-serve feature. Returns the whole list: dependents can change with it. */\n setFeature(key: string, enabled: boolean) {\n return put<{ features: TenantFeature[] }>(`/admin/features/${encodeURIComponent(key)}`, { enabled });\n },\n\n /** Ask the platform team to turn a feature on. `emailed` is false when the ask was saved but no email went out. */\n requestFeature(key: string, note?: string) {\n return post<{ feature: TenantFeature; emailed: boolean; alreadyRequested: boolean }>(\n `/admin/features/${encodeURIComponent(key)}/request`,\n note ? { note } : {},\n );\n },\n\n getEmailNotifications() {\n return apiFetch<EmailNotificationSettings>('/admin/settings/email-notifications');\n },\n\n saveEmailNotifications(settings: EmailNotificationSettings) {\n return put<{ success: boolean }>('/admin/settings/email-notifications', settings);\n },\n\n getSupportChannel() {\n return apiFetch<SupportChannelSettings>('/admin/settings/support-channel');\n },\n\n saveSupportChannel(settings: SupportChannelSettings) {\n return put<{ success: boolean }>('/admin/settings/support-channel', settings);\n },\n\n getBillingReminders() {\n return apiFetch<BillingReminderSettings>('/admin/settings/billing-reminders');\n },\n\n saveBillingReminders(settings: BillingReminderSettings) {\n return put<{ success: boolean }>('/admin/settings/billing-reminders', settings);\n },\n\n // ── Products ───────────────────────────────────────────────────\n\n getProducts(params?: AdminListParams & { category?: string }) {\n return apiFetch<{ products: AdminProduct[]; total: number; hasMore: boolean }>(`/admin/products${qs(params)}`);\n },\n\n getProduct(id: string) {\n return apiFetch<{ product: AdminProduct }>(`/admin/products/${id}`);\n },\n\n updateProduct(\n id: string,\n payload: Partial<Omit<AdminProduct, 'id' | 'createdAt' | 'updatedAt' | AdminProductOverlayField>>,\n ) {\n return patch<{ product: AdminProduct }>(`/admin/products/${id}`, payload);\n },\n\n deleteProduct(id: string) {\n return del(`/admin/products/${id}`);\n },\n\n getApexDrugs() {\n return apiFetch<{ drugs: AdminApexDrug[]; error?: string }>('/admin/products/apex-drugs');\n },\n\n importFromApex(drugs: Array<{ drugId: string; name: string }>) {\n return post<{ imported: Array<{ productId: string; drugId: string; name: string }>; skipped: Array<{ drugId: string; reason: string }> }>('/admin/products/import-from-apex', { drugs });\n },\n\n uploadThumbnail(productId: string, file: File) {\n const formData = new FormData();\n formData.append('file', file);\n return apiFetch<{ thumbnailUrl: string }>(`/admin/products/${productId}/thumbnail`, {\n method: 'POST',\n body: formData,\n });\n },\n\n deleteThumbnail(productId: string) {\n return del(`/admin/products/${productId}/thumbnail`);\n },\n\n // ── Sales ──────────────────────────────────────────────────────\n\n getSales() {\n return apiFetch<{ sales: AdminSale[] }>('/admin/sales');\n },\n\n createSale(payload: AdminSaleInput) {\n return post<{ sale: AdminSale }>('/admin/sales', payload);\n },\n\n updateSale(id: string, payload: Partial<AdminSaleInput>) {\n return patch<{ sale: AdminSale }>(`/admin/sales/${id}`, payload);\n },\n\n deleteSale(id: string) {\n return del(`/admin/sales/${id}`);\n },\n\n // ── Promo Codes ────────────────────────────────────────────────\n\n getPromoCodes() {\n return apiFetch<{ promoCodes: AdminPromoCode[] }>('/admin/promo-codes');\n },\n\n createPromoCode(payload: AdminPromoCodeInput) {\n return post<{ promoCode: AdminPromoCode }>('/admin/promo-codes', payload);\n },\n\n updatePromoCode(id: string, payload: Partial<AdminPromoCodeInput>) {\n return patch<{ promoCode: AdminPromoCode }>(`/admin/promo-codes/${id}`, payload);\n },\n\n deletePromoCode(id: string) {\n return del(`/admin/promo-codes/${id}`);\n },\n\n // ── Offers ─────────────────────────────────────────────────────\n // A discount one person holds before they subscribe. The offer is the\n // definition; a grant is one person holding it, with their own deadline.\n\n getOffers() {\n return apiFetch<{ offers: AdminOffer[] }>('/admin/offers');\n },\n\n createOffer(payload: AdminOfferInput) {\n return post<{ offer: AdminOfferBase }>('/admin/offers', payload);\n },\n\n /** Whole object. Grants already issued keep the terms they were issued with. */\n updateOffer(id: string, payload: AdminOfferInput) {\n return put<{ offer: AdminOfferBase }>(`/admin/offers/${id}`, payload);\n },\n\n /** Archive. 409 (the message names the sequence) while a sequence hands it out. */\n archiveOffer(id: string) {\n return del(`/admin/offers/${id}`);\n },\n\n getOfferGrants(offerId: string, params?: { limit?: number; offset?: number }) {\n return apiFetch<{ grants: AdminOfferGrant[] }>(`/admin/offers/${offerId}/grants${qs(params)}`);\n },\n\n /**\n * Give the offer to one person. Idempotent: a person holds an offer once, so\n * `created: false` returns the grant they already have, original deadline\n * included.\n */\n issueOfferGrant(offerId: string, payload: { email: string; userId?: string; validDays: number }) {\n return post<{ grant: AdminOfferGrantBase; created: boolean }>(`/admin/offers/${offerId}/grants`, payload);\n },\n\n /** Take back an unclaimed grant. 409 once it has been claimed. */\n revokeOfferGrant(grantId: string) {\n return apiFetch<{ grant: AdminOfferGrantBase }>(`/admin/offers/grants/${grantId}`, { method: 'DELETE' });\n },\n\n // ── Categories ─────────────────────────────────────────────────\n\n getCategories() {\n return apiFetch<{ categories: AdminCategory[] }>('/admin/categories');\n },\n\n createCategory(payload: AdminCategoryInput) {\n return post<{ category: AdminCategory }>('/admin/categories', payload);\n },\n\n updateCategory(id: string, payload: AdminCategoryUpdate) {\n return patch<{ category: AdminCategory }>(`/admin/categories/${id}`, payload);\n },\n\n deleteCategory(id: string) {\n return del(`/admin/categories/${id}`);\n },\n\n // ── Support inbox ──\n //\n // The admin side of `supportApi`. Deliberately NOT merged with clinical\n // messaging the way the member portal is: support staff triage their own\n // queue and have no business reading patient <-> prescriber threads.\n\n getSupportStats() {\n return apiFetch<AdminSupportStats>('/admin/support/stats');\n },\n\n getSupportThreads(params?: { status?: SupportThreadStatus; category?: SupportThreadCategory; cursor?: string }) {\n return apiFetch<{ threads: AdminSupportThread[]; nextCursor?: string }>(\n `/admin/support/threads${qs(params)}`,\n );\n },\n\n /** Fetching a thread also clears its unread flag server-side. */\n getSupportThread(id: string) {\n return apiFetch<{\n thread: AdminSupportThread;\n messages: SupportMessage[];\n customer: AdminSupportCustomer | null;\n }>(`/admin/support/threads/${id}`);\n },\n\n replyToSupportThread(id: string, body: string) {\n return post<{ message: SupportMessage }>(`/admin/support/threads/${id}/messages`, { body });\n },\n\n setSupportThreadStatus(id: string, status: SupportThreadStatus) {\n return patch<{ thread: AdminSupportThread }>(`/admin/support/threads/${id}`, { status });\n },\n\n /** Inline re-file from the admin detail view. `null` clears the category. */\n updateSupportThreadCategory(id: string, category: SupportThreadCategory | null) {\n return patch<{ thread: AdminSupportThread }>(`/admin/support/threads/${id}`, { category });\n },\n\n /**\n * Forward this thread to the customer's care team: sends every customer\n * message as one note to their prescriber, then redacts those message\n * bodies (`[moved to care team]`, attachments removed) and marks the\n * thread `transferred`. Support's own messages are untouched.\n *\n * - `409 no_care_team` — customer has no Apex member / no prescriber yet.\n * - `502` — could not reach the care team; safe to retry.\n * - `alreadyTransferred: true` — thread was already forwarded; no-op.\n * - `redacted: false` — the transfer happened but the redaction cleanup\n * step threw; the thread is transferred but bodies may not be scrubbed.\n */\n transferSupportThread(id: string) {\n return post<{\n thread: AdminSupportThread;\n conversationId: string;\n alreadyTransferred: boolean;\n redacted: boolean;\n }>(`/admin/support/threads/${id}/transfer`);\n },\n\n getSupportAttachmentUrl(attachmentId: string) {\n return apiFetch<{ url: string }>(`/admin/support/attachments/${attachmentId}`);\n },\n\n /** Sends a file as a support reply, with optional accompanying text. */\n uploadSupportAttachment(threadId: string, file: File, body?: string) {\n const formData = new FormData();\n formData.append('file', file);\n if (body) formData.append('body', body);\n return apiFetch<{ message: SupportMessage }>(`/admin/support/threads/${threadId}/attachments`, {\n method: 'POST',\n body: formData,\n });\n },\n};\n\nexport interface AdminSupportStats {\n total: number;\n /** Threads awaiting a support reply. */\n unread: number;\n open: number;\n /** Uncategorized covers threads created without a category. */\n byCategory: Record<SupportThreadCategory | 'uncategorized', number>;\n}\n\nexport interface AdminSupportCustomer {\n id: string;\n firstName?: string;\n lastName?: string;\n email: string;\n}\n\nexport interface AdminSupportThread extends SupportThread {\n /** True when support has not read the latest customer message. */\n adminUnread: boolean;\n userId: string;\n /** Attached on list responses; null when the user row has gone. */\n customer?: AdminSupportCustomer | null;\n /** Set on threads created from an Apex care-team handoff\n * (`apex:handoff:<conversationId>:<messageId>`); null otherwise. */\n sourceRef: string | null;\n /** Set once this thread has been forwarded to the customer's care team\n * (`status` is then `'transferred'`). */\n transferredConversationId: string | null;\n}\n\n// ── Promotions types ──────────────────────────────────────────────\n\nexport type DiscountType = 'percent' | 'fixed';\n\nexport interface AdminSale {\n id: string;\n tenantId: string;\n name: string;\n discountType: DiscountType;\n discountValueCents: number;\n startDate?: string;\n endDate?: string;\n productIds: string[];\n isExclusive: boolean;\n isActive: boolean;\n recurringCharges: number;\n recurringIndefinite: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface AdminSaleInput {\n name: string;\n discountType: DiscountType;\n discountValueCents: number;\n startDate?: string | null;\n endDate?: string | null;\n productIds: string[];\n isExclusive?: boolean;\n isActive?: boolean;\n recurringCharges?: number;\n recurringIndefinite?: boolean;\n}\n\nexport interface AdminPromoCode {\n id: string;\n tenantId: string;\n code: string;\n discountType: DiscountType;\n discountValueCents: number;\n startDate?: string;\n endDate?: string;\n productIds: string[];\n isExclusive: boolean;\n isActive: boolean;\n recurringCharges: number;\n recurringIndefinite: boolean;\n affiliateId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface AdminPromoCodeInput {\n code: string;\n discountType: DiscountType;\n discountValueCents: number;\n startDate?: string | null;\n endDate?: string | null;\n productIds?: string[];\n isExclusive?: boolean;\n isActive?: boolean;\n recurringCharges?: number;\n recurringIndefinite?: boolean;\n affiliateId?: string | null;\n}\n\n/** An offer as create/update return it; the list adds counts (`AdminOffer`). */\nexport interface AdminOfferBase {\n id: string;\n tenantId: string;\n name: string;\n discountType: DiscountType;\n /** percent: 1–100. fixed: cents. */\n discountValueCents: number;\n /** Rebills after the first charge that carry the discount; ignored when indefinite. */\n recurringCharges: number;\n recurringIndefinite: boolean;\n /** Empty = any product. */\n productIds: string[];\n isActive: boolean;\n createdAt: string;\n updatedAt: string;\n archivedAt?: string | null;\n}\n\nexport type OfferGrantState = 'open' | 'claimed' | 'expired' | 'revoked';\n\nexport interface AdminOffer extends AdminOfferBase {\n grants: Record<OfferGrantState, number>;\n /** Sequences that hand this offer out. */\n usedBy: Array<{ sequenceId: string; sequenceName: string }>;\n}\n\nexport interface AdminOfferInput {\n name: string;\n discountType: DiscountType;\n discountValueCents: number;\n recurringIndefinite: boolean;\n recurringCharges: number;\n productIds: string[];\n isActive: boolean;\n}\n\n/** One person holding one offer. The terms are a copy, frozen when it was issued. */\nexport interface AdminOfferGrantBase {\n id: string;\n offerId: string;\n email: string;\n userId: string | null;\n /** The offer's name when the grant was issued. */\n label: string;\n discountType: DiscountType;\n discountValueCents: number;\n recurringCharges: number;\n recurringIndefinite: boolean;\n productIds: string[];\n issuedAt: string;\n /** `admin:<uid>` or `sequence:<id>`. */\n issuedBy: string;\n sequenceId: string | null;\n /** The deadline to claim it, not the end of the discount. */\n expiresAt: string;\n redeemedAt: string | null;\n revokedAt: string | null;\n}\n\n/** A grant as the list returns it; issue and revoke return it without `state`. */\nexport interface AdminOfferGrant extends AdminOfferGrantBase {\n state: OfferGrantState;\n}\n\n// ── Affiliates types ──────────────────────────────────────────────\n\nexport type AffiliateStatus = 'pending' | 'active' | 'suspended' | 'rejected';\nexport type CommissionStatus = 'pending' | 'approved' | 'paid' | 'cancelled';\nexport type AttributionMethod = 'link' | 'promo_code' | 'both';\nexport type PaymentType = 'initial' | 'rebill' | 'onetime';\nexport type AffiliatePaymentMethod = 'paypal' | 'bank_transfer' | 'other';\n\nexport interface CommissionConfig {\n fixedAmountCents?: number;\n percentageRate?: number;\n}\n\nexport interface CustomerDiscountConfig {\n percentDiscount: number;\n includesShipping: boolean;\n canCombine: boolean;\n}\n\nexport interface AffiliateProgram {\n id: string;\n tenantId: string;\n name: string;\n description?: string;\n defaultCommission: CommissionConfig;\n /** Default override paid to a parent affiliate on each of their subs' sales. */\n secondTierCommission?: CommissionConfig;\n customerDiscount?: CustomerDiscountConfig;\n cookieDurationDays: number;\n paymentThresholdCents: number;\n commissionHoldDays: number;\n minPayoutCycles: number;\n recurringCommissions: boolean;\n oneTimeCommissions: boolean;\n isActive: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface Affiliate {\n id: string;\n tenantId: string;\n email: string;\n firstName?: string;\n lastName?: string;\n paymentEmail?: string;\n paymentMethod?: AffiliatePaymentMethod;\n programId: string;\n affiliateCode: string;\n status: AffiliateStatus;\n /** Upline affiliate this one is placed under (admin-assigned). */\n parentAffiliateId?: string;\n customCommission?: CommissionConfig;\n /** Per-affiliate override of the program's second-tier rate (this affiliate as a parent). */\n customSecondTierCommission?: CommissionConfig;\n customCustomerDiscountPercent?: number;\n customMinPayoutCycles?: number;\n notes?: string;\n totalEarningsCents: number;\n paidOutCents: number;\n pendingCents: number;\n lastLoginAt?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface AffiliateConversion {\n id: string;\n tenantId: string;\n affiliateId: string;\n affiliateCode: string;\n /** 1 = direct commission; 2 = override earned by this affiliate's parent on a sub's sale. */\n tier: number;\n /** For tier-2 rows: the sub-affiliate whose conversion generated this override. */\n sourceAffiliateId?: string;\n /** For tier-2 rows: the originating tier-1 conversion. */\n parentConversionId?: string;\n orderId?: string;\n subscriptionId?: string;\n paymentId?: string;\n attributionMethod: AttributionMethod;\n promoCode?: string;\n paymentType: PaymentType;\n productSubtotalCents: number;\n shippingCents: number;\n orderTotalCents: number;\n commissionCents: number;\n commissionFixedAmountCents?: number;\n commissionPercentageRate?: number;\n commissionPercentageAmountCents?: number;\n minPayoutCycles: number;\n status: CommissionStatus;\n payableAt?: string;\n paidAt?: string;\n paymentBatchId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface AffiliateEarningsBreakdown {\n pending: number;\n approved: number;\n paid: number;\n cancelled: number;\n}\n\nexport interface CreateAffiliatePayload {\n email: string;\n password: string;\n firstName?: string;\n lastName?: string;\n paymentEmail?: string;\n paymentMethod?: AffiliatePaymentMethod;\n programId: string;\n affiliateCode: string;\n status?: AffiliateStatus;\n parentAffiliateId?: string;\n customCommission?: CommissionConfig;\n customSecondTierCommission?: CommissionConfig;\n customCustomerDiscountPercent?: number;\n customMinPayoutCycles?: number;\n notes?: string;\n}\n\n// Update allows clearing optional overrides/parent by sending `null` (matches the\n// backend's UpdateAffiliateInput); other fields are simply omitted when unchanged.\nexport type UpdateAffiliatePayload = Partial<\n Omit<\n CreateAffiliatePayload,\n | 'parentAffiliateId'\n | 'customCommission'\n | 'customSecondTierCommission'\n | 'customCustomerDiscountPercent'\n | 'customMinPayoutCycles'\n >\n> & {\n parentAffiliateId?: string | null;\n customCommission?: CommissionConfig | null;\n customSecondTierCommission?: CommissionConfig | null;\n customCustomerDiscountPercent?: number | null;\n customMinPayoutCycles?: number | null;\n};\n\nexport interface CreateAffiliateProgramPayload {\n name: string;\n description?: string;\n defaultCommission: CommissionConfig;\n secondTierCommission?: CommissionConfig;\n customerDiscount?: CustomerDiscountConfig;\n cookieDurationDays?: number;\n paymentThresholdCents?: number;\n commissionHoldDays?: number;\n minPayoutCycles?: number;\n recurringCommissions?: boolean;\n oneTimeCommissions?: boolean;\n isActive?: boolean;\n}\n\nexport type UpdateAffiliateProgramPayload = Partial<CreateAffiliateProgramPayload>;\n\nexport interface AffiliateStatsResponse {\n earnings: AffiliateEarningsBreakdown;\n recentConversions: AffiliateConversion[];\n}\n\n/** A single sub-affiliate in an affiliate's downline (one hop, no recursion). */\nexport interface AffiliateDownlineMember {\n id: string;\n affiliateCode: string;\n firstName?: string;\n lastName?: string;\n status: AffiliateStatus;\n createdAt: string;\n}\n\n// ── Admin affiliate API ───────────────────────────────────────────\n\nexport const adminAffiliatesApi = {\n // Affiliates\n list() {\n return apiFetch<{ affiliates: Affiliate[] }>('/admin/affiliates');\n },\n get(id: string) {\n return apiFetch<{ affiliate: Affiliate }>(`/admin/affiliates/${id}`);\n },\n getStats(id: string) {\n return apiFetch<AffiliateStatsResponse>(`/admin/affiliates/${id}/stats`);\n },\n getDownline(id: string) {\n return apiFetch<{ downline: Affiliate[] }>(`/admin/affiliates/${id}/downline`);\n },\n getPromoCodes(id: string) {\n return apiFetch<{ promoCodes: AdminPromoCode[] }>(`/admin/affiliates/${id}/promo-codes`);\n },\n create(payload: CreateAffiliatePayload) {\n return post<{ affiliate: Affiliate }>('/admin/affiliates', payload);\n },\n update(id: string, payload: UpdateAffiliatePayload) {\n return patch<{ affiliate: Affiliate }>(`/admin/affiliates/${id}`, payload);\n },\n remove(id: string) {\n return del(`/admin/affiliates/${id}`);\n },\n\n // Programs\n listPrograms() {\n return apiFetch<{ programs: AffiliateProgram[] }>('/admin/affiliate-programs');\n },\n getProgram(id: string) {\n return apiFetch<{ program: AffiliateProgram }>(`/admin/affiliate-programs/${id}`);\n },\n createProgram(payload: CreateAffiliateProgramPayload) {\n return post<{ program: AffiliateProgram }>('/admin/affiliate-programs', payload);\n },\n updateProgram(id: string, payload: UpdateAffiliateProgramPayload) {\n return patch<{ program: AffiliateProgram }>(`/admin/affiliate-programs/${id}`, payload);\n },\n removeProgram(id: string) {\n return del(`/admin/affiliate-programs/${id}`);\n },\n\n // Conversions\n listConversions(params?: { status?: CommissionStatus; limit?: number }) {\n return apiFetch<{ conversions: AffiliateConversion[] }>(\n `/admin/affiliate-conversions${qs(params)}`,\n );\n },\n runTransitions() {\n return post<{ transitioned: number }>('/admin/affiliate-conversions/run-transitions');\n },\n markPaid(id: string, paymentBatchId?: string) {\n return post<{ success: boolean }>(\n `/admin/affiliate-conversions/${id}/mark-paid`,\n paymentBatchId ? { paymentBatchId } : {},\n );\n },\n};\n\n// ── Affiliate self-service API ─────────────────────────────────────\n//\n// Affiliates are a separate identity track from patient/admin users. They\n// authenticate via /affiliates/login (returning their own JWT + refresh\n// token) and hit /affiliates/dashboard/* endpoints scoped to the calling\n// affiliate. We keep token storage and the refresh loop completely\n// separate from `apiFetch` so a 401 in one track can't disturb the other.\n\nexport const affiliateAuthStorageKey = () => `${getConfig().storagePrefix}-affiliate-auth`;\n\nexport interface AffiliateAuthTokens {\n accessToken: string;\n refreshToken: string;\n affiliateId: string;\n}\n\nexport interface AffiliateSession {\n affiliateId: string;\n idToken: string;\n refreshToken: string;\n expiresIn: number;\n status: AffiliateStatus;\n}\n\nexport interface AffiliateRegisterInput {\n email: string;\n password: string;\n firstName: string;\n lastName: string;\n affiliateCode: string;\n paymentEmail?: string;\n paymentMethod?: AffiliatePaymentMethod;\n}\n\nexport interface AffiliateRegisterResponse {\n affiliate: { id: string; email: string; status: AffiliateStatus };\n}\n\nexport interface AffiliateDashboardProfile {\n affiliate: Affiliate;\n effectiveCommission?: CommissionConfig;\n customerDiscountPercent?: number;\n}\n\nexport interface AffiliateDashboardStats {\n totalClicks: number;\n totalConversions: number;\n conversionRate: number;\n totalEarningsCents: number;\n pendingCents: number;\n approvedCents: number;\n paidCents: number;\n recentConversions: AffiliateConversion[];\n}\n\nexport interface AffiliateClickRecord {\n id: string;\n affiliateId: string;\n affiliateCode: string;\n ipAddress?: string;\n userAgent?: string;\n referrer?: string;\n landingPage?: string;\n createdAt: string;\n}\n\nexport interface AffiliateDashboardLinks {\n affiliateCode: string;\n links: { homepage: string; signup: string };\n}\n\nexport interface AffiliateTrackResponse {\n success: boolean;\n tracked: boolean;\n affiliateCode?: string;\n cookieDurationDays?: number;\n}\n\nexport function getAffiliateTokens(): AffiliateAuthTokens | null {\n try {\n const raw = localStorage.getItem(affiliateAuthStorageKey());\n if (!raw) return null;\n return JSON.parse(raw) as AffiliateAuthTokens;\n } catch {\n return null;\n }\n}\n\nexport function setAffiliateTokens(tokens: AffiliateAuthTokens): void {\n localStorage.setItem(affiliateAuthStorageKey(), JSON.stringify(tokens));\n}\n\nexport function clearAffiliateTokens(): void {\n localStorage.removeItem(affiliateAuthStorageKey());\n notifyTokensCleared('affiliate');\n}\n\nlet affiliateRefreshPromise: Promise<AffiliateAuthTokens | null> | null = null;\n\nconst affiliateRefreshLockName = () => refreshLockName(affiliateAuthStorageKey());\n\n/** Affiliate mirror of adoptPatientTokens (see the patient refresh queue). */\nconst adoptAffiliateTokens = (presented: AffiliateAuthTokens): AffiliateAuthTokens | null =>\n adoptRotatedTokens(\n getAffiliateTokens,\n presented,\n (latest) => latest.affiliateId === presented.affiliateId,\n );\n\nasync function refreshAffiliateAccessToken(): Promise<AffiliateAuthTokens | null> {\n if (affiliateRefreshPromise) return affiliateRefreshPromise;\n\n const presented = getAffiliateTokens();\n if (!presented?.refreshToken || !presented?.affiliateId) return null;\n\n affiliateRefreshPromise = withRefreshLock(affiliateRefreshLockName(), async () => {\n const adopted = adoptAffiliateTokens(presented);\n if (adopted) return adopted;\n\n try {\n const cfg = getConfig();\n const res = await fetchWithTimeout(\n `${cfg.apiBase}/affiliates/refresh`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n },\n body: JSON.stringify({\n refreshToken: presented.refreshToken,\n affiliateId: presented.affiliateId,\n }),\n },\n REFRESH_TIMEOUT_MS,\n );\n\n if (!res.ok) {\n const raced = adoptAffiliateTokens(presented);\n if (raced) return raced;\n // Same rule as the patient queue: only a definitive 401/403 on the\n // refresh call ends the session; a 5xx blip keeps the tokens.\n if (res.status === 401 || res.status === 403) clearAffiliateTokens();\n return null;\n }\n\n const data = (await res.json()) as {\n idToken: string;\n refreshToken: string;\n expiresIn: number;\n };\n const newTokens: AffiliateAuthTokens = {\n accessToken: data.idToken,\n refreshToken: data.refreshToken,\n affiliateId: presented.affiliateId,\n };\n setAffiliateTokens(newTokens);\n return newTokens;\n } catch {\n const raced = adoptAffiliateTokens(presented);\n if (raced) return raced;\n // Network drop / timeout — keep the tokens; a later attempt retries.\n return null;\n }\n }).finally(() => {\n affiliateRefreshPromise = null;\n });\n\n return affiliateRefreshPromise;\n}\n\nconst AFFILIATE_TRACK: TransportTrack = {\n getAccessToken: () => getAffiliateTokens()?.accessToken,\n clear: clearAffiliateTokens,\n refresh: () => refreshAffiliateAccessToken(),\n credentials: 'include',\n sessionExpiredMessage: 'Affiliate session expired. Please log in again.',\n enrichErrorDetails: false,\n};\n\nasync function affiliateFetch<T = unknown>(\n endpoint: string,\n options: RequestInit & { skipAuth?: boolean } = {},\n): Promise<T> {\n const { skipAuth, ...fetchOpts } = options;\n return coreFetch<T>(endpoint, fetchOpts, AFFILIATE_TRACK, { skipAuth });\n}\n\nexport const affiliatePortalApi = {\n register(input: AffiliateRegisterInput): Promise<AffiliateRegisterResponse> {\n return affiliateFetch<AffiliateRegisterResponse>('/affiliates/register', {\n method: 'POST',\n body: JSON.stringify(input),\n skipAuth: true,\n });\n },\n // Self-serve password reset (mirror of authApi's customer pair — affiliates\n // are a separate account table with their own endpoints). `requestPasswordReset`\n // always 200s with generic copy for anti-enumeration.\n requestPasswordReset(params: { email: string; redirectUrl: string }) {\n return affiliateFetch<{ message: string }>('/affiliates/request-password-reset', {\n method: 'POST',\n body: JSON.stringify(params),\n skipAuth: true,\n });\n },\n resetPassword(params: { email: string; token: string; newPassword: string }) {\n return affiliateFetch<{ message: string }>('/affiliates/reset-password', {\n method: 'POST',\n body: JSON.stringify(params),\n skipAuth: true,\n });\n },\n async login(email: string, password: string): Promise<AffiliateSession> {\n const session = await affiliateFetch<AffiliateSession>('/affiliates/login', {\n method: 'POST',\n body: JSON.stringify({ email, password }),\n skipAuth: true,\n });\n setAffiliateTokens({\n accessToken: session.idToken,\n refreshToken: session.refreshToken,\n affiliateId: session.affiliateId,\n });\n return session;\n },\n async logout(): Promise<void> {\n try {\n await affiliateFetch('/affiliates/logout', { method: 'POST' });\n } catch {\n // Network failure shouldn't block local logout.\n }\n clearAffiliateTokens();\n },\n getProfile(): Promise<AffiliateDashboardProfile> {\n return affiliateFetch<AffiliateDashboardProfile>('/affiliates/dashboard/profile');\n },\n getStats(): Promise<{ stats: AffiliateDashboardStats }> {\n return affiliateFetch<{ stats: AffiliateDashboardStats }>('/affiliates/dashboard/stats');\n },\n listConversions(params?: { limit?: number }): Promise<{ conversions: AffiliateConversion[] }> {\n return affiliateFetch<{ conversions: AffiliateConversion[] }>(\n `/affiliates/dashboard/conversions${qs(params)}`,\n );\n },\n listClicks(params?: { limit?: number }): Promise<{ clicks: AffiliateClickRecord[] }> {\n return affiliateFetch<{ clicks: AffiliateClickRecord[] }>(\n `/affiliates/dashboard/clicks${qs(params)}`,\n );\n },\n getLinks(): Promise<AffiliateDashboardLinks> {\n return affiliateFetch<AffiliateDashboardLinks>('/affiliates/dashboard/links');\n },\n getPromoCodes(): Promise<{ promoCodes: AdminPromoCode[] }> {\n return affiliateFetch<{ promoCodes: AdminPromoCode[] }>('/affiliates/dashboard/promo-codes');\n },\n getDownline(): Promise<{ downline: AffiliateDownlineMember[] }> {\n return affiliateFetch<{ downline: AffiliateDownlineMember[] }>('/affiliates/dashboard/downline');\n },\n // Public: server sets the `affiliate_ref` cookie used by attribution.\n // Backend route is GET, so we encode query params + use skipAuth.\n track(refCode: string, landingPage?: string): Promise<AffiliateTrackResponse> {\n const params = new URLSearchParams({ ref: refCode });\n if (landingPage) params.set('landing', landingPage);\n return affiliateFetch<AffiliateTrackResponse>(\n `/affiliates/track?${params.toString()}`,\n { method: 'GET', skipAuth: true },\n );\n },\n};\n"]}
|