@edx/frontend-app-alacarte-checkout 1.26.0 → 1.27.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.
- package/dist/data/hooks/useAlacarteCheckout.d.ts +10 -3
- package/dist/data/hooks/useAlacarteCheckout.js +73 -16
- package/dist/data/hooks/useAlacarteCheckout.js.map +1 -1
- package/dist/data/hooks/useCheckoutGate.js +10 -9
- package/dist/data/hooks/useCheckoutGate.js.map +1 -1
- package/dist/data/hooks/useCheckoutQueries.d.ts +1 -1
- package/dist/data/hooks/useCheckoutQueries.js +1 -1
- package/dist/data/hooks/useCheckoutQueries.js.map +1 -1
- package/package.json +1 -1
|
@@ -76,11 +76,14 @@ export interface UseAlacarteCheckoutResult extends AlacartePhaseState {
|
|
|
76
76
|
placedOrderPlacedAt: string | null;
|
|
77
77
|
}
|
|
78
78
|
/**
|
|
79
|
-
* Read the product selector from the URL:
|
|
80
|
-
*
|
|
79
|
+
* Read the product selector from the URL: course_uuid+course_run_key, or
|
|
80
|
+
* program_uuid, or neither. Both course params must be present together; if a
|
|
81
81
|
* course param and a program param are both present, that's
|
|
82
82
|
* CONFLICTING_SELECTION.
|
|
83
83
|
*
|
|
84
|
+
* Legacy aliases `course_uid` / `program_uid` are still accepted; the `*_uuid`
|
|
85
|
+
* names win when both are present.
|
|
86
|
+
*
|
|
84
87
|
* NOTE: course_run_key values look like "course-v1:HarvardX+CS50+X" — nuqs
|
|
85
88
|
* decodes query values the standards-compliant way (literal `+` -> space),
|
|
86
89
|
* same as native URLSearchParams. runKey is therefore read from the raw query
|
|
@@ -138,8 +141,12 @@ export declare function deriveAlacartePhase(input: DeriveAlacartePhaseInput): Al
|
|
|
138
141
|
* line that still carries the old coupon discount/amountDue, so that line is
|
|
139
142
|
* patched to clear it. An automatic offer (bundle / first-order) the backend
|
|
140
143
|
* re-applied once the coupon is gone is the real state and is kept as-is.
|
|
144
|
+
*
|
|
145
|
+
* When the backend clears the coupon but does not re-apply the automatic
|
|
146
|
+
* offer that was present before the coupon, `priorCheckout` (typically the
|
|
147
|
+
* pre-coupon select response) is used to restore that offer.
|
|
141
148
|
*/
|
|
142
|
-
export declare function checkoutWithoutCoupon(checkout: AlacarteCheckout): AlacarteCheckout;
|
|
149
|
+
export declare function checkoutWithoutCoupon(checkout: AlacarteCheckout, priorCheckout?: AlacarteCheckout | null): AlacarteCheckout;
|
|
143
150
|
export declare function useAlacarteCheckout(options: {
|
|
144
151
|
apiUrl?: string;
|
|
145
152
|
edxSessionUrl?: string;
|
|
@@ -38,11 +38,14 @@ import { useOwnedProductQuery, useAlacarteCheckoutQuery, useSelectProductMutatio
|
|
|
38
38
|
import { alacarteKeys } from './keys';
|
|
39
39
|
import { derivePlacedOrderView } from './placedOrderPoll';
|
|
40
40
|
/**
|
|
41
|
-
* Read the product selector from the URL:
|
|
42
|
-
*
|
|
41
|
+
* Read the product selector from the URL: course_uuid+course_run_key, or
|
|
42
|
+
* program_uuid, or neither. Both course params must be present together; if a
|
|
43
43
|
* course param and a program param are both present, that's
|
|
44
44
|
* CONFLICTING_SELECTION.
|
|
45
45
|
*
|
|
46
|
+
* Legacy aliases `course_uid` / `program_uid` are still accepted; the `*_uuid`
|
|
47
|
+
* names win when both are present.
|
|
48
|
+
*
|
|
46
49
|
* NOTE: course_run_key values look like "course-v1:HarvardX+CS50+X" — nuqs
|
|
47
50
|
* decodes query values the standards-compliant way (literal `+` -> space),
|
|
48
51
|
* same as native URLSearchParams. runKey is therefore read from the raw query
|
|
@@ -50,17 +53,23 @@ import { derivePlacedOrderView } from './placedOrderPoll';
|
|
|
50
53
|
*/
|
|
51
54
|
export function useProductSelector() {
|
|
52
55
|
var _a;
|
|
53
|
-
const [{
|
|
54
|
-
|
|
56
|
+
const [{ courseUuid, courseUidLegacy, runKey: nuqsRunKey, programUuid, programUidLegacy, }] = useQueryStates({
|
|
57
|
+
courseUuid: parseAsString,
|
|
58
|
+
courseUidLegacy: parseAsString,
|
|
55
59
|
runKey: parseAsString,
|
|
56
|
-
|
|
60
|
+
programUuid: parseAsString,
|
|
61
|
+
programUidLegacy: parseAsString,
|
|
57
62
|
}, {
|
|
58
63
|
urlKeys: {
|
|
59
|
-
|
|
64
|
+
courseUuid: 'course_uuid',
|
|
65
|
+
courseUidLegacy: 'course_uid',
|
|
60
66
|
runKey: 'course_run_key',
|
|
61
|
-
|
|
67
|
+
programUuid: 'program_uuid',
|
|
68
|
+
programUidLegacy: 'program_uid',
|
|
62
69
|
},
|
|
63
70
|
});
|
|
71
|
+
const courseUid = courseUuid !== null && courseUuid !== void 0 ? courseUuid : courseUidLegacy;
|
|
72
|
+
const programUid = programUuid !== null && programUuid !== void 0 ? programUuid : programUidLegacy;
|
|
64
73
|
const runKey = nuqsRunKey ? ((_a = getCourseRunKeyFromUrl()) !== null && _a !== void 0 ? _a : nuqsRunKey) : null;
|
|
65
74
|
return useMemo(() => {
|
|
66
75
|
const hasCourse = !!courseUid || !!runKey;
|
|
@@ -238,21 +247,53 @@ export function deriveAlacartePhase(input) {
|
|
|
238
247
|
}
|
|
239
248
|
return Object.assign(Object.assign({ phase: 'noActiveCheckout', noticeMessageId: 'noActiveCheckout' }, empty), { isAlreadyOwned: false, ownedProductName: null });
|
|
240
249
|
}
|
|
250
|
+
/** amountDue with coupon/automatic discount removed (price − program deduction). */
|
|
251
|
+
function amountDueWithoutDiscount(line) {
|
|
252
|
+
if (!line.price)
|
|
253
|
+
return null;
|
|
254
|
+
if (line.kind === 'program' && line.deduction) {
|
|
255
|
+
return {
|
|
256
|
+
amount: line.price.amount - line.deduction.amount,
|
|
257
|
+
currency: line.price.currency,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
return line.price;
|
|
261
|
+
}
|
|
262
|
+
/** amountDue after applying a discount on top of price (− program deduction). */
|
|
263
|
+
function amountDueWithDiscount(line, discount) {
|
|
264
|
+
const base = amountDueWithoutDiscount(line);
|
|
265
|
+
if (!base)
|
|
266
|
+
return null;
|
|
267
|
+
return { amount: base.amount - discount.amount, currency: base.currency };
|
|
268
|
+
}
|
|
241
269
|
/**
|
|
242
270
|
* Checkout to show once a coupon removal succeeds. The backend may return a
|
|
243
271
|
* line that still carries the old coupon discount/amountDue, so that line is
|
|
244
272
|
* patched to clear it. An automatic offer (bundle / first-order) the backend
|
|
245
273
|
* re-applied once the coupon is gone is the real state and is kept as-is.
|
|
274
|
+
*
|
|
275
|
+
* When the backend clears the coupon but does not re-apply the automatic
|
|
276
|
+
* offer that was present before the coupon, `priorCheckout` (typically the
|
|
277
|
+
* pre-coupon select response) is used to restore that offer.
|
|
246
278
|
*/
|
|
247
|
-
export function checkoutWithoutCoupon(checkout) {
|
|
279
|
+
export function checkoutWithoutCoupon(checkout, priorCheckout) {
|
|
280
|
+
var _a;
|
|
248
281
|
const { line } = checkout;
|
|
249
|
-
if (!line
|
|
282
|
+
if (!line) {
|
|
250
283
|
return Object.assign(Object.assign({}, checkout), { couponCode: null });
|
|
251
284
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
285
|
+
if (line.discountSource === 'automatic') {
|
|
286
|
+
return Object.assign(Object.assign({}, checkout), { couponCode: null });
|
|
287
|
+
}
|
|
288
|
+
const priorLine = priorCheckout === null || priorCheckout === void 0 ? void 0 : priorCheckout.line;
|
|
289
|
+
const priorAutomatic = (priorLine === null || priorLine === void 0 ? void 0 : priorLine.discountSource) === 'automatic' && priorLine.discount
|
|
290
|
+
? priorLine
|
|
291
|
+
: null;
|
|
292
|
+
const clearedLine = Object.assign(Object.assign({}, line), { discount: null, discountSource: null, discountName: null, amountDue: amountDueWithoutDiscount(line) });
|
|
293
|
+
if (priorAutomatic === null || priorAutomatic === void 0 ? void 0 : priorAutomatic.discount) {
|
|
294
|
+
return Object.assign(Object.assign({}, checkout), { couponCode: null, line: Object.assign(Object.assign({}, clearedLine), { discount: priorAutomatic.discount, discountSource: 'automatic', discountName: (_a = priorAutomatic.discountName) !== null && _a !== void 0 ? _a : null, amountDue: amountDueWithDiscount(clearedLine, priorAutomatic.discount) }) });
|
|
295
|
+
}
|
|
296
|
+
return Object.assign(Object.assign({}, checkout), { couponCode: null, line: clearedLine });
|
|
256
297
|
}
|
|
257
298
|
export function useAlacarteCheckout(options) {
|
|
258
299
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
|
|
@@ -354,6 +395,9 @@ export function useAlacarteCheckout(options) {
|
|
|
354
395
|
// client-side. The next attempt must skip tCheckoutUpdate (it would fail
|
|
355
396
|
// with CHECKOUT_NOT_OPEN) and go straight to tCheckoutPlaceOrder again.
|
|
356
397
|
const [cardRetryBiId, setCardRetryBiId] = useState(null);
|
|
398
|
+
// Last checkout that carried an automatic offer — restored after a custom
|
|
399
|
+
// coupon is removed if the backend does not re-apply it.
|
|
400
|
+
const automaticBaselineRef = useRef(null);
|
|
357
401
|
// Reset local overrides and in-flight select/coupon when the product changes
|
|
358
402
|
// so viewedPrice / couponRecheck run again for the new selection.
|
|
359
403
|
useEffect(() => {
|
|
@@ -364,6 +408,7 @@ export function useAlacarteCheckout(options) {
|
|
|
364
408
|
setPaymentTimedOut(false);
|
|
365
409
|
setSanctionsBlocked(null);
|
|
366
410
|
setCardRetryBiId(null);
|
|
411
|
+
automaticBaselineRef.current = null;
|
|
367
412
|
selectReset();
|
|
368
413
|
urlCouponReset();
|
|
369
414
|
}, [selector, selectReset, urlCouponReset]);
|
|
@@ -473,12 +518,24 @@ export function useAlacarteCheckout(options) {
|
|
|
473
518
|
},
|
|
474
519
|
});
|
|
475
520
|
}, [(_k = derived.checkout) === null || _k === void 0 ? void 0 : _k.biId, client, manualUpdateMutation]);
|
|
476
|
-
|
|
521
|
+
// Remember the latest automatic offer so removeCoupon can restore it.
|
|
522
|
+
useEffect(() => {
|
|
477
523
|
var _a;
|
|
524
|
+
const checkout = derived.checkout;
|
|
525
|
+
if (((_a = checkout === null || checkout === void 0 ? void 0 : checkout.line) === null || _a === void 0 ? void 0 : _a.discountSource) === 'automatic'
|
|
526
|
+
&& checkout.line.discount) {
|
|
527
|
+
automaticBaselineRef.current = checkout;
|
|
528
|
+
}
|
|
529
|
+
}, [derived.checkout]);
|
|
530
|
+
const removeCoupon = useCallback(() => {
|
|
531
|
+
var _a, _b, _c;
|
|
478
532
|
const currentCheckout = derived.checkout;
|
|
479
533
|
if (!(currentCheckout === null || currentCheckout === void 0 ? void 0 : currentCheckout.biId) || !client)
|
|
480
534
|
return;
|
|
481
535
|
const removedCode = ((_a = currentCheckout.couponCode) === null || _a === void 0 ? void 0 : _a.trim()) || null;
|
|
536
|
+
// Prefer the remembered automatic offer; fall back to the pre-coupon
|
|
537
|
+
// select response when the baseline was never captured.
|
|
538
|
+
const priorCheckout = (_b = automaticBaselineRef.current) !== null && _b !== void 0 ? _b : (((_c = selectMutation.data) === null || _c === void 0 ? void 0 : _c.ok) ? selectMutation.data.checkout : null);
|
|
482
539
|
setCouponError(null);
|
|
483
540
|
manualUpdateMutation.mutate({ biId: currentCheckout.biId, couponCode: '' }, {
|
|
484
541
|
onSuccess: (result) => {
|
|
@@ -487,7 +544,7 @@ export function useAlacarteCheckout(options) {
|
|
|
487
544
|
setCouponError(getCouponErrorMessage(result.error));
|
|
488
545
|
return;
|
|
489
546
|
}
|
|
490
|
-
setCheckoutOverride(checkoutWithoutCoupon((_a = result.checkout) !== null && _a !== void 0 ? _a : currentCheckout));
|
|
547
|
+
setCheckoutOverride(checkoutWithoutCoupon((_a = result.checkout) !== null && _a !== void 0 ? _a : currentCheckout, priorCheckout));
|
|
491
548
|
setCouponError(null);
|
|
492
549
|
if (removedCode)
|
|
493
550
|
setRemovedCouponCode(removedCode);
|
|
@@ -496,7 +553,7 @@ export function useAlacarteCheckout(options) {
|
|
|
496
553
|
setCouponError(errorMessage(err));
|
|
497
554
|
},
|
|
498
555
|
});
|
|
499
|
-
}, [derived.checkout, client, manualUpdateMutation]);
|
|
556
|
+
}, [derived.checkout, client, manualUpdateMutation, selectMutation.data]);
|
|
500
557
|
const placeOrderCore = useCallback((opts) => __awaiter(this, void 0, void 0, function* () {
|
|
501
558
|
const checkout = derived.checkout;
|
|
502
559
|
if (!checkout || !client)
|
|
@@ -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,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,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EACL,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAChG,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACvF,OAAO,EAAE,6BAA6B,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC1F,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,EAAE,kBAAkB,GACnE,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,YAA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oBACzC,IAAI,KAAK,CAAC,EAAE,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;wBAC/B,mBAAmB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;wBACpC,WAAW,CAAC,YAAY,CAAC,YAAY,CAAC,QAAQ,EAAE,EAAE,KAAK,CAAC,CAAC;oBAC3D,CAAC;gBACH,CAAC;gBAAC,WAAM,CAAC;oBACP,uEAAuE;gBACzE,CAAC;YACH,CAAC;YACD,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC;QAC3B,CAAC,CAAA,CAAC,EAAE,CAAC;QAEL,OAAO,SAAS,CAAC;IACnB,CAAC,EAAE,CAAC,SAAS,EAAE,UAAU,CAAC,gBAAgB,EAAE,MAAM,EAAE,YAAY,EAAE,WAAW,CAAC,CAAC,CAAC;IAEhF,uCACK,OAAO,KACV,WAAW,EACX,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,UAAU,EACV,eAAe,EAAE,cAAc,EAC/B,oBAAoB,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EACpD,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 toAlacarteBillingAddress,\n} from '../../utils/alacartePayment';\nimport { AlacartePlaceOrderError, isSanctionsBlockedError } from '../../utils/placeOrderErrors';\nimport { CardValidationError } from '../../utils/stripeCard';\nimport { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';\nimport { useSubscriptionCourseKeyQuery, useViaxSessionQuery } 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, useOrderDatesQuery,\n} from './useAlacarteQueries';\nimport { alacarteKeys } from './keys';\nimport { derivePlacedOrderView } from './placedOrderPoll';\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 /**\n * Accepts price (if needed) + terms, calls tCheckoutPlaceOrder with billing,\n * confirms the card via Stripe.js, then sets ?order_bi_id= to poll tPlacedOrder.\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 clearPlaceOrderError: () => 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. PLACEHOLDER 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 tPlacedOrder is still PAYMENT_PENDING (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_uid+course_run_key, or\n * program_uid, 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 * 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 [{ courseUid, runKey: nuqsRunKey, programUid }] = useQueryStates({\n courseUid: parseAsString,\n runKey: parseAsString,\n programUid: parseAsString,\n }, {\n urlKeys: {\n courseUid: 'course_uid',\n runKey: 'course_run_key',\n programUid: 'program_uid',\n },\n });\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/**\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 */\nexport function checkoutWithoutCoupon(checkout: AlacarteCheckout): AlacarteCheckout {\n const { line } = checkout;\n if (!line || line.discountSource === 'automatic') {\n return { ...checkout, couponCode: null };\n }\n const patchedLine = {\n ...line,\n discount: null,\n amountDue: line.price && line.kind === 'program' && 'deduction' in line && line.deduction\n ? { amount: line.price.amount - line.deduction.amount, currency: line.price.currency }\n : line.price,\n } as typeof line;\n return { ...checkout, couponCode: null, line: patchedLine };\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 const client = useMemo(\n () => (apiUrl ? createAlacarteCheckoutClient({ apiUrl }) : null),\n [apiUrl],\n );\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\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 [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\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 setPaymentTimedOut(false);\n setSanctionsBlocked(null);\n setCardRetryBiId(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 const manualUpdateMutation = useUpdateCheckoutMutation(client);\n\n const placedOrderQuery = usePlacedOrderQuery(\n client,\n orderBiId,\n sessionReady && !!orderBiId,\n );\n\n const orderDatesQuery = useOrderDatesQuery(\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 } 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 const removeCoupon = useCallback(() => {\n const currentCheckout = derived.checkout;\n if (!currentCheckout?.biId || !client) return;\n const removedCode = currentCheckout.couponCode?.trim() || 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(checkoutWithoutCoupon(result.checkout ?? currentCheckout));\n setCouponError(null);\n if (removedCode) setRemovedCouponCode(removedCode);\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout, client, manualUpdateMutation]);\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\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: 'PLACEHOLDER' });\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 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\n const dates = orderDatesQuery.data?.ok ? orderDatesQuery.data.dates : null;\n const placedOrderPlacedAt = dates?.tPlacedAt ?? dates?.biCreatedAt ?? null;\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\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 placeOrder,\n placeOrderAsync: placeOrderCore,\n clearPlaceOrderError: () => setPlaceOrderError(null),\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,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EACL,kBAAkB,EACl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AAc,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 toAlacarteBillingAddress,\n} from '../../utils/alacartePayment';\nimport { AlacartePlaceOrderError, isSanctionsBlockedError } from '../../utils/placeOrderErrors';\nimport { CardValidationError } from '../../utils/stripeCard';\nimport { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';\nimport { useSubscriptionCourseKeyQuery, useViaxSessionQuery } 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, useOrderDatesQuery,\n} from './useAlacarteQueries';\nimport { alacarteKeys } from './keys';\nimport { derivePlacedOrderView } from './placedOrderPoll';\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 /**\n * Accepts price (if needed) + terms, calls tCheckoutPlaceOrder with billing,\n * confirms the card via Stripe.js, then sets ?order_bi_id= to poll tPlacedOrder.\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 clearPlaceOrderError: () => 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. PLACEHOLDER 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 tPlacedOrder is still PAYMENT_PENDING (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 const client = useMemo(\n () => (apiUrl ? createAlacarteCheckoutClient({ apiUrl }) : null),\n [apiUrl],\n );\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\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 [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\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 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 const manualUpdateMutation = useUpdateCheckoutMutation(client);\n\n const placedOrderQuery = usePlacedOrderQuery(\n client,\n orderBiId,\n sessionReady && !!orderBiId,\n );\n\n const orderDatesQuery = useOrderDatesQuery(\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 } 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\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: 'PLACEHOLDER' });\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 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\n const dates = orderDatesQuery.data?.ok ? orderDatesQuery.data.dates : null;\n const placedOrderPlacedAt = dates?.tPlacedAt ?? dates?.biCreatedAt ?? null;\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\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 placeOrder,\n placeOrderAsync: placeOrderCore,\n clearPlaceOrderError: () => setPlaceOrderError(null),\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"]}
|
|
@@ -31,15 +31,16 @@ export function useCheckoutGate(options = {}) {
|
|
|
31
31
|
const ipGeoSettled = (!sessionReady)
|
|
32
32
|
|| ipQuery.isError
|
|
33
33
|
|| (!!ipQuery.data && !geoQuery.isLoading);
|
|
34
|
-
// Both
|
|
35
|
-
// valid product selectors in this app
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
//
|
|
40
|
-
//
|
|
41
|
-
// the
|
|
42
|
-
//
|
|
34
|
+
// Both course_uuid + course_run_key (course) or program_uuid (program) are
|
|
35
|
+
// valid product selectors in this app (legacy course_uid / program_uid still
|
|
36
|
+
// work) — use the same selector the rest of checkout uses
|
|
37
|
+
// (useAlacarteCheckout) to know *which* case we're in. But for the actual
|
|
38
|
+
// course_run_key value, don't use productSelector.runKey — nuqs decodes
|
|
39
|
+
// literal `+` as a space (standards-compliant, but course run keys like
|
|
40
|
+
// "course-v1:edX+DemoX+Demo_Course" rely on literal `+`), which corrupts
|
|
41
|
+
// the id sent to compliance-check. getCourseRunKeyFromUrl() reads the raw
|
|
42
|
+
// query string and preserves `+` correctly (same util useCheckout uses for
|
|
43
|
+
// the real course lookup).
|
|
43
44
|
const productSelector = useProductSelector();
|
|
44
45
|
const rawCourseRunKey = getCourseRunKeyFromUrl();
|
|
45
46
|
const courseIds = productSelector.kind === 'course'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCheckoutGate.js","sourceRoot":"","sources":["../../../src/data/hooks/useCheckoutGate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AA2B9B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;;IAClE,MAAM,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E,MAAA,OAAO,CAAC,IAAI,mCAAI,IAAI;QAC/B,SAAS;KACV,EACD,oBAAoB,CACrB,CAAC;IAEF,MAAM,WAAW,GAAG,MAAA,MAAA,YAAY,CAAC,IAAI,0CAAE,OAAO,mCAAI,IAAI,CAAC;IAEvD,MAAM,OAAO,GAAG,CAAC,CAAC,YAAY,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC;WACnD,CAAC,YAAY,IAAI,CAAC,cAAc,CAAC;WACjC,CAAC,CAAC,sBAAsB,IAAI,YAAY,IAAI,cAAc,IAAI,CAAC,YAAY,CAAC;WAC5E,CAAC,oBAAoB,IAAI,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAE9D,IAAI,UAAsB,CAAC;IAC3B,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC;QACzB,UAAU,GAAG,OAAO,CAAC;IACvB,CAAC;SAAM,IAAI,OAAO,EAAE,CAAC;QACnB,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;SAAM,IAAI,CAAC,sBAAsB,KAAI,MAAA,oBAAoB,CAAC,IAAI,0CAAE,SAAS,CAAA,EAAE,CAAC;QAC3E,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;SAAM,CAAC;QACN,yEAAyE;QACzE,6EAA6E;QAC7E,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;IAED,IAAI,WAAW,GAAkB,IAAI,CAAC;IACtC,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,WAAW,GAAG,YAAY,CAAC,KAAK,YAAY,KAAK;YAC/C,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,OAAO;YAC5B,CAAC,CAAC,uCAAuC,CAAC;IAC9C,CAAC;IAED,OAAO;QACL,UAAU;QACV,WAAW;QACX,mBAAmB;QACnB,WAAW;KACZ,CAAC;AACJ,CAAC","sourcesContent":["import { useProductSelector } from './useAlacarteCheckout';\nimport { getCourseRunKeyFromUrl } from '../../utils/url';\nimport {\n useViaxSessionQuery,\n useUserProfileQuery,\n usePublicIpQuery,\n useIpGeolocationQuery,\n useComplianceCheckQuery,\n} from './useCheckoutQueries';\n\nexport interface UseCheckoutGateOptions {\n /** Kept for call-site compatibility; no longer used (subscriber check removed). */\n apiUrl?: string,\n edxSessionUrl?: string,\n /** Endpoint used to resolve city/etc. for the learner's public IP. */\n geolocationUrl?: string,\n /** ALC-307 compliance-check endpoint — decides whether the learner is embargoed. */\n complianceCheckUrl?: string,\n /** When true, skip the compliance-check request and do not block on its result. */\n disableComplianceCheck?: boolean,\n learnerDashboardUrl?: string,\n}\n\nexport type GateStatus = 'loading' | 'blocked' | 'allowed' | 'error';\n\nexport interface UseCheckoutGateResult {\n /** 'loading' while checks are in flight, 'blocked' if the compliance check rejects the learner, 'allowed' if clear (or compliance check failed), 'error' if session failed. */\n gateStatus: GateStatus,\n /** ISO 3166-1 alpha-2 country code — passed down to Checkout for the UK/CA checkbox. */\n userCountry: string | null,\n learnerDashboardUrl: string | undefined,\n /** Message shown when gateStatus is not 'allowed'. */\n gateMessage: string | null,\n}\n\n/**\n * Session + embargo compliance gate for à la carte checkout.\n *\n * Calls the ALC-307 compliance-check endpoint with the learner's identity,\n * account-profile country, and public IP/city. The compliance-check call\n * fails open (gateStatus = 'allowed') on network/CORS/HTTP errors — only an\n * explicit non-compliant response blocks checkout. Profile/IP/geolocation\n * lookups likewise fail open as request-body inputs.\n *\n * When disableComplianceCheck is true, the compliance-check request is not\n * made. Checkout opens once the session and profile have settled.\n */\nexport function useCheckoutGate(options: UseCheckoutGateOptions = {}): UseCheckoutGateResult {\n const {\n edxSessionUrl,\n geolocationUrl,\n complianceCheckUrl,\n disableComplianceCheck = false,\n learnerDashboardUrl,\n } = options;\n\n const sessionQuery = useViaxSessionQuery(edxSessionUrl ?? null);\n const sessionReady = !!sessionQuery.data;\n\n const profileQuery = useUserProfileQuery(\n sessionReady ? (edxSessionUrl ?? null) : null,\n sessionQuery.data?.username ?? null,\n );\n // fetchUserProfile fails open internally (never throws) — \"settled\" means\n // isLoading is false, regardless of whether data came back null.\n const profileSettled = !profileQuery.isLoading;\n\n const ipQuery = usePublicIpQuery(sessionReady && !disableComplianceCheck);\n const geoQuery = useIpGeolocationQuery(\n sessionReady && !disableComplianceCheck ? (geolocationUrl ?? null) : null,\n ipQuery.data ?? null,\n );\n // IP/geo lookups are best-effort inputs to the request body, not gating\n // signals themselves — treat any terminal state (success OR error) as\n // settled so a flaky ipify/geolocation call never blocks the\n // compliance-check call.\n const ipGeoSettled = (!sessionReady)\n || ipQuery.isError\n || (!!ipQuery.data && !geoQuery.isLoading);\n\n // Both course_uuid + course_run_key (course) or program_uuid (program) are\n // valid product selectors in this app (legacy course_uid / program_uid still\n // work) — use the same selector the rest of checkout uses\n // (useAlacarteCheckout) to know *which* case we're in. But for the actual\n // course_run_key value, don't use productSelector.runKey — nuqs decodes\n // literal `+` as a space (standards-compliant, but course run keys like\n // \"course-v1:edX+DemoX+Demo_Course\" rely on literal `+`), which corrupts\n // the id sent to compliance-check. getCourseRunKeyFromUrl() reads the raw\n // query string and preserves `+` correctly (same util useCheckout uses for\n // the real course lookup).\n const productSelector = useProductSelector();\n const rawCourseRunKey = getCourseRunKeyFromUrl();\n const courseIds = productSelector.kind === 'course'\n ? [rawCourseRunKey ?? productSelector.runKey]\n : productSelector.kind === 'program'\n ? [productSelector.programUid]\n : [];\n\n const complianceCheckReady = !disableComplianceCheck\n && sessionReady\n && profileSettled\n && ipGeoSettled;\n\n const complianceCheckQuery = useComplianceCheckQuery(\n disableComplianceCheck ? null : (complianceCheckUrl ?? null),\n {\n lmsUserId: sessionQuery.data?.edxUserId ?? null,\n fullName: profileQuery.data?.name ?? null,\n country: profileQuery.data?.country ?? null,\n city: geoQuery.data?.city ?? null,\n username: sessionQuery.data?.username ?? null,\n ipAddress: ipQuery.data ?? null,\n courseIds,\n },\n complianceCheckReady,\n );\n\n const userCountry = profileQuery.data?.country ?? null;\n\n const loading = (!sessionReady && !sessionQuery.isError)\n || (sessionReady && !profileSettled)\n || (!disableComplianceCheck && sessionReady && profileSettled && !ipGeoSettled)\n || (complianceCheckReady && complianceCheckQuery.isLoading);\n\n let gateStatus: GateStatus;\n if (sessionQuery.isError) {\n gateStatus = 'error';\n } else if (loading) {\n gateStatus = 'loading';\n } else if (!disableComplianceCheck && complianceCheckQuery.data?.isBlocked) {\n gateStatus = 'blocked';\n } else {\n // Compliant, compliance check skipped/disabled, or compliance API failed\n // (CORS, network, 5xx, etc.) — always fail open so checkout stays available.\n gateStatus = 'allowed';\n }\n\n let gateMessage: string | null = null;\n if (gateStatus === 'error') {\n gateMessage = sessionQuery.error instanceof Error\n ? sessionQuery.error.message\n : 'Failed to establish checkout session.';\n }\n\n return {\n gateStatus,\n userCountry,\n learnerDashboardUrl,\n gateMessage,\n };\n}\n"]}
|
|
@@ -36,7 +36,7 @@ export declare function useSubscriptionIdQuery(client: CheckoutClient | null, ca
|
|
|
36
36
|
/**
|
|
37
37
|
* Resolves the Viax course key for a course run via
|
|
38
38
|
* GET /api/subscription/course_runs/?key=<course run key>.
|
|
39
|
-
* Used when the URL has both course_uid and course_run_key.
|
|
39
|
+
* Used when the URL has both course_uuid (or legacy course_uid) and course_run_key.
|
|
40
40
|
* Pass null for lmsBaseUrl or courseRunKey to disable (e.g. when
|
|
41
41
|
* SKIP_SUBSCRIPTION_COURSE_RUNS derives the key locally instead).
|
|
42
42
|
*/
|
|
@@ -124,7 +124,7 @@ export function useSubscriptionIdQuery(client, cartBiId, enabled) {
|
|
|
124
124
|
/**
|
|
125
125
|
* Resolves the Viax course key for a course run via
|
|
126
126
|
* GET /api/subscription/course_runs/?key=<course run key>.
|
|
127
|
-
* Used when the URL has both course_uid and course_run_key.
|
|
127
|
+
* Used when the URL has both course_uuid (or legacy course_uid) and course_run_key.
|
|
128
128
|
* Pass null for lmsBaseUrl or courseRunKey to disable (e.g. when
|
|
129
129
|
* SKIP_SUBSCRIPTION_COURSE_RUNS derives the key locally instead).
|
|
130
130
|
*/
|
|
@@ -1 +1 @@
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BAAoB,CAClC,MAA6B,EAC7B,YAAqB,EACrB,YAA2B;IAE3B,OAAO,QAAQ,CAAC;QACd,QAAQ,EAAE,YAAY,CAAC,YAAY,CAAC,YAAY,aAAZ,YAAY,cAAZ,YAAY,GAAI,MAAM,CAAC;QAC3D,OAAO,EAAE,CAAC,CAAC,MAAM,IAAI,YAAY,IAAI,CAAC,CAAC,YAAY;QACnD,OAAO,EAAE,GAAiC,EAAE,CAAC,MAAO,CAAC,eAAe,CAAC,YAAa,CAAC;QACnF,SAAS,EAAE,QAAQ;QACnB,oBAAoB,EAAE,KAAK;QAC3B,KAAK,EAAE,CAAC;KACT,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * query/useCheckoutQueries.ts — read-side TanStack Query hooks.\n *\n * useViaxSessionQuery runs on mount to exchange the edX session for a viax\n * token.\n */\nimport { useQuery } from '@tanstack/react-query';\nimport { isTerminalStatus } from '../../constants';\nimport { checkoutKeys } from './keys';\nimport {\n fetchEdxSession,\n fetchUserProfile,\n fetchPublicIp,\n fetchIpGeolocation,\n fetchComplianceCheck,\n fetchSubscriptionCourseKey\n} from '../../utils/provision';\nimport type { ComplianceCheckRequest } from '../../utils/provision';\nimport type {\n CheckoutClient, CartStatusResult, CourseDetail,\n} from '../../types';\n\n/** Exchange edX session cookies for a viax token on page load. */\nexport function useViaxSessionQuery(sessionUrl: string | null) {\n return useQuery({\n queryKey: checkoutKeys.viaxSession(),\n enabled: !!sessionUrl,\n queryFn: () => fetchEdxSession(sessionUrl!),\n staleTime: 5 * 60 * 1000,\n // Avoid tearing down CheckoutGate (and remounting Checkout) when the\n // learner alt-tabs away and back after the session becomes stale.\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Checks whether the authenticated learner already has an active subscription. */\nexport function useCurrentUserSubscriberQuery(client: CheckoutClient | null, sessionReady: boolean) {\n return useQuery({\n queryKey: ['checkout', 'currentUserSubscriber'],\n enabled: !!client && sessionReady,\n queryFn: () => client!.isCurrentUserSubscriber(),\n staleTime: 5 * 60 * 1000,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/**\n * Fetches the user's country and full name from their edX account profile.\n * Derives the LMS base URL from the session URL (same origin).\n * Returns nulls if the fetch fails or a field is absent — checkout stays open in that case.\n */\nexport function useUserProfileQuery(sessionUrl: string | null, username: string | null) {\n return useQuery({\n queryKey: ['checkout', 'userProfile', username],\n enabled: !!sessionUrl && !!username,\n queryFn: () => {\n const lmsBaseUrl = new URL(sessionUrl!).origin;\n return fetchUserProfile(lmsBaseUrl, username!);\n },\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Fetches the learner's current public IP once the viax session is ready. */\nexport function usePublicIpQuery(sessionReady: boolean) {\n return useQuery({\n queryKey: ['checkout', 'publicIp'],\n enabled: sessionReady,\n queryFn: () => fetchPublicIp(),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Resolves city/etc. for the public IP via the LMS geolocation endpoint. */\nexport function useIpGeolocationQuery(geolocationUrl: string | null, ipAddress: string | null) {\n return useQuery({\n queryKey: ['checkout', 'ipGeolocation', ipAddress ?? 'none'],\n enabled: !!geolocationUrl && !!ipAddress,\n queryFn: () => fetchIpGeolocation(geolocationUrl!, ipAddress!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\nexport interface ComplianceCheckInputs {\n lmsUserId: string | null,\n fullName: string | null,\n country: string | null,\n city: string | null,\n username: string | null,\n ipAddress: string | null,\n courseIds: string[],\n}\n\n/**\n * Calls the ALC-307 compliance-check endpoint once identity, country, and\n * IP/city are resolved. Errors surface via isError; useCheckoutGate treats\n * those as fail-open (gateStatus = 'allowed') so CORS/network failures do\n * not block checkout — only an explicit isBlocked result does.\n */\nexport function useComplianceCheckQuery(\n complianceCheckUrl: string | null,\n inputs: ComplianceCheckInputs,\n ready: boolean,\n) {\n const {\n lmsUserId, fullName, country, city, username, ipAddress, courseIds,\n } = inputs;\n\n return useQuery({\n queryKey: ['checkout', 'complianceCheck', username ?? 'none', ipAddress ?? 'none'],\n enabled: !!complianceCheckUrl && ready && !!lmsUserId && !!username,\n queryFn: () => {\n const requestBody: ComplianceCheckRequest = {\n lms_user_id: lmsUserId!,\n full_name: fullName ?? '',\n country: country ?? '',\n city: city ?? '',\n user: username!,\n ip_address: ipAddress ?? '',\n course_ids: courseIds,\n };\n return fetchComplianceCheck(complianceCheckUrl!, requestBody);\n },\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Polls the cart state machine every second; stops on terminal states. */\nexport function useCartStatusQuery(client: CheckoutClient | null, cartBiId: string | null) {\n return useQuery({\n queryKey: checkoutKeys.status(cartBiId ?? 'none'),\n enabled: !!client && !!cartBiId,\n queryFn: (): Promise<CartStatusResult> => client!.getCartStatus(cartBiId!),\n refetchInterval: (query) =>\n isTerminalStatus(query.state.data?.status ?? null) ? false : 1000,\n refetchOnWindowFocus: false,\n gcTime: 0,\n });\n}\n\n/** Looks up the created subscription biId after success. */\nexport function useSubscriptionIdQuery(\n client: CheckoutClient | null,\n cartBiId: string | null,\n enabled: boolean,\n) {\n return useQuery({\n queryKey: checkoutKeys.subscriptionId(cartBiId ?? 'none'),\n enabled: enabled && !!client && !!cartBiId,\n queryFn: () => client!.findSubscriptionBiId(cartBiId!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n });\n}\n\n/**\n * Resolves the Viax course key for a course run via\n * GET /api/subscription/course_runs/?key=<course run key>.\n * Used when the URL has both course_uid and course_run_key.\n * Pass null for lmsBaseUrl or courseRunKey to disable (e.g. when\n * SKIP_SUBSCRIPTION_COURSE_RUNS derives the key locally instead).\n */\nexport function useSubscriptionCourseKeyQuery(\n lmsBaseUrl: string | null,\n courseRunKey: string | null,\n) {\n return useQuery({\n queryKey: checkoutKeys.subscriptionCourseKey(courseRunKey ?? 'none'),\n enabled: !!lmsBaseUrl && !!courseRunKey,\n queryFn: () => fetchSubscriptionCourseKey(lmsBaseUrl!, courseRunKey!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/**\n * Fetches Viax course details by the `course` value returned from\n * GET /api/subscription/course_runs/ (not the course-run `key` or the raw URL param).\n * Skipped entirely when that value is absent.\n */\nexport function useCourseDetailQuery(\n client: CheckoutClient | null,\n sessionReady: boolean,\n courseRunKey: string | null,\n) {\n return useQuery({\n queryKey: checkoutKeys.courseDetail(courseRunKey ?? 'none'),\n enabled: !!client && sessionReady && !!courseRunKey,\n queryFn: (): Promise<CourseDetail | null> => client!.getCourseDetail(courseRunKey!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useCheckoutQueries.js","sourceRoot":"","sources":["../../../src/data/hooks/useCheckoutQueries.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,kBAAkB,EAClB,oBAAoB,EACpB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC;AAM/B,kEAAkE;AAClE,MAAM,UAAU,mBAAmB,CAAC,UAAyB;IAC3D,OAAO,QAAQ,CAAC;QACd,QAAQ,EAAE,YAAY,CAAC,WAAW,EAAE;QACpC,OAAO,EAAE,CAAC,CAAC,UAAU;QACrB,OAAO,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,UAAW,CAAC;QAC3C,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;QACxB,qEAAqE;QACrE,kEAAkE;QAClE,oBAAoB,EAAE,KAAK;QAC3B,KAAK,EAAE,CAAC;KACT,CAAC,CAAC;AACL,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU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,UAAU,6BAA6B,CAC3C,UAAyB,EACzB,YAA2B;IAE3B,OAAO,QAAQ,CAAC;QACd,QAAQ,EAAE,YAAY,CAAC,qBAAqB,CAAC,YAAY,aAAZ,YAAY,cAAZ,YAAY,GAAI,MAAM,CAAC;QACpE,OAAO,EAAE,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,YAAY;QACvC,OAAO,EAAE,GAAG,EAAE,CAAC,0BAA0B,CAAC,UAAW,EAAE,YAAa,CAAC;QACrE,SAAS,EAAE,QAAQ;QACnB,oBAAoB,EAAE,KAAK;QAC3B,KAAK,EAAE,CAAC;KACT,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAA6B,EAC7B,YAAqB,EACrB,YAA2B;IAE3B,OAAO,QAAQ,CAAC;QACd,QAAQ,EAAE,YAAY,CAAC,YAAY,CAAC,YAAY,aAAZ,YAAY,cAAZ,YAAY,GAAI,MAAM,CAAC;QAC3D,OAAO,EAAE,CAAC,CAAC,MAAM,IAAI,YAAY,IAAI,CAAC,CAAC,YAAY;QACnD,OAAO,EAAE,GAAiC,EAAE,CAAC,MAAO,CAAC,eAAe,CAAC,YAAa,CAAC;QACnF,SAAS,EAAE,QAAQ;QACnB,oBAAoB,EAAE,KAAK;QAC3B,KAAK,EAAE,CAAC;KACT,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * query/useCheckoutQueries.ts — read-side TanStack Query hooks.\n *\n * useViaxSessionQuery runs on mount to exchange the edX session for a viax\n * token.\n */\nimport { useQuery } from '@tanstack/react-query';\nimport { isTerminalStatus } from '../../constants';\nimport { checkoutKeys } from './keys';\nimport {\n fetchEdxSession,\n fetchUserProfile,\n fetchPublicIp,\n fetchIpGeolocation,\n fetchComplianceCheck,\n fetchSubscriptionCourseKey\n} from '../../utils/provision';\nimport type { ComplianceCheckRequest } from '../../utils/provision';\nimport type {\n CheckoutClient, CartStatusResult, CourseDetail,\n} from '../../types';\n\n/** Exchange edX session cookies for a viax token on page load. */\nexport function useViaxSessionQuery(sessionUrl: string | null) {\n return useQuery({\n queryKey: checkoutKeys.viaxSession(),\n enabled: !!sessionUrl,\n queryFn: () => fetchEdxSession(sessionUrl!),\n staleTime: 5 * 60 * 1000,\n // Avoid tearing down CheckoutGate (and remounting Checkout) when the\n // learner alt-tabs away and back after the session becomes stale.\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Checks whether the authenticated learner already has an active subscription. */\nexport function useCurrentUserSubscriberQuery(client: CheckoutClient | null, sessionReady: boolean) {\n return useQuery({\n queryKey: ['checkout', 'currentUserSubscriber'],\n enabled: !!client && sessionReady,\n queryFn: () => client!.isCurrentUserSubscriber(),\n staleTime: 5 * 60 * 1000,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/**\n * Fetches the user's country and full name from their edX account profile.\n * Derives the LMS base URL from the session URL (same origin).\n * Returns nulls if the fetch fails or a field is absent — checkout stays open in that case.\n */\nexport function useUserProfileQuery(sessionUrl: string | null, username: string | null) {\n return useQuery({\n queryKey: ['checkout', 'userProfile', username],\n enabled: !!sessionUrl && !!username,\n queryFn: () => {\n const lmsBaseUrl = new URL(sessionUrl!).origin;\n return fetchUserProfile(lmsBaseUrl, username!);\n },\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Fetches the learner's current public IP once the viax session is ready. */\nexport function usePublicIpQuery(sessionReady: boolean) {\n return useQuery({\n queryKey: ['checkout', 'publicIp'],\n enabled: sessionReady,\n queryFn: () => fetchPublicIp(),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Resolves city/etc. for the public IP via the LMS geolocation endpoint. */\nexport function useIpGeolocationQuery(geolocationUrl: string | null, ipAddress: string | null) {\n return useQuery({\n queryKey: ['checkout', 'ipGeolocation', ipAddress ?? 'none'],\n enabled: !!geolocationUrl && !!ipAddress,\n queryFn: () => fetchIpGeolocation(geolocationUrl!, ipAddress!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\nexport interface ComplianceCheckInputs {\n lmsUserId: string | null,\n fullName: string | null,\n country: string | null,\n city: string | null,\n username: string | null,\n ipAddress: string | null,\n courseIds: string[],\n}\n\n/**\n * Calls the ALC-307 compliance-check endpoint once identity, country, and\n * IP/city are resolved. Errors surface via isError; useCheckoutGate treats\n * those as fail-open (gateStatus = 'allowed') so CORS/network failures do\n * not block checkout — only an explicit isBlocked result does.\n */\nexport function useComplianceCheckQuery(\n complianceCheckUrl: string | null,\n inputs: ComplianceCheckInputs,\n ready: boolean,\n) {\n const {\n lmsUserId, fullName, country, city, username, ipAddress, courseIds,\n } = inputs;\n\n return useQuery({\n queryKey: ['checkout', 'complianceCheck', username ?? 'none', ipAddress ?? 'none'],\n enabled: !!complianceCheckUrl && ready && !!lmsUserId && !!username,\n queryFn: () => {\n const requestBody: ComplianceCheckRequest = {\n lms_user_id: lmsUserId!,\n full_name: fullName ?? '',\n country: country ?? '',\n city: city ?? '',\n user: username!,\n ip_address: ipAddress ?? '',\n course_ids: courseIds,\n };\n return fetchComplianceCheck(complianceCheckUrl!, requestBody);\n },\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/** Polls the cart state machine every second; stops on terminal states. */\nexport function useCartStatusQuery(client: CheckoutClient | null, cartBiId: string | null) {\n return useQuery({\n queryKey: checkoutKeys.status(cartBiId ?? 'none'),\n enabled: !!client && !!cartBiId,\n queryFn: (): Promise<CartStatusResult> => client!.getCartStatus(cartBiId!),\n refetchInterval: (query) =>\n isTerminalStatus(query.state.data?.status ?? null) ? false : 1000,\n refetchOnWindowFocus: false,\n gcTime: 0,\n });\n}\n\n/** Looks up the created subscription biId after success. */\nexport function useSubscriptionIdQuery(\n client: CheckoutClient | null,\n cartBiId: string | null,\n enabled: boolean,\n) {\n return useQuery({\n queryKey: checkoutKeys.subscriptionId(cartBiId ?? 'none'),\n enabled: enabled && !!client && !!cartBiId,\n queryFn: () => client!.findSubscriptionBiId(cartBiId!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n });\n}\n\n/**\n * Resolves the Viax course key for a course run via\n * GET /api/subscription/course_runs/?key=<course run key>.\n * Used when the URL has both course_uuid (or legacy course_uid) and course_run_key.\n * Pass null for lmsBaseUrl or courseRunKey to disable (e.g. when\n * SKIP_SUBSCRIPTION_COURSE_RUNS derives the key locally instead).\n */\nexport function useSubscriptionCourseKeyQuery(\n lmsBaseUrl: string | null,\n courseRunKey: string | null,\n) {\n return useQuery({\n queryKey: checkoutKeys.subscriptionCourseKey(courseRunKey ?? 'none'),\n enabled: !!lmsBaseUrl && !!courseRunKey,\n queryFn: () => fetchSubscriptionCourseKey(lmsBaseUrl!, courseRunKey!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n\n/**\n * Fetches Viax course details by the `course` value returned from\n * GET /api/subscription/course_runs/ (not the course-run `key` or the raw URL param).\n * Skipped entirely when that value is absent.\n */\nexport function useCourseDetailQuery(\n client: CheckoutClient | null,\n sessionReady: boolean,\n courseRunKey: string | null,\n) {\n return useQuery({\n queryKey: checkoutKeys.courseDetail(courseRunKey ?? 'none'),\n enabled: !!client && sessionReady && !!courseRunKey,\n queryFn: (): Promise<CourseDetail | null> => client!.getCourseDetail(courseRunKey!),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n retry: 1,\n });\n}\n"]}
|