@edx/frontend-app-alacarte-checkout 1.63.0 → 1.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -258,12 +258,12 @@ const ExpressCheckout = ({ stripe, totalAmountCents, currency, onPaymentAuthoriz
258
258
  });
259
259
  // A new wallet attempt is starting — clear the last attempt's errors.
260
260
  // Once a click handler is registered Stripe waits for resolve() (1s
261
- // limit) before opening the sheet, so resolve with the create options.
261
+ // limit) before opening the sheet; required fields are configured on create.
262
262
  expressElement.on('click', (event) => {
263
263
  var _a;
264
264
  setWalletError(null);
265
+ event.resolve();
265
266
  (_a = onWalletClickRef.current) === null || _a === void 0 ? void 0 : _a.call(onWalletClickRef);
266
- event.resolve({ emailRequired: true, billingAddressRequired: true });
267
267
  });
268
268
  // The learner dismissed the wallet sheet without paying.
269
269
  expressElement.on('cancel', () => {
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressCheckout.js","sourceRoot":"","sources":["../../../src/components/ExpressCheckout/ExpressCheckout.tsx"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAc,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAU5C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,QAAQ,MAAM,YAAY,CAAC;AAqClC,uFAAuF;AACvF,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,eAAe,GAAmC,CAAC,EACvD,MAAM,EACN,gBAAgB,EAChB,QAAQ,EACR,mBAAmB,EACnB,aAAa,EACb,c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AAU,EAAE,YAAY,CAAC,iBACvC,UAAU,IAAI,CAAC,YAAY,iBAC5B,gBAAgB,GAC5B,EACF,cACE,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,eAAe,CAAC,WAAW,EAAE,aAAa,CAAC,iBACzC,WAAW,IAAI,CAAC,aAAa,iBAC9B,iBAAiB,GAC7B,IACE,EACL,WAAW,IAAI,CACd,YAAG,SAAS,EAAC,yBAAyB,EAAC,IAAI,EAAC,OAAO,YAChD,WAAW,GACV,CACL,EAEA,YAAY,IAAI,CACf,KAAC,QAAQ,IAAC,kBAAkB,EAAC,4BAA4B,EAAC,MAAM,EAAC,MAAM,EAAC,YAAY,EAAE,CAAC,EAAE,MAAM,SAAG,CACnG,IACG,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,eAAe,CAAC","sourcesContent":["import React, { useEffect, useRef, useState } from 'react';\nimport { useIntl } from '@openedx/frontend-base';\nimport { Skeleton } from '@openedx/paragon';\nimport type {\n ExpressCheckoutAvailablePaymentMethodsChangeEvent,\n ExpressCheckoutClickEvent,\n ExpressCheckoutConfirmEvent,\n ExpressCheckoutReadyEvent,\n StripeElementsLike,\n StripeElementLike,\n StripeLike,\n} from '../../types';\nimport { PayPalWordmark } from '../BrandMarks/BrandMarks';\nimport { useInert } from '../../utils/inert';\nimport { loadPaypal } from '../../utils/paypal';\nimport messages from './Messages';\n\nexport interface ExpressCheckoutProps {\n /** Stripe.js instance — null until loaded. */\n stripe: StripeLike | null,\n /** Total amount in the smallest currency unit (cents). */\n totalAmountCents: number | null,\n /** ISO 4217 currency code, e.g. 'USD'. */\n currency: string | null,\n /** Two-letter country code (kept for API stability). */\n country: string,\n /**\n * Called when the user authorises a wallet payment (Apple Pay / Google Pay).\n * Receives the Stripe PaymentMethod id and the billing country from the wallet.\n * Must resolve on success or reject on failure.\n */\n onPaymentAuthorized: (paymentMethodId: string, walletCountry?: string) => Promise<void>,\n /** Called when the learner clicks Apple Pay / Google Pay, before the sheet opens. */\n onWalletClick?: () => void,\n /** Called when the learner closes the Apple Pay / Google Pay sheet without paying. */\n onWalletCancel?: () => void,\n /** PayPal JS SDK client id — PayPal stays disabled without it. */\n paypalClientId?: string | null,\n /** PayPal `createOrder`: places the order with PayPal and resolves its id. */\n onPaypalCreateOrder?: () => Promise<string>,\n /** PayPal `onApprove`: captures the approved PayPal order. */\n onPaypalApprove?: (paypalOrderId: string) => Promise<void>,\n /** PayPal `onCancel` / `onError`: abandons the unapproved PayPal order. */\n onPaypalCancel?: (paypalOrderId: string) => Promise<void>,\n /** Disables the Apple Pay / Google Pay slots. */\n disabled?: boolean,\n /** Disables the PayPal slot — PayPal doesn't need Stripe, so it has its own flag. */\n paypalDisabled?: boolean,\n}\n\ntype WalletSlot = 'apple' | 'google';\n\n// Shows the block anyway if an SDK never settles (blocked script, Stripe never loads).\nexport const SKELETON_MAX_MS = 10000;\n\n/**\n * Express checkout: PayPal (local) | Apple Pay | Google Pay.\n *\n * Apple and Google each get their own Express Checkout Element (one wallet per\n * mount) so we can lay them out in equal columns. A single ECE with both wallets\n * stacks / overflows in this narrow column. `always` keeps the Shopify-like\n * show-even-without-a-saved-card behaviour.\n */\nconst ExpressCheckout: React.FC<ExpressCheckoutProps> = ({\n stripe,\n totalAmountCents,\n currency,\n onPaymentAuthorized,\n onWalletClick,\n onWalletCancel,\n paypalClientId,\n onPaypalCreateOrder,\n onPaypalApprove,\n onPaypalCancel,\n disabled,\n paypalDisabled,\n}) => {\n const { formatMessage } = useIntl();\n const appleMountRef = useRef<HTMLDivElement | null>(null);\n const googleMountRef = useRef<HTMLDivElement | null>(null);\n const appleElementsRef = useRef<StripeElementsLike | null>(null);\n const googleElementsRef = useRef<StripeElementsLike | null>(null);\n const appleElementRef = useRef<StripeElementLike | null>(null);\n const googleElementRef = useRef<StripeElementLike | null>(null);\n const onPaymentAuthorizedRef = useRef(onPaymentAuthorized);\n const onWalletClickRef = useRef(onWalletClick);\n const onWalletCancelRef = useRef(onWalletCancel);\n const paypalMountRef = useRef<HTMLDivElement | null>(null);\n // The disabled class only blocks the pointer — inert drops the slot's\n // iframe from the tab order too.\n const paypalSlotRef = useInert<HTMLDivElement>(!!paypalDisabled);\n const paypalHandlersRef = useRef({ onPaypalCreateOrder, onPaypalApprove, onPaypalCancel });\n // PayPal order created but not yet approved — cancelled if the buttons error out.\n const openPaypalOrderRef = useRef<string | null>(null);\n\n const [appleReady, setAppleReady] = useState(false);\n const [googleReady, setGoogleReady] = useState(false);\n const [appleVisible, setAppleVisible] = useState(false);\n const [googleVisible, setGoogleVisible] = useState(false);\n const [walletError, setWalletError] = useState<string | null>(null);\n const [paypalRendered, setPaypalRendered] = useState(false);\n // PayPal finished: rendered, ineligible, failed, or never possible (no client id).\n const [paypalSettled, setPaypalSettled] = useState(false);\n // Latched so later remounts (currency / amount change) don't bring the skeleton back.\n const [loaded, setLoaded] = useState(false);\n\n // Stripe wallets require a positive charge. Use an explicit > 0 check —\n // `!!totalAmountCents` treats a $0 (free) total as \"no amount\" and would\n // also break remounts after a coupon brings the total to zero.\n const canCharge = totalAmountCents != null && totalAmountCents > 0 && !!currency;\n const paypalEnabled = !!paypalClientId && canCharge && !!onPaypalCreateOrder && !!onPaypalApprove;\n // Keep slots in the grid until ready so Stripe measures a full column width.\n const showAppleSlot = !appleReady || appleVisible;\n const showGoogleSlot = !googleReady || googleVisible;\n const columnCount = 1 + (showAppleSlot ? 1 : 0) + (showGoogleSlot ? 1 : 0);\n const allSettled = paypalSettled && appleReady && googleReady;\n const showSkeleton = !loaded && !allSettled;\n\n useEffect(() => {\n if (allSettled) setLoaded(true);\n }, [allSettled]);\n\n useEffect(() => {\n const timer = setTimeout(() => setLoaded(true), SKELETON_MAX_MS);\n return () => clearTimeout(timer);\n }, []);\n\n useEffect(() => {\n onPaymentAuthorizedRef.current = onPaymentAuthorized;\n }, [onPaymentAuthorized]);\n\n useEffect(() => {\n onWalletClickRef.current = onWalletClick;\n }, [onWalletClick]);\n\n useEffect(() => {\n onWalletCancelRef.current = onWalletCancel;\n }, [onWalletCancel]);\n\n // Wallet hosts keep object refs for remounts, so toggle inert here instead.\n useEffect(() => {\n appleMountRef.current?.toggleAttribute('inert', !!disabled);\n googleMountRef.current?.toggleAttribute('inert', !!disabled);\n }, [disabled]);\n\n useEffect(() => {\n paypalHandlersRef.current = { onPaypalCreateOrder, onPaypalApprove, onPaypalCancel };\n }, [onPaypalCreateOrder, onPaypalApprove, onPaypalCancel]);\n\n // PayPal buttons: tCheckoutPlaceOrder(PAYPAL) on click, capture on approve,\n // cancel when the learner closes the PayPal window.\n useEffect(() => {\n const mountNode = paypalMountRef.current;\n if (!paypalEnabled || !paypalClientId || !currency || !mountNode) {\n console.log('[ExpressCheckout] PayPal disabled', {\n hasClientId: !!paypalClientId,\n canCharge,\n hasCreateOrder: !!onPaypalCreateOrder,\n hasApprove: !!onPaypalApprove,\n });\n setPaypalRendered(false);\n // Without a client id PayPal can never render — don't wait for it.\n // Same for a $0 total: express PayPal is not applicable.\n setPaypalSettled(!paypalClientId || !canCharge);\n return undefined;\n }\n\n let cancelled = false;\n const cancelOpenOrder = async () => {\n const orderId = openPaypalOrderRef.current;\n openPaypalOrderRef.current = null;\n if (orderId) await paypalHandlersRef.current.onPaypalCancel?.(orderId);\n };\n\n loadPaypal(paypalClientId, currency)\n .then(async (paypal) => {\n if (cancelled) return;\n const buttons = paypal.Buttons({\n fundingSource: paypal.FUNDING.PAYPAL,\n style: {\n layout: 'horizontal',\n color: 'gold',\n shape: 'rect',\n label: 'paypal',\n height: 48,\n // Matches the Stripe wallets' `borderRadius: '12px'` appearance.\n borderRadius: 12,\n tagline: false,\n },\n createOrder: async () => {\n setWalletError(null);\n const orderId = await paypalHandlersRef.current.onPaypalCreateOrder!();\n openPaypalOrderRef.current = orderId;\n return orderId;\n },\n onApprove: async ({ orderID }) => {\n openPaypalOrderRef.current = null;\n try {\n await paypalHandlersRef.current.onPaypalApprove!(orderID);\n } catch (err) {\n // The checkout page already shows the capture error.\n console.warn('[ExpressCheckout] PayPal capture failed', err);\n }\n },\n onCancel: async () => {\n await cancelOpenOrder();\n },\n onError: (err) => {\n console.warn('[ExpressCheckout] PayPal error', err);\n // createOrder failures are already shown by the checkout page.\n if (openPaypalOrderRef.current) {\n setWalletError(formatMessage(messages.paypalError));\n cancelOpenOrder().catch(() => {});\n }\n },\n });\n if (!buttons.isEligible()) {\n console.warn('[ExpressCheckout] PayPal buttons not eligible', { currency });\n if (!cancelled) setPaypalSettled(true);\n return;\n }\n await buttons.render(mountNode);\n if (!cancelled) {\n setPaypalRendered(true);\n setPaypalSettled(true);\n }\n })\n .catch((err) => {\n console.warn('[ExpressCheckout] PayPal SDK unavailable', err);\n if (!cancelled) {\n setPaypalRendered(false);\n setPaypalSettled(true);\n }\n });\n\n return () => {\n cancelled = true;\n mountNode.innerHTML = '';\n setPaypalRendered(false);\n setPaypalSettled(false);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [paypalEnabled, paypalClientId, currency]);\n\n useEffect(() => {\n if (\n !stripe\n || !canCharge\n || totalAmountCents == null\n || !currency\n || !appleMountRef.current\n || !googleMountRef.current\n ) {\n console.log('[ExpressCheckout] skip mount', {\n hasStripe: !!stripe,\n totalAmountCents,\n currency,\n canCharge,\n hasAppleMount: !!appleMountRef.current,\n hasGoogleMount: !!googleMountRef.current,\n });\n setAppleReady(false);\n setGoogleReady(false);\n setAppleVisible(false);\n setGoogleVisible(false);\n setWalletError(null);\n return undefined;\n }\n\n console.log('[ExpressCheckout] mounting wallet slots', { totalAmountCents, currency });\n setAppleReady(false);\n setGoogleReady(false);\n setAppleVisible(false);\n setGoogleVisible(false);\n\n const sharedElementsOpts = {\n mode: 'payment' as const,\n amount: totalAmountCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n appearance: {\n variables: { borderRadius: '12px' },\n },\n };\n\n const bindWallet = (\n slot: WalletSlot,\n elements: StripeElementsLike,\n expressElement: StripeElementLike,\n mountNode: HTMLDivElement,\n setReady: (v: boolean) => void,\n setVisible: (v: boolean) => void,\n ) => {\n // Availability comes from `availablepaymentmethodschange`: it fires on initial\n // render and again if it changes later (iOS checks Apple Pay asynchronously,\n // so a one-shot read on `ready` could hide the button for good).\n let availabilityReported = false;\n expressElement.on(\n 'availablepaymentmethodschange',\n (event: ExpressCheckoutAvailablePaymentMethodsChangeEvent) => {\n const methods = event.paymentMethods;\n const visible = !!(slot === 'apple' ? methods?.applePay : methods?.googlePay)?.available;\n console.log(`[ExpressCheckout] available payment methods (${slot})`, {\n visible,\n raw: methods ?? null,\n });\n availabilityReported = true;\n setVisible(visible);\n setReady(true);\n },\n );\n\n // Fallback for the deprecated `ready` payload, only while the change event\n // hasn't reported. A negative answer here may be stale, so it's ignored.\n expressElement.on('ready', (event: ExpressCheckoutReadyEvent) => {\n const methods = event.availablePaymentMethods;\n const visible = slot === 'apple' ? !!methods?.applePay : !!methods?.googlePay;\n console.log(`[ExpressCheckout] ready (${slot})`, { visible, raw: methods ?? null });\n if (availabilityReported || !visible) return;\n setVisible(true);\n setReady(true);\n });\n\n // A wallet that fails to load counts as unavailable, so it can't hold the skeleton.\n expressElement.on('loaderror', (event: unknown) => {\n console.warn(`[ExpressCheckout] load error (${slot})`, event);\n setVisible(false);\n setReady(true);\n });\n\n // A new wallet attempt is starting — clear the last attempt's errors.\n // Once a click handler is registered Stripe waits for resolve() (1s\n // limit) before opening the sheet, so resolve with the create options.\n expressElement.on('click', (event: ExpressCheckoutClickEvent) => {\n setWalletError(null);\n onWalletClickRef.current?.();\n event.resolve({ emailRequired: true, billingAddressRequired: true });\n });\n\n // The learner dismissed the wallet sheet without paying.\n expressElement.on('cancel', () => {\n onWalletCancelRef.current?.();\n });\n\n expressElement.on('confirm', async (event: ExpressCheckoutConfirmEvent) => {\n setWalletError(null);\n if (!elements.submit) {\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n const walletLabel = formatMessage(\n slot === 'apple' ? messages.applePay : messages.googlePay,\n );\n\n let paymentMethodId: string;\n let walletCountry: string | undefined;\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n setWalletError(submitError.message || formatMessage(messages.walletUnavailable, {\n wallet: walletLabel,\n }));\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n const { paymentMethod, error } = await stripe.createPaymentMethod({ elements });\n if (error || !paymentMethod?.id) {\n setWalletError(error?.message || formatMessage(messages.walletUnavailable, {\n wallet: walletLabel,\n }));\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n paymentMethodId = paymentMethod.id;\n walletCountry = event.billingDetails?.address?.country\n || paymentMethod.billing_details?.address?.country;\n } catch (err) {\n console.warn(`[ExpressCheckout] wallet setup failed (${slot})`, err);\n setWalletError(formatMessage(messages.walletUnavailable, { wallet: walletLabel }));\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n try {\n await onPaymentAuthorizedRef.current(paymentMethodId, walletCountry);\n } catch (err) {\n // The wallet worked; the payment itself failed (e.g. card declined).\n // The checkout page already shows that error, so don't blame the wallet.\n console.warn(`[ExpressCheckout] payment failed (${slot})`, err);\n event.paymentFailed({ reason: 'fail' });\n }\n });\n\n expressElement.mount(mountNode);\n };\n\n const appleElements = stripe.elements(sharedElementsOpts);\n const googleElements = stripe.elements(sharedElementsOpts);\n appleElementsRef.current = appleElements;\n googleElementsRef.current = googleElements;\n\n const appleElement = appleElements.create('expressCheckout', {\n buttonHeight: 48,\n emailRequired: true,\n billingAddressRequired: true,\n paymentMethodOrder: ['applePay'],\n buttonType: { applePay: 'plain' },\n buttonTheme: { applePay: 'black' },\n paymentMethods: {\n applePay: 'always',\n googlePay: 'never',\n link: 'never',\n paypal: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, maxRows: 0, overflow: 'never' },\n });\n appleElementRef.current = appleElement;\n\n const googleElement = googleElements.create('expressCheckout', {\n buttonHeight: 48,\n emailRequired: true,\n billingAddressRequired: true,\n paymentMethodOrder: ['googlePay'],\n buttonType: { googlePay: 'plain' },\n buttonTheme: { googlePay: 'black' },\n paymentMethods: {\n applePay: 'never',\n googlePay: 'always',\n link: 'never',\n paypal: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, maxRows: 0, overflow: 'never' },\n });\n googleElementRef.current = googleElement;\n\n bindWallet(\n 'apple',\n appleElements,\n appleElement,\n appleMountRef.current,\n setAppleReady,\n setAppleVisible,\n );\n bindWallet(\n 'google',\n googleElements,\n googleElement,\n googleMountRef.current,\n setGoogleReady,\n setGoogleVisible,\n );\n\n return () => {\n try {\n appleElement.unmount?.();\n appleElement.destroy?.();\n googleElement.unmount?.();\n googleElement.destroy?.();\n } catch {\n // Elements may already be gone.\n }\n appleElementRef.current = null;\n googleElementRef.current = null;\n appleElementsRef.current = null;\n googleElementsRef.current = null;\n setAppleReady(false);\n setGoogleReady(false);\n setAppleVisible(false);\n setGoogleVisible(false);\n };\n // Remount when the chargeable total changes (e.g. coupon apply). Calling\n // elements.update() alone can leave ECE wallets stuck unavailable after the\n // amount changes; a fresh mount re-runs availability cleanly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [stripe, currency, totalAmountCents, canCharge]);\n\n const walletClassName = (ready: boolean, visible: boolean) => {\n const base = `express-checkout__wallet${disabled ? ' express-checkout__slot--disabled' : ''}`;\n if (!ready) return `${base} express-checkout__wallet--pending`;\n if (!visible) return `${base} express-checkout__wallet--unavailable`;\n return base;\n };\n\n return (\n <div\n className={`express-checkout${showSkeleton ? ' express-checkout--loading' : ''}`}\n role=\"group\"\n aria-labelledby=\"express-checkout-heading\"\n aria-busy={showSkeleton}\n >\n <h3 id=\"express-checkout-heading\" className=\"express-checkout__heading\">\n {formatMessage(messages.heading)}\n </h3>\n <div\n className={`express-checkout__buttons express-checkout__buttons--cols-${columnCount}`}\n style={{ gridTemplateColumns: `repeat(${columnCount}, minmax(0, 1fr))` }}\n >\n <div\n ref={paypalSlotRef}\n className={`express-checkout__paypal${paypalDisabled ? ' express-checkout__slot--disabled' : ''}`}\n >\n {/* PayPal SDK renders its button here; the wordmark stands in until it does. */}\n <div\n ref={paypalMountRef}\n className={paypalRendered ? undefined : 'express-checkout__paypal-mount--pending'}\n data-testid=\"paypal-slot\"\n />\n {!paypalRendered && (\n <button\n type=\"button\"\n disabled\n aria-label={formatMessage(messages.paypal)}\n className=\"express-checkout__button express-checkout__button--paypal\"\n >\n <PayPalWordmark />\n </button>\n )}\n </div>\n\n {/* Always in the DOM so remounts can find the nodes; CSS hides unavailable.\n No aria-label on the slots: a labelled div is exposed as a group, so\n screen readers would announce a group around each wallet's own button. */}\n <div\n ref={appleMountRef}\n className={walletClassName(appleReady, appleVisible)}\n aria-hidden={appleReady && !appleVisible}\n data-testid=\"apple-pay-slot\"\n />\n <div\n ref={googleMountRef}\n className={walletClassName(googleReady, googleVisible)}\n aria-hidden={googleReady && !googleVisible}\n data-testid=\"google-pay-slot\"\n />\n </div>\n {walletError && (\n <p className=\"express-checkout__error\" role=\"alert\">\n {walletError}\n </p>\n )}\n {/* One skeleton over the whole block; the slots stay mounted underneath so the SDKs can load. */}\n {showSkeleton && (\n <Skeleton containerClassName=\"express-checkout__skeleton\" height=\"100%\" borderRadius={8} inline />\n )}\n </div>\n );\n};\n\nexport default ExpressCheckout;\n"]}
1
+ {"version":3,"file":"ExpressCheckout.js","sourceRoot":"","sources":["../../../src/components/ExpressCheckout/ExpressCheckout.tsx"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAc,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAU5C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,QAA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AAC,MAAM,CAAC,EAC1C,SAAS,EAAC,2DAA2D,YAErE,KAAC,cAAc,KAAG,GACX,CACV,IACG,EAKN,cACE,GAAG,EAAE,aAAa,EAClB,SAAS,EAAE,eAAe,CAAC,UAAU,EAAE,YAAY,CAAC,iBACvC,UAAU,IAAI,CAAC,YAAY,iBAC5B,gBAAgB,GAC5B,EACF,cACE,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,eAAe,CAAC,WAAW,EAAE,aAAa,CAAC,iBACzC,WAAW,IAAI,CAAC,aAAa,iBAC9B,iBAAiB,GAC7B,IACE,EACL,WAAW,IAAI,CACd,YAAG,SAAS,EAAC,yBAAyB,EAAC,IAAI,EAAC,OAAO,YAChD,WAAW,GACV,CACL,EAEA,YAAY,IAAI,CACf,KAAC,QAAQ,IAAC,kBAAkB,EAAC,4BAA4B,EAAC,MAAM,EAAC,MAAM,EAAC,YAAY,EAAE,CAAC,EAAE,MAAM,SAAG,CACnG,IACG,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,eAAe,CAAC","sourcesContent":["import React, { useEffect, useRef, useState } from 'react';\nimport { useIntl } from '@openedx/frontend-base';\nimport { Skeleton } from '@openedx/paragon';\nimport type {\n ExpressCheckoutAvailablePaymentMethodsChangeEvent,\n ExpressCheckoutClickEvent,\n ExpressCheckoutConfirmEvent,\n ExpressCheckoutReadyEvent,\n StripeElementsLike,\n StripeElementLike,\n StripeLike,\n} from '../../types';\nimport { PayPalWordmark } from '../BrandMarks/BrandMarks';\nimport { useInert } from '../../utils/inert';\nimport { loadPaypal } from '../../utils/paypal';\nimport messages from './Messages';\n\nexport interface ExpressCheckoutProps {\n /** Stripe.js instance — null until loaded. */\n stripe: StripeLike | null,\n /** Total amount in the smallest currency unit (cents). */\n totalAmountCents: number | null,\n /** ISO 4217 currency code, e.g. 'USD'. */\n currency: string | null,\n /** Two-letter country code (kept for API stability). */\n country: string,\n /**\n * Called when the user authorises a wallet payment (Apple Pay / Google Pay).\n * Receives the Stripe PaymentMethod id and the billing country from the wallet.\n * Must resolve on success or reject on failure.\n */\n onPaymentAuthorized: (paymentMethodId: string, walletCountry?: string) => Promise<void>,\n /** Called when the learner clicks Apple Pay / Google Pay, before the sheet opens. */\n onWalletClick?: () => void,\n /** Called when the learner closes the Apple Pay / Google Pay sheet without paying. */\n onWalletCancel?: () => void,\n /** PayPal JS SDK client id — PayPal stays disabled without it. */\n paypalClientId?: string | null,\n /** PayPal `createOrder`: places the order with PayPal and resolves its id. */\n onPaypalCreateOrder?: () => Promise<string>,\n /** PayPal `onApprove`: captures the approved PayPal order. */\n onPaypalApprove?: (paypalOrderId: string) => Promise<void>,\n /** PayPal `onCancel` / `onError`: abandons the unapproved PayPal order. */\n onPaypalCancel?: (paypalOrderId: string) => Promise<void>,\n /** Disables the Apple Pay / Google Pay slots. */\n disabled?: boolean,\n /** Disables the PayPal slot — PayPal doesn't need Stripe, so it has its own flag. */\n paypalDisabled?: boolean,\n}\n\ntype WalletSlot = 'apple' | 'google';\n\n// Shows the block anyway if an SDK never settles (blocked script, Stripe never loads).\nexport const SKELETON_MAX_MS = 10000;\n\n/**\n * Express checkout: PayPal (local) | Apple Pay | Google Pay.\n *\n * Apple and Google each get their own Express Checkout Element (one wallet per\n * mount) so we can lay them out in equal columns. A single ECE with both wallets\n * stacks / overflows in this narrow column. `always` keeps the Shopify-like\n * show-even-without-a-saved-card behaviour.\n */\nconst ExpressCheckout: React.FC<ExpressCheckoutProps> = ({\n stripe,\n totalAmountCents,\n currency,\n onPaymentAuthorized,\n onWalletClick,\n onWalletCancel,\n paypalClientId,\n onPaypalCreateOrder,\n onPaypalApprove,\n onPaypalCancel,\n disabled,\n paypalDisabled,\n}) => {\n const { formatMessage } = useIntl();\n const appleMountRef = useRef<HTMLDivElement | null>(null);\n const googleMountRef = useRef<HTMLDivElement | null>(null);\n const appleElementsRef = useRef<StripeElementsLike | null>(null);\n const googleElementsRef = useRef<StripeElementsLike | null>(null);\n const appleElementRef = useRef<StripeElementLike | null>(null);\n const googleElementRef = useRef<StripeElementLike | null>(null);\n const onPaymentAuthorizedRef = useRef(onPaymentAuthorized);\n const onWalletClickRef = useRef(onWalletClick);\n const onWalletCancelRef = useRef(onWalletCancel);\n const paypalMountRef = useRef<HTMLDivElement | null>(null);\n // The disabled class only blocks the pointer — inert drops the slot's\n // iframe from the tab order too.\n const paypalSlotRef = useInert<HTMLDivElement>(!!paypalDisabled);\n const paypalHandlersRef = useRef({ onPaypalCreateOrder, onPaypalApprove, onPaypalCancel });\n // PayPal order created but not yet approved — cancelled if the buttons error out.\n const openPaypalOrderRef = useRef<string | null>(null);\n\n const [appleReady, setAppleReady] = useState(false);\n const [googleReady, setGoogleReady] = useState(false);\n const [appleVisible, setAppleVisible] = useState(false);\n const [googleVisible, setGoogleVisible] = useState(false);\n const [walletError, setWalletError] = useState<string | null>(null);\n const [paypalRendered, setPaypalRendered] = useState(false);\n // PayPal finished: rendered, ineligible, failed, or never possible (no client id).\n const [paypalSettled, setPaypalSettled] = useState(false);\n // Latched so later remounts (currency / amount change) don't bring the skeleton back.\n const [loaded, setLoaded] = useState(false);\n\n // Stripe wallets require a positive charge. Use an explicit > 0 check —\n // `!!totalAmountCents` treats a $0 (free) total as \"no amount\" and would\n // also break remounts after a coupon brings the total to zero.\n const canCharge = totalAmountCents != null && totalAmountCents > 0 && !!currency;\n const paypalEnabled = !!paypalClientId && canCharge && !!onPaypalCreateOrder && !!onPaypalApprove;\n // Keep slots in the grid until ready so Stripe measures a full column width.\n const showAppleSlot = !appleReady || appleVisible;\n const showGoogleSlot = !googleReady || googleVisible;\n const columnCount = 1 + (showAppleSlot ? 1 : 0) + (showGoogleSlot ? 1 : 0);\n const allSettled = paypalSettled && appleReady && googleReady;\n const showSkeleton = !loaded && !allSettled;\n\n useEffect(() => {\n if (allSettled) setLoaded(true);\n }, [allSettled]);\n\n useEffect(() => {\n const timer = setTimeout(() => setLoaded(true), SKELETON_MAX_MS);\n return () => clearTimeout(timer);\n }, []);\n\n useEffect(() => {\n onPaymentAuthorizedRef.current = onPaymentAuthorized;\n }, [onPaymentAuthorized]);\n\n useEffect(() => {\n onWalletClickRef.current = onWalletClick;\n }, [onWalletClick]);\n\n useEffect(() => {\n onWalletCancelRef.current = onWalletCancel;\n }, [onWalletCancel]);\n\n // Wallet hosts keep object refs for remounts, so toggle inert here instead.\n useEffect(() => {\n appleMountRef.current?.toggleAttribute('inert', !!disabled);\n googleMountRef.current?.toggleAttribute('inert', !!disabled);\n }, [disabled]);\n\n useEffect(() => {\n paypalHandlersRef.current = { onPaypalCreateOrder, onPaypalApprove, onPaypalCancel };\n }, [onPaypalCreateOrder, onPaypalApprove, onPaypalCancel]);\n\n // PayPal buttons: tCheckoutPlaceOrder(PAYPAL) on click, capture on approve,\n // cancel when the learner closes the PayPal window.\n useEffect(() => {\n const mountNode = paypalMountRef.current;\n if (!paypalEnabled || !paypalClientId || !currency || !mountNode) {\n console.log('[ExpressCheckout] PayPal disabled', {\n hasClientId: !!paypalClientId,\n canCharge,\n hasCreateOrder: !!onPaypalCreateOrder,\n hasApprove: !!onPaypalApprove,\n });\n setPaypalRendered(false);\n // Without a client id PayPal can never render — don't wait for it.\n // Same for a $0 total: express PayPal is not applicable.\n setPaypalSettled(!paypalClientId || !canCharge);\n return undefined;\n }\n\n let cancelled = false;\n const cancelOpenOrder = async () => {\n const orderId = openPaypalOrderRef.current;\n openPaypalOrderRef.current = null;\n if (orderId) await paypalHandlersRef.current.onPaypalCancel?.(orderId);\n };\n\n loadPaypal(paypalClientId, currency)\n .then(async (paypal) => {\n if (cancelled) return;\n const buttons = paypal.Buttons({\n fundingSource: paypal.FUNDING.PAYPAL,\n style: {\n layout: 'horizontal',\n color: 'gold',\n shape: 'rect',\n label: 'paypal',\n height: 48,\n // Matches the Stripe wallets' `borderRadius: '12px'` appearance.\n borderRadius: 12,\n tagline: false,\n },\n createOrder: async () => {\n setWalletError(null);\n const orderId = await paypalHandlersRef.current.onPaypalCreateOrder!();\n openPaypalOrderRef.current = orderId;\n return orderId;\n },\n onApprove: async ({ orderID }) => {\n openPaypalOrderRef.current = null;\n try {\n await paypalHandlersRef.current.onPaypalApprove!(orderID);\n } catch (err) {\n // The checkout page already shows the capture error.\n console.warn('[ExpressCheckout] PayPal capture failed', err);\n }\n },\n onCancel: async () => {\n await cancelOpenOrder();\n },\n onError: (err) => {\n console.warn('[ExpressCheckout] PayPal error', err);\n // createOrder failures are already shown by the checkout page.\n if (openPaypalOrderRef.current) {\n setWalletError(formatMessage(messages.paypalError));\n cancelOpenOrder().catch(() => {});\n }\n },\n });\n if (!buttons.isEligible()) {\n console.warn('[ExpressCheckout] PayPal buttons not eligible', { currency });\n if (!cancelled) setPaypalSettled(true);\n return;\n }\n await buttons.render(mountNode);\n if (!cancelled) {\n setPaypalRendered(true);\n setPaypalSettled(true);\n }\n })\n .catch((err) => {\n console.warn('[ExpressCheckout] PayPal SDK unavailable', err);\n if (!cancelled) {\n setPaypalRendered(false);\n setPaypalSettled(true);\n }\n });\n\n return () => {\n cancelled = true;\n mountNode.innerHTML = '';\n setPaypalRendered(false);\n setPaypalSettled(false);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [paypalEnabled, paypalClientId, currency]);\n\n useEffect(() => {\n if (\n !stripe\n || !canCharge\n || totalAmountCents == null\n || !currency\n || !appleMountRef.current\n || !googleMountRef.current\n ) {\n console.log('[ExpressCheckout] skip mount', {\n hasStripe: !!stripe,\n totalAmountCents,\n currency,\n canCharge,\n hasAppleMount: !!appleMountRef.current,\n hasGoogleMount: !!googleMountRef.current,\n });\n setAppleReady(false);\n setGoogleReady(false);\n setAppleVisible(false);\n setGoogleVisible(false);\n setWalletError(null);\n return undefined;\n }\n\n console.log('[ExpressCheckout] mounting wallet slots', { totalAmountCents, currency });\n setAppleReady(false);\n setGoogleReady(false);\n setAppleVisible(false);\n setGoogleVisible(false);\n\n const sharedElementsOpts = {\n mode: 'payment' as const,\n amount: totalAmountCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n appearance: {\n variables: { borderRadius: '12px' },\n },\n };\n\n const bindWallet = (\n slot: WalletSlot,\n elements: StripeElementsLike,\n expressElement: StripeElementLike,\n mountNode: HTMLDivElement,\n setReady: (v: boolean) => void,\n setVisible: (v: boolean) => void,\n ) => {\n // Availability comes from `availablepaymentmethodschange`: it fires on initial\n // render and again if it changes later (iOS checks Apple Pay asynchronously,\n // so a one-shot read on `ready` could hide the button for good).\n let availabilityReported = false;\n expressElement.on(\n 'availablepaymentmethodschange',\n (event: ExpressCheckoutAvailablePaymentMethodsChangeEvent) => {\n const methods = event.paymentMethods;\n const visible = !!(slot === 'apple' ? methods?.applePay : methods?.googlePay)?.available;\n console.log(`[ExpressCheckout] available payment methods (${slot})`, {\n visible,\n raw: methods ?? null,\n });\n availabilityReported = true;\n setVisible(visible);\n setReady(true);\n },\n );\n\n // Fallback for the deprecated `ready` payload, only while the change event\n // hasn't reported. A negative answer here may be stale, so it's ignored.\n expressElement.on('ready', (event: ExpressCheckoutReadyEvent) => {\n const methods = event.availablePaymentMethods;\n const visible = slot === 'apple' ? !!methods?.applePay : !!methods?.googlePay;\n console.log(`[ExpressCheckout] ready (${slot})`, { visible, raw: methods ?? null });\n if (availabilityReported || !visible) return;\n setVisible(true);\n setReady(true);\n });\n\n // A wallet that fails to load counts as unavailable, so it can't hold the skeleton.\n expressElement.on('loaderror', (event: unknown) => {\n console.warn(`[ExpressCheckout] load error (${slot})`, event);\n setVisible(false);\n setReady(true);\n });\n\n // A new wallet attempt is starting — clear the last attempt's errors.\n // Once a click handler is registered Stripe waits for resolve() (1s\n // limit) before opening the sheet; required fields are configured on create.\n expressElement.on('click', (event: ExpressCheckoutClickEvent) => {\n setWalletError(null);\n event.resolve();\n onWalletClickRef.current?.();\n });\n\n // The learner dismissed the wallet sheet without paying.\n expressElement.on('cancel', () => {\n onWalletCancelRef.current?.();\n });\n\n expressElement.on('confirm', async (event: ExpressCheckoutConfirmEvent) => {\n setWalletError(null);\n if (!elements.submit) {\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n const walletLabel = formatMessage(\n slot === 'apple' ? messages.applePay : messages.googlePay,\n );\n\n let paymentMethodId: string;\n let walletCountry: string | undefined;\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n setWalletError(submitError.message || formatMessage(messages.walletUnavailable, {\n wallet: walletLabel,\n }));\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n const { paymentMethod, error } = await stripe.createPaymentMethod({ elements });\n if (error || !paymentMethod?.id) {\n setWalletError(error?.message || formatMessage(messages.walletUnavailable, {\n wallet: walletLabel,\n }));\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n paymentMethodId = paymentMethod.id;\n walletCountry = event.billingDetails?.address?.country\n || paymentMethod.billing_details?.address?.country;\n } catch (err) {\n console.warn(`[ExpressCheckout] wallet setup failed (${slot})`, err);\n setWalletError(formatMessage(messages.walletUnavailable, { wallet: walletLabel }));\n event.paymentFailed({ reason: 'fail' });\n return;\n }\n\n try {\n await onPaymentAuthorizedRef.current(paymentMethodId, walletCountry);\n } catch (err) {\n // The wallet worked; the payment itself failed (e.g. card declined).\n // The checkout page already shows that error, so don't blame the wallet.\n console.warn(`[ExpressCheckout] payment failed (${slot})`, err);\n event.paymentFailed({ reason: 'fail' });\n }\n });\n\n expressElement.mount(mountNode);\n };\n\n const appleElements = stripe.elements(sharedElementsOpts);\n const googleElements = stripe.elements(sharedElementsOpts);\n appleElementsRef.current = appleElements;\n googleElementsRef.current = googleElements;\n\n const appleElement = appleElements.create('expressCheckout', {\n buttonHeight: 48,\n emailRequired: true,\n billingAddressRequired: true,\n paymentMethodOrder: ['applePay'],\n buttonType: { applePay: 'plain' },\n buttonTheme: { applePay: 'black' },\n paymentMethods: {\n applePay: 'always',\n googlePay: 'never',\n link: 'never',\n paypal: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, maxRows: 0, overflow: 'never' },\n });\n appleElementRef.current = appleElement;\n\n const googleElement = googleElements.create('expressCheckout', {\n buttonHeight: 48,\n emailRequired: true,\n billingAddressRequired: true,\n paymentMethodOrder: ['googlePay'],\n buttonType: { googlePay: 'plain' },\n buttonTheme: { googlePay: 'black' },\n paymentMethods: {\n applePay: 'never',\n googlePay: 'always',\n link: 'never',\n paypal: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, maxRows: 0, overflow: 'never' },\n });\n googleElementRef.current = googleElement;\n\n bindWallet(\n 'apple',\n appleElements,\n appleElement,\n appleMountRef.current,\n setAppleReady,\n setAppleVisible,\n );\n bindWallet(\n 'google',\n googleElements,\n googleElement,\n googleMountRef.current,\n setGoogleReady,\n setGoogleVisible,\n );\n\n return () => {\n try {\n appleElement.unmount?.();\n appleElement.destroy?.();\n googleElement.unmount?.();\n googleElement.destroy?.();\n } catch {\n // Elements may already be gone.\n }\n appleElementRef.current = null;\n googleElementRef.current = null;\n appleElementsRef.current = null;\n googleElementsRef.current = null;\n setAppleReady(false);\n setGoogleReady(false);\n setAppleVisible(false);\n setGoogleVisible(false);\n };\n // Remount when the chargeable total changes (e.g. coupon apply). Calling\n // elements.update() alone can leave ECE wallets stuck unavailable after the\n // amount changes; a fresh mount re-runs availability cleanly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [stripe, currency, totalAmountCents, canCharge]);\n\n const walletClassName = (ready: boolean, visible: boolean) => {\n const base = `express-checkout__wallet${disabled ? ' express-checkout__slot--disabled' : ''}`;\n if (!ready) return `${base} express-checkout__wallet--pending`;\n if (!visible) return `${base} express-checkout__wallet--unavailable`;\n return base;\n };\n\n return (\n <div\n className={`express-checkout${showSkeleton ? ' express-checkout--loading' : ''}`}\n role=\"group\"\n aria-labelledby=\"express-checkout-heading\"\n aria-busy={showSkeleton}\n >\n <h3 id=\"express-checkout-heading\" className=\"express-checkout__heading\">\n {formatMessage(messages.heading)}\n </h3>\n <div\n className={`express-checkout__buttons express-checkout__buttons--cols-${columnCount}`}\n style={{ gridTemplateColumns: `repeat(${columnCount}, minmax(0, 1fr))` }}\n >\n <div\n ref={paypalSlotRef}\n className={`express-checkout__paypal${paypalDisabled ? ' express-checkout__slot--disabled' : ''}`}\n >\n {/* PayPal SDK renders its button here; the wordmark stands in until it does. */}\n <div\n ref={paypalMountRef}\n className={paypalRendered ? undefined : 'express-checkout__paypal-mount--pending'}\n data-testid=\"paypal-slot\"\n />\n {!paypalRendered && (\n <button\n type=\"button\"\n disabled\n aria-label={formatMessage(messages.paypal)}\n className=\"express-checkout__button express-checkout__button--paypal\"\n >\n <PayPalWordmark />\n </button>\n )}\n </div>\n\n {/* Always in the DOM so remounts can find the nodes; CSS hides unavailable.\n No aria-label on the slots: a labelled div is exposed as a group, so\n screen readers would announce a group around each wallet's own button. */}\n <div\n ref={appleMountRef}\n className={walletClassName(appleReady, appleVisible)}\n aria-hidden={appleReady && !appleVisible}\n data-testid=\"apple-pay-slot\"\n />\n <div\n ref={googleMountRef}\n className={walletClassName(googleReady, googleVisible)}\n aria-hidden={googleReady && !googleVisible}\n data-testid=\"google-pay-slot\"\n />\n </div>\n {walletError && (\n <p className=\"express-checkout__error\" role=\"alert\">\n {walletError}\n </p>\n )}\n {/* One skeleton over the whole block; the slots stay mounted underneath so the SDKs can load. */}\n {showSkeleton && (\n <Skeleton containerClassName=\"express-checkout__skeleton\" height=\"100%\" borderRadius={8} inline />\n )}\n </div>\n );\n};\n\nexport default ExpressCheckout;\n"]}
@@ -26,7 +26,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
26
26
  import { useQueryClient } from '@tanstack/react-query';
27
27
  import { useQueryStates, useQueryState, parseAsString } from 'nuqs';
28
28
  import { createAlacarteCheckoutClient } from '../../utils/alacarteCheckout';
29
- import { getCouponErrorMessage, getCouponRecheckMessage } from '../../utils/couponErrors';
29
+ import { getCouponErrorMessage, getCouponRecheckMessage, isCouponError } from '../../utils/couponErrors';
30
30
  import { placeAlacarteOrder, startAlacartePaypalOrder, toAlacarteBillingAddress, } from '../../utils/alacartePayment';
31
31
  import { AlacartePlaceOrderError, isSanctionsBlockedError, toPlaceOrderError } from '../../utils/placeOrderErrors';
32
32
  import { CardValidationError } from '../../utils/stripeCard';
@@ -669,6 +669,7 @@ export function useAlacarteCheckout(options) {
669
669
  setCheckoutOverride(err.checkout);
670
670
  }
671
671
  // The timeout warning and sanctions modal replace the generic error banner.
672
+ const errMsg = err instanceof Error ? err.message : '';
672
673
  if (isRequestTimeoutError(err)) {
673
674
  setPaymentTimedOut(true);
674
675
  }
@@ -676,6 +677,10 @@ export function useAlacarteCheckout(options) {
676
677
  // TODO: use the backend reference code once tCheckoutPlaceOrder returns one.
677
678
  setSanctionsBlocked({ referenceCode: 'REF-8F2K-40QX-1177' });
678
679
  }
680
+ else if (isCouponError(errMsg)) {
681
+ // Coupon errors show inline below the promo code input, not as a top banner.
682
+ setCouponError(getCouponErrorMessage(errMsg));
683
+ }
679
684
  else {
680
685
  setPlaceOrderError(errorMessage(err));
681
686
  }
@@ -753,9 +758,13 @@ export function useAlacarteCheckout(options) {
753
758
  if (err instanceof AlacartePlaceOrderError && err.checkout) {
754
759
  setCheckoutOverride(err.checkout);
755
760
  }
761
+ const paypalErrMsg = err instanceof Error ? err.message : '';
756
762
  if (isRequestTimeoutError(err)) {
757
763
  setPaymentTimedOut(true);
758
764
  }
765
+ else if (isCouponError(paypalErrMsg)) {
766
+ setCouponError(getCouponErrorMessage(paypalErrMsg));
767
+ }
759
768
  else {
760
769
  setPlaceOrderError(errorMessage(err));
761
770
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAlacarteCheckout.js","sourceRoot":"","sources":["../../../src/data/hooks/useAlacarteCheckout.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,C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cAAc,EAAE,oBAAoB,CAAC,SAAS,EAC9C,WAAW;QACX,YAAY,EACZ,gBAAgB,EAAE,GAAG,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,EAC5C,iBAAiB,EACjB,sBAAsB,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,EACxD,YAAY;QACZ,eAAe;QACf,kBAAkB;QAClB,sBAAsB;QACtB,UAAU,EACV,eAAe,EAAE,cAAc,EAC/B,gBAAgB;QAChB,kBAAkB;QAClB,iBAAiB,EACjB,oBAAoB,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EACpD,uBAAuB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAC3D,0BAA0B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,IAAI,CAAC,EACjE,2BAA2B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,KAAK,CAAC,EACnE,kBAAkB;QAClB,eAAe;QACf,gBAAgB,EAChB,cAAc,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,0CAAE,cAAc,mCAAI,IAAI,EACxD,WAAW,EACX,mBAAmB,EAAE,UAAU,CAAC,mBAAmB,EACnD,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAC7C,mBAAmB,IACnB;AACJ,CAAC;AAED,eAAe,mBAAmB,CAAC","sourcesContent":["/**\n * data/hooks/useAlacarteCheckout.ts — page-level orchestration for the à la\n * carte checkout flow:\n *\n * 1. Read a product selector (course or program) from the URL via nuqs.\n * 2. If a product is selected: check ownership (tOwnedProducts). Already\n * owned -> 'alreadyOwned'. Otherwise select it into the checkout\n * (tCheckoutSelect) and fetch its display details in parallel.\n * 3. If no product is selected: look for an existing open checkout\n * (tCheckout). Found -> 'ready'. Not found -> 'noActiveCheckout'.\n * 4. Coupon apply/remove and payment prep via tCheckoutUpdate.\n *\n * See /alacarte-checkout-api.md and /alacarte-owned-products-api.md at the\n * repo root for the underlying API contract.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useQueryStates, useQueryState, parseAsString } from 'nuqs';\nimport { createAlacarteCheckoutClient } from '../../utils/alacarteCheckout';\nimport { getCouponErrorMessage, getCouponRecheckMessage } from '../../utils/couponErrors';\nimport {\n placeAlacarteOrder,\n startAlacartePaypalOrder,\n toAlacarteBillingAddress,\n} from '../../utils/alacartePayment';\nimport { AlacartePlaceOrderError, isSanctionsBlockedError, toPlaceOrderError } from '../../utils/placeOrderErrors';\nimport { CardValidationError } from '../../utils/stripeCard';\nimport { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';\nimport {\n useSubscriptionCourseKeyQuery, useViaxSessionQuery, useRefreshViaxSession, viaxTokenForRejectedCall,\n} from './useCheckoutQueries';\nimport {\n courseKeyFromCourseRunKey, lmsOriginFromSessionUrl, isCourseNotFoundError,\n} from '../../utils/provision';\nimport { getCourseRunKeyFromUrl } from '../../utils/url';\nimport {\n useOwnedProductQuery, useAlacarteCheckoutQuery, useSelectProductMutation, useProductDetailQuery,\n useUpdateCheckoutMutation, usePlacedOrderQuery,\n} from './useAlacarteQueries';\nimport { alacarteKeys } from './keys';\nimport { derivePlacedOrderView } from './placedOrderPoll';\nimport { trackEvent, trackEventOnce } from '../../analytics/trackEvent';\nimport { buildProductsFromLine, buildProductsFromOrder } from '../../analytics/buildProducts';\nimport type {\n AlacarteCheckout, AlacarteCheckoutResult, AlacarteLine, AlacarteMoney, AlacartePaymentDecline,\n AlacartePriceChanged, OwnedProduct, OwnedProductResult, PlacedOrder, ProductDetail, ProductSelector,\n} from '../../types/alacarte';\nimport type { BillingInfo } from '../../types';\n\nexport type AlacartePhase = 'loading' | 'alreadyOwned' | 'noActiveCheckout' | 'notPurchasable' | 'ready' | 'error';\n\nexport type AlacarteNoticeMessageId = 'alreadyOwnedCourse' | 'alreadyOwnedProgram' | 'noActiveCheckout';\n\n/** Pure phase decision output — no action callbacks. */\nexport interface AlacartePhaseState {\n phase: AlacartePhase,\n noticeMessageId?: AlacarteNoticeMessageId,\n selector: ProductSelector,\n checkout: AlacarteCheckout | null,\n line: AlacarteLine | null,\n productDetail: ProductDetail | null,\n error: string | null,\n priceChanged: AlacartePriceChanged | null,\n priceAccepted: boolean,\n /** True when the learner already owns this product. The checkout data may\n * still be populated so the UI can render the full page under an overlay. */\n isAlreadyOwned: boolean,\n /** Product name from the owned-products query — used as a fallback when the\n * checkout line (which normally carries the name) is not available. */\n ownedProductName: string | null,\n}\n\nexport interface UseAlacarteCheckoutResult extends AlacartePhaseState {\n couponError: string | null,\n couponApplying: boolean,\n applyCoupon: (code: string) => void,\n removeCoupon: () => void,\n clearCouponError: () => void,\n /** Code of the coupon just removed, set only once the removal round-trip\n * completes — kept in sync with when the discount actually leaves the line. */\n removedCouponCode: string | null,\n clearRemovedCouponCode: () => void,\n placingOrder: boolean,\n placeOrderError: string | null,\n /** True when the learner returns to checkout without completing payment. */\n paymentInterrupted: boolean,\n /** True when the learner dismissed the Apple Pay / Google Pay sheet without paying. */\n walletPaymentCancelled: boolean,\n /**\n * Accepts price (if needed) + terms, calls tCheckoutPlaceOrder with billing,\n * confirms the card via Stripe.js, then sets ?order_bi_id= to poll getTwouOrder.\n * Fire-and-forget — errors go to placeOrderError state.\n */\n placeOrder: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => void,\n /**\n * Same as placeOrder but returns a Promise — used by ExpressCheckout\n * so the wallet sheet can await the result and call ev.complete().\n */\n placeOrderAsync: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => Promise<void>,\n /**\n * PayPal buttons `createOrder`: accepts price + terms and calls\n * tCheckoutPlaceOrder(paymentMethod: PAYPAL). Resolves the PayPal order id.\n */\n startPaypalOrder: (opts: { billing: BillingInfo }) => Promise<string>,\n /** PayPal buttons `onApprove`: tCheckoutCapturePaypalOrder, then sets ?order_bi_id=. */\n approvePaypalOrder: (paypalOrderId: string) => Promise<void>,\n /** PayPal buttons `onCancel` / `onError`: tCheckoutCancelPaypalOrder and reload tCheckout. */\n cancelPaypalOrder: (paypalOrderId: string) => Promise<void>,\n clearPlaceOrderError: () => void,\n clearPaymentInterrupted: () => void,\n /** Express Checkout Element `cancel`: the wallet sheet was closed without paying. */\n markWalletPaymentCancelled: () => void,\n clearWalletPaymentCancelled: () => void,\n /**\n * Express Checkout Element `click`: a new Apple Pay / Google Pay attempt is\n * starting, so the previous attempt's banners go (PayPal does this in\n * startPaypalOrder).\n */\n clearPaymentAlerts: () => void,\n /** True once the payment provider timed out during place order (HTTP 408 /\n * Stripe network error). The order may still go through, so further\n * attempts are blocked and the UI shows the timeout warning instead. */\n paymentTimedOut: boolean,\n /** Set when tCheckoutPlaceOrder returned SANCTIONS_BLOCKED. No charge was\n * made; the UI shows a blocking modal with a code the learner can quote\n * to support. Hardcoded until the backend returns a reference code\n * with SANCTIONS_BLOCKED. */\n sanctionsBlocked: { referenceCode: string } | null,\n /** Decline details from the last card attempt on this checkout, if any. */\n paymentDecline: AlacartePaymentDecline | null,\n /** When ?order_bi_id= is present, the placed order (or null while polling). */\n placedOrder: PlacedOrder | null,\n /**\n * True while getTwouOrder is still awaiting tPlacedAt (payment confirming,\n * including 3DS) or while we reload tCheckout after NOT_PLACED.\n */\n awaitingPlacedOrder: boolean,\n placedOrderError: string | null,\n /** ISO timestamp the order was placed (tPlacedAt, falling back to\n * biCreatedAt); null while the order-dates query hasn't resolved yet. */\n placedOrderPlacedAt: string | null,\n}\n\n/**\n * Read the product selector from the URL: course_uuid+course_run_key, or\n * program_uuid, or neither. Both course params must be present together; if a\n * course param and a program param are both present, that's\n * CONFLICTING_SELECTION.\n *\n * Legacy aliases `course_uid` / `program_uid` are still accepted; the `*_uuid`\n * names win when both are present.\n *\n * NOTE: course_run_key values look like \"course-v1:HarvardX+CS50+X\" — nuqs\n * decodes query values the standards-compliant way (literal `+` -> space),\n * same as native URLSearchParams. runKey is therefore read from the raw query\n * string via getCourseRunKeyFromUrl(), which preserves literal `+`.\n */\nexport function useProductSelector(): ProductSelector {\n const [{\n courseUuid, courseUidLegacy, runKey: nuqsRunKey, programUuid, programUidLegacy,\n }] = useQueryStates({\n courseUuid: parseAsString,\n courseUidLegacy: parseAsString,\n runKey: parseAsString,\n programUuid: parseAsString,\n programUidLegacy: parseAsString,\n }, {\n urlKeys: {\n courseUuid: 'course_uuid',\n courseUidLegacy: 'course_uid',\n runKey: 'course_run_key',\n programUuid: 'program_uuid',\n programUidLegacy: 'program_uid',\n },\n });\n const courseUid = courseUuid ?? courseUidLegacy;\n const programUid = programUuid ?? programUidLegacy;\n const runKey = nuqsRunKey ? (getCourseRunKeyFromUrl() ?? nuqsRunKey) : null;\n\n return useMemo<ProductSelector>(() => {\n const hasCourse = !!courseUid || !!runKey;\n const hasProgram = !!programUid;\n if (hasCourse && hasProgram) return { kind: 'invalid' };\n if (courseUid && runKey) return { kind: 'course', courseUid, runKey };\n if (programUid) return { kind: 'program', programUid };\n return { kind: 'none' };\n }, [courseUid, runKey, programUid]);\n}\n\n/** Reads ?discount_code= — applied to the checkout right after it's created. */\nexport function useDiscountCode(): string | null {\n const [discountCode] = useQueryState('discount_code', parseAsString);\n return discountCode;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : 'Unknown error';\n}\n\n/**\n * Build a synthetic AlacarteLine from the owned-product pricing data so the\n * checkout overlay can show subtotal / deduction / total even when the backend\n * blocks tCheckoutSelect and returns no checkout object.\n */\nfunction buildLineFromOwnedProduct(product: OwnedProduct): AlacarteLine | null {\n if (!product.price) return null;\n const { full, deduction, amountDue, currency } = product.price;\n const toMoney = (amount: number): AlacarteMoney => ({ amount, currency });\n\n if (product.kind === 'program') {\n return {\n biiId: '',\n kind: 'program',\n programId: product.productId,\n programName: product.name,\n price: toMoney(full),\n deduction: deduction ? toMoney(deduction) : null,\n ownedCourses: product.ownedCourses.map((c) => ({\n courseId: c.courseId, name: c.name, via: c.via,\n })),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n }\n\n return {\n biiId: '',\n kind: 'course',\n courseName: product.name,\n courseUid: product.productId,\n courseRunKey: '',\n seatType: 'verified',\n price: toMoney(full),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n}\n\ninterface QueryLikeState<T> {\n isLoading: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\ninterface MutationLikeState<T> {\n isIdle: boolean,\n isPending: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\nexport interface DeriveAlacartePhaseInput {\n selector: ProductSelector,\n sessionReady: boolean,\n sessionIsError: boolean,\n sessionErrorMessage?: string,\n ownedQuery: QueryLikeState<OwnedProductResult>,\n selectMutation: MutationLikeState<AlacarteCheckoutResult>,\n checkoutQuery: QueryLikeState<AlacarteCheckoutResult>,\n productDetail: ProductDetail | null,\n /** Coupon (?discount_code=) applied right after the checkout is created —\n * when it succeeds, its checkout (with the coupon's discount reflected)\n * is shown in place of the pre-coupon one from selectMutation. */\n couponMutation?: MutationLikeState<AlacarteCheckoutResult>,\n /** True when a URL discount code still needs to be applied — the phase\n * stays 'loading' until the coupon mutation resolves so the user never sees\n * the pre-discount price flash. */\n urlCouponPending?: boolean,\n /** Latest successful manual update (coupon / acceptPrice / terms). Wins over\n * select + URL coupon when present. */\n checkoutOverride?: AlacarteCheckout | null,\n /** Course-runs lookup for a course selector. Empty `elements` is notFound. */\n courseRunLookup?: { pending: boolean, notFound: boolean },\n}\n\n/**\n * Pure decision function — no hooks, no React Query/nuqs types beyond plain\n * data — so every branch combination can be unit-tested directly.\n */\nexport function deriveAlacartePhase(input: DeriveAlacartePhaseInput): AlacartePhaseState {\n const {\n selector, sessionReady, sessionIsError, sessionErrorMessage,\n ownedQuery, selectMutation, checkoutQuery, productDetail, couponMutation,\n checkoutOverride = null, urlCouponPending: urlCouponPendingProp = false,\n courseRunLookup = { pending: false, notFound: false },\n } = input;\n\n const ownedProductName = ownedQuery.data?.product?.name ?? null;\n\n const empty: Omit<AlacartePhaseState, 'phase'> = {\n selector,\n checkout: null,\n line: null,\n productDetail: null,\n error: null,\n priceChanged: null,\n priceAccepted: false,\n isAlreadyOwned: false,\n ownedProductName: null,\n };\n\n const withCheckout = (\n checkout: AlacarteCheckout | null,\n priceChanged: AlacartePriceChanged | null = null,\n isAlreadyOwned = false,\n ): AlacartePhaseState => ({\n phase: isAlreadyOwned ? 'alreadyOwned' : 'ready',\n selector,\n checkout,\n line: checkout?.line ?? null,\n productDetail,\n error: null,\n priceChanged: priceChanged ?? null,\n priceAccepted: checkout?.priceAccepted === true,\n isAlreadyOwned,\n ownedProductName: isAlreadyOwned ? ownedProductName : null,\n });\n\n if (selector.kind === 'invalid') {\n return { phase: 'error', ...empty, error: 'CONFLICTING_SELECTION' };\n }\n if (sessionIsError) {\n return { phase: 'error', ...empty, error: sessionErrorMessage ?? 'Session error' };\n }\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n\n if (hasSelector) {\n if (selector.kind === 'course' && courseRunLookup.notFound) {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (!sessionReady || ownedQuery.isLoading || courseRunLookup.pending) {\n return { phase: 'loading', ...empty };\n }\n if (ownedQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(ownedQuery.error) };\n }\n\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n if (selectMutation.isIdle || selectMutation.isPending) {\n return { phase: 'loading', ...empty };\n }\n if (selectMutation.isError) {\n return { phase: 'error', ...empty, error: errorMessage(selectMutation.error) };\n }\n if (selectMutation.data && !selectMutation.data.ok) {\n // The backend may block ALREADY_OWNED at select time. When the\n // blocked response still includes checkout data (line, pricing), use\n // it so the overlay page shows the real totals. Fall back to the\n // standalone tCheckout query, then to an empty state.\n if (selectMutation.data.blocked?.reason === 'ALREADY_OWNED') {\n const blockedCheckout = selectMutation.data.checkout\n ?? (checkoutQuery.data?.ok ? checkoutQuery.data.checkout : null);\n if (blockedCheckout) {\n return withCheckout(blockedCheckout, selectMutation.data.priceChanged ?? null, true);\n }\n // Build a synthetic line from the owned-product pricing so the\n // overlay can show subtotal / deduction / total.\n const ownedProduct = ownedQuery.data?.product;\n const syntheticLine = ownedProduct ? buildLineFromOwnedProduct(ownedProduct) : null;\n return {\n phase: 'alreadyOwned',\n noticeMessageId: selectMutation.data.blocked.kind === 'course' ? 'alreadyOwnedCourse' : 'alreadyOwnedProgram',\n ...empty,\n line: syntheticLine,\n productDetail,\n isAlreadyOwned: true,\n ownedProductName,\n };\n }\n if (selectMutation.data.blocked?.reason === 'NOT_PURCHASABLE') {\n return {\n phase: 'notPurchasable',\n ...empty,\n productDetail,\n error: selectMutation.data.blocked.kind === 'program'\n ? 'This program is not eligible for checkout.'\n : 'This course is not eligible for checkout.',\n };\n }\n const selectError = selectMutation.data.error;\n if (selectError === 'COURSE_NOT_FOUND' || selectError === 'PRODUCT_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (selectError === 'PROGRAM_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This program could not be found.',\n };\n }\n const blockedDetail = selectMutation.data.blocked?.detail;\n return {\n phase: 'error',\n ...empty,\n error: blockedDetail ?? selectError ?? 'unknown',\n };\n }\n\n // When a URL discount code still needs to be applied, stay in 'loading'\n // so the user never sees the pre-discount price flash.\n if (urlCouponPendingProp && !checkoutOverride) {\n return { phase: 'loading', ...empty };\n }\n\n // Once the coupon-apply (?discount_code=) mutation succeeds, its checkout\n // (with the discount reflected) supersedes the pre-coupon one. Manual\n // updates (override) win over both.\n const finalCheckout = checkoutOverride\n ?? (couponMutation?.data?.ok\n ? couponMutation.data.checkout\n : selectMutation.data?.checkout ?? null);\n\n // When select succeeds but the owned-products query says the learner\n // already has this product, show the full checkout under an overlay.\n return withCheckout(\n finalCheckout,\n selectMutation.data?.priceChanged\n ?? (couponMutation?.data?.ok ? couponMutation.data.priceChanged : undefined)\n ?? null,\n isOwned,\n );\n }\n\n // No selector: fall back to the learner's existing open checkout, if any.\n if (!sessionReady || checkoutQuery.isLoading) {\n return { phase: 'loading', ...empty };\n }\n if (checkoutQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(checkoutQuery.error) };\n }\n if (checkoutOverride || checkoutQuery.data?.checkout) {\n const checkout = checkoutOverride ?? checkoutQuery.data!.checkout;\n return withCheckout(checkout, checkoutQuery.data?.priceChanged ?? null);\n }\n\n return { phase: 'noActiveCheckout', noticeMessageId: 'noActiveCheckout', ...empty, isAlreadyOwned: false, ownedProductName: null };\n}\n\n/** amountDue with coupon/automatic discount removed (price − program deduction). */\nfunction amountDueWithoutDiscount(line: AlacarteLine): AlacarteMoney | null {\n if (!line.price) return null;\n if (line.kind === 'program' && line.deduction) {\n return {\n amount: line.price.amount - line.deduction.amount,\n currency: line.price.currency,\n };\n }\n return line.price;\n}\n\n/** amountDue after applying a discount on top of price (− program deduction). */\nfunction amountDueWithDiscount(\n line: AlacarteLine,\n discount: AlacarteMoney,\n): AlacarteMoney | null {\n const base = amountDueWithoutDiscount(line);\n if (!base) return null;\n return { amount: base.amount - discount.amount, currency: base.currency };\n}\n\n/**\n * Checkout to show once a coupon removal succeeds. The backend may return a\n * line that still carries the old coupon discount/amountDue, so that line is\n * patched to clear it. An automatic offer (bundle / first-order) the backend\n * re-applied once the coupon is gone is the real state and is kept as-is.\n *\n * When the backend clears the coupon but does not re-apply the automatic\n * offer that was present before the coupon, `priorCheckout` (typically the\n * pre-coupon select response) is used to restore that offer.\n */\nexport function checkoutWithoutCoupon(\n checkout: AlacarteCheckout,\n priorCheckout?: AlacarteCheckout | null,\n): AlacarteCheckout {\n const { line } = checkout;\n if (!line) {\n return { ...checkout, couponCode: null };\n }\n if (line.discountSource === 'automatic') {\n return { ...checkout, couponCode: null };\n }\n\n const priorLine = priorCheckout?.line;\n const priorAutomatic = priorLine?.discountSource === 'automatic' && priorLine.discount\n ? priorLine\n : null;\n\n const clearedLine = {\n ...line,\n discount: null,\n discountSource: null,\n discountName: null,\n amountDue: amountDueWithoutDiscount(line),\n } as typeof line;\n\n if (priorAutomatic?.discount) {\n return {\n ...checkout,\n couponCode: null,\n line: {\n ...clearedLine,\n discount: priorAutomatic.discount,\n discountSource: 'automatic',\n discountName: priorAutomatic.discountName ?? null,\n amountDue: amountDueWithDiscount(clearedLine, priorAutomatic.discount),\n } as typeof line,\n };\n }\n\n return { ...checkout, couponCode: null, line: clearedLine };\n}\n\nexport function useAlacarteCheckout(\n options: {\n apiUrl?: string,\n edxSessionUrl?: string,\n /**\n * When true, skip GET /api/subscription/course_runs/ and call Viax with a\n * course key derived from ?course_run_key= instead.\n */\n skipSubscriptionCourseRuns?: boolean,\n },\n): UseAlacarteCheckoutResult {\n const { apiUrl, edxSessionUrl, skipSubscriptionCourseRuns = false } = options;\n const queryClient = useQueryClient();\n const selector = useProductSelector();\n const discountCode = useDiscountCode();\n const [orderBiId, setOrderBiId] = useQueryState('order_bi_id', parseAsString);\n\n // Reuses the same query key as useCheckout's session exchange — React\n // Query dedupes the network call regardless of how many hooks read it.\n const sessionQuery = useViaxSessionQuery(edxSessionUrl ?? null);\n const sessionReady = !!sessionQuery.data;\n const refreshSession = useRefreshViaxSession(edxSessionUrl ?? null);\n\n // Stable ref so the onRefreshToken callback always uses the latest\n // refreshSession without recreating the client on every render.\n const refreshSessionRef = useRef(refreshSession);\n refreshSessionRef.current = refreshSession;\n\n const client = useMemo(\n () => (apiUrl ? createAlacarteCheckoutClient({\n apiUrl,\n onRefreshToken: () => viaxTokenForRejectedCall(() => refreshSessionRef.current()),\n }) : null),\n [apiUrl],\n );\n\n useEffect(() => {\n if (sessionQuery.data && client) {\n client.setToken(sessionQuery.data.viaxToken);\n }\n }, [sessionQuery.data, client]);\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n const productId = selector.kind === 'course'\n ? selector.courseUid\n : selector.kind === 'program' ? selector.programUid : null;\n\n const ownedQuery = useOwnedProductQuery(client, sessionReady && hasSelector, productId);\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n const selectMutation = useSelectProductMutation(client);\n const {\n isIdle: selectIsIdle, mutate: selectMutate, reset: selectReset,\n } = selectMutation;\n\n const courseRunKey = selector.kind === 'course' ? selector.runKey : null;\n const lmsBaseUrl = useMemo(\n () => lmsOriginFromSessionUrl(edxSessionUrl),\n [edxSessionUrl],\n );\n const courseLookupEnabled = !skipSubscriptionCourseRuns\n && selector.kind === 'course'\n && !!lmsBaseUrl\n && !!courseRunKey;\n const courseKeyQuery = useSubscriptionCourseKeyQuery(\n skipSubscriptionCourseRuns ? null : lmsBaseUrl,\n skipSubscriptionCourseRuns ? null : courseRunKey,\n );\n const courseKey = skipSubscriptionCourseRuns\n ? (courseRunKey ? courseKeyFromCourseRunKey(courseRunKey) : null)\n : (courseKeyQuery.data ?? null);\n const courseNotFound = courseLookupEnabled\n && courseKeyQuery.isError\n && isCourseNotFoundError(courseKeyQuery.error);\n\n // Mutations aren't called during render — fire once the owned-products\n // query resolves (regardless of result) so we always get checkout/line data.\n // A course is not selected until the course-runs lookup returns a course.\n // Pass viewedPrice from tOwnedProducts.amountDue (ALC-159) when available.\n useEffect(() => {\n if (!hasSelector || ownedQuery.isLoading || ownedQuery.isError) return;\n if (selector.kind === 'course' && !courseKey) return;\n if (!selectIsIdle) return;\n const amountDue = ownedQuery.data?.product?.price?.amountDue;\n selectMutate({\n selector,\n viewedPrice: typeof amountDue === 'number' ? amountDue : undefined,\n });\n }, [\n hasSelector,\n ownedQuery.isLoading,\n ownedQuery.isError,\n ownedQuery.data?.product?.price?.amountDue,\n selector,\n courseKey,\n selectIsIdle,\n selectMutate,\n ]);\n\n const productDetailEnabled = hasSelector && sessionReady && !ownedQuery.isLoading\n && (selector.kind !== 'course' || !!courseKey);\n const productDetailQuery = useProductDetailQuery(client, productDetailEnabled, selector, courseKey);\n\n // Run the checkout query when there's no selector (standard path) OR when\n // the product is already owned — after the select mutation is blocked with\n // ALREADY_OWNED the server may still have an open checkout with pricing data.\n const selectBlocked = !selectMutation.isIdle && !selectMutation.isPending\n && selectMutation.data && !selectMutation.data.ok;\n const checkoutQuery = useAlacarteCheckoutQuery(\n client,\n sessionReady && (!hasSelector || (isOwned && !!selectBlocked)),\n );\n\n // Apply ?discount_code= to the freshly-created checkout — fired once the\n // select mutation succeeds with a checkout that doesn't already carry it.\n const urlCouponMutation = useUpdateCheckoutMutation(client);\n const {\n isIdle: couponIsIdle, mutate: couponMutate, reset: urlCouponReset,\n } = urlCouponMutation;\n const createdCheckout = selectMutation.data?.ok ? selectMutation.data.checkout : null;\n\n useEffect(() => {\n if (!createdCheckout || !discountCode) return;\n if (createdCheckout.couponCode === discountCode) return;\n if (couponIsIdle) {\n couponMutate({ biId: createdCheckout.biId, couponCode: discountCode });\n }\n }, [createdCheckout, discountCode, couponIsIdle, couponMutate]);\n\n const [checkoutOverride, setCheckoutOverride] = useState<AlacarteCheckout | null>(null);\n const [couponError, setCouponError] = useState<string | null>(null);\n const [removedCouponCode, setRemovedCouponCode] = useState<string | null>(null);\n const [placeOrderError, setPlaceOrderError] = useState<string | null>(null);\n const [paymentInterrupted, setPaymentInterrupted] = useState(false);\n const [walletPaymentCancelled, setWalletPaymentCancelled] = useState(false);\n const [placingOrder, setPlacingOrder] = useState(false);\n const [paymentTimedOut, setPaymentTimedOut] = useState(false);\n const [sanctionsBlocked, setSanctionsBlocked] = useState<{ referenceCode: string } | null>(null);\n // biId of a checkout that's locked (CART_PAYMENT_PENDING) from a prior\n // tCheckoutPlaceOrder call whose Stripe confirmation was rejected\n // client-side. The next attempt must skip tCheckoutUpdate (it would fail\n // with CHECKOUT_NOT_OPEN) and go straight to tCheckoutPlaceOrder again.\n const [cardRetryBiId, setCardRetryBiId] = useState<string | null>(null);\n // Last checkout that carried an automatic offer — restored after a custom\n // coupon is removed if the backend does not re-apply it.\n const automaticBaselineRef = useRef<AlacarteCheckout | null>(null);\n // Tracks the payment method/processor used for the last place-order attempt,\n // so the Order Completed event can include them.\n const lastPaymentInfoRef = useRef<{ method: string, processor: string }>({ method: 'card', processor: 'stripe' });\n // Ref for product detail so trackEvent inside useCallback always reads the\n // latest value instead of a stale closure capture.\n const productDetailRef = useRef<ProductDetail | null>(null);\n productDetailRef.current = productDetailQuery.data ?? null;\n\n // Reset local overrides and in-flight select/coupon when the product changes\n // so viewedPrice / couponRecheck run again for the new selection.\n useEffect(() => {\n setCheckoutOverride(null);\n setCouponError(null);\n setRemovedCouponCode(null);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n setPaymentTimedOut(false);\n setSanctionsBlocked(null);\n setCardRetryBiId(null);\n automaticBaselineRef.current = null;\n selectReset();\n urlCouponReset();\n }, [selector, selectReset, urlCouponReset]);\n\n // Surface couponRecheck from product switch (section 2 of the API doc).\n useEffect(() => {\n const result = selectMutation.data;\n if (!result?.ok) return;\n const message = getCouponRecheckMessage(\n result.couponRecheck,\n result.checkout?.line?.discountSource,\n );\n if (message) setCouponError(message);\n }, [selectMutation.data]);\n\n // Surface ?discount_code= apply failures (domain ok:false or transport error).\n useEffect(() => {\n if (!discountCode) return;\n if (urlCouponMutation.isIdle || urlCouponMutation.isPending) return;\n if (urlCouponMutation.isError) {\n setCouponError(errorMessage(urlCouponMutation.error));\n return;\n }\n const result = urlCouponMutation.data;\n if (result && !result.ok) {\n setCouponError(getCouponErrorMessage(result.error, discountCode));\n }\n }, [\n discountCode,\n urlCouponMutation.isIdle,\n urlCouponMutation.isPending,\n urlCouponMutation.isError,\n urlCouponMutation.error,\n urlCouponMutation.data,\n ]);\n\n // Segment: Coupon Applied for ?discount_code= auto-apply.\n const urlCouponTrackedRef = useRef(false);\n useEffect(() => {\n if (urlCouponTrackedRef.current) return;\n const result = urlCouponMutation.data;\n if (!result?.ok || !result.checkout?.line) return;\n urlCouponTrackedRef.current = true;\n const line = result.checkout.line;\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? discountCode ?? '',\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }, [urlCouponMutation.data, discountCode, productDetailQuery.data]);\n\n const manualUpdateMutation = useUpdateCheckoutMutation(client);\n\n const placedOrderQuery = usePlacedOrderQuery(\n client,\n orderBiId,\n sessionReady && !!orderBiId,\n );\n\n const derived = deriveAlacartePhase({\n selector,\n sessionReady,\n sessionIsError: sessionQuery.isError,\n sessionErrorMessage: sessionQuery.error?.message,\n ownedQuery: {\n isLoading: ownedQuery.isLoading,\n isError: ownedQuery.isError,\n error: ownedQuery.error,\n data: ownedQuery.data,\n },\n selectMutation: {\n isIdle: selectMutation.isIdle,\n isPending: selectMutation.isPending,\n isError: selectMutation.isError,\n error: selectMutation.error,\n data: selectMutation.data,\n },\n checkoutQuery: {\n isLoading: checkoutQuery.isLoading,\n isError: checkoutQuery.isError,\n error: checkoutQuery.error,\n data: checkoutQuery.data,\n },\n productDetail: productDetailQuery.data ?? null,\n courseRunLookup: {\n pending: courseLookupEnabled && courseKeyQuery.isLoading,\n notFound: courseNotFound,\n },\n couponMutation: {\n isIdle: urlCouponMutation.isIdle,\n isPending: urlCouponMutation.isPending,\n isError: urlCouponMutation.isError,\n error: urlCouponMutation.error,\n data: urlCouponMutation.data,\n },\n checkoutOverride,\n // The URL coupon is pending only when the checkout exists, doesn't already\n // carry the code, and the mutation hasn't completed yet. When the backend\n // returns the coupon pre-applied (couponCode === discountCode) or when\n // there's no discount_code param at all, this is false from the start.\n urlCouponPending: !!discountCode\n && !!createdCheckout\n && createdCheckout.couponCode !== discountCode\n && (urlCouponMutation.isIdle || urlCouponMutation.isPending),\n });\n\n const applyCoupon = useCallback((code: string) => {\n const biId = derived.checkout?.biId;\n if (!biId || !client) return;\n const trimmed = code.trim();\n if (!trimmed) return;\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId, couponCode: trimmed },\n {\n onSuccess: (result) => {\n if (result.ok && result.checkout) {\n setCheckoutOverride(result.checkout);\n setCouponError(null);\n setRemovedCouponCode(null);\n // Segment: Coupon Applied (track_plan_id 30)\n const line = result.checkout.line;\n if (line) {\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? trimmed,\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }\n } else {\n setCouponError(getCouponErrorMessage(result.error, trimmed));\n }\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout?.biId, client, manualUpdateMutation]);\n\n // Remember the latest automatic offer so removeCoupon can restore it.\n useEffect(() => {\n const checkout = derived.checkout;\n if (\n checkout?.line?.discountSource === 'automatic'\n && checkout.line.discount\n ) {\n automaticBaselineRef.current = checkout;\n }\n }, [derived.checkout]);\n\n const removeCoupon = useCallback(() => {\n const currentCheckout = derived.checkout;\n if (!currentCheckout?.biId || !client) return;\n const removedCode = currentCheckout.couponCode?.trim() || null;\n // Prefer the remembered automatic offer; fall back to the pre-coupon\n // select response when the baseline was never captured.\n const priorCheckout = automaticBaselineRef.current\n ?? (selectMutation.data?.ok ? selectMutation.data.checkout : null);\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId: currentCheckout.biId, couponCode: '' },\n {\n onSuccess: (result) => {\n if (!result.ok) {\n setCouponError(getCouponErrorMessage(result.error));\n return;\n }\n setCheckoutOverride(\n checkoutWithoutCoupon(result.checkout ?? currentCheckout, priorCheckout),\n );\n setCouponError(null);\n if (removedCode) setRemovedCouponCode(removedCode);\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout, client, manualUpdateMutation, selectMutation.data]);\n\n const placeOrderCore = useCallback(async (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n // A timed-out attempt may still complete — never start a second one.\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'card', processor: 'stripe' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'card',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated } = await placeAlacarteOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing) => client.placeCheckoutOrder(biId, billing),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n confirmCardPayment: opts.confirmCardPayment,\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n\n setCardRetryBiId(null);\n setCheckoutOverride(updated);\n await setOrderBiId(updated.biId);\n } catch (err: unknown) {\n if (err instanceof CardValidationError) {\n // tCheckoutPlaceOrder already succeeded and locked the checkout\n // (CART_PAYMENT_PENDING); Stripe rejected the card before it ever\n // reached the backend. Next attempt must retry tCheckoutPlaceOrder\n // directly, not tCheckoutUpdate.\n setCardRetryBiId(checkout.biId);\n } else {\n setCardRetryBiId(null);\n }\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n // The timeout warning and sanctions modal replace the generic error banner.\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isSanctionsBlockedError(err)) {\n // TODO: use the backend reference code once tCheckoutPlaceOrder returns one.\n setSanctionsBlocked({ referenceCode: 'REF-8F2K-40QX-1177' });\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [derived.checkout, client, setOrderBiId, cardRetryBiId, paymentTimedOut]);\n\n /** Fire-and-forget wrapper for card payments. */\n const placeOrder = useCallback((opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n if (placingOrder || paymentTimedOut) return;\n placeOrderCore(opts).catch(() => { /* error already in state */ });\n }, [placeOrderCore, placingOrder, paymentTimedOut]);\n\n // biId of the checkout the open PayPal order belongs to — capture/cancel need it.\n const paypalBiIdRef = useRef<string | null>(null);\n\n const reloadCheckout = useCallback(async () => {\n if (!client) return;\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // The learner can still retry from the current checkout.\n }\n }, [client, queryClient]);\n\n const startPaypalOrder = useCallback(async (opts: { billing: BillingInfo }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'paypal', processor: 'paypal' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n await trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'paypal',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated, paypalOrderId } = await startAlacartePaypalOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing, paymentMethod) => (\n client.placeCheckoutOrder(biId, billing, paymentMethod)\n ),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n // tCheckoutPlaceOrder locked the checkout (CART_PAYMENT_PENDING) until\n // the PayPal order is captured or cancelled; a retry must skip tCheckoutUpdate.\n setCardRetryBiId(updated.biId);\n setCheckoutOverride(updated);\n paypalBiIdRef.current = updated.biId;\n return paypalOrderId;\n } catch (err: unknown) {\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n setPlacingOrder(false);\n throw err;\n }\n }, [derived.checkout, client, cardRetryBiId, paymentTimedOut]);\n\n const cancelPaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) {\n setPlacingOrder(false);\n return;\n }\n try {\n const result = await client.cancelPaypalOrder(biId, paypalOrderId);\n if (result.ok) {\n // Settled as a failed payment — the checkout is open again.\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n setPaymentInterrupted(true);\n }\n await reloadCheckout();\n } catch {\n // Leave cardRetryBiId set so the next attempt reuses the locked checkout.\n } finally {\n setPlacingOrder(false);\n }\n }, [client, reloadCheckout]);\n\n const approvePaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) throw new Error('Checkout not ready');\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n\n try {\n const result = await client.capturePaypalOrder(biId, paypalOrderId);\n // PAYMENT_IN_PROGRESS: another capture holds the lock and will settle the\n // order — poll getTwouOrder like a COMPLETED / PENDING capture.\n const placed = result.ok\n ? result.status === 'COMPLETED' || result.status === 'PENDING'\n : result.error === 'PAYMENT_IN_PROGRESS';\n if (!placed) {\n throw toPlaceOrderError(result.ok ? 'PAYPAL_PAYMENT_DECLINED' : (result.error ?? 'CAPTURE_FAILED'));\n }\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n await setOrderBiId(biId);\n } catch (err: unknown) {\n setPlaceOrderError(errorMessage(err));\n // A declined/failed capture leaves the order settled as failed — reload so\n // the learner can retry (paymentDecline comes back on tCheckout).\n setCardRetryBiId(null);\n await reloadCheckout();\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [client, setOrderBiId, reloadCheckout]);\n\n const clearPaymentAlerts = useCallback(() => {\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n }, []);\n\n const placedView = derivePlacedOrderView({\n orderBiId,\n result: placedOrderQuery.data,\n pollTimedOut: placedOrderQuery.pollTimedOut,\n isLoading: placedOrderQuery.isLoading,\n isFetching: placedOrderQuery.isFetching,\n });\n const { placedOrder } = placedView;\n const placedOrderPlacedAt = placedOrder?.placedAt ?? null;\n\n // Segment: Order Completed (track_plan_id 32), deduplicated by order number.\n useEffect(() => {\n if (!placedOrder || !orderBiId) return;\n const { method, processor } = lastPaymentInfoRef.current;\n trackEventOnce('Order Completed', {\n checkoutType: 'a_la_carte',\n track_plan_id: 32,\n trigger_source: 'client-side',\n order_id: placedOrder.orderNumber,\n checkout_id: orderBiId,\n total: placedOrder.totals.paid,\n revenue: placedOrder.totals.paid,\n currency: placedOrder.totals.currency,\n tax: placedOrder.totals.discount === 0 && placedOrder.totals.paid === 0 ? 0 : placedOrder.totals.deduction,\n coupon: placedOrder.couponCode ?? null,\n coupon_name: [],\n discount: placedOrder.totals.discount,\n processor_name: processor,\n payment_method: method,\n products: derived.line\n ? buildProductsFromLine(derived.line, productDetailRef.current)\n : buildProductsFromOrder(placedOrder.lines, productDetailRef.current),\n });\n }, [placedOrder, orderBiId, productDetailQuery.data, derived.line]);\n\n // NOT_PLACED: the payment did not go through and the cart is editable again.\n // Reload tCheckout (it carries paymentDecline) and drop ?order_bi_id= so the\n // learner can try another card instead of sitting on the confirmation error.\n // The ref blocks a second reload for the same attempt. It is not cleared in\n // cleanup — a re-run must not cancel the reload that is already in flight.\n const returnedToCheckoutFor = useRef<string | null>(null);\n useEffect(() => {\n if (!orderBiId) {\n returnedToCheckoutFor.current = null;\n return undefined;\n }\n if (!placedView.returnToCheckout) return undefined;\n if (returnedToCheckoutFor.current === orderBiId) return undefined;\n returnedToCheckoutFor.current = orderBiId;\n setPaymentInterrupted(true);\n\n (async () => {\n if (client) {\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // Still leave the poll — the cart is editable even if this read fails.\n }\n }\n await setOrderBiId(null);\n })();\n\n return undefined;\n }, [orderBiId, placedView.returnToCheckout, client, setOrderBiId, queryClient]);\n\n return {\n ...derived,\n couponError,\n couponApplying: manualUpdateMutation.isPending,\n applyCoupon,\n removeCoupon,\n clearCouponError: () => setCouponError(null),\n removedCouponCode,\n clearRemovedCouponCode: () => setRemovedCouponCode(null),\n placingOrder,\n placeOrderError,\n paymentInterrupted,\n walletPaymentCancelled,\n placeOrder,\n placeOrderAsync: placeOrderCore,\n startPaypalOrder,\n approvePaypalOrder,\n cancelPaypalOrder,\n clearPlaceOrderError: () => setPlaceOrderError(null),\n clearPaymentInterrupted: () => setPaymentInterrupted(false),\n markWalletPaymentCancelled: () => setWalletPaymentCancelled(true),\n clearWalletPaymentCancelled: () => setWalletPaymentCancelled(false),\n clearPaymentAlerts,\n paymentTimedOut,\n sanctionsBlocked,\n paymentDecline: derived.checkout?.paymentDecline ?? null,\n placedOrder,\n awaitingPlacedOrder: placedView.awaitingPlacedOrder,\n placedOrderError: placedView.placedOrderError,\n placedOrderPlacedAt,\n };\n}\n\nexport default useAlacarteCheckout;\n"]}
1
+ {"version":3,"file":"useAlacarteCheckout.js","sourceRoot":"","sources":["../../../src/data/hooks/useAlacarteCheckout.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AACpE,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzG,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACnH,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACvF,OAAO,EACL,6BAA6B,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,wBAAwB,GACpG,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,yBAAyB,EAAE,uBAAuB,EAAE,qBAAqB,GAC1E,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,oBAAoB,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,qBAAqB,EAC/F,yBAAyB,EAAE,mBAAmB,GAC/C,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E,GAAG,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EACpD,uBAAuB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAC3D,0BAA0B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,IAAI,CAAC,EACjE,2BAA2B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,KAAK,CAAC,EACnE,kBAAkB;QAClB,eAAe;QACf,gBAAgB,EAChB,cAAc,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,0CAAE,cAAc,mCAAI,IAAI,EACxD,WAAW,EACX,mBAAmB,EAAE,UAAU,CAAC,mBAAmB,EACnD,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAC7C,mBAAmB,IACnB;AACJ,CAAC;AAED,eAAe,mBAAmB,CAAC","sourcesContent":["/**\n * data/hooks/useAlacarteCheckout.ts — page-level orchestration for the à la\n * carte checkout flow:\n *\n * 1. Read a product selector (course or program) from the URL via nuqs.\n * 2. If a product is selected: check ownership (tOwnedProducts). Already\n * owned -> 'alreadyOwned'. Otherwise select it into the checkout\n * (tCheckoutSelect) and fetch its display details in parallel.\n * 3. If no product is selected: look for an existing open checkout\n * (tCheckout). Found -> 'ready'. Not found -> 'noActiveCheckout'.\n * 4. Coupon apply/remove and payment prep via tCheckoutUpdate.\n *\n * See /alacarte-checkout-api.md and /alacarte-owned-products-api.md at the\n * repo root for the underlying API contract.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useQueryStates, useQueryState, parseAsString } from 'nuqs';\nimport { createAlacarteCheckoutClient } from '../../utils/alacarteCheckout';\nimport { getCouponErrorMessage, getCouponRecheckMessage, isCouponError } from '../../utils/couponErrors';\nimport {\n placeAlacarteOrder,\n startAlacartePaypalOrder,\n toAlacarteBillingAddress,\n} from '../../utils/alacartePayment';\nimport { AlacartePlaceOrderError, isSanctionsBlockedError, toPlaceOrderError } from '../../utils/placeOrderErrors';\nimport { CardValidationError } from '../../utils/stripeCard';\nimport { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';\nimport {\n useSubscriptionCourseKeyQuery, useViaxSessionQuery, useRefreshViaxSession, viaxTokenForRejectedCall,\n} from './useCheckoutQueries';\nimport {\n courseKeyFromCourseRunKey, lmsOriginFromSessionUrl, isCourseNotFoundError,\n} from '../../utils/provision';\nimport { getCourseRunKeyFromUrl } from '../../utils/url';\nimport {\n useOwnedProductQuery, useAlacarteCheckoutQuery, useSelectProductMutation, useProductDetailQuery,\n useUpdateCheckoutMutation, usePlacedOrderQuery,\n} from './useAlacarteQueries';\nimport { alacarteKeys } from './keys';\nimport { derivePlacedOrderView } from './placedOrderPoll';\nimport { trackEvent, trackEventOnce } from '../../analytics/trackEvent';\nimport { buildProductsFromLine, buildProductsFromOrder } from '../../analytics/buildProducts';\nimport type {\n AlacarteCheckout, AlacarteCheckoutResult, AlacarteLine, AlacarteMoney, AlacartePaymentDecline,\n AlacartePriceChanged, OwnedProduct, OwnedProductResult, PlacedOrder, ProductDetail, ProductSelector,\n} from '../../types/alacarte';\nimport type { BillingInfo } from '../../types';\n\nexport type AlacartePhase = 'loading' | 'alreadyOwned' | 'noActiveCheckout' | 'notPurchasable' | 'ready' | 'error';\n\nexport type AlacarteNoticeMessageId = 'alreadyOwnedCourse' | 'alreadyOwnedProgram' | 'noActiveCheckout';\n\n/** Pure phase decision output — no action callbacks. */\nexport interface AlacartePhaseState {\n phase: AlacartePhase,\n noticeMessageId?: AlacarteNoticeMessageId,\n selector: ProductSelector,\n checkout: AlacarteCheckout | null,\n line: AlacarteLine | null,\n productDetail: ProductDetail | null,\n error: string | null,\n priceChanged: AlacartePriceChanged | null,\n priceAccepted: boolean,\n /** True when the learner already owns this product. The checkout data may\n * still be populated so the UI can render the full page under an overlay. */\n isAlreadyOwned: boolean,\n /** Product name from the owned-products query — used as a fallback when the\n * checkout line (which normally carries the name) is not available. */\n ownedProductName: string | null,\n}\n\nexport interface UseAlacarteCheckoutResult extends AlacartePhaseState {\n couponError: string | null,\n couponApplying: boolean,\n applyCoupon: (code: string) => void,\n removeCoupon: () => void,\n clearCouponError: () => void,\n /** Code of the coupon just removed, set only once the removal round-trip\n * completes — kept in sync with when the discount actually leaves the line. */\n removedCouponCode: string | null,\n clearRemovedCouponCode: () => void,\n placingOrder: boolean,\n placeOrderError: string | null,\n /** True when the learner returns to checkout without completing payment. */\n paymentInterrupted: boolean,\n /** True when the learner dismissed the Apple Pay / Google Pay sheet without paying. */\n walletPaymentCancelled: boolean,\n /**\n * Accepts price (if needed) + terms, calls tCheckoutPlaceOrder with billing,\n * confirms the card via Stripe.js, then sets ?order_bi_id= to poll getTwouOrder.\n * Fire-and-forget — errors go to placeOrderError state.\n */\n placeOrder: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => void,\n /**\n * Same as placeOrder but returns a Promise — used by ExpressCheckout\n * so the wallet sheet can await the result and call ev.complete().\n */\n placeOrderAsync: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => Promise<void>,\n /**\n * PayPal buttons `createOrder`: accepts price + terms and calls\n * tCheckoutPlaceOrder(paymentMethod: PAYPAL). Resolves the PayPal order id.\n */\n startPaypalOrder: (opts: { billing: BillingInfo }) => Promise<string>,\n /** PayPal buttons `onApprove`: tCheckoutCapturePaypalOrder, then sets ?order_bi_id=. */\n approvePaypalOrder: (paypalOrderId: string) => Promise<void>,\n /** PayPal buttons `onCancel` / `onError`: tCheckoutCancelPaypalOrder and reload tCheckout. */\n cancelPaypalOrder: (paypalOrderId: string) => Promise<void>,\n clearPlaceOrderError: () => void,\n clearPaymentInterrupted: () => void,\n /** Express Checkout Element `cancel`: the wallet sheet was closed without paying. */\n markWalletPaymentCancelled: () => void,\n clearWalletPaymentCancelled: () => void,\n /**\n * Express Checkout Element `click`: a new Apple Pay / Google Pay attempt is\n * starting, so the previous attempt's banners go (PayPal does this in\n * startPaypalOrder).\n */\n clearPaymentAlerts: () => void,\n /** True once the payment provider timed out during place order (HTTP 408 /\n * Stripe network error). The order may still go through, so further\n * attempts are blocked and the UI shows the timeout warning instead. */\n paymentTimedOut: boolean,\n /** Set when tCheckoutPlaceOrder returned SANCTIONS_BLOCKED. No charge was\n * made; the UI shows a blocking modal with a code the learner can quote\n * to support. Hardcoded until the backend returns a reference code\n * with SANCTIONS_BLOCKED. */\n sanctionsBlocked: { referenceCode: string } | null,\n /** Decline details from the last card attempt on this checkout, if any. */\n paymentDecline: AlacartePaymentDecline | null,\n /** When ?order_bi_id= is present, the placed order (or null while polling). */\n placedOrder: PlacedOrder | null,\n /**\n * True while getTwouOrder is still awaiting tPlacedAt (payment confirming,\n * including 3DS) or while we reload tCheckout after NOT_PLACED.\n */\n awaitingPlacedOrder: boolean,\n placedOrderError: string | null,\n /** ISO timestamp the order was placed (tPlacedAt, falling back to\n * biCreatedAt); null while the order-dates query hasn't resolved yet. */\n placedOrderPlacedAt: string | null,\n}\n\n/**\n * Read the product selector from the URL: course_uuid+course_run_key, or\n * program_uuid, or neither. Both course params must be present together; if a\n * course param and a program param are both present, that's\n * CONFLICTING_SELECTION.\n *\n * Legacy aliases `course_uid` / `program_uid` are still accepted; the `*_uuid`\n * names win when both are present.\n *\n * NOTE: course_run_key values look like \"course-v1:HarvardX+CS50+X\" — nuqs\n * decodes query values the standards-compliant way (literal `+` -> space),\n * same as native URLSearchParams. runKey is therefore read from the raw query\n * string via getCourseRunKeyFromUrl(), which preserves literal `+`.\n */\nexport function useProductSelector(): ProductSelector {\n const [{\n courseUuid, courseUidLegacy, runKey: nuqsRunKey, programUuid, programUidLegacy,\n }] = useQueryStates({\n courseUuid: parseAsString,\n courseUidLegacy: parseAsString,\n runKey: parseAsString,\n programUuid: parseAsString,\n programUidLegacy: parseAsString,\n }, {\n urlKeys: {\n courseUuid: 'course_uuid',\n courseUidLegacy: 'course_uid',\n runKey: 'course_run_key',\n programUuid: 'program_uuid',\n programUidLegacy: 'program_uid',\n },\n });\n const courseUid = courseUuid ?? courseUidLegacy;\n const programUid = programUuid ?? programUidLegacy;\n const runKey = nuqsRunKey ? (getCourseRunKeyFromUrl() ?? nuqsRunKey) : null;\n\n return useMemo<ProductSelector>(() => {\n const hasCourse = !!courseUid || !!runKey;\n const hasProgram = !!programUid;\n if (hasCourse && hasProgram) return { kind: 'invalid' };\n if (courseUid && runKey) return { kind: 'course', courseUid, runKey };\n if (programUid) return { kind: 'program', programUid };\n return { kind: 'none' };\n }, [courseUid, runKey, programUid]);\n}\n\n/** Reads ?discount_code= — applied to the checkout right after it's created. */\nexport function useDiscountCode(): string | null {\n const [discountCode] = useQueryState('discount_code', parseAsString);\n return discountCode;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : 'Unknown error';\n}\n\n/**\n * Build a synthetic AlacarteLine from the owned-product pricing data so the\n * checkout overlay can show subtotal / deduction / total even when the backend\n * blocks tCheckoutSelect and returns no checkout object.\n */\nfunction buildLineFromOwnedProduct(product: OwnedProduct): AlacarteLine | null {\n if (!product.price) return null;\n const { full, deduction, amountDue, currency } = product.price;\n const toMoney = (amount: number): AlacarteMoney => ({ amount, currency });\n\n if (product.kind === 'program') {\n return {\n biiId: '',\n kind: 'program',\n programId: product.productId,\n programName: product.name,\n price: toMoney(full),\n deduction: deduction ? toMoney(deduction) : null,\n ownedCourses: product.ownedCourses.map((c) => ({\n courseId: c.courseId, name: c.name, via: c.via,\n })),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n }\n\n return {\n biiId: '',\n kind: 'course',\n courseName: product.name,\n courseUid: product.productId,\n courseRunKey: '',\n seatType: 'verified',\n price: toMoney(full),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n}\n\ninterface QueryLikeState<T> {\n isLoading: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\ninterface MutationLikeState<T> {\n isIdle: boolean,\n isPending: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\nexport interface DeriveAlacartePhaseInput {\n selector: ProductSelector,\n sessionReady: boolean,\n sessionIsError: boolean,\n sessionErrorMessage?: string,\n ownedQuery: QueryLikeState<OwnedProductResult>,\n selectMutation: MutationLikeState<AlacarteCheckoutResult>,\n checkoutQuery: QueryLikeState<AlacarteCheckoutResult>,\n productDetail: ProductDetail | null,\n /** Coupon (?discount_code=) applied right after the checkout is created —\n * when it succeeds, its checkout (with the coupon's discount reflected)\n * is shown in place of the pre-coupon one from selectMutation. */\n couponMutation?: MutationLikeState<AlacarteCheckoutResult>,\n /** True when a URL discount code still needs to be applied — the phase\n * stays 'loading' until the coupon mutation resolves so the user never sees\n * the pre-discount price flash. */\n urlCouponPending?: boolean,\n /** Latest successful manual update (coupon / acceptPrice / terms). Wins over\n * select + URL coupon when present. */\n checkoutOverride?: AlacarteCheckout | null,\n /** Course-runs lookup for a course selector. Empty `elements` is notFound. */\n courseRunLookup?: { pending: boolean, notFound: boolean },\n}\n\n/**\n * Pure decision function — no hooks, no React Query/nuqs types beyond plain\n * data — so every branch combination can be unit-tested directly.\n */\nexport function deriveAlacartePhase(input: DeriveAlacartePhaseInput): AlacartePhaseState {\n const {\n selector, sessionReady, sessionIsError, sessionErrorMessage,\n ownedQuery, selectMutation, checkoutQuery, productDetail, couponMutation,\n checkoutOverride = null, urlCouponPending: urlCouponPendingProp = false,\n courseRunLookup = { pending: false, notFound: false },\n } = input;\n\n const ownedProductName = ownedQuery.data?.product?.name ?? null;\n\n const empty: Omit<AlacartePhaseState, 'phase'> = {\n selector,\n checkout: null,\n line: null,\n productDetail: null,\n error: null,\n priceChanged: null,\n priceAccepted: false,\n isAlreadyOwned: false,\n ownedProductName: null,\n };\n\n const withCheckout = (\n checkout: AlacarteCheckout | null,\n priceChanged: AlacartePriceChanged | null = null,\n isAlreadyOwned = false,\n ): AlacartePhaseState => ({\n phase: isAlreadyOwned ? 'alreadyOwned' : 'ready',\n selector,\n checkout,\n line: checkout?.line ?? null,\n productDetail,\n error: null,\n priceChanged: priceChanged ?? null,\n priceAccepted: checkout?.priceAccepted === true,\n isAlreadyOwned,\n ownedProductName: isAlreadyOwned ? ownedProductName : null,\n });\n\n if (selector.kind === 'invalid') {\n return { phase: 'error', ...empty, error: 'CONFLICTING_SELECTION' };\n }\n if (sessionIsError) {\n return { phase: 'error', ...empty, error: sessionErrorMessage ?? 'Session error' };\n }\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n\n if (hasSelector) {\n if (selector.kind === 'course' && courseRunLookup.notFound) {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (!sessionReady || ownedQuery.isLoading || courseRunLookup.pending) {\n return { phase: 'loading', ...empty };\n }\n if (ownedQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(ownedQuery.error) };\n }\n\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n if (selectMutation.isIdle || selectMutation.isPending) {\n return { phase: 'loading', ...empty };\n }\n if (selectMutation.isError) {\n return { phase: 'error', ...empty, error: errorMessage(selectMutation.error) };\n }\n if (selectMutation.data && !selectMutation.data.ok) {\n // The backend may block ALREADY_OWNED at select time. When the\n // blocked response still includes checkout data (line, pricing), use\n // it so the overlay page shows the real totals. Fall back to the\n // standalone tCheckout query, then to an empty state.\n if (selectMutation.data.blocked?.reason === 'ALREADY_OWNED') {\n const blockedCheckout = selectMutation.data.checkout\n ?? (checkoutQuery.data?.ok ? checkoutQuery.data.checkout : null);\n if (blockedCheckout) {\n return withCheckout(blockedCheckout, selectMutation.data.priceChanged ?? null, true);\n }\n // Build a synthetic line from the owned-product pricing so the\n // overlay can show subtotal / deduction / total.\n const ownedProduct = ownedQuery.data?.product;\n const syntheticLine = ownedProduct ? buildLineFromOwnedProduct(ownedProduct) : null;\n return {\n phase: 'alreadyOwned',\n noticeMessageId: selectMutation.data.blocked.kind === 'course' ? 'alreadyOwnedCourse' : 'alreadyOwnedProgram',\n ...empty,\n line: syntheticLine,\n productDetail,\n isAlreadyOwned: true,\n ownedProductName,\n };\n }\n if (selectMutation.data.blocked?.reason === 'NOT_PURCHASABLE') {\n return {\n phase: 'notPurchasable',\n ...empty,\n productDetail,\n error: selectMutation.data.blocked.kind === 'program'\n ? 'This program is not eligible for checkout.'\n : 'This course is not eligible for checkout.',\n };\n }\n const selectError = selectMutation.data.error;\n if (selectError === 'COURSE_NOT_FOUND' || selectError === 'PRODUCT_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (selectError === 'PROGRAM_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This program could not be found.',\n };\n }\n const blockedDetail = selectMutation.data.blocked?.detail;\n return {\n phase: 'error',\n ...empty,\n error: blockedDetail ?? selectError ?? 'unknown',\n };\n }\n\n // When a URL discount code still needs to be applied, stay in 'loading'\n // so the user never sees the pre-discount price flash.\n if (urlCouponPendingProp && !checkoutOverride) {\n return { phase: 'loading', ...empty };\n }\n\n // Once the coupon-apply (?discount_code=) mutation succeeds, its checkout\n // (with the discount reflected) supersedes the pre-coupon one. Manual\n // updates (override) win over both.\n const finalCheckout = checkoutOverride\n ?? (couponMutation?.data?.ok\n ? couponMutation.data.checkout\n : selectMutation.data?.checkout ?? null);\n\n // When select succeeds but the owned-products query says the learner\n // already has this product, show the full checkout under an overlay.\n return withCheckout(\n finalCheckout,\n selectMutation.data?.priceChanged\n ?? (couponMutation?.data?.ok ? couponMutation.data.priceChanged : undefined)\n ?? null,\n isOwned,\n );\n }\n\n // No selector: fall back to the learner's existing open checkout, if any.\n if (!sessionReady || checkoutQuery.isLoading) {\n return { phase: 'loading', ...empty };\n }\n if (checkoutQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(checkoutQuery.error) };\n }\n if (checkoutOverride || checkoutQuery.data?.checkout) {\n const checkout = checkoutOverride ?? checkoutQuery.data!.checkout;\n return withCheckout(checkout, checkoutQuery.data?.priceChanged ?? null);\n }\n\n return { phase: 'noActiveCheckout', noticeMessageId: 'noActiveCheckout', ...empty, isAlreadyOwned: false, ownedProductName: null };\n}\n\n/** amountDue with coupon/automatic discount removed (price − program deduction). */\nfunction amountDueWithoutDiscount(line: AlacarteLine): AlacarteMoney | null {\n if (!line.price) return null;\n if (line.kind === 'program' && line.deduction) {\n return {\n amount: line.price.amount - line.deduction.amount,\n currency: line.price.currency,\n };\n }\n return line.price;\n}\n\n/** amountDue after applying a discount on top of price (− program deduction). */\nfunction amountDueWithDiscount(\n line: AlacarteLine,\n discount: AlacarteMoney,\n): AlacarteMoney | null {\n const base = amountDueWithoutDiscount(line);\n if (!base) return null;\n return { amount: base.amount - discount.amount, currency: base.currency };\n}\n\n/**\n * Checkout to show once a coupon removal succeeds. The backend may return a\n * line that still carries the old coupon discount/amountDue, so that line is\n * patched to clear it. An automatic offer (bundle / first-order) the backend\n * re-applied once the coupon is gone is the real state and is kept as-is.\n *\n * When the backend clears the coupon but does not re-apply the automatic\n * offer that was present before the coupon, `priorCheckout` (typically the\n * pre-coupon select response) is used to restore that offer.\n */\nexport function checkoutWithoutCoupon(\n checkout: AlacarteCheckout,\n priorCheckout?: AlacarteCheckout | null,\n): AlacarteCheckout {\n const { line } = checkout;\n if (!line) {\n return { ...checkout, couponCode: null };\n }\n if (line.discountSource === 'automatic') {\n return { ...checkout, couponCode: null };\n }\n\n const priorLine = priorCheckout?.line;\n const priorAutomatic = priorLine?.discountSource === 'automatic' && priorLine.discount\n ? priorLine\n : null;\n\n const clearedLine = {\n ...line,\n discount: null,\n discountSource: null,\n discountName: null,\n amountDue: amountDueWithoutDiscount(line),\n } as typeof line;\n\n if (priorAutomatic?.discount) {\n return {\n ...checkout,\n couponCode: null,\n line: {\n ...clearedLine,\n discount: priorAutomatic.discount,\n discountSource: 'automatic',\n discountName: priorAutomatic.discountName ?? null,\n amountDue: amountDueWithDiscount(clearedLine, priorAutomatic.discount),\n } as typeof line,\n };\n }\n\n return { ...checkout, couponCode: null, line: clearedLine };\n}\n\nexport function useAlacarteCheckout(\n options: {\n apiUrl?: string,\n edxSessionUrl?: string,\n /**\n * When true, skip GET /api/subscription/course_runs/ and call Viax with a\n * course key derived from ?course_run_key= instead.\n */\n skipSubscriptionCourseRuns?: boolean,\n },\n): UseAlacarteCheckoutResult {\n const { apiUrl, edxSessionUrl, skipSubscriptionCourseRuns = false } = options;\n const queryClient = useQueryClient();\n const selector = useProductSelector();\n const discountCode = useDiscountCode();\n const [orderBiId, setOrderBiId] = useQueryState('order_bi_id', parseAsString);\n\n // Reuses the same query key as useCheckout's session exchange — React\n // Query dedupes the network call regardless of how many hooks read it.\n const sessionQuery = useViaxSessionQuery(edxSessionUrl ?? null);\n const sessionReady = !!sessionQuery.data;\n const refreshSession = useRefreshViaxSession(edxSessionUrl ?? null);\n\n // Stable ref so the onRefreshToken callback always uses the latest\n // refreshSession without recreating the client on every render.\n const refreshSessionRef = useRef(refreshSession);\n refreshSessionRef.current = refreshSession;\n\n const client = useMemo(\n () => (apiUrl ? createAlacarteCheckoutClient({\n apiUrl,\n onRefreshToken: () => viaxTokenForRejectedCall(() => refreshSessionRef.current()),\n }) : null),\n [apiUrl],\n );\n\n useEffect(() => {\n if (sessionQuery.data && client) {\n client.setToken(sessionQuery.data.viaxToken);\n }\n }, [sessionQuery.data, client]);\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n const productId = selector.kind === 'course'\n ? selector.courseUid\n : selector.kind === 'program' ? selector.programUid : null;\n\n const ownedQuery = useOwnedProductQuery(client, sessionReady && hasSelector, productId);\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n const selectMutation = useSelectProductMutation(client);\n const {\n isIdle: selectIsIdle, mutate: selectMutate, reset: selectReset,\n } = selectMutation;\n\n const courseRunKey = selector.kind === 'course' ? selector.runKey : null;\n const lmsBaseUrl = useMemo(\n () => lmsOriginFromSessionUrl(edxSessionUrl),\n [edxSessionUrl],\n );\n const courseLookupEnabled = !skipSubscriptionCourseRuns\n && selector.kind === 'course'\n && !!lmsBaseUrl\n && !!courseRunKey;\n const courseKeyQuery = useSubscriptionCourseKeyQuery(\n skipSubscriptionCourseRuns ? null : lmsBaseUrl,\n skipSubscriptionCourseRuns ? null : courseRunKey,\n );\n const courseKey = skipSubscriptionCourseRuns\n ? (courseRunKey ? courseKeyFromCourseRunKey(courseRunKey) : null)\n : (courseKeyQuery.data ?? null);\n const courseNotFound = courseLookupEnabled\n && courseKeyQuery.isError\n && isCourseNotFoundError(courseKeyQuery.error);\n\n // Mutations aren't called during render — fire once the owned-products\n // query resolves (regardless of result) so we always get checkout/line data.\n // A course is not selected until the course-runs lookup returns a course.\n // Pass viewedPrice from tOwnedProducts.amountDue (ALC-159) when available.\n useEffect(() => {\n if (!hasSelector || ownedQuery.isLoading || ownedQuery.isError) return;\n if (selector.kind === 'course' && !courseKey) return;\n if (!selectIsIdle) return;\n const amountDue = ownedQuery.data?.product?.price?.amountDue;\n selectMutate({\n selector,\n viewedPrice: typeof amountDue === 'number' ? amountDue : undefined,\n });\n }, [\n hasSelector,\n ownedQuery.isLoading,\n ownedQuery.isError,\n ownedQuery.data?.product?.price?.amountDue,\n selector,\n courseKey,\n selectIsIdle,\n selectMutate,\n ]);\n\n const productDetailEnabled = hasSelector && sessionReady && !ownedQuery.isLoading\n && (selector.kind !== 'course' || !!courseKey);\n const productDetailQuery = useProductDetailQuery(client, productDetailEnabled, selector, courseKey);\n\n // Run the checkout query when there's no selector (standard path) OR when\n // the product is already owned — after the select mutation is blocked with\n // ALREADY_OWNED the server may still have an open checkout with pricing data.\n const selectBlocked = !selectMutation.isIdle && !selectMutation.isPending\n && selectMutation.data && !selectMutation.data.ok;\n const checkoutQuery = useAlacarteCheckoutQuery(\n client,\n sessionReady && (!hasSelector || (isOwned && !!selectBlocked)),\n );\n\n // Apply ?discount_code= to the freshly-created checkout — fired once the\n // select mutation succeeds with a checkout that doesn't already carry it.\n const urlCouponMutation = useUpdateCheckoutMutation(client);\n const {\n isIdle: couponIsIdle, mutate: couponMutate, reset: urlCouponReset,\n } = urlCouponMutation;\n const createdCheckout = selectMutation.data?.ok ? selectMutation.data.checkout : null;\n\n useEffect(() => {\n if (!createdCheckout || !discountCode) return;\n if (createdCheckout.couponCode === discountCode) return;\n if (couponIsIdle) {\n couponMutate({ biId: createdCheckout.biId, couponCode: discountCode });\n }\n }, [createdCheckout, discountCode, couponIsIdle, couponMutate]);\n\n const [checkoutOverride, setCheckoutOverride] = useState<AlacarteCheckout | null>(null);\n const [couponError, setCouponError] = useState<string | null>(null);\n const [removedCouponCode, setRemovedCouponCode] = useState<string | null>(null);\n const [placeOrderError, setPlaceOrderError] = useState<string | null>(null);\n const [paymentInterrupted, setPaymentInterrupted] = useState(false);\n const [walletPaymentCancelled, setWalletPaymentCancelled] = useState(false);\n const [placingOrder, setPlacingOrder] = useState(false);\n const [paymentTimedOut, setPaymentTimedOut] = useState(false);\n const [sanctionsBlocked, setSanctionsBlocked] = useState<{ referenceCode: string } | null>(null);\n // biId of a checkout that's locked (CART_PAYMENT_PENDING) from a prior\n // tCheckoutPlaceOrder call whose Stripe confirmation was rejected\n // client-side. The next attempt must skip tCheckoutUpdate (it would fail\n // with CHECKOUT_NOT_OPEN) and go straight to tCheckoutPlaceOrder again.\n const [cardRetryBiId, setCardRetryBiId] = useState<string | null>(null);\n // Last checkout that carried an automatic offer — restored after a custom\n // coupon is removed if the backend does not re-apply it.\n const automaticBaselineRef = useRef<AlacarteCheckout | null>(null);\n // Tracks the payment method/processor used for the last place-order attempt,\n // so the Order Completed event can include them.\n const lastPaymentInfoRef = useRef<{ method: string, processor: string }>({ method: 'card', processor: 'stripe' });\n // Ref for product detail so trackEvent inside useCallback always reads the\n // latest value instead of a stale closure capture.\n const productDetailRef = useRef<ProductDetail | null>(null);\n productDetailRef.current = productDetailQuery.data ?? null;\n\n // Reset local overrides and in-flight select/coupon when the product changes\n // so viewedPrice / couponRecheck run again for the new selection.\n useEffect(() => {\n setCheckoutOverride(null);\n setCouponError(null);\n setRemovedCouponCode(null);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n setPaymentTimedOut(false);\n setSanctionsBlocked(null);\n setCardRetryBiId(null);\n automaticBaselineRef.current = null;\n selectReset();\n urlCouponReset();\n }, [selector, selectReset, urlCouponReset]);\n\n // Surface couponRecheck from product switch (section 2 of the API doc).\n useEffect(() => {\n const result = selectMutation.data;\n if (!result?.ok) return;\n const message = getCouponRecheckMessage(\n result.couponRecheck,\n result.checkout?.line?.discountSource,\n );\n if (message) setCouponError(message);\n }, [selectMutation.data]);\n\n // Surface ?discount_code= apply failures (domain ok:false or transport error).\n useEffect(() => {\n if (!discountCode) return;\n if (urlCouponMutation.isIdle || urlCouponMutation.isPending) return;\n if (urlCouponMutation.isError) {\n setCouponError(errorMessage(urlCouponMutation.error));\n return;\n }\n const result = urlCouponMutation.data;\n if (result && !result.ok) {\n setCouponError(getCouponErrorMessage(result.error, discountCode));\n }\n }, [\n discountCode,\n urlCouponMutation.isIdle,\n urlCouponMutation.isPending,\n urlCouponMutation.isError,\n urlCouponMutation.error,\n urlCouponMutation.data,\n ]);\n\n // Segment: Coupon Applied for ?discount_code= auto-apply.\n const urlCouponTrackedRef = useRef(false);\n useEffect(() => {\n if (urlCouponTrackedRef.current) return;\n const result = urlCouponMutation.data;\n if (!result?.ok || !result.checkout?.line) return;\n urlCouponTrackedRef.current = true;\n const line = result.checkout.line;\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? discountCode ?? '',\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }, [urlCouponMutation.data, discountCode, productDetailQuery.data]);\n\n const manualUpdateMutation = useUpdateCheckoutMutation(client);\n\n const placedOrderQuery = usePlacedOrderQuery(\n client,\n orderBiId,\n sessionReady && !!orderBiId,\n );\n\n const derived = deriveAlacartePhase({\n selector,\n sessionReady,\n sessionIsError: sessionQuery.isError,\n sessionErrorMessage: sessionQuery.error?.message,\n ownedQuery: {\n isLoading: ownedQuery.isLoading,\n isError: ownedQuery.isError,\n error: ownedQuery.error,\n data: ownedQuery.data,\n },\n selectMutation: {\n isIdle: selectMutation.isIdle,\n isPending: selectMutation.isPending,\n isError: selectMutation.isError,\n error: selectMutation.error,\n data: selectMutation.data,\n },\n checkoutQuery: {\n isLoading: checkoutQuery.isLoading,\n isError: checkoutQuery.isError,\n error: checkoutQuery.error,\n data: checkoutQuery.data,\n },\n productDetail: productDetailQuery.data ?? null,\n courseRunLookup: {\n pending: courseLookupEnabled && courseKeyQuery.isLoading,\n notFound: courseNotFound,\n },\n couponMutation: {\n isIdle: urlCouponMutation.isIdle,\n isPending: urlCouponMutation.isPending,\n isError: urlCouponMutation.isError,\n error: urlCouponMutation.error,\n data: urlCouponMutation.data,\n },\n checkoutOverride,\n // The URL coupon is pending only when the checkout exists, doesn't already\n // carry the code, and the mutation hasn't completed yet. When the backend\n // returns the coupon pre-applied (couponCode === discountCode) or when\n // there's no discount_code param at all, this is false from the start.\n urlCouponPending: !!discountCode\n && !!createdCheckout\n && createdCheckout.couponCode !== discountCode\n && (urlCouponMutation.isIdle || urlCouponMutation.isPending),\n });\n\n const applyCoupon = useCallback((code: string) => {\n const biId = derived.checkout?.biId;\n if (!biId || !client) return;\n const trimmed = code.trim();\n if (!trimmed) return;\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId, couponCode: trimmed },\n {\n onSuccess: (result) => {\n if (result.ok && result.checkout) {\n setCheckoutOverride(result.checkout);\n setCouponError(null);\n setRemovedCouponCode(null);\n // Segment: Coupon Applied (track_plan_id 30)\n const line = result.checkout.line;\n if (line) {\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? trimmed,\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }\n } else {\n setCouponError(getCouponErrorMessage(result.error, trimmed));\n }\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout?.biId, client, manualUpdateMutation]);\n\n // Remember the latest automatic offer so removeCoupon can restore it.\n useEffect(() => {\n const checkout = derived.checkout;\n if (\n checkout?.line?.discountSource === 'automatic'\n && checkout.line.discount\n ) {\n automaticBaselineRef.current = checkout;\n }\n }, [derived.checkout]);\n\n const removeCoupon = useCallback(() => {\n const currentCheckout = derived.checkout;\n if (!currentCheckout?.biId || !client) return;\n const removedCode = currentCheckout.couponCode?.trim() || null;\n // Prefer the remembered automatic offer; fall back to the pre-coupon\n // select response when the baseline was never captured.\n const priorCheckout = automaticBaselineRef.current\n ?? (selectMutation.data?.ok ? selectMutation.data.checkout : null);\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId: currentCheckout.biId, couponCode: '' },\n {\n onSuccess: (result) => {\n if (!result.ok) {\n setCouponError(getCouponErrorMessage(result.error));\n return;\n }\n setCheckoutOverride(\n checkoutWithoutCoupon(result.checkout ?? currentCheckout, priorCheckout),\n );\n setCouponError(null);\n if (removedCode) setRemovedCouponCode(removedCode);\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout, client, manualUpdateMutation, selectMutation.data]);\n\n const placeOrderCore = useCallback(async (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n // A timed-out attempt may still complete — never start a second one.\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'card', processor: 'stripe' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'card',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated } = await placeAlacarteOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing) => client.placeCheckoutOrder(biId, billing),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n confirmCardPayment: opts.confirmCardPayment,\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n\n setCardRetryBiId(null);\n setCheckoutOverride(updated);\n await setOrderBiId(updated.biId);\n } catch (err: unknown) {\n if (err instanceof CardValidationError) {\n // tCheckoutPlaceOrder already succeeded and locked the checkout\n // (CART_PAYMENT_PENDING); Stripe rejected the card before it ever\n // reached the backend. Next attempt must retry tCheckoutPlaceOrder\n // directly, not tCheckoutUpdate.\n setCardRetryBiId(checkout.biId);\n } else {\n setCardRetryBiId(null);\n }\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n // The timeout warning and sanctions modal replace the generic error banner.\n const errMsg = err instanceof Error ? err.message : '';\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isSanctionsBlockedError(err)) {\n // TODO: use the backend reference code once tCheckoutPlaceOrder returns one.\n setSanctionsBlocked({ referenceCode: 'REF-8F2K-40QX-1177' });\n } else if (isCouponError(errMsg)) {\n // Coupon errors show inline below the promo code input, not as a top banner.\n setCouponError(getCouponErrorMessage(errMsg));\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [derived.checkout, client, setOrderBiId, cardRetryBiId, paymentTimedOut]);\n\n /** Fire-and-forget wrapper for card payments. */\n const placeOrder = useCallback((opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n if (placingOrder || paymentTimedOut) return;\n placeOrderCore(opts).catch(() => { /* error already in state */ });\n }, [placeOrderCore, placingOrder, paymentTimedOut]);\n\n // biId of the checkout the open PayPal order belongs to — capture/cancel need it.\n const paypalBiIdRef = useRef<string | null>(null);\n\n const reloadCheckout = useCallback(async () => {\n if (!client) return;\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // The learner can still retry from the current checkout.\n }\n }, [client, queryClient]);\n\n const startPaypalOrder = useCallback(async (opts: { billing: BillingInfo }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'paypal', processor: 'paypal' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n await trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'paypal',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated, paypalOrderId } = await startAlacartePaypalOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing, paymentMethod) => (\n client.placeCheckoutOrder(biId, billing, paymentMethod)\n ),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n // tCheckoutPlaceOrder locked the checkout (CART_PAYMENT_PENDING) until\n // the PayPal order is captured or cancelled; a retry must skip tCheckoutUpdate.\n setCardRetryBiId(updated.biId);\n setCheckoutOverride(updated);\n paypalBiIdRef.current = updated.biId;\n return paypalOrderId;\n } catch (err: unknown) {\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n const paypalErrMsg = err instanceof Error ? err.message : '';\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isCouponError(paypalErrMsg)) {\n setCouponError(getCouponErrorMessage(paypalErrMsg));\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n setPlacingOrder(false);\n throw err;\n }\n }, [derived.checkout, client, cardRetryBiId, paymentTimedOut]);\n\n const cancelPaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) {\n setPlacingOrder(false);\n return;\n }\n try {\n const result = await client.cancelPaypalOrder(biId, paypalOrderId);\n if (result.ok) {\n // Settled as a failed payment — the checkout is open again.\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n setPaymentInterrupted(true);\n }\n await reloadCheckout();\n } catch {\n // Leave cardRetryBiId set so the next attempt reuses the locked checkout.\n } finally {\n setPlacingOrder(false);\n }\n }, [client, reloadCheckout]);\n\n const approvePaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) throw new Error('Checkout not ready');\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n\n try {\n const result = await client.capturePaypalOrder(biId, paypalOrderId);\n // PAYMENT_IN_PROGRESS: another capture holds the lock and will settle the\n // order — poll getTwouOrder like a COMPLETED / PENDING capture.\n const placed = result.ok\n ? result.status === 'COMPLETED' || result.status === 'PENDING'\n : result.error === 'PAYMENT_IN_PROGRESS';\n if (!placed) {\n throw toPlaceOrderError(result.ok ? 'PAYPAL_PAYMENT_DECLINED' : (result.error ?? 'CAPTURE_FAILED'));\n }\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n await setOrderBiId(biId);\n } catch (err: unknown) {\n setPlaceOrderError(errorMessage(err));\n // A declined/failed capture leaves the order settled as failed — reload so\n // the learner can retry (paymentDecline comes back on tCheckout).\n setCardRetryBiId(null);\n await reloadCheckout();\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [client, setOrderBiId, reloadCheckout]);\n\n const clearPaymentAlerts = useCallback(() => {\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n }, []);\n\n const placedView = derivePlacedOrderView({\n orderBiId,\n result: placedOrderQuery.data,\n pollTimedOut: placedOrderQuery.pollTimedOut,\n isLoading: placedOrderQuery.isLoading,\n isFetching: placedOrderQuery.isFetching,\n });\n const { placedOrder } = placedView;\n const placedOrderPlacedAt = placedOrder?.placedAt ?? null;\n\n // Segment: Order Completed (track_plan_id 32), deduplicated by order number.\n useEffect(() => {\n if (!placedOrder || !orderBiId) return;\n const { method, processor } = lastPaymentInfoRef.current;\n trackEventOnce('Order Completed', {\n checkoutType: 'a_la_carte',\n track_plan_id: 32,\n trigger_source: 'client-side',\n order_id: placedOrder.orderNumber,\n checkout_id: orderBiId,\n total: placedOrder.totals.paid,\n revenue: placedOrder.totals.paid,\n currency: placedOrder.totals.currency,\n tax: placedOrder.totals.discount === 0 && placedOrder.totals.paid === 0 ? 0 : placedOrder.totals.deduction,\n coupon: placedOrder.couponCode ?? null,\n coupon_name: [],\n discount: placedOrder.totals.discount,\n processor_name: processor,\n payment_method: method,\n products: derived.line\n ? buildProductsFromLine(derived.line, productDetailRef.current)\n : buildProductsFromOrder(placedOrder.lines, productDetailRef.current),\n });\n }, [placedOrder, orderBiId, productDetailQuery.data, derived.line]);\n\n // NOT_PLACED: the payment did not go through and the cart is editable again.\n // Reload tCheckout (it carries paymentDecline) and drop ?order_bi_id= so the\n // learner can try another card instead of sitting on the confirmation error.\n // The ref blocks a second reload for the same attempt. It is not cleared in\n // cleanup — a re-run must not cancel the reload that is already in flight.\n const returnedToCheckoutFor = useRef<string | null>(null);\n useEffect(() => {\n if (!orderBiId) {\n returnedToCheckoutFor.current = null;\n return undefined;\n }\n if (!placedView.returnToCheckout) return undefined;\n if (returnedToCheckoutFor.current === orderBiId) return undefined;\n returnedToCheckoutFor.current = orderBiId;\n setPaymentInterrupted(true);\n\n (async () => {\n if (client) {\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // Still leave the poll — the cart is editable even if this read fails.\n }\n }\n await setOrderBiId(null);\n })();\n\n return undefined;\n }, [orderBiId, placedView.returnToCheckout, client, setOrderBiId, queryClient]);\n\n return {\n ...derived,\n couponError,\n couponApplying: manualUpdateMutation.isPending,\n applyCoupon,\n removeCoupon,\n clearCouponError: () => setCouponError(null),\n removedCouponCode,\n clearRemovedCouponCode: () => setRemovedCouponCode(null),\n placingOrder,\n placeOrderError,\n paymentInterrupted,\n walletPaymentCancelled,\n placeOrder,\n placeOrderAsync: placeOrderCore,\n startPaypalOrder,\n approvePaypalOrder,\n cancelPaypalOrder,\n clearPlaceOrderError: () => setPlaceOrderError(null),\n clearPaymentInterrupted: () => setPaymentInterrupted(false),\n markWalletPaymentCancelled: () => setWalletPaymentCancelled(true),\n clearWalletPaymentCancelled: () => setWalletPaymentCancelled(false),\n clearPaymentAlerts,\n paymentTimedOut,\n sanctionsBlocked,\n paymentDecline: derived.checkout?.paymentDecline ?? null,\n placedOrder,\n awaitingPlacedOrder: placedView.awaitingPlacedOrder,\n placedOrderError: placedView.placedOrderError,\n placedOrderPlacedAt,\n };\n}\n\nexport default useAlacarteCheckout;\n"]}
package/dist/types.d.ts CHANGED
@@ -268,10 +268,7 @@ export interface ConfirmCardPaymentData {
268
268
  /** Express Checkout Element `click` — `resolve` must be called within 1s or the sheet won't open. */
269
269
  export interface ExpressCheckoutClickEvent {
270
270
  expressPaymentType?: string;
271
- resolve: (opts?: {
272
- emailRequired?: boolean;
273
- billingAddressRequired?: boolean;
274
- }) => void;
271
+ resolve: () => void;
275
272
  }
276
273
  export interface ExpressCheckoutConfirmEvent {
277
274
  expressPaymentType?: string;
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Status, Phase } from './constants';\n\nexport type { Status, Phase };\n\n// --- Bootstrap domain --------------------------------------------------------\nexport type GqlRunner = (query: string, variables?: Record<string, unknown>, retry?: boolean) => Promise<any>;\n\n// --- Cart domain -------------------------------------------------------------\nexport interface Cart {\n biId: string,\n uid: string,\n}\n\nexport interface CartIds {\n customerUid: string,\n salableUid: string,\n billingPlanUid: string,\n}\n\nexport type BillingCycle = 'monthly' | 'annual';\n\nexport type PaymentMethod = 'card' | 'googlepay' | 'paypal';\n\nexport type SupportedPaymentMethod = Exclude<PaymentMethod, 'googlepay'>;\n\nexport type BillingPeriod = 'MONTHLY' | 'ANNUAL' | 'QUARTERLY' | string;\n\nexport interface BillingPlanOwnershipModel {\n uid: string,\n omName: string,\n}\n\nexport interface BillingPlan {\n uid: string,\n stripePriceId: string,\n /** Price amount e.g. \"39.99\" */\n amount: string,\n /** Currency code e.g. \"USD\" */\n currency: string,\n isTemplate: boolean,\n ownershipModel: BillingPlanOwnershipModel,\n}\n\nexport interface CurrentUserSubscriberResult {\n isSubscriber: boolean,\n subscriptionBiId: string | null,\n status: string | null,\n subscriptionStartDate: string | null,\n currentPeriodEnd: string | null,\n}\n\n/** Course shown on checkout / post-checkout when arriving via ?course_run_key=. */\nexport interface CourseDetail {\n maId: string,\n maName: string,\n maDescription: string | null,\n tShortDescription: string | null,\n imageUrl: string | null,\n tCourseKey: string | null,\n tBrandText: string | null,\n tPrimarySubjectArea: string | null,\n tLevelType: string | null,\n tLanguage: string | null,\n tPacingType: string | null,\n tDurationLow: number | null,\n tDurationHigh: number | null,\n tDurationUnit: string | null,\n tEffortLow: number | null,\n tEffortHigh: number | null,\n tEffortUnit: string | null,\n tUrlCourse: string | null,\n tB2cSubscriptionInclusion: boolean | null,\n tHasOfacRestrictions: boolean | null,\n tCatalogActive: boolean | null,\n /** How many learners are enrolled in this course — real per-course count, not the\n * platform-wide subscription figure. */\n tEnrollmentCount: number | null,\n}\n\n/** Returned by legacy subscription billing lookups (unused by à la carte). */\nexport interface BillingPlansResult {\n plans: BillingPlan[],\n}\n\n/** Returned by getSalableUid — the product uid and its ownership models. */\nexport interface ProductInfo {\n uid: string,\n maName: string,\n ownershipModels: { uid: string, omName: string }[],\n}\n\nexport interface CartStatusResult {\n status: Status | null,\n stripeSubscriptionId: string | null,\n /** Stripe-hosted challenge URL for the checkout confirmation step. */\n stripeConfirmationRedirectUrl: string | null,\n /** PayPal-hosted approval URL for the same checkout confirmation step. */\n paypalApprovalUrl: string | null,\n lastComment: string,\n}\n\nexport interface CartBillingAddress {\n tFirstName: string,\n tLastName: string,\n upaLine1: string,\n upaCity: string,\n upaPostcode: string,\n gadStateOrProvince: string,\n gadCountry: { iso2Code: string },\n}\n\nexport interface UpdateCartItemArgs {\n cartItemUid: string,\n billingAddress?: CartBillingAddress,\n paymentMethodId?: string,\n /** Payer email attached when the payment type is TwouPaypalPayment. */\n paypalEmail?: string | null,\n}\n\n/** Auto-renewal consent captured on TwouCart at checkout confirmation (SUBS-228). */\nexport interface CheckoutConsent {\n /** Main auto-renewal checkbox — always required at submit. */\n tConsentRecurring: boolean,\n /** UK/CA resident checkbox; null when that checkbox is not shown. */\n tConsentUkCa: boolean | null,\n /** ISO-8601 timestamp when consent was captured. */\n tConsentAt: string,\n /** Exact disclosure text shown to the learner (audit trail). */\n tConsentText: string,\n}\n\nexport interface UpdateCartConsentArgs {\n cartUid: string,\n consent: CheckoutConsent,\n /** Absolute checkout return URL stored in the backend's tStripeReturnUrl field. */\n returnUrl?: string | null,\n}\n\nexport interface BillingInfo {\n firstName: string,\n lastName: string,\n city: string,\n zip: string,\n country: string,\n line1: string,\n state: string,\n}\n\n// --- Checkout client surface -------------------------------------------------\nexport interface CheckoutClient {\n gql: GqlRunner,\n setToken: (token: string) => void,\n createCart: (vars: CartIds) => Promise<Cart>,\n getCartItem: (biId: string) => Promise<{ cartUid: string, cartItemUid: string }>,\n updateCartItem: (args: UpdateCartItemArgs) => Promise<void>,\n updateCartConsent: (args: UpdateCartConsentArgs) => Promise<void>,\n placeOrder: (cartUid: string) => Promise<unknown>,\n getCartStatus: (biId: string) => Promise<CartStatusResult>,\n getSalableUid: (maId: string) => Promise<ProductInfo>,\n isCurrentUserSubscriber: () => Promise<CurrentUserSubscriberResult | null>,\n getCourseDetail: (courseKey: string) => Promise<CourseDetail | null>,\n}\n\nexport interface DevAuth {\n iamUrl: string,\n clientId: string,\n clientSecret: string,\n}\n\n// --- Minimal Stripe.js types -------------------------------------------------\n// Just the surface this module uses. If you depend on `@stripe/stripe-js`,\n// you can replace these with its richer types.\nexport interface StripeElementChangeEvent {\n empty?: boolean,\n complete?: boolean,\n error?: { message?: string, code?: string },\n [key: string]: unknown,\n}\n\nexport interface CardFieldState {\n empty: boolean,\n complete: boolean,\n /** Stripe validation error message (e.g. \"Your card number is invalid.\"), empty string if no error. */\n error: string,\n /** True once the element has been blurred at least once. */\n blurred: boolean,\n /** True while the element's input has focus. */\n focused?: boolean,\n /** Card network Stripe detected from the number (e.g. 'visa'); card number only. */\n brand?: string,\n}\n\nexport interface CardFieldStates {\n number: CardFieldState,\n expiry: CardFieldState,\n cvc: CardFieldState,\n}\n\n// --- Stripe Payment Request (Apple Pay / Google Pay) -------------------------\nexport interface PaymentRequestPaymentMethodEvent {\n paymentMethod: {\n id: string,\n billing_details?: {\n address?: { country?: string },\n name?: string,\n email?: string,\n },\n },\n complete: (status: 'success' | 'fail') => void,\n}\n\nexport interface PaymentRequestCanMakePaymentResult {\n applePay?: boolean,\n googlePay?: boolean,\n link?: boolean,\n}\n\nexport interface PaymentRequestLike {\n canMakePayment: () => Promise<PaymentRequestCanMakePaymentResult | null>,\n on: (event: string, handler: (ev: PaymentRequestPaymentMethodEvent) => void) => void,\n show: () => void | Promise<void>,\n update: (details: { total: { label: string, amount: number } }) => void,\n}\n\nexport interface StripeElementLike {\n mount: (node: HTMLElement) => void,\n on: (event: string, handler: (...args: any[]) => void) => void,\n unmount?: () => void,\n destroy?: () => void,\n focus?: () => void,\n}\n\nexport interface StripeElementsOptions {\n mode?: 'payment' | 'setup' | 'subscription',\n amount?: number,\n currency?: string,\n /** Lets Express Checkout Element yield a PaymentMethod for our place-order flow. */\n paymentMethodCreation?: 'manual',\n}\n\nexport interface StripeElementsLike {\n create: (type: string, options?: Record<string, unknown>) => StripeElementLike,\n submit?: () => Promise<{ error?: StripeError }>,\n update?: (options: { amount?: number, currency?: string }) => void,\n}\n\nexport interface StripeError {\n message?: string,\n code?: string,\n /** Stripe.js error category, e.g. 'card_error' or 'api_connection_error'. */\n type?: string,\n}\n\nexport interface PaymentMethodResult {\n paymentMethod?: {\n id: string,\n billing_details?: {\n address?: { country?: string },\n name?: string,\n email?: string,\n },\n },\n error?: StripeError,\n}\n\nexport interface ConfirmResult {\n error?: StripeError,\n setupIntent?: unknown,\n paymentIntent?: unknown,\n}\n\nexport type CreatePaymentMethodParams =\n | {\n type: 'card',\n card: StripeElementLike,\n billing_details?: Record<string, unknown>,\n }\n | {\n elements: StripeElementsLike,\n };\n\nexport interface ConfirmCardPaymentData {\n payment_method?:\n | {\n card: StripeElementLike,\n billing_details?: Record<string, unknown>,\n }\n | string,\n}\n\n/** Express Checkout Element `click` — `resolve` must be called within 1s or the sheet won't open. */\nexport interface ExpressCheckoutClickEvent {\n expressPaymentType?: string,\n resolve: (opts?: { emailRequired?: boolean, billingAddressRequired?: boolean }) => void,\n}\n\nexport interface ExpressCheckoutConfirmEvent {\n expressPaymentType?: string,\n billingDetails?: {\n address?: { country?: string },\n name?: string,\n email?: string,\n },\n paymentFailed: (opts?: { reason?: string }) => void,\n}\n\nexport interface ExpressCheckoutReadyEvent {\n /** Deprecated by Stripe — prefer `availablepaymentmethodschange`. */\n availablePaymentMethods?: {\n applePay?: boolean,\n googlePay?: boolean,\n link?: boolean,\n } | undefined,\n}\n\n/** Fires on initial render and whenever wallet availability changes after load. */\nexport interface ExpressCheckoutAvailablePaymentMethodsChangeEvent {\n /** `undefined` when no buttons will render. */\n paymentMethods?: {\n applePay?: { available: boolean },\n googlePay?: { available: boolean },\n link?: { available: boolean },\n } | undefined,\n}\n\nexport interface StripeLike {\n elements: (options?: StripeElementsOptions) => StripeElementsLike,\n createPaymentMethod: (params: CreatePaymentMethodParams) => Promise<PaymentMethodResult>,\n confirmCardSetup: (clientSecret: string) => Promise<ConfirmResult>,\n confirmCardPayment: (\n clientSecret: string,\n data?: ConfirmCardPaymentData,\n ) => Promise<ConfirmResult>,\n paymentRequest: (options: {\n country: string,\n currency: string,\n total: { label: string, amount: number },\n requestPayerName?: boolean,\n requestPayerEmail?: boolean,\n disableWallets?: ('link' | 'applePay' | 'googlePay' | 'browserCard')[],\n }) => PaymentRequestLike,\n}\n\ndeclare global {\n interface Window {\n Stripe?: (publishableKey: string) => StripeLike,\n }\n}\n\nexport interface TrialDateRange {\n /** e.g. \"June 22, 2026\" */\n displayStart: string,\n /** e.g. \"June 29, 2026\" */\n displayEnd: string,\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Status, Phase } from './constants';\n\nexport type { Status, Phase };\n\n// --- Bootstrap domain --------------------------------------------------------\nexport type GqlRunner = (query: string, variables?: Record<string, unknown>, retry?: boolean) => Promise<any>;\n\n// --- Cart domain -------------------------------------------------------------\nexport interface Cart {\n biId: string,\n uid: string,\n}\n\nexport interface CartIds {\n customerUid: string,\n salableUid: string,\n billingPlanUid: string,\n}\n\nexport type BillingCycle = 'monthly' | 'annual';\n\nexport type PaymentMethod = 'card' | 'googlepay' | 'paypal';\n\nexport type SupportedPaymentMethod = Exclude<PaymentMethod, 'googlepay'>;\n\nexport type BillingPeriod = 'MONTHLY' | 'ANNUAL' | 'QUARTERLY' | string;\n\nexport interface BillingPlanOwnershipModel {\n uid: string,\n omName: string,\n}\n\nexport interface BillingPlan {\n uid: string,\n stripePriceId: string,\n /** Price amount e.g. \"39.99\" */\n amount: string,\n /** Currency code e.g. \"USD\" */\n currency: string,\n isTemplate: boolean,\n ownershipModel: BillingPlanOwnershipModel,\n}\n\nexport interface CurrentUserSubscriberResult {\n isSubscriber: boolean,\n subscriptionBiId: string | null,\n status: string | null,\n subscriptionStartDate: string | null,\n currentPeriodEnd: string | null,\n}\n\n/** Course shown on checkout / post-checkout when arriving via ?course_run_key=. */\nexport interface CourseDetail {\n maId: string,\n maName: string,\n maDescription: string | null,\n tShortDescription: string | null,\n imageUrl: string | null,\n tCourseKey: string | null,\n tBrandText: string | null,\n tPrimarySubjectArea: string | null,\n tLevelType: string | null,\n tLanguage: string | null,\n tPacingType: string | null,\n tDurationLow: number | null,\n tDurationHigh: number | null,\n tDurationUnit: string | null,\n tEffortLow: number | null,\n tEffortHigh: number | null,\n tEffortUnit: string | null,\n tUrlCourse: string | null,\n tB2cSubscriptionInclusion: boolean | null,\n tHasOfacRestrictions: boolean | null,\n tCatalogActive: boolean | null,\n /** How many learners are enrolled in this course — real per-course count, not the\n * platform-wide subscription figure. */\n tEnrollmentCount: number | null,\n}\n\n/** Returned by legacy subscription billing lookups (unused by à la carte). */\nexport interface BillingPlansResult {\n plans: BillingPlan[],\n}\n\n/** Returned by getSalableUid — the product uid and its ownership models. */\nexport interface ProductInfo {\n uid: string,\n maName: string,\n ownershipModels: { uid: string, omName: string }[],\n}\n\nexport interface CartStatusResult {\n status: Status | null,\n stripeSubscriptionId: string | null,\n /** Stripe-hosted challenge URL for the checkout confirmation step. */\n stripeConfirmationRedirectUrl: string | null,\n /** PayPal-hosted approval URL for the same checkout confirmation step. */\n paypalApprovalUrl: string | null,\n lastComment: string,\n}\n\nexport interface CartBillingAddress {\n tFirstName: string,\n tLastName: string,\n upaLine1: string,\n upaCity: string,\n upaPostcode: string,\n gadStateOrProvince: string,\n gadCountry: { iso2Code: string },\n}\n\nexport interface UpdateCartItemArgs {\n cartItemUid: string,\n billingAddress?: CartBillingAddress,\n paymentMethodId?: string,\n /** Payer email attached when the payment type is TwouPaypalPayment. */\n paypalEmail?: string | null,\n}\n\n/** Auto-renewal consent captured on TwouCart at checkout confirmation (SUBS-228). */\nexport interface CheckoutConsent {\n /** Main auto-renewal checkbox — always required at submit. */\n tConsentRecurring: boolean,\n /** UK/CA resident checkbox; null when that checkbox is not shown. */\n tConsentUkCa: boolean | null,\n /** ISO-8601 timestamp when consent was captured. */\n tConsentAt: string,\n /** Exact disclosure text shown to the learner (audit trail). */\n tConsentText: string,\n}\n\nexport interface UpdateCartConsentArgs {\n cartUid: string,\n consent: CheckoutConsent,\n /** Absolute checkout return URL stored in the backend's tStripeReturnUrl field. */\n returnUrl?: string | null,\n}\n\nexport interface BillingInfo {\n firstName: string,\n lastName: string,\n city: string,\n zip: string,\n country: string,\n line1: string,\n state: string,\n}\n\n// --- Checkout client surface -------------------------------------------------\nexport interface CheckoutClient {\n gql: GqlRunner,\n setToken: (token: string) => void,\n createCart: (vars: CartIds) => Promise<Cart>,\n getCartItem: (biId: string) => Promise<{ cartUid: string, cartItemUid: string }>,\n updateCartItem: (args: UpdateCartItemArgs) => Promise<void>,\n updateCartConsent: (args: UpdateCartConsentArgs) => Promise<void>,\n placeOrder: (cartUid: string) => Promise<unknown>,\n getCartStatus: (biId: string) => Promise<CartStatusResult>,\n getSalableUid: (maId: string) => Promise<ProductInfo>,\n isCurrentUserSubscriber: () => Promise<CurrentUserSubscriberResult | null>,\n getCourseDetail: (courseKey: string) => Promise<CourseDetail | null>,\n}\n\nexport interface DevAuth {\n iamUrl: string,\n clientId: string,\n clientSecret: string,\n}\n\n// --- Minimal Stripe.js types -------------------------------------------------\n// Just the surface this module uses. If you depend on `@stripe/stripe-js`,\n// you can replace these with its richer types.\nexport interface StripeElementChangeEvent {\n empty?: boolean,\n complete?: boolean,\n error?: { message?: string, code?: string },\n [key: string]: unknown,\n}\n\nexport interface CardFieldState {\n empty: boolean,\n complete: boolean,\n /** Stripe validation error message (e.g. \"Your card number is invalid.\"), empty string if no error. */\n error: string,\n /** True once the element has been blurred at least once. */\n blurred: boolean,\n /** True while the element's input has focus. */\n focused?: boolean,\n /** Card network Stripe detected from the number (e.g. 'visa'); card number only. */\n brand?: string,\n}\n\nexport interface CardFieldStates {\n number: CardFieldState,\n expiry: CardFieldState,\n cvc: CardFieldState,\n}\n\n// --- Stripe Payment Request (Apple Pay / Google Pay) -------------------------\nexport interface PaymentRequestPaymentMethodEvent {\n paymentMethod: {\n id: string,\n billing_details?: {\n address?: { country?: string },\n name?: string,\n email?: string,\n },\n },\n complete: (status: 'success' | 'fail') => void,\n}\n\nexport interface PaymentRequestCanMakePaymentResult {\n applePay?: boolean,\n googlePay?: boolean,\n link?: boolean,\n}\n\nexport interface PaymentRequestLike {\n canMakePayment: () => Promise<PaymentRequestCanMakePaymentResult | null>,\n on: (event: string, handler: (ev: PaymentRequestPaymentMethodEvent) => void) => void,\n show: () => void | Promise<void>,\n update: (details: { total: { label: string, amount: number } }) => void,\n}\n\nexport interface StripeElementLike {\n mount: (node: HTMLElement) => void,\n on: (event: string, handler: (...args: any[]) => void) => void,\n unmount?: () => void,\n destroy?: () => void,\n focus?: () => void,\n}\n\nexport interface StripeElementsOptions {\n mode?: 'payment' | 'setup' | 'subscription',\n amount?: number,\n currency?: string,\n /** Lets Express Checkout Element yield a PaymentMethod for our place-order flow. */\n paymentMethodCreation?: 'manual',\n}\n\nexport interface StripeElementsLike {\n create: (type: string, options?: Record<string, unknown>) => StripeElementLike,\n submit?: () => Promise<{ error?: StripeError }>,\n update?: (options: { amount?: number, currency?: string }) => void,\n}\n\nexport interface StripeError {\n message?: string,\n code?: string,\n /** Stripe.js error category, e.g. 'card_error' or 'api_connection_error'. */\n type?: string,\n}\n\nexport interface PaymentMethodResult {\n paymentMethod?: {\n id: string,\n billing_details?: {\n address?: { country?: string },\n name?: string,\n email?: string,\n },\n },\n error?: StripeError,\n}\n\nexport interface ConfirmResult {\n error?: StripeError,\n setupIntent?: unknown,\n paymentIntent?: unknown,\n}\n\nexport type CreatePaymentMethodParams =\n | {\n type: 'card',\n card: StripeElementLike,\n billing_details?: Record<string, unknown>,\n }\n | {\n elements: StripeElementsLike,\n };\n\nexport interface ConfirmCardPaymentData {\n payment_method?:\n | {\n card: StripeElementLike,\n billing_details?: Record<string, unknown>,\n }\n | string,\n}\n\n/** Express Checkout Element `click` — `resolve` must be called within 1s or the sheet won't open. */\nexport interface ExpressCheckoutClickEvent {\n expressPaymentType?: string,\n resolve: () => void,\n}\n\nexport interface ExpressCheckoutConfirmEvent {\n expressPaymentType?: string,\n billingDetails?: {\n address?: { country?: string },\n name?: string,\n email?: string,\n },\n paymentFailed: (opts?: { reason?: string }) => void,\n}\n\nexport interface ExpressCheckoutReadyEvent {\n /** Deprecated by Stripe — prefer `availablepaymentmethodschange`. */\n availablePaymentMethods?: {\n applePay?: boolean,\n googlePay?: boolean,\n link?: boolean,\n } | undefined,\n}\n\n/** Fires on initial render and whenever wallet availability changes after load. */\nexport interface ExpressCheckoutAvailablePaymentMethodsChangeEvent {\n /** `undefined` when no buttons will render. */\n paymentMethods?: {\n applePay?: { available: boolean },\n googlePay?: { available: boolean },\n link?: { available: boolean },\n } | undefined,\n}\n\nexport interface StripeLike {\n elements: (options?: StripeElementsOptions) => StripeElementsLike,\n createPaymentMethod: (params: CreatePaymentMethodParams) => Promise<PaymentMethodResult>,\n confirmCardSetup: (clientSecret: string) => Promise<ConfirmResult>,\n confirmCardPayment: (\n clientSecret: string,\n data?: ConfirmCardPaymentData,\n ) => Promise<ConfirmResult>,\n paymentRequest: (options: {\n country: string,\n currency: string,\n total: { label: string, amount: number },\n requestPayerName?: boolean,\n requestPayerEmail?: boolean,\n disableWallets?: ('link' | 'applePay' | 'googlePay' | 'browserCard')[],\n }) => PaymentRequestLike,\n}\n\ndeclare global {\n interface Window {\n Stripe?: (publishableKey: string) => StripeLike,\n }\n}\n\nexport interface TrialDateRange {\n /** e.g. \"June 22, 2026\" */\n displayStart: string,\n /** e.g. \"June 29, 2026\" */\n displayEnd: string,\n}\n"]}
@@ -25,7 +25,7 @@ export function createGqlClient({ apiUrl }, options) {
25
25
  };
26
26
  tokenClears.add(clearToken);
27
27
  const gql = (query_1, variables_1, ...args_1) => __awaiter(this, [query_1, variables_1, ...args_1], void 0, function* (query, variables, retry = false) {
28
- var _a, _b;
28
+ var _a, _b, _c, _d, _e, _f;
29
29
  if (!token)
30
30
  throw new Error('No viax token available. Please try placing your order again.');
31
31
  const res = yield fetch(apiUrl, {
@@ -43,7 +43,7 @@ export function createGqlClient({ apiUrl }, options) {
43
43
  return gql(query, variables, true);
44
44
  }
45
45
  }
46
- catch (_c) {
46
+ catch (_g) {
47
47
  // Refresh failed — fall through to the existing error.
48
48
  }
49
49
  }
@@ -56,7 +56,9 @@ export function createGqlClient({ apiUrl }, options) {
56
56
  }
57
57
  const json = yield res.json();
58
58
  if ((_a = json.errors) === null || _a === void 0 ? void 0 : _a.length) {
59
- const msg = ((_b = json.errors[0]) === null || _b === void 0 ? void 0 : _b.message) || 'GraphQL error';
59
+ const msg = ((_e = (_d = (_c = (_b = json.extensions) === null || _b === void 0 ? void 0 : _b.validation) === null || _c === void 0 ? void 0 : _c.errors) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.message)
60
+ || ((_f = json.errors[0]) === null || _f === void 0 ? void 0 : _f.message)
61
+ || 'GraphQL error';
60
62
  throw new Error(msg);
61
63
  }
62
64
  return json.data;
@@ -1 +1 @@
1
- {"version":3,"file":"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3C,CAAC,CAAC;QAEH,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;YACjC,6CAA6C;YAC7C,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,cAAc,EAAE,CAAC;gBAC5B,IAAI,CAAC;oBACH,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,cAAc,EAAE,CAAC;oBAChD,IAAI,QAAQ,EAAE,CAAC;wBACb,QAAQ,CAAC,QAAQ,CAAC,CAAC;wBACnB,OAAO,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;oBACrC,CAAC;gBACH,CAAC;gBAAC,WAAM,CAAC;oBACP,uDAAuD;gBACzD,CAAC;YACH,CAAC;YACD,KAAK,GAAG,IAAI,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC3E,CAAC;QAED,sEAAsE;QACtE,IAAI,GAAG,CAAC,MAAM,KAAK,oBAAoB,EAAE,CAAC;YACxC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QAClC,CAAC;QAED,MAAM,IAAI,GAAgB,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC3C,IAAI,MAAA,IAAI,CAAC,MAAM,0CAAE,MAAM,EAAE,CAAC;YACxB,MAAM,GAAG,GAAG,CAAA,MAAA,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,0CAAE,OAAO,KAAI,eAAe,CAAC;YACvD,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC,CAAA,CAAC;IAEF,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["/**\n * api/graphqlClient.ts — authed GraphQL client.\n *\n * The viax access token lives only in this module's memory. It is never\n * written to localStorage or sessionStorage. Call setToken(viaxToken) after\n * POST /api/edx-session returns.\n *\n * On 401, onRefreshToken re-calls /api/edx-session and the request is retried\n * once. If that fails, the in-memory token is dropped.\n */\nimport type { GqlRunner } from '../types';\nimport { HTTP_REQUEST_TIMEOUT, RequestTimeoutError } from './timeoutErrors';\n\nconst tokenClears = new Set<() => void>();\n\n/** Drop every in-memory viax token. Used when the edX user signs out or changes. */\nexport function dropInMemoryViaxTokens(): void {\n tokenClears.forEach((clear) => clear());\n}\n\ninterface GqlResponse {\n\n data?: any,\n errors?: { message?: string }[],\n}\n\nexport interface GqlClientOptions {\n /** Called on 401 to get a fresh viax token. Return the raw token or null. */\n onRefreshToken?: () => Promise<string | null>,\n}\n\nexport function createGqlClient(\n { apiUrl }: { apiUrl: string },\n options?: GqlClientOptions,\n): { gql: GqlRunner, setToken: (token: string) => void } {\n if (!apiUrl) throw new Error('createGqlClient: apiUrl is required');\n\n let token: string | null = null;\n\n const setToken = (raw: string): void => {\n token = raw.startsWith('Bearer ') ? raw : `Bearer ${raw}`;\n };\n\n const clearToken = (): void => {\n token = null;\n };\n tokenClears.add(clearToken);\n\n const gql: GqlRunner = async (query, variables, retry = false) => {\n if (!token) throw new Error('No viax token available. Please try placing your order again.');\n\n const res = await fetch(apiUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: token },\n body: JSON.stringify({ query, variables }),\n });\n\n if (res.status === 401 && !retry) {\n // Try to refresh the token before giving up.\n if (options?.onRefreshToken) {\n try {\n const newToken = await options.onRefreshToken();\n if (newToken) {\n setToken(newToken);\n return gql(query, variables, true);\n }\n } catch {\n // Refresh failed — fall through to the existing error.\n }\n }\n token = null;\n throw new Error('Session expired. Please try placing your order again.');\n }\n\n // Checked before res.json() — a 408 body isn't guaranteed to be JSON.\n if (res.status === HTTP_REQUEST_TIMEOUT) {\n throw new RequestTimeoutError();\n }\n\n const json: GqlResponse = await res.json();\n if (json.errors?.length) {\n const msg = json.errors[0]?.message || 'GraphQL error';\n throw new Error(msg);\n }\n return json.data;\n };\n\n return { gql, setToken };\n}\n"]}
1
+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/**\n * api/graphqlClient.ts — authed GraphQL client.\n *\n * The viax access token lives only in this module's memory. It is never\n * written to localStorage or sessionStorage. Call setToken(viaxToken) after\n * POST /api/edx-session returns.\n *\n * On 401, onRefreshToken re-calls /api/edx-session and the request is retried\n * once. If that fails, the in-memory token is dropped.\n */\nimport type { GqlRunner } from '../types';\nimport { HTTP_REQUEST_TIMEOUT, RequestTimeoutError } from './timeoutErrors';\n\nconst tokenClears = new Set<() => void>();\n\n/** Drop every in-memory viax token. Used when the edX user signs out or changes. */\nexport function dropInMemoryViaxTokens(): void {\n tokenClears.forEach((clear) => clear());\n}\n\ninterface GqlResponse {\n data?: any,\n errors?: { message?: string }[],\n extensions?: { validation?: { errors?: { message?: string }[] } },\n}\n\nexport interface GqlClientOptions {\n /** Called on 401 to get a fresh viax token. Return the raw token or null. */\n onRefreshToken?: () => Promise<string | null>,\n}\n\nexport function createGqlClient(\n { apiUrl }: { apiUrl: string },\n options?: GqlClientOptions,\n): { gql: GqlRunner, setToken: (token: string) => void } {\n if (!apiUrl) throw new Error('createGqlClient: apiUrl is required');\n\n let token: string | null = null;\n\n const setToken = (raw: string): void => {\n token = raw.startsWith('Bearer ') ? raw : `Bearer ${raw}`;\n };\n\n const clearToken = (): void => {\n token = null;\n };\n tokenClears.add(clearToken);\n\n const gql: GqlRunner = async (query, variables, retry = false) => {\n if (!token) throw new Error('No viax token available. Please try placing your order again.');\n\n const res = await fetch(apiUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: token },\n body: JSON.stringify({ query, variables }),\n });\n\n if (res.status === 401 && !retry) {\n // Try to refresh the token before giving up.\n if (options?.onRefreshToken) {\n try {\n const newToken = await options.onRefreshToken();\n if (newToken) {\n setToken(newToken);\n return gql(query, variables, true);\n }\n } catch {\n // Refresh failed — fall through to the existing error.\n }\n }\n token = null;\n throw new Error('Session expired. Please try placing your order again.');\n }\n\n // Checked before res.json() — a 408 body isn't guaranteed to be JSON.\n if (res.status === HTTP_REQUEST_TIMEOUT) {\n throw new RequestTimeoutError();\n }\n\n const json: GqlResponse = await res.json();\n if (json.errors?.length) {\n const msg = json.extensions?.validation?.errors?.[0]?.message\n || json.errors[0]?.message\n || 'GraphQL error';\n throw new Error(msg);\n }\n return json.data;\n };\n\n return { gql, setToken };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edx/frontend-app-alacarte-checkout",
3
- "version": "1.63.0",
3
+ "version": "1.65.0",
4
4
  "description": "alacarte Checkout Frontend application",
5
5
  "repository": {
6
6
  "type": "git",