@edx/frontend-app-alacarte-checkout 1.65.0 → 1.66.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/analytics/buildProducts.js +14 -10
- package/dist/analytics/buildProducts.js.map +1 -1
- package/dist/data/hooks/placedOrderPoll.d.ts +5 -1
- package/dist/data/hooks/placedOrderPoll.js +10 -10
- package/dist/data/hooks/placedOrderPoll.js.map +1 -1
- package/dist/data/hooks/useAlacarteCheckout.js +15 -6
- package/dist/data/hooks/useAlacarteCheckout.js.map +1 -1
- package/dist/types/alacarte.js.map +1 -1
- package/dist/utils/placeOrderErrors.d.ts +2 -0
- package/dist/utils/placeOrderErrors.js +4 -0
- package/dist/utils/placeOrderErrors.js.map +1 -1
- package/package.json +1 -1
|
@@ -8,13 +8,16 @@
|
|
|
8
8
|
function isCourseDetail(d) {
|
|
9
9
|
return 'maId' in d;
|
|
10
10
|
}
|
|
11
|
+
function isProgramDetail(d) {
|
|
12
|
+
return 'tCourses' in d;
|
|
13
|
+
}
|
|
11
14
|
/** Build products from a checkout line + optional catalog detail. */
|
|
12
15
|
export function buildProductsFromLine(line, productDetail) {
|
|
13
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
16
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
14
17
|
const courseDetail = productDetail && isCourseDetail(productDetail) ? productDetail : null;
|
|
15
18
|
if (line.kind === 'course') {
|
|
16
19
|
return [{
|
|
17
|
-
product_id: line.
|
|
20
|
+
product_id: line.courseRunKey,
|
|
18
21
|
sku: null,
|
|
19
22
|
name: line.courseName,
|
|
20
23
|
price: (_b = (_a = line.price) === null || _a === void 0 ? void 0 : _a.amount) !== null && _b !== void 0 ? _b : 0,
|
|
@@ -28,11 +31,12 @@ export function buildProductsFromLine(line, productDetail) {
|
|
|
28
31
|
}];
|
|
29
32
|
}
|
|
30
33
|
// Program: one product entry for the program itself.
|
|
34
|
+
const programDetail = productDetail && isProgramDetail(productDetail) ? productDetail : null;
|
|
31
35
|
return [{
|
|
32
|
-
product_id: line.programId,
|
|
36
|
+
product_id: (_g = programDetail === null || programDetail === void 0 ? void 0 : programDetail.tMarketingSlug) !== null && _g !== void 0 ? _g : line.programId,
|
|
33
37
|
sku: null,
|
|
34
38
|
name: line.programName,
|
|
35
|
-
price: (
|
|
39
|
+
price: (_j = (_h = line.price) === null || _h === void 0 ? void 0 : _h.amount) !== null && _j !== void 0 ? _j : 0,
|
|
36
40
|
quantity: 1,
|
|
37
41
|
category: null,
|
|
38
42
|
url: null,
|
|
@@ -46,18 +50,18 @@ export function buildProductsFromLine(line, productDetail) {
|
|
|
46
50
|
export function buildProductsFromOrder(lines, productDetail) {
|
|
47
51
|
const courseDetail = productDetail && isCourseDetail(productDetail) ? productDetail : null;
|
|
48
52
|
return lines.map((line) => {
|
|
49
|
-
var _a, _b, _c, _d, _e;
|
|
53
|
+
var _a, _b, _c, _d, _e, _f;
|
|
50
54
|
return ({
|
|
51
|
-
product_id: (_a = line.
|
|
55
|
+
product_id: (_b = (_a = line.courseRunKey) !== null && _a !== void 0 ? _a : line.productId) !== null && _b !== void 0 ? _b : line.lineId,
|
|
52
56
|
sku: null,
|
|
53
57
|
name: line.name,
|
|
54
58
|
price: line.amounts.price,
|
|
55
59
|
quantity: 1,
|
|
56
|
-
category: (
|
|
57
|
-
url: (
|
|
60
|
+
category: (_c = courseDetail === null || courseDetail === void 0 ? void 0 : courseDetail.tPrimarySubjectArea) !== null && _c !== void 0 ? _c : null,
|
|
61
|
+
url: (_d = courseDetail === null || courseDetail === void 0 ? void 0 : courseDetail.tUrlCourse) !== null && _d !== void 0 ? _d : null,
|
|
58
62
|
lob: 'edx',
|
|
59
|
-
image_url: (
|
|
60
|
-
brand: (
|
|
63
|
+
image_url: (_e = courseDetail === null || courseDetail === void 0 ? void 0 : courseDetail.imageUrl) !== null && _e !== void 0 ? _e : null,
|
|
64
|
+
brand: (_f = courseDetail === null || courseDetail === void 0 ? void 0 : courseDetail.tBrandText) !== null && _f !== void 0 ? _f : null,
|
|
61
65
|
product_type: line.kind === 'course' ? 'edX Course Entitlement' : 'program',
|
|
62
66
|
});
|
|
63
67
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildProducts.js","sourceRoot":"","sources":["../../src/analytics/buildProducts.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,SAAS,cAAc,CAAC,CAAgB;IACtC,OAAO,MAAM,IAAI,CAAC,CAAC;AACrB,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,qBAAqB,CACnC,IAAkB,EAClB,aAAmC;;IAEnC,MAAM,YAAY,GAAG,aAAa,IAAI,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC;IAE3F,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC3B,OAAO,CAAC;gBACN,UAAU,EAAE,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"buildProducts.js","sourceRoot":"","sources":["../../src/analytics/buildProducts.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,SAAS,cAAc,CAAC,CAAgB;IACtC,OAAO,MAAM,IAAI,CAAC,CAAC;AACrB,CAAC;AAED,SAAS,eAAe,CAAC,CAAgB;IACvC,OAAO,UAAU,IAAI,CAAC,CAAC;AACzB,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,qBAAqB,CACnC,IAAkB,EAClB,aAAmC;;IAEnC,MAAM,YAAY,GAAG,aAAa,IAAI,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC;IAE3F,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC3B,OAAO,CAAC;gBACN,UAAU,EAAE,IAAI,CAAC,YAAY;gBAC7B,GAAG,EAAE,IAAI;gBACT,IAAI,EAAE,IAAI,CAAC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CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC;IAE3F,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;;QAAC,OAAA,CAAC;YAC1B,UAAU,EAAE,MAAA,MAAA,IAAI,CAAC,YAAY,mCAAI,IAAI,CAAC,SAAS,mCAAI,IAAI,CAAC,MAAM;YAC9D,GAAG,EAAE,IAAI;YACT,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK;YACzB,QAAQ,EAAE,CAAC;YACX,QAAQ,EAAE,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,mBAAmB,mCAAI,IAAI;YACnD,GAAG,EAAE,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,UAAU,mCAAI,IAAI;YACrC,GAAG,EAAE,KAAK;YACV,SAAS,EAAE,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,mCAAI,IAAI;YACzC,KAAK,EAAE,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,UAAU,mCAAI,IAAI;YACvC,YAAY,EAAE,IAAI,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,SAAS;SAC5E,CAAC,CAAA;KAAA,CAAC,CAAC;AACN,CAAC","sourcesContent":["/**\n * Builds the Segment `products` array from checkout and catalog data.\n *\n * The checkout line gives us name, price, and kind. The catalog detail\n * (CourseDetail / ProgramDetail) fills in category, url, image, and brand.\n * Fields that the checkout doesn't carry are set to null.\n */\n\nimport type { AlacarteLine, PlacedOrderLine, ProductDetail, ProgramDetail } from '../types/alacarte';\nimport type { CourseDetail } from '../types';\nimport type { SegmentProduct } from './events';\n\nfunction isCourseDetail(d: ProductDetail): d is CourseDetail {\n return 'maId' in d;\n}\n\nfunction isProgramDetail(d: ProductDetail): d is ProgramDetail {\n return 'tCourses' in d;\n}\n\n/** Build products from a checkout line + optional catalog detail. */\nexport function buildProductsFromLine(\n line: AlacarteLine,\n productDetail: ProductDetail | null,\n): SegmentProduct[] {\n const courseDetail = productDetail && isCourseDetail(productDetail) ? productDetail : null;\n\n if (line.kind === 'course') {\n return [{\n product_id: line.courseRunKey,\n sku: null,\n name: line.courseName,\n price: line.price?.amount ?? 0,\n quantity: 1,\n category: courseDetail?.tPrimarySubjectArea ?? null,\n url: courseDetail?.tUrlCourse ?? null,\n lob: 'edx',\n image_url: courseDetail?.imageUrl ?? null,\n brand: courseDetail?.tBrandText ?? null,\n product_type: 'edX Course Entitlement',\n }];\n }\n\n // Program: one product entry for the program itself.\n const programDetail = productDetail && isProgramDetail(productDetail) ? productDetail : null;\n return [{\n product_id: programDetail?.tMarketingSlug ?? line.programId,\n sku: null,\n name: line.programName,\n price: line.price?.amount ?? 0,\n quantity: 1,\n category: null,\n url: null,\n lob: 'edx',\n image_url: null,\n brand: null,\n product_type: 'program',\n }];\n}\n\n/** Build products from placed order lines + optional catalog detail. */\nexport function buildProductsFromOrder(\n lines: PlacedOrderLine[],\n productDetail: ProductDetail | null,\n): SegmentProduct[] {\n const courseDetail = productDetail && isCourseDetail(productDetail) ? productDetail : null;\n\n return lines.map((line) => ({\n product_id: line.courseRunKey ?? line.productId ?? line.lineId,\n sku: null,\n name: line.name,\n price: line.amounts.price,\n quantity: 1,\n category: courseDetail?.tPrimarySubjectArea ?? null,\n url: courseDetail?.tUrlCourse ?? null,\n lob: 'edx',\n image_url: courseDetail?.imageUrl ?? null,\n brand: courseDetail?.tBrandText ?? null,\n product_type: line.kind === 'course' ? 'edX Course Entitlement' : 'program',\n }));\n}\n"]}
|
|
@@ -24,8 +24,12 @@ export interface PlacedOrderView {
|
|
|
24
24
|
placedOrder: PlacedOrder | null;
|
|
25
25
|
placedOrderError: string | null;
|
|
26
26
|
awaitingPlacedOrder: boolean;
|
|
27
|
-
/**
|
|
27
|
+
/** Stop waiting and send the learner back to the editable cart.
|
|
28
|
+
* Triggered by NOT_PLACED (payment failed) or a poll timeout (ALC-452 #6). */
|
|
28
29
|
returnToCheckout: boolean;
|
|
30
|
+
/** True when returnToCheckout was caused by the poll window expiring rather
|
|
31
|
+
* than a definitive NOT_PLACED response from the backend. */
|
|
32
|
+
returnedByPollTimeout: boolean;
|
|
29
33
|
}
|
|
30
34
|
export declare function derivePlacedOrderView(args: {
|
|
31
35
|
orderBiId: string | null;
|
|
@@ -31,13 +31,19 @@ export function placedOrderRefetchInterval(result, elapsedMs) {
|
|
|
31
31
|
return false;
|
|
32
32
|
}
|
|
33
33
|
export function derivePlacedOrderView(args) {
|
|
34
|
-
var _a
|
|
34
|
+
var _a;
|
|
35
35
|
const { orderBiId, result, pollTimedOut, isLoading, isFetching, } = args;
|
|
36
36
|
const placedOrder = isPaidPlacedOrder(result) ? result.order : null;
|
|
37
|
+
const isNotPlaced = (result === null || result === void 0 ? void 0 : result.ok) === false && result.error === 'NOT_PLACED';
|
|
38
|
+
// ALC-452 #6: when the poll window expires without a payment outcome,
|
|
39
|
+
// return the learner to the editable cart so they can retry.
|
|
40
|
+
const isPollTimeoutPending = pollTimedOut
|
|
41
|
+
&& (!result || (!result.ok
|
|
42
|
+
&& (!result.error || TRANSIENT_PLACED_ORDER_ERRORS.has(result.error))));
|
|
37
43
|
const returnToCheckout = !!orderBiId
|
|
38
44
|
&& !placedOrder
|
|
39
|
-
&& (
|
|
40
|
-
|
|
45
|
+
&& (isNotPlaced || isPollTimeoutPending);
|
|
46
|
+
const returnedByPollTimeout = returnToCheckout && !isNotPlaced && isPollTimeoutPending;
|
|
41
47
|
let placedOrderError = null;
|
|
42
48
|
if (orderBiId && !placedOrder && !returnToCheckout && result && !result.ok) {
|
|
43
49
|
const error = (_a = result.error) !== null && _a !== void 0 ? _a : 'ORDER_READ_FAILED';
|
|
@@ -45,13 +51,6 @@ export function derivePlacedOrderView(args) {
|
|
|
45
51
|
if (!stillWaiting)
|
|
46
52
|
placedOrderError = error;
|
|
47
53
|
}
|
|
48
|
-
else if (orderBiId
|
|
49
|
-
&& !placedOrder
|
|
50
|
-
&& !returnToCheckout
|
|
51
|
-
&& pollTimedOut
|
|
52
|
-
&& !(result === null || result === void 0 ? void 0 : result.ok)) {
|
|
53
|
-
placedOrderError = (_b = result === null || result === void 0 ? void 0 : result.error) !== null && _b !== void 0 ? _b : 'PAYMENT_PENDING';
|
|
54
|
-
}
|
|
55
54
|
const stillPending = !!result
|
|
56
55
|
&& !result.ok
|
|
57
56
|
&& !!result.error
|
|
@@ -67,6 +66,7 @@ export function derivePlacedOrderView(args) {
|
|
|
67
66
|
placedOrderError,
|
|
68
67
|
awaitingPlacedOrder,
|
|
69
68
|
returnToCheckout,
|
|
69
|
+
returnedByPollTimeout,
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
72
|
//# sourceMappingURL=placedOrderPoll.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placedOrderPoll.js","sourceRoot":"","sources":["../../../src/data/hooks/placedOrderPoll.ts"],"names":[],"mappings":"AAcA,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAClD,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAM,CAAC;AAEnD,8EAA8E;AAC9E,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,cAAc;IACd,kBAAkB;IAClB,iBAAiB;IACjB,yBAAyB;CACjB,CAAC;AAEX,MAAM,6BAA6B,GAAG,IAAI,GAAG,CAAC;IAC5C,iBAAiB;IACjB,mBAAmB;CACpB,CAAC,CAAC;AAEH,MAAM,UAAU,iBAAiB,CAAC,MAAqC;IACrE,OAAO,CAAC,CAAC,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,EAAE,CAAA,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;AACxC,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,0BAA0B,CACxC,MAAqC,EACrC,SAAiB;IAEjB,IAAI,iBAAiB,CAAC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AAoB,CAAC,CAAC;IAC3C,MAAM,qBAAqB,GAAG,gBAAgB,IAAI,CAAC,WAAW,IAAI,oBAAoB,CAAC;IAEvF,IAAI,gBAAgB,GAAkB,IAAI,CAAC;IAC3C,IAAI,SAAS,IAAI,CAAC,WAAW,IAAI,CAAC,gBAAgB,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QAC3E,MAAM,KAAK,GAAG,MAAA,MAAM,CAAC,KAAK,mCAAI,mBAAmB,CAAC;QAClD,MAAM,YAAY,GAAG,6BAA6B,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC;QAC/E,IAAI,CAAC,YAAY;YAAE,gBAAgB,GAAG,KAAK,CAAC;IAC9C,CAAC;IAED,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM;WACxB,CAAC,MAAM,CAAC,EAAE;WACV,CAAC,CAAC,MAAM,CAAC,KAAK;WACd,6BAA6B,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAErD,MAAM,mBAAmB,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,WAAW,IAAI,CAAC,gBAAgB,IAAI,CAC9E,gBAAgB;WACb,SAAS;WACT,UAAU;WACV,CAAC,MAAM;WACP,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;WAC5B,YAAY,CAChB,CAAC;IAEF,OAAO;QACL,WAAW;QACX,gBAAgB;QAChB,mBAAmB;QACnB,gBAAgB;QAChB,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Polling rules for getTwouOrder after the learner pays.\n *\n * Until tPlacedAt is set, getPlacedOrder reports PAYMENT_PENDING (the payment\n * is still being confirmed, including a 3D Secure check, or the order record\n * is not readable yet). Poll for up to 30 seconds. The next read is one of:\n * - ok: true with the order — payment went through. Show confirmation.\n * bpStatus only tracks how far enrollment has got.\n * - error: NOT_PLACED — the payment did not go through. The cart is editable\n * again (tCheckout includes paymentDecline). Leave the poll and return\n * the learner to checkout.\n */\nimport type { PlacedOrder, PlacedOrderResult } from '../../types/alacarte';\n\nexport const PLACED_ORDER_POLL_INTERVAL_MS = 2000;\nexport const PLACED_ORDER_POLL_TIMEOUT_MS = 30_000;\n\n/** Paid placements. Fulfillment progress does not change the confirmation. */\nexport const PAID_PLACED_ORDER_STATUSES = [\n 'ORDER_PLACED',\n 'ORDER_FULFILLING',\n 'ORDER_COMPLETED',\n 'ORDER_FULFILMENT_FAILED',\n] as const;\n\nconst TRANSIENT_PLACED_ORDER_ERRORS = new Set([\n 'PAYMENT_PENDING',\n 'ORDER_READ_FAILED',\n]);\n\nexport function isPaidPlacedOrder(result: PlacedOrderResult | undefined): result is PlacedOrderResult & { order: PlacedOrder } {\n return !!result?.ok && !!result.order;\n}\n\n/** How long to wait before the next getTwouOrder read, or false to stop. */\nexport function placedOrderRefetchInterval(\n result: PlacedOrderResult | undefined,\n elapsedMs: number,\n): number | false {\n if (isPaidPlacedOrder(result)) return false;\n // Declined (or otherwise not placed): cart is editable again. Do not keep polling.\n if (result && !result.ok && result.error === 'NOT_PLACED') return false;\n if (elapsedMs >= PLACED_ORDER_POLL_TIMEOUT_MS) return false;\n if (!result || (result.ok && !result.order)) return PLACED_ORDER_POLL_INTERVAL_MS;\n if (!result.ok && result.error && TRANSIENT_PLACED_ORDER_ERRORS.has(result.error)) {\n return PLACED_ORDER_POLL_INTERVAL_MS;\n }\n return false;\n}\n\nexport interface PlacedOrderView {\n placedOrder: PlacedOrder | null,\n placedOrderError: string | null,\n awaitingPlacedOrder: boolean,\n /** Stop waiting and send the learner back to the editable cart.\n * Triggered by NOT_PLACED (payment failed) or a poll timeout (ALC-452 #6). */\n returnToCheckout: boolean,\n /** True when returnToCheckout was caused by the poll window expiring rather\n * than a definitive NOT_PLACED response from the backend. */\n returnedByPollTimeout: boolean,\n}\n\nexport function derivePlacedOrderView(args: {\n orderBiId: string | null,\n result: PlacedOrderResult | undefined,\n pollTimedOut: boolean,\n isLoading: boolean,\n isFetching: boolean,\n}): PlacedOrderView {\n const {\n orderBiId, result, pollTimedOut, isLoading, isFetching,\n } = args;\n const placedOrder = isPaidPlacedOrder(result) ? result.order : null;\n\n const isNotPlaced = result?.ok === false && result.error === 'NOT_PLACED';\n\n // ALC-452 #6: when the poll window expires without a payment outcome,\n // return the learner to the editable cart so they can retry.\n const isPollTimeoutPending = pollTimedOut\n && (!result || (!result.ok\n && (!result.error || TRANSIENT_PLACED_ORDER_ERRORS.has(result.error))));\n\n const returnToCheckout = !!orderBiId\n && !placedOrder\n && (isNotPlaced || isPollTimeoutPending);\n const returnedByPollTimeout = returnToCheckout && !isNotPlaced && isPollTimeoutPending;\n\n let placedOrderError: string | null = null;\n if (orderBiId && !placedOrder && !returnToCheckout && result && !result.ok) {\n const error = result.error ?? 'ORDER_READ_FAILED';\n const stillWaiting = TRANSIENT_PLACED_ORDER_ERRORS.has(error) && !pollTimedOut;\n if (!stillWaiting) placedOrderError = error;\n }\n\n const stillPending = !!result\n && !result.ok\n && !!result.error\n && TRANSIENT_PLACED_ORDER_ERRORS.has(result.error);\n\n const awaitingPlacedOrder = !!orderBiId && !placedOrder && !placedOrderError && (\n returnToCheckout\n || isLoading\n || isFetching\n || !result\n || (result.ok && !result.order)\n || stillPending\n );\n\n return {\n placedOrder,\n placedOrderError,\n awaitingPlacedOrder,\n returnToCheckout,\n returnedByPollTimeout,\n };\n}\n"]}
|
|
@@ -28,7 +28,7 @@ import { useQueryStates, useQueryState, parseAsString } from 'nuqs';
|
|
|
28
28
|
import { createAlacarteCheckoutClient } from '../../utils/alacarteCheckout';
|
|
29
29
|
import { getCouponErrorMessage, getCouponRecheckMessage, isCouponError } from '../../utils/couponErrors';
|
|
30
30
|
import { placeAlacarteOrder, startAlacartePaypalOrder, toAlacarteBillingAddress, } from '../../utils/alacartePayment';
|
|
31
|
-
import { AlacartePlaceOrderError, isSanctionsBlockedError, toPlaceOrderError } from '../../utils/placeOrderErrors';
|
|
31
|
+
import { AlacartePlaceOrderError, isSanctionsBlockedError, POLL_TIMEOUT_MESSAGE, toPlaceOrderError } from '../../utils/placeOrderErrors';
|
|
32
32
|
import { CardValidationError } from '../../utils/stripeCard';
|
|
33
33
|
import { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';
|
|
34
34
|
import { useSubscriptionCourseKeyQuery, useViaxSessionQuery, useRefreshViaxSession, viaxTokenForRejectedCall, } from './useCheckoutQueries';
|
|
@@ -870,9 +870,9 @@ export function useAlacarteCheckout(options) {
|
|
|
870
870
|
: buildProductsFromOrder(placedOrder.lines, productDetailRef.current),
|
|
871
871
|
});
|
|
872
872
|
}, [placedOrder, orderBiId, productDetailQuery.data, derived.line]);
|
|
873
|
-
// NOT_PLACED: the payment
|
|
874
|
-
//
|
|
875
|
-
//
|
|
873
|
+
// NOT_PLACED / poll timeout: the payment either failed or we couldn't confirm
|
|
874
|
+
// it in time. Reload tCheckout and drop ?order_bi_id= so the learner can
|
|
875
|
+
// retry instead of sitting on the confirmation error.
|
|
876
876
|
// The ref blocks a second reload for the same attempt. It is not cleared in
|
|
877
877
|
// cleanup — a re-run must not cancel the reload that is already in flight.
|
|
878
878
|
const returnedToCheckoutFor = useRef(null);
|
|
@@ -886,7 +886,16 @@ export function useAlacarteCheckout(options) {
|
|
|
886
886
|
if (returnedToCheckoutFor.current === orderBiId)
|
|
887
887
|
return undefined;
|
|
888
888
|
returnedToCheckoutFor.current = orderBiId;
|
|
889
|
-
|
|
889
|
+
if (placedView.returnedByPollTimeout) {
|
|
890
|
+
// ALC-452 #6: the poll window expired without a payment outcome.
|
|
891
|
+
// Show a retry-friendly error instead of the "payment interrupted"
|
|
892
|
+
// message, which implies "you haven't been charged".
|
|
893
|
+
setPlaceOrderError(POLL_TIMEOUT_MESSAGE);
|
|
894
|
+
}
|
|
895
|
+
else {
|
|
896
|
+
// NOT_PLACED: the backend confirmed the payment did not go through.
|
|
897
|
+
setPaymentInterrupted(true);
|
|
898
|
+
}
|
|
890
899
|
(() => __awaiter(this, void 0, void 0, function* () {
|
|
891
900
|
if (client) {
|
|
892
901
|
try {
|
|
@@ -903,7 +912,7 @@ export function useAlacarteCheckout(options) {
|
|
|
903
912
|
yield setOrderBiId(null);
|
|
904
913
|
}))();
|
|
905
914
|
return undefined;
|
|
906
|
-
}, [orderBiId, placedView.returnToCheckout, client, setOrderBiId, queryClient]);
|
|
915
|
+
}, [orderBiId, placedView.returnToCheckout, placedView.returnedByPollTimeout, client, setOrderBiId, queryClient]);
|
|
907
916
|
return Object.assign(Object.assign({}, derived), { couponError, couponApplying: manualUpdateMutation.isPending, applyCoupon,
|
|
908
917
|
removeCoupon, clearCouponError: () => setCouponError(null), removedCouponCode, clearRemovedCouponCode: () => setRemovedCouponCode(null), placingOrder,
|
|
909
918
|
placeOrderError,
|
|
@@ -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,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzG,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACnH,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,C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AE,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,kBAAkB;QAClB,sBAAsB;QACtB,UAAU,EACV,eAAe,EAAE,cAAc,EAC/B,gBAAgB;QAChB,kBAAkB;QAClB,iBAAiB,EACjB,oBAAoB,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EACpD,uBAAuB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAC3D,0BAA0B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,IAAI,CAAC,EACjE,2BAA2B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,KAAK,CAAC,EACnE,kBAAkB;QAClB,eAAe;QACf,gBAAgB,EAChB,cAAc,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,0CAAE,cAAc,mCAAI,IAAI,EACxD,WAAW,EACX,mBAAmB,EAAE,UAAU,CAAC,mBAAmB,EACnD,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAC7C,mBAAmB,IACnB;AACJ,CAAC;AAED,eAAe,mBAAmB,CAAC","sourcesContent":["/**\n * data/hooks/useAlacarteCheckout.ts — page-level orchestration for the à la\n * carte checkout flow:\n *\n * 1. Read a product selector (course or program) from the URL via nuqs.\n * 2. If a product is selected: check ownership (tOwnedProducts). Already\n * owned -> 'alreadyOwned'. Otherwise select it into the checkout\n * (tCheckoutSelect) and fetch its display details in parallel.\n * 3. If no product is selected: look for an existing open checkout\n * (tCheckout). Found -> 'ready'. Not found -> 'noActiveCheckout'.\n * 4. Coupon apply/remove and payment prep via tCheckoutUpdate.\n *\n * See /alacarte-checkout-api.md and /alacarte-owned-products-api.md at the\n * repo root for the underlying API contract.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useQueryStates, useQueryState, parseAsString } from 'nuqs';\nimport { createAlacarteCheckoutClient } from '../../utils/alacarteCheckout';\nimport { getCouponErrorMessage, getCouponRecheckMessage, isCouponError } from '../../utils/couponErrors';\nimport {\n placeAlacarteOrder,\n startAlacartePaypalOrder,\n toAlacarteBillingAddress,\n} from '../../utils/alacartePayment';\nimport { AlacartePlaceOrderError, isSanctionsBlockedError, toPlaceOrderError } from '../../utils/placeOrderErrors';\nimport { CardValidationError } from '../../utils/stripeCard';\nimport { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';\nimport {\n useSubscriptionCourseKeyQuery, useViaxSessionQuery, useRefreshViaxSession, viaxTokenForRejectedCall,\n} from './useCheckoutQueries';\nimport {\n courseKeyFromCourseRunKey, lmsOriginFromSessionUrl, isCourseNotFoundError,\n} from '../../utils/provision';\nimport { getCourseRunKeyFromUrl } from '../../utils/url';\nimport {\n useOwnedProductQuery, useAlacarteCheckoutQuery, useSelectProductMutation, useProductDetailQuery,\n useUpdateCheckoutMutation, usePlacedOrderQuery,\n} from './useAlacarteQueries';\nimport { alacarteKeys } from './keys';\nimport { derivePlacedOrderView } from './placedOrderPoll';\nimport { trackEvent, trackEventOnce } from '../../analytics/trackEvent';\nimport { buildProductsFromLine, buildProductsFromOrder } from '../../analytics/buildProducts';\nimport type {\n AlacarteCheckout, AlacarteCheckoutResult, AlacarteLine, AlacarteMoney, AlacartePaymentDecline,\n AlacartePriceChanged, OwnedProduct, OwnedProductResult, PlacedOrder, ProductDetail, ProductSelector,\n} from '../../types/alacarte';\nimport type { BillingInfo } from '../../types';\n\nexport type AlacartePhase = 'loading' | 'alreadyOwned' | 'noActiveCheckout' | 'notPurchasable' | 'ready' | 'error';\n\nexport type AlacarteNoticeMessageId = 'alreadyOwnedCourse' | 'alreadyOwnedProgram' | 'noActiveCheckout';\n\n/** Pure phase decision output — no action callbacks. */\nexport interface AlacartePhaseState {\n phase: AlacartePhase,\n noticeMessageId?: AlacarteNoticeMessageId,\n selector: ProductSelector,\n checkout: AlacarteCheckout | null,\n line: AlacarteLine | null,\n productDetail: ProductDetail | null,\n error: string | null,\n priceChanged: AlacartePriceChanged | null,\n priceAccepted: boolean,\n /** True when the learner already owns this product. The checkout data may\n * still be populated so the UI can render the full page under an overlay. */\n isAlreadyOwned: boolean,\n /** Product name from the owned-products query — used as a fallback when the\n * checkout line (which normally carries the name) is not available. */\n ownedProductName: string | null,\n}\n\nexport interface UseAlacarteCheckoutResult extends AlacartePhaseState {\n couponError: string | null,\n couponApplying: boolean,\n applyCoupon: (code: string) => void,\n removeCoupon: () => void,\n clearCouponError: () => void,\n /** Code of the coupon just removed, set only once the removal round-trip\n * completes — kept in sync with when the discount actually leaves the line. */\n removedCouponCode: string | null,\n clearRemovedCouponCode: () => void,\n placingOrder: boolean,\n placeOrderError: string | null,\n /** True when the learner returns to checkout without completing payment. */\n paymentInterrupted: boolean,\n /** True when the learner dismissed the Apple Pay / Google Pay sheet without paying. */\n walletPaymentCancelled: boolean,\n /**\n * Accepts price (if needed) + terms, calls tCheckoutPlaceOrder with billing,\n * confirms the card via Stripe.js, then sets ?order_bi_id= to poll getTwouOrder.\n * Fire-and-forget — errors go to placeOrderError state.\n */\n placeOrder: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => void,\n /**\n * Same as placeOrder but returns a Promise — used by ExpressCheckout\n * so the wallet sheet can await the result and call ev.complete().\n */\n placeOrderAsync: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => Promise<void>,\n /**\n * PayPal buttons `createOrder`: accepts price + terms and calls\n * tCheckoutPlaceOrder(paymentMethod: PAYPAL). Resolves the PayPal order id.\n */\n startPaypalOrder: (opts: { billing: BillingInfo }) => Promise<string>,\n /** PayPal buttons `onApprove`: tCheckoutCapturePaypalOrder, then sets ?order_bi_id=. */\n approvePaypalOrder: (paypalOrderId: string) => Promise<void>,\n /** PayPal buttons `onCancel` / `onError`: tCheckoutCancelPaypalOrder and reload tCheckout. */\n cancelPaypalOrder: (paypalOrderId: string) => Promise<void>,\n clearPlaceOrderError: () => void,\n clearPaymentInterrupted: () => void,\n /** Express Checkout Element `cancel`: the wallet sheet was closed without paying. */\n markWalletPaymentCancelled: () => void,\n clearWalletPaymentCancelled: () => void,\n /**\n * Express Checkout Element `click`: a new Apple Pay / Google Pay attempt is\n * starting, so the previous attempt's banners go (PayPal does this in\n * startPaypalOrder).\n */\n clearPaymentAlerts: () => void,\n /** True once the payment provider timed out during place order (HTTP 408 /\n * Stripe network error). The order may still go through, so further\n * attempts are blocked and the UI shows the timeout warning instead. */\n paymentTimedOut: boolean,\n /** Set when tCheckoutPlaceOrder returned SANCTIONS_BLOCKED. No charge was\n * made; the UI shows a blocking modal with a code the learner can quote\n * to support. Hardcoded until the backend returns a reference code\n * with SANCTIONS_BLOCKED. */\n sanctionsBlocked: { referenceCode: string } | null,\n /** Decline details from the last card attempt on this checkout, if any. */\n paymentDecline: AlacartePaymentDecline | null,\n /** When ?order_bi_id= is present, the placed order (or null while polling). */\n placedOrder: PlacedOrder | null,\n /**\n * True while getTwouOrder is still awaiting tPlacedAt (payment confirming,\n * including 3DS) or while we reload tCheckout after NOT_PLACED.\n */\n awaitingPlacedOrder: boolean,\n placedOrderError: string | null,\n /** ISO timestamp the order was placed (tPlacedAt, falling back to\n * biCreatedAt); null while the order-dates query hasn't resolved yet. */\n placedOrderPlacedAt: string | null,\n}\n\n/**\n * Read the product selector from the URL: course_uuid+course_run_key, or\n * program_uuid, or neither. Both course params must be present together; if a\n * course param and a program param are both present, that's\n * CONFLICTING_SELECTION.\n *\n * Legacy aliases `course_uid` / `program_uid` are still accepted; the `*_uuid`\n * names win when both are present.\n *\n * NOTE: course_run_key values look like \"course-v1:HarvardX+CS50+X\" — nuqs\n * decodes query values the standards-compliant way (literal `+` -> space),\n * same as native URLSearchParams. runKey is therefore read from the raw query\n * string via getCourseRunKeyFromUrl(), which preserves literal `+`.\n */\nexport function useProductSelector(): ProductSelector {\n const [{\n courseUuid, courseUidLegacy, runKey: nuqsRunKey, programUuid, programUidLegacy,\n }] = useQueryStates({\n courseUuid: parseAsString,\n courseUidLegacy: parseAsString,\n runKey: parseAsString,\n programUuid: parseAsString,\n programUidLegacy: parseAsString,\n }, {\n urlKeys: {\n courseUuid: 'course_uuid',\n courseUidLegacy: 'course_uid',\n runKey: 'course_run_key',\n programUuid: 'program_uuid',\n programUidLegacy: 'program_uid',\n },\n });\n const courseUid = courseUuid ?? courseUidLegacy;\n const programUid = programUuid ?? programUidLegacy;\n const runKey = nuqsRunKey ? (getCourseRunKeyFromUrl() ?? nuqsRunKey) : null;\n\n return useMemo<ProductSelector>(() => {\n const hasCourse = !!courseUid || !!runKey;\n const hasProgram = !!programUid;\n if (hasCourse && hasProgram) return { kind: 'invalid' };\n if (courseUid && runKey) return { kind: 'course', courseUid, runKey };\n if (programUid) return { kind: 'program', programUid };\n return { kind: 'none' };\n }, [courseUid, runKey, programUid]);\n}\n\n/** Reads ?discount_code= — applied to the checkout right after it's created. */\nexport function useDiscountCode(): string | null {\n const [discountCode] = useQueryState('discount_code', parseAsString);\n return discountCode;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : 'Unknown error';\n}\n\n/**\n * Build a synthetic AlacarteLine from the owned-product pricing data so the\n * checkout overlay can show subtotal / deduction / total even when the backend\n * blocks tCheckoutSelect and returns no checkout object.\n */\nfunction buildLineFromOwnedProduct(product: OwnedProduct): AlacarteLine | null {\n if (!product.price) return null;\n const { full, deduction, amountDue, currency } = product.price;\n const toMoney = (amount: number): AlacarteMoney => ({ amount, currency });\n\n if (product.kind === 'program') {\n return {\n biiId: '',\n kind: 'program',\n programId: product.productId,\n programName: product.name,\n price: toMoney(full),\n deduction: deduction ? toMoney(deduction) : null,\n ownedCourses: product.ownedCourses.map((c) => ({\n courseId: c.courseId, name: c.name, via: c.via,\n })),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n }\n\n return {\n biiId: '',\n kind: 'course',\n courseName: product.name,\n courseUid: product.productId,\n courseRunKey: '',\n seatType: 'verified',\n price: toMoney(full),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n}\n\ninterface QueryLikeState<T> {\n isLoading: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\ninterface MutationLikeState<T> {\n isIdle: boolean,\n isPending: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\nexport interface DeriveAlacartePhaseInput {\n selector: ProductSelector,\n sessionReady: boolean,\n sessionIsError: boolean,\n sessionErrorMessage?: string,\n ownedQuery: QueryLikeState<OwnedProductResult>,\n selectMutation: MutationLikeState<AlacarteCheckoutResult>,\n checkoutQuery: QueryLikeState<AlacarteCheckoutResult>,\n productDetail: ProductDetail | null,\n /** Coupon (?discount_code=) applied right after the checkout is created —\n * when it succeeds, its checkout (with the coupon's discount reflected)\n * is shown in place of the pre-coupon one from selectMutation. */\n couponMutation?: MutationLikeState<AlacarteCheckoutResult>,\n /** True when a URL discount code still needs to be applied — the phase\n * stays 'loading' until the coupon mutation resolves so the user never sees\n * the pre-discount price flash. */\n urlCouponPending?: boolean,\n /** Latest successful manual update (coupon / acceptPrice / terms). Wins over\n * select + URL coupon when present. */\n checkoutOverride?: AlacarteCheckout | null,\n /** Course-runs lookup for a course selector. Empty `elements` is notFound. */\n courseRunLookup?: { pending: boolean, notFound: boolean },\n}\n\n/**\n * Pure decision function — no hooks, no React Query/nuqs types beyond plain\n * data — so every branch combination can be unit-tested directly.\n */\nexport function deriveAlacartePhase(input: DeriveAlacartePhaseInput): AlacartePhaseState {\n const {\n selector, sessionReady, sessionIsError, sessionErrorMessage,\n ownedQuery, selectMutation, checkoutQuery, productDetail, couponMutation,\n checkoutOverride = null, urlCouponPending: urlCouponPendingProp = false,\n courseRunLookup = { pending: false, notFound: false },\n } = input;\n\n const ownedProductName = ownedQuery.data?.product?.name ?? null;\n\n const empty: Omit<AlacartePhaseState, 'phase'> = {\n selector,\n checkout: null,\n line: null,\n productDetail: null,\n error: null,\n priceChanged: null,\n priceAccepted: false,\n isAlreadyOwned: false,\n ownedProductName: null,\n };\n\n const withCheckout = (\n checkout: AlacarteCheckout | null,\n priceChanged: AlacartePriceChanged | null = null,\n isAlreadyOwned = false,\n ): AlacartePhaseState => ({\n phase: isAlreadyOwned ? 'alreadyOwned' : 'ready',\n selector,\n checkout,\n line: checkout?.line ?? null,\n productDetail,\n error: null,\n priceChanged: priceChanged ?? null,\n priceAccepted: checkout?.priceAccepted === true,\n isAlreadyOwned,\n ownedProductName: isAlreadyOwned ? ownedProductName : null,\n });\n\n if (selector.kind === 'invalid') {\n return { phase: 'error', ...empty, error: 'CONFLICTING_SELECTION' };\n }\n if (sessionIsError) {\n return { phase: 'error', ...empty, error: sessionErrorMessage ?? 'Session error' };\n }\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n\n if (hasSelector) {\n if (selector.kind === 'course' && courseRunLookup.notFound) {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (!sessionReady || ownedQuery.isLoading || courseRunLookup.pending) {\n return { phase: 'loading', ...empty };\n }\n if (ownedQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(ownedQuery.error) };\n }\n\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n if (selectMutation.isIdle || selectMutation.isPending) {\n return { phase: 'loading', ...empty };\n }\n if (selectMutation.isError) {\n return { phase: 'error', ...empty, error: errorMessage(selectMutation.error) };\n }\n if (selectMutation.data && !selectMutation.data.ok) {\n // The backend may block ALREADY_OWNED at select time. When the\n // blocked response still includes checkout data (line, pricing), use\n // it so the overlay page shows the real totals. Fall back to the\n // standalone tCheckout query, then to an empty state.\n if (selectMutation.data.blocked?.reason === 'ALREADY_OWNED') {\n const blockedCheckout = selectMutation.data.checkout\n ?? (checkoutQuery.data?.ok ? checkoutQuery.data.checkout : null);\n if (blockedCheckout) {\n return withCheckout(blockedCheckout, selectMutation.data.priceChanged ?? null, true);\n }\n // Build a synthetic line from the owned-product pricing so the\n // overlay can show subtotal / deduction / total.\n const ownedProduct = ownedQuery.data?.product;\n const syntheticLine = ownedProduct ? buildLineFromOwnedProduct(ownedProduct) : null;\n return {\n phase: 'alreadyOwned',\n noticeMessageId: selectMutation.data.blocked.kind === 'course' ? 'alreadyOwnedCourse' : 'alreadyOwnedProgram',\n ...empty,\n line: syntheticLine,\n productDetail,\n isAlreadyOwned: true,\n ownedProductName,\n };\n }\n if (selectMutation.data.blocked?.reason === 'NOT_PURCHASABLE') {\n return {\n phase: 'notPurchasable',\n ...empty,\n productDetail,\n error: selectMutation.data.blocked.kind === 'program'\n ? 'This program is not eligible for checkout.'\n : 'This course is not eligible for checkout.',\n };\n }\n const selectError = selectMutation.data.error;\n if (selectError === 'COURSE_NOT_FOUND' || selectError === 'PRODUCT_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (selectError === 'PROGRAM_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This program could not be found.',\n };\n }\n const blockedDetail = selectMutation.data.blocked?.detail;\n return {\n phase: 'error',\n ...empty,\n error: blockedDetail ?? selectError ?? 'unknown',\n };\n }\n\n // When a URL discount code still needs to be applied, stay in 'loading'\n // so the user never sees the pre-discount price flash.\n if (urlCouponPendingProp && !checkoutOverride) {\n return { phase: 'loading', ...empty };\n }\n\n // Once the coupon-apply (?discount_code=) mutation succeeds, its checkout\n // (with the discount reflected) supersedes the pre-coupon one. Manual\n // updates (override) win over both.\n const finalCheckout = checkoutOverride\n ?? (couponMutation?.data?.ok\n ? couponMutation.data.checkout\n : selectMutation.data?.checkout ?? null);\n\n // When select succeeds but the owned-products query says the learner\n // already has this product, show the full checkout under an overlay.\n return withCheckout(\n finalCheckout,\n selectMutation.data?.priceChanged\n ?? (couponMutation?.data?.ok ? couponMutation.data.priceChanged : undefined)\n ?? null,\n isOwned,\n );\n }\n\n // No selector: fall back to the learner's existing open checkout, if any.\n if (!sessionReady || checkoutQuery.isLoading) {\n return { phase: 'loading', ...empty };\n }\n if (checkoutQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(checkoutQuery.error) };\n }\n if (checkoutOverride || checkoutQuery.data?.checkout) {\n const checkout = checkoutOverride ?? checkoutQuery.data!.checkout;\n return withCheckout(checkout, checkoutQuery.data?.priceChanged ?? null);\n }\n\n return { phase: 'noActiveCheckout', noticeMessageId: 'noActiveCheckout', ...empty, isAlreadyOwned: false, ownedProductName: null };\n}\n\n/** amountDue with coupon/automatic discount removed (price − program deduction). */\nfunction amountDueWithoutDiscount(line: AlacarteLine): AlacarteMoney | null {\n if (!line.price) return null;\n if (line.kind === 'program' && line.deduction) {\n return {\n amount: line.price.amount - line.deduction.amount,\n currency: line.price.currency,\n };\n }\n return line.price;\n}\n\n/** amountDue after applying a discount on top of price (− program deduction). */\nfunction amountDueWithDiscount(\n line: AlacarteLine,\n discount: AlacarteMoney,\n): AlacarteMoney | null {\n const base = amountDueWithoutDiscount(line);\n if (!base) return null;\n return { amount: base.amount - discount.amount, currency: base.currency };\n}\n\n/**\n * Checkout to show once a coupon removal succeeds. The backend may return a\n * line that still carries the old coupon discount/amountDue, so that line is\n * patched to clear it. An automatic offer (bundle / first-order) the backend\n * re-applied once the coupon is gone is the real state and is kept as-is.\n *\n * When the backend clears the coupon but does not re-apply the automatic\n * offer that was present before the coupon, `priorCheckout` (typically the\n * pre-coupon select response) is used to restore that offer.\n */\nexport function checkoutWithoutCoupon(\n checkout: AlacarteCheckout,\n priorCheckout?: AlacarteCheckout | null,\n): AlacarteCheckout {\n const { line } = checkout;\n if (!line) {\n return { ...checkout, couponCode: null };\n }\n if (line.discountSource === 'automatic') {\n return { ...checkout, couponCode: null };\n }\n\n const priorLine = priorCheckout?.line;\n const priorAutomatic = priorLine?.discountSource === 'automatic' && priorLine.discount\n ? priorLine\n : null;\n\n const clearedLine = {\n ...line,\n discount: null,\n discountSource: null,\n discountName: null,\n amountDue: amountDueWithoutDiscount(line),\n } as typeof line;\n\n if (priorAutomatic?.discount) {\n return {\n ...checkout,\n couponCode: null,\n line: {\n ...clearedLine,\n discount: priorAutomatic.discount,\n discountSource: 'automatic',\n discountName: priorAutomatic.discountName ?? null,\n amountDue: amountDueWithDiscount(clearedLine, priorAutomatic.discount),\n } as typeof line,\n };\n }\n\n return { ...checkout, couponCode: null, line: clearedLine };\n}\n\nexport function useAlacarteCheckout(\n options: {\n apiUrl?: string,\n edxSessionUrl?: string,\n /**\n * When true, skip GET /api/subscription/course_runs/ and call Viax with a\n * course key derived from ?course_run_key= instead.\n */\n skipSubscriptionCourseRuns?: boolean,\n },\n): UseAlacarteCheckoutResult {\n const { apiUrl, edxSessionUrl, skipSubscriptionCourseRuns = false } = options;\n const queryClient = useQueryClient();\n const selector = useProductSelector();\n const discountCode = useDiscountCode();\n const [orderBiId, setOrderBiId] = useQueryState('order_bi_id', parseAsString);\n\n // Reuses the same query key as useCheckout's session exchange — React\n // Query dedupes the network call regardless of how many hooks read it.\n const sessionQuery = useViaxSessionQuery(edxSessionUrl ?? null);\n const sessionReady = !!sessionQuery.data;\n const refreshSession = useRefreshViaxSession(edxSessionUrl ?? null);\n\n // Stable ref so the onRefreshToken callback always uses the latest\n // refreshSession without recreating the client on every render.\n const refreshSessionRef = useRef(refreshSession);\n refreshSessionRef.current = refreshSession;\n\n const client = useMemo(\n () => (apiUrl ? createAlacarteCheckoutClient({\n apiUrl,\n onRefreshToken: () => viaxTokenForRejectedCall(() => refreshSessionRef.current()),\n }) : null),\n [apiUrl],\n );\n\n useEffect(() => {\n if (sessionQuery.data && client) {\n client.setToken(sessionQuery.data.viaxToken);\n }\n }, [sessionQuery.data, client]);\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n const productId = selector.kind === 'course'\n ? selector.courseUid\n : selector.kind === 'program' ? selector.programUid : null;\n\n const ownedQuery = useOwnedProductQuery(client, sessionReady && hasSelector, productId);\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n const selectMutation = useSelectProductMutation(client);\n const {\n isIdle: selectIsIdle, mutate: selectMutate, reset: selectReset,\n } = selectMutation;\n\n const courseRunKey = selector.kind === 'course' ? selector.runKey : null;\n const lmsBaseUrl = useMemo(\n () => lmsOriginFromSessionUrl(edxSessionUrl),\n [edxSessionUrl],\n );\n const courseLookupEnabled = !skipSubscriptionCourseRuns\n && selector.kind === 'course'\n && !!lmsBaseUrl\n && !!courseRunKey;\n const courseKeyQuery = useSubscriptionCourseKeyQuery(\n skipSubscriptionCourseRuns ? null : lmsBaseUrl,\n skipSubscriptionCourseRuns ? null : courseRunKey,\n );\n const courseKey = skipSubscriptionCourseRuns\n ? (courseRunKey ? courseKeyFromCourseRunKey(courseRunKey) : null)\n : (courseKeyQuery.data ?? null);\n const courseNotFound = courseLookupEnabled\n && courseKeyQuery.isError\n && isCourseNotFoundError(courseKeyQuery.error);\n\n // Mutations aren't called during render — fire once the owned-products\n // query resolves (regardless of result) so we always get checkout/line data.\n // A course is not selected until the course-runs lookup returns a course.\n // Pass viewedPrice from tOwnedProducts.amountDue (ALC-159) when available.\n useEffect(() => {\n if (!hasSelector || ownedQuery.isLoading || ownedQuery.isError) return;\n if (selector.kind === 'course' && !courseKey) return;\n if (!selectIsIdle) return;\n const amountDue = ownedQuery.data?.product?.price?.amountDue;\n selectMutate({\n selector,\n viewedPrice: typeof amountDue === 'number' ? amountDue : undefined,\n });\n }, [\n hasSelector,\n ownedQuery.isLoading,\n ownedQuery.isError,\n ownedQuery.data?.product?.price?.amountDue,\n selector,\n courseKey,\n selectIsIdle,\n selectMutate,\n ]);\n\n const productDetailEnabled = hasSelector && sessionReady && !ownedQuery.isLoading\n && (selector.kind !== 'course' || !!courseKey);\n const productDetailQuery = useProductDetailQuery(client, productDetailEnabled, selector, courseKey);\n\n // Run the checkout query when there's no selector (standard path) OR when\n // the product is already owned — after the select mutation is blocked with\n // ALREADY_OWNED the server may still have an open checkout with pricing data.\n const selectBlocked = !selectMutation.isIdle && !selectMutation.isPending\n && selectMutation.data && !selectMutation.data.ok;\n const checkoutQuery = useAlacarteCheckoutQuery(\n client,\n sessionReady && (!hasSelector || (isOwned && !!selectBlocked)),\n );\n\n // Apply ?discount_code= to the freshly-created checkout — fired once the\n // select mutation succeeds with a checkout that doesn't already carry it.\n const urlCouponMutation = useUpdateCheckoutMutation(client);\n const {\n isIdle: couponIsIdle, mutate: couponMutate, reset: urlCouponReset,\n } = urlCouponMutation;\n const createdCheckout = selectMutation.data?.ok ? selectMutation.data.checkout : null;\n\n useEffect(() => {\n if (!createdCheckout || !discountCode) return;\n if (createdCheckout.couponCode === discountCode) return;\n if (couponIsIdle) {\n couponMutate({ biId: createdCheckout.biId, couponCode: discountCode });\n }\n }, [createdCheckout, discountCode, couponIsIdle, couponMutate]);\n\n const [checkoutOverride, setCheckoutOverride] = useState<AlacarteCheckout | null>(null);\n const [couponError, setCouponError] = useState<string | null>(null);\n const [removedCouponCode, setRemovedCouponCode] = useState<string | null>(null);\n const [placeOrderError, setPlaceOrderError] = useState<string | null>(null);\n const [paymentInterrupted, setPaymentInterrupted] = useState(false);\n const [walletPaymentCancelled, setWalletPaymentCancelled] = useState(false);\n const [placingOrder, setPlacingOrder] = useState(false);\n const [paymentTimedOut, setPaymentTimedOut] = useState(false);\n const [sanctionsBlocked, setSanctionsBlocked] = useState<{ referenceCode: string } | null>(null);\n // biId of a checkout that's locked (CART_PAYMENT_PENDING) from a prior\n // tCheckoutPlaceOrder call whose Stripe confirmation was rejected\n // client-side. The next attempt must skip tCheckoutUpdate (it would fail\n // with CHECKOUT_NOT_OPEN) and go straight to tCheckoutPlaceOrder again.\n const [cardRetryBiId, setCardRetryBiId] = useState<string | null>(null);\n // Last checkout that carried an automatic offer — restored after a custom\n // coupon is removed if the backend does not re-apply it.\n const automaticBaselineRef = useRef<AlacarteCheckout | null>(null);\n // Tracks the payment method/processor used for the last place-order attempt,\n // so the Order Completed event can include them.\n const lastPaymentInfoRef = useRef<{ method: string, processor: string }>({ method: 'card', processor: 'stripe' });\n // Ref for product detail so trackEvent inside useCallback always reads the\n // latest value instead of a stale closure capture.\n const productDetailRef = useRef<ProductDetail | null>(null);\n productDetailRef.current = productDetailQuery.data ?? null;\n\n // Reset local overrides and in-flight select/coupon when the product changes\n // so viewedPrice / couponRecheck run again for the new selection.\n useEffect(() => {\n setCheckoutOverride(null);\n setCouponError(null);\n setRemovedCouponCode(null);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n setPaymentTimedOut(false);\n setSanctionsBlocked(null);\n setCardRetryBiId(null);\n automaticBaselineRef.current = null;\n selectReset();\n urlCouponReset();\n }, [selector, selectReset, urlCouponReset]);\n\n // Surface couponRecheck from product switch (section 2 of the API doc).\n useEffect(() => {\n const result = selectMutation.data;\n if (!result?.ok) return;\n const message = getCouponRecheckMessage(\n result.couponRecheck,\n result.checkout?.line?.discountSource,\n );\n if (message) setCouponError(message);\n }, [selectMutation.data]);\n\n // Surface ?discount_code= apply failures (domain ok:false or transport error).\n useEffect(() => {\n if (!discountCode) return;\n if (urlCouponMutation.isIdle || urlCouponMutation.isPending) return;\n if (urlCouponMutation.isError) {\n setCouponError(errorMessage(urlCouponMutation.error));\n return;\n }\n const result = urlCouponMutation.data;\n if (result && !result.ok) {\n setCouponError(getCouponErrorMessage(result.error, discountCode));\n }\n }, [\n discountCode,\n urlCouponMutation.isIdle,\n urlCouponMutation.isPending,\n urlCouponMutation.isError,\n urlCouponMutation.error,\n urlCouponMutation.data,\n ]);\n\n // Segment: Coupon Applied for ?discount_code= auto-apply.\n const urlCouponTrackedRef = useRef(false);\n useEffect(() => {\n if (urlCouponTrackedRef.current) return;\n const result = urlCouponMutation.data;\n if (!result?.ok || !result.checkout?.line) return;\n urlCouponTrackedRef.current = true;\n const line = result.checkout.line;\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? discountCode ?? '',\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }, [urlCouponMutation.data, discountCode, productDetailQuery.data]);\n\n const manualUpdateMutation = useUpdateCheckoutMutation(client);\n\n const placedOrderQuery = usePlacedOrderQuery(\n client,\n orderBiId,\n sessionReady && !!orderBiId,\n );\n\n const derived = deriveAlacartePhase({\n selector,\n sessionReady,\n sessionIsError: sessionQuery.isError,\n sessionErrorMessage: sessionQuery.error?.message,\n ownedQuery: {\n isLoading: ownedQuery.isLoading,\n isError: ownedQuery.isError,\n error: ownedQuery.error,\n data: ownedQuery.data,\n },\n selectMutation: {\n isIdle: selectMutation.isIdle,\n isPending: selectMutation.isPending,\n isError: selectMutation.isError,\n error: selectMutation.error,\n data: selectMutation.data,\n },\n checkoutQuery: {\n isLoading: checkoutQuery.isLoading,\n isError: checkoutQuery.isError,\n error: checkoutQuery.error,\n data: checkoutQuery.data,\n },\n productDetail: productDetailQuery.data ?? null,\n courseRunLookup: {\n pending: courseLookupEnabled && courseKeyQuery.isLoading,\n notFound: courseNotFound,\n },\n couponMutation: {\n isIdle: urlCouponMutation.isIdle,\n isPending: urlCouponMutation.isPending,\n isError: urlCouponMutation.isError,\n error: urlCouponMutation.error,\n data: urlCouponMutation.data,\n },\n checkoutOverride,\n // The URL coupon is pending only when the checkout exists, doesn't already\n // carry the code, and the mutation hasn't completed yet. When the backend\n // returns the coupon pre-applied (couponCode === discountCode) or when\n // there's no discount_code param at all, this is false from the start.\n urlCouponPending: !!discountCode\n && !!createdCheckout\n && createdCheckout.couponCode !== discountCode\n && (urlCouponMutation.isIdle || urlCouponMutation.isPending),\n });\n\n const applyCoupon = useCallback((code: string) => {\n const biId = derived.checkout?.biId;\n if (!biId || !client) return;\n const trimmed = code.trim();\n if (!trimmed) return;\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId, couponCode: trimmed },\n {\n onSuccess: (result) => {\n if (result.ok && result.checkout) {\n setCheckoutOverride(result.checkout);\n setCouponError(null);\n setRemovedCouponCode(null);\n // Segment: Coupon Applied (track_plan_id 30)\n const line = result.checkout.line;\n if (line) {\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? trimmed,\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }\n } else {\n setCouponError(getCouponErrorMessage(result.error, trimmed));\n }\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout?.biId, client, manualUpdateMutation]);\n\n // Remember the latest automatic offer so removeCoupon can restore it.\n useEffect(() => {\n const checkout = derived.checkout;\n if (\n checkout?.line?.discountSource === 'automatic'\n && checkout.line.discount\n ) {\n automaticBaselineRef.current = checkout;\n }\n }, [derived.checkout]);\n\n const removeCoupon = useCallback(() => {\n const currentCheckout = derived.checkout;\n if (!currentCheckout?.biId || !client) return;\n const removedCode = currentCheckout.couponCode?.trim() || null;\n // Prefer the remembered automatic offer; fall back to the pre-coupon\n // select response when the baseline was never captured.\n const priorCheckout = automaticBaselineRef.current\n ?? (selectMutation.data?.ok ? selectMutation.data.checkout : null);\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId: currentCheckout.biId, couponCode: '' },\n {\n onSuccess: (result) => {\n if (!result.ok) {\n setCouponError(getCouponErrorMessage(result.error));\n return;\n }\n setCheckoutOverride(\n checkoutWithoutCoupon(result.checkout ?? currentCheckout, priorCheckout),\n );\n setCouponError(null);\n if (removedCode) setRemovedCouponCode(removedCode);\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout, client, manualUpdateMutation, selectMutation.data]);\n\n const placeOrderCore = useCallback(async (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n // A timed-out attempt may still complete — never start a second one.\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'card', processor: 'stripe' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'card',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated } = await placeAlacarteOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing) => client.placeCheckoutOrder(biId, billing),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n confirmCardPayment: opts.confirmCardPayment,\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n\n setCardRetryBiId(null);\n setCheckoutOverride(updated);\n await setOrderBiId(updated.biId);\n } catch (err: unknown) {\n if (err instanceof CardValidationError) {\n // tCheckoutPlaceOrder already succeeded and locked the checkout\n // (CART_PAYMENT_PENDING); Stripe rejected the card before it ever\n // reached the backend. Next attempt must retry tCheckoutPlaceOrder\n // directly, not tCheckoutUpdate.\n setCardRetryBiId(checkout.biId);\n } else {\n setCardRetryBiId(null);\n }\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n // The timeout warning and sanctions modal replace the generic error banner.\n const errMsg = err instanceof Error ? err.message : '';\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isSanctionsBlockedError(err)) {\n // TODO: use the backend reference code once tCheckoutPlaceOrder returns one.\n setSanctionsBlocked({ referenceCode: 'REF-8F2K-40QX-1177' });\n } else if (isCouponError(errMsg)) {\n // Coupon errors show inline below the promo code input, not as a top banner.\n setCouponError(getCouponErrorMessage(errMsg));\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [derived.checkout, client, setOrderBiId, cardRetryBiId, paymentTimedOut]);\n\n /** Fire-and-forget wrapper for card payments. */\n const placeOrder = useCallback((opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n if (placingOrder || paymentTimedOut) return;\n placeOrderCore(opts).catch(() => { /* error already in state */ });\n }, [placeOrderCore, placingOrder, paymentTimedOut]);\n\n // biId of the checkout the open PayPal order belongs to — capture/cancel need it.\n const paypalBiIdRef = useRef<string | null>(null);\n\n const reloadCheckout = useCallback(async () => {\n if (!client) return;\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // The learner can still retry from the current checkout.\n }\n }, [client, queryClient]);\n\n const startPaypalOrder = useCallback(async (opts: { billing: BillingInfo }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'paypal', processor: 'paypal' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n await trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'paypal',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated, paypalOrderId } = await startAlacartePaypalOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing, paymentMethod) => (\n client.placeCheckoutOrder(biId, billing, paymentMethod)\n ),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n // tCheckoutPlaceOrder locked the checkout (CART_PAYMENT_PENDING) until\n // the PayPal order is captured or cancelled; a retry must skip tCheckoutUpdate.\n setCardRetryBiId(updated.biId);\n setCheckoutOverride(updated);\n paypalBiIdRef.current = updated.biId;\n return paypalOrderId;\n } catch (err: unknown) {\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n const paypalErrMsg = err instanceof Error ? err.message : '';\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isCouponError(paypalErrMsg)) {\n setCouponError(getCouponErrorMessage(paypalErrMsg));\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n setPlacingOrder(false);\n throw err;\n }\n }, [derived.checkout, client, cardRetryBiId, paymentTimedOut]);\n\n const cancelPaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) {\n setPlacingOrder(false);\n return;\n }\n try {\n const result = await client.cancelPaypalOrder(biId, paypalOrderId);\n if (result.ok) {\n // Settled as a failed payment — the checkout is open again.\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n setPaymentInterrupted(true);\n }\n await reloadCheckout();\n } catch {\n // Leave cardRetryBiId set so the next attempt reuses the locked checkout.\n } finally {\n setPlacingOrder(false);\n }\n }, [client, reloadCheckout]);\n\n const approvePaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) throw new Error('Checkout not ready');\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n\n try {\n const result = await client.capturePaypalOrder(biId, paypalOrderId);\n // PAYMENT_IN_PROGRESS: another capture holds the lock and will settle the\n // order — poll getTwouOrder like a COMPLETED / PENDING capture.\n const placed = result.ok\n ? result.status === 'COMPLETED' || result.status === 'PENDING'\n : result.error === 'PAYMENT_IN_PROGRESS';\n if (!placed) {\n throw toPlaceOrderError(result.ok ? 'PAYPAL_PAYMENT_DECLINED' : (result.error ?? 'CAPTURE_FAILED'));\n }\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n await setOrderBiId(biId);\n } catch (err: unknown) {\n setPlaceOrderError(errorMessage(err));\n // A declined/failed capture leaves the order settled as failed — reload so\n // the learner can retry (paymentDecline comes back on tCheckout).\n setCardRetryBiId(null);\n await reloadCheckout();\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [client, setOrderBiId, reloadCheckout]);\n\n const clearPaymentAlerts = useCallback(() => {\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n }, []);\n\n const placedView = derivePlacedOrderView({\n orderBiId,\n result: placedOrderQuery.data,\n pollTimedOut: placedOrderQuery.pollTimedOut,\n isLoading: placedOrderQuery.isLoading,\n isFetching: placedOrderQuery.isFetching,\n });\n const { placedOrder } = placedView;\n const placedOrderPlacedAt = placedOrder?.placedAt ?? null;\n\n // Segment: Order Completed (track_plan_id 32), deduplicated by order number.\n useEffect(() => {\n if (!placedOrder || !orderBiId) return;\n const { method, processor } = lastPaymentInfoRef.current;\n trackEventOnce('Order Completed', {\n checkoutType: 'a_la_carte',\n track_plan_id: 32,\n trigger_source: 'client-side',\n order_id: placedOrder.orderNumber,\n checkout_id: orderBiId,\n total: placedOrder.totals.paid,\n revenue: placedOrder.totals.paid,\n currency: placedOrder.totals.currency,\n tax: placedOrder.totals.discount === 0 && placedOrder.totals.paid === 0 ? 0 : placedOrder.totals.deduction,\n coupon: placedOrder.couponCode ?? null,\n coupon_name: [],\n discount: placedOrder.totals.discount,\n processor_name: processor,\n payment_method: method,\n products: derived.line\n ? buildProductsFromLine(derived.line, productDetailRef.current)\n : buildProductsFromOrder(placedOrder.lines, productDetailRef.current),\n });\n }, [placedOrder, orderBiId, productDetailQuery.data, derived.line]);\n\n // NOT_PLACED: the payment did not go through and the cart is editable again.\n // Reload tCheckout (it carries paymentDecline) and drop ?order_bi_id= so the\n // learner can try another card instead of sitting on the confirmation error.\n // The ref blocks a second reload for the same attempt. It is not cleared in\n // cleanup — a re-run must not cancel the reload that is already in flight.\n const returnedToCheckoutFor = useRef<string | null>(null);\n useEffect(() => {\n if (!orderBiId) {\n returnedToCheckoutFor.current = null;\n return undefined;\n }\n if (!placedView.returnToCheckout) return undefined;\n if (returnedToCheckoutFor.current === orderBiId) return undefined;\n returnedToCheckoutFor.current = orderBiId;\n setPaymentInterrupted(true);\n\n (async () => {\n if (client) {\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // Still leave the poll — the cart is editable even if this read fails.\n }\n }\n await setOrderBiId(null);\n })();\n\n return undefined;\n }, [orderBiId, placedView.returnToCheckout, client, setOrderBiId, queryClient]);\n\n return {\n ...derived,\n couponError,\n couponApplying: manualUpdateMutation.isPending,\n applyCoupon,\n removeCoupon,\n clearCouponError: () => setCouponError(null),\n removedCouponCode,\n clearRemovedCouponCode: () => setRemovedCouponCode(null),\n placingOrder,\n placeOrderError,\n paymentInterrupted,\n walletPaymentCancelled,\n placeOrder,\n placeOrderAsync: placeOrderCore,\n startPaypalOrder,\n approvePaypalOrder,\n cancelPaypalOrder,\n clearPlaceOrderError: () => setPlaceOrderError(null),\n clearPaymentInterrupted: () => setPaymentInterrupted(false),\n markWalletPaymentCancelled: () => setWalletPaymentCancelled(true),\n clearWalletPaymentCancelled: () => setWalletPaymentCancelled(false),\n clearPaymentAlerts,\n paymentTimedOut,\n sanctionsBlocked,\n paymentDecline: derived.checkout?.paymentDecline ?? null,\n placedOrder,\n awaitingPlacedOrder: placedView.awaitingPlacedOrder,\n placedOrderError: placedView.placedOrderError,\n placedOrderPlacedAt,\n };\n}\n\nexport default useAlacarteCheckout;\n"]}
|
|
1
|
+
{"version":3,"file":"useAlacarteCheckout.js","sourceRoot":"","sources":["../../../src/data/hooks/useAlacarteCheckout.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AACpE,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzG,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACzI,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACvF,OAAO,EACL,6BAA6B,EAAE,mBAAmB,EA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,SAAS,EAAE,UAAU,CAAC,gBAAgB,EAAE,UAAU,CAAC,qBAAqB,EAAE,MAAM,EAAE,YAAY,EAAE,WAAW,CAAC,CAAC,CAAC;IAElH,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,kBAAkB;QAClB,sBAAsB;QACtB,UAAU,EACV,eAAe,EAAE,cAAc,EAC/B,gBAAgB;QAChB,kBAAkB;QAClB,iBAAiB,EACjB,oBAAoB,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EACpD,uBAAuB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAC3D,0BAA0B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,IAAI,CAAC,EACjE,2BAA2B,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,KAAK,CAAC,EACnE,kBAAkB;QAClB,eAAe;QACf,gBAAgB,EAChB,cAAc,EAAE,MAAA,MAAA,OAAO,CAAC,QAAQ,0CAAE,cAAc,mCAAI,IAAI,EACxD,WAAW,EACX,mBAAmB,EAAE,UAAU,CAAC,mBAAmB,EACnD,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAC7C,mBAAmB,IACnB;AACJ,CAAC;AAED,eAAe,mBAAmB,CAAC","sourcesContent":["/**\n * data/hooks/useAlacarteCheckout.ts — page-level orchestration for the à la\n * carte checkout flow:\n *\n * 1. Read a product selector (course or program) from the URL via nuqs.\n * 2. If a product is selected: check ownership (tOwnedProducts). Already\n * owned -> 'alreadyOwned'. Otherwise select it into the checkout\n * (tCheckoutSelect) and fetch its display details in parallel.\n * 3. If no product is selected: look for an existing open checkout\n * (tCheckout). Found -> 'ready'. Not found -> 'noActiveCheckout'.\n * 4. Coupon apply/remove and payment prep via tCheckoutUpdate.\n *\n * See /alacarte-checkout-api.md and /alacarte-owned-products-api.md at the\n * repo root for the underlying API contract.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useQueryStates, useQueryState, parseAsString } from 'nuqs';\nimport { createAlacarteCheckoutClient } from '../../utils/alacarteCheckout';\nimport { getCouponErrorMessage, getCouponRecheckMessage, isCouponError } from '../../utils/couponErrors';\nimport {\n placeAlacarteOrder,\n startAlacartePaypalOrder,\n toAlacarteBillingAddress,\n} from '../../utils/alacartePayment';\nimport { AlacartePlaceOrderError, isSanctionsBlockedError, POLL_TIMEOUT_MESSAGE, toPlaceOrderError } from '../../utils/placeOrderErrors';\nimport { CardValidationError } from '../../utils/stripeCard';\nimport { isRequestTimeoutError, RequestTimeoutError } from '../../utils/timeoutErrors';\nimport {\n useSubscriptionCourseKeyQuery, useViaxSessionQuery, useRefreshViaxSession, viaxTokenForRejectedCall,\n} from './useCheckoutQueries';\nimport {\n courseKeyFromCourseRunKey, lmsOriginFromSessionUrl, isCourseNotFoundError,\n} from '../../utils/provision';\nimport { getCourseRunKeyFromUrl } from '../../utils/url';\nimport {\n useOwnedProductQuery, useAlacarteCheckoutQuery, useSelectProductMutation, useProductDetailQuery,\n useUpdateCheckoutMutation, usePlacedOrderQuery,\n} from './useAlacarteQueries';\nimport { alacarteKeys } from './keys';\nimport { derivePlacedOrderView } from './placedOrderPoll';\nimport { trackEvent, trackEventOnce } from '../../analytics/trackEvent';\nimport { buildProductsFromLine, buildProductsFromOrder } from '../../analytics/buildProducts';\nimport type {\n AlacarteCheckout, AlacarteCheckoutResult, AlacarteLine, AlacarteMoney, AlacartePaymentDecline,\n AlacartePriceChanged, OwnedProduct, OwnedProductResult, PlacedOrder, ProductDetail, ProductSelector,\n} from '../../types/alacarte';\nimport type { BillingInfo } from '../../types';\n\nexport type AlacartePhase = 'loading' | 'alreadyOwned' | 'noActiveCheckout' | 'notPurchasable' | 'ready' | 'error';\n\nexport type AlacarteNoticeMessageId = 'alreadyOwnedCourse' | 'alreadyOwnedProgram' | 'noActiveCheckout';\n\n/** Pure phase decision output — no action callbacks. */\nexport interface AlacartePhaseState {\n phase: AlacartePhase,\n noticeMessageId?: AlacarteNoticeMessageId,\n selector: ProductSelector,\n checkout: AlacarteCheckout | null,\n line: AlacarteLine | null,\n productDetail: ProductDetail | null,\n error: string | null,\n priceChanged: AlacartePriceChanged | null,\n priceAccepted: boolean,\n /** True when the learner already owns this product. The checkout data may\n * still be populated so the UI can render the full page under an overlay. */\n isAlreadyOwned: boolean,\n /** Product name from the owned-products query — used as a fallback when the\n * checkout line (which normally carries the name) is not available. */\n ownedProductName: string | null,\n}\n\nexport interface UseAlacarteCheckoutResult extends AlacartePhaseState {\n couponError: string | null,\n couponApplying: boolean,\n applyCoupon: (code: string) => void,\n removeCoupon: () => void,\n clearCouponError: () => void,\n /** Code of the coupon just removed, set only once the removal round-trip\n * completes — kept in sync with when the discount actually leaves the line. */\n removedCouponCode: string | null,\n clearRemovedCouponCode: () => void,\n placingOrder: boolean,\n placeOrderError: string | null,\n /** True when the learner returns to checkout without completing payment. */\n paymentInterrupted: boolean,\n /** True when the learner dismissed the Apple Pay / Google Pay sheet without paying. */\n walletPaymentCancelled: boolean,\n /**\n * Accepts price (if needed) + terms, calls tCheckoutPlaceOrder with billing,\n * confirms the card via Stripe.js, then sets ?order_bi_id= to poll getTwouOrder.\n * Fire-and-forget — errors go to placeOrderError state.\n */\n placeOrder: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => void,\n /**\n * Same as placeOrder but returns a Promise — used by ExpressCheckout\n * so the wallet sheet can await the result and call ev.complete().\n */\n placeOrderAsync: (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => Promise<void>,\n /**\n * PayPal buttons `createOrder`: accepts price + terms and calls\n * tCheckoutPlaceOrder(paymentMethod: PAYPAL). Resolves the PayPal order id.\n */\n startPaypalOrder: (opts: { billing: BillingInfo }) => Promise<string>,\n /** PayPal buttons `onApprove`: tCheckoutCapturePaypalOrder, then sets ?order_bi_id=. */\n approvePaypalOrder: (paypalOrderId: string) => Promise<void>,\n /** PayPal buttons `onCancel` / `onError`: tCheckoutCancelPaypalOrder and reload tCheckout. */\n cancelPaypalOrder: (paypalOrderId: string) => Promise<void>,\n clearPlaceOrderError: () => void,\n clearPaymentInterrupted: () => void,\n /** Express Checkout Element `cancel`: the wallet sheet was closed without paying. */\n markWalletPaymentCancelled: () => void,\n clearWalletPaymentCancelled: () => void,\n /**\n * Express Checkout Element `click`: a new Apple Pay / Google Pay attempt is\n * starting, so the previous attempt's banners go (PayPal does this in\n * startPaypalOrder).\n */\n clearPaymentAlerts: () => void,\n /** True once the payment provider timed out during place order (HTTP 408 /\n * Stripe network error). The order may still go through, so further\n * attempts are blocked and the UI shows the timeout warning instead. */\n paymentTimedOut: boolean,\n /** Set when tCheckoutPlaceOrder returned SANCTIONS_BLOCKED. No charge was\n * made; the UI shows a blocking modal with a code the learner can quote\n * to support. Hardcoded until the backend returns a reference code\n * with SANCTIONS_BLOCKED. */\n sanctionsBlocked: { referenceCode: string } | null,\n /** Decline details from the last card attempt on this checkout, if any. */\n paymentDecline: AlacartePaymentDecline | null,\n /** When ?order_bi_id= is present, the placed order (or null while polling). */\n placedOrder: PlacedOrder | null,\n /**\n * True while getTwouOrder is still awaiting tPlacedAt (payment confirming,\n * including 3DS) or while we reload tCheckout after NOT_PLACED.\n */\n awaitingPlacedOrder: boolean,\n placedOrderError: string | null,\n /** ISO timestamp the order was placed (tPlacedAt, falling back to\n * biCreatedAt); null while the order-dates query hasn't resolved yet. */\n placedOrderPlacedAt: string | null,\n}\n\n/**\n * Read the product selector from the URL: course_uuid+course_run_key, or\n * program_uuid, or neither. Both course params must be present together; if a\n * course param and a program param are both present, that's\n * CONFLICTING_SELECTION.\n *\n * Legacy aliases `course_uid` / `program_uid` are still accepted; the `*_uuid`\n * names win when both are present.\n *\n * NOTE: course_run_key values look like \"course-v1:HarvardX+CS50+X\" — nuqs\n * decodes query values the standards-compliant way (literal `+` -> space),\n * same as native URLSearchParams. runKey is therefore read from the raw query\n * string via getCourseRunKeyFromUrl(), which preserves literal `+`.\n */\nexport function useProductSelector(): ProductSelector {\n const [{\n courseUuid, courseUidLegacy, runKey: nuqsRunKey, programUuid, programUidLegacy,\n }] = useQueryStates({\n courseUuid: parseAsString,\n courseUidLegacy: parseAsString,\n runKey: parseAsString,\n programUuid: parseAsString,\n programUidLegacy: parseAsString,\n }, {\n urlKeys: {\n courseUuid: 'course_uuid',\n courseUidLegacy: 'course_uid',\n runKey: 'course_run_key',\n programUuid: 'program_uuid',\n programUidLegacy: 'program_uid',\n },\n });\n const courseUid = courseUuid ?? courseUidLegacy;\n const programUid = programUuid ?? programUidLegacy;\n const runKey = nuqsRunKey ? (getCourseRunKeyFromUrl() ?? nuqsRunKey) : null;\n\n return useMemo<ProductSelector>(() => {\n const hasCourse = !!courseUid || !!runKey;\n const hasProgram = !!programUid;\n if (hasCourse && hasProgram) return { kind: 'invalid' };\n if (courseUid && runKey) return { kind: 'course', courseUid, runKey };\n if (programUid) return { kind: 'program', programUid };\n return { kind: 'none' };\n }, [courseUid, runKey, programUid]);\n}\n\n/** Reads ?discount_code= — applied to the checkout right after it's created. */\nexport function useDiscountCode(): string | null {\n const [discountCode] = useQueryState('discount_code', parseAsString);\n return discountCode;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : 'Unknown error';\n}\n\n/**\n * Build a synthetic AlacarteLine from the owned-product pricing data so the\n * checkout overlay can show subtotal / deduction / total even when the backend\n * blocks tCheckoutSelect and returns no checkout object.\n */\nfunction buildLineFromOwnedProduct(product: OwnedProduct): AlacarteLine | null {\n if (!product.price) return null;\n const { full, deduction, amountDue, currency } = product.price;\n const toMoney = (amount: number): AlacarteMoney => ({ amount, currency });\n\n if (product.kind === 'program') {\n return {\n biiId: '',\n kind: 'program',\n programId: product.productId,\n programName: product.name,\n price: toMoney(full),\n deduction: deduction ? toMoney(deduction) : null,\n ownedCourses: product.ownedCourses.map((c) => ({\n courseId: c.courseId, name: c.name, via: c.via,\n })),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n }\n\n return {\n biiId: '',\n kind: 'course',\n courseName: product.name,\n courseUid: product.productId,\n courseRunKey: '',\n seatType: 'verified',\n price: toMoney(full),\n discount: null,\n amountDue: toMoney(amountDue),\n billingAddressSet: false,\n };\n}\n\ninterface QueryLikeState<T> {\n isLoading: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\ninterface MutationLikeState<T> {\n isIdle: boolean,\n isPending: boolean,\n isError: boolean,\n error?: unknown,\n data?: T,\n}\n\nexport interface DeriveAlacartePhaseInput {\n selector: ProductSelector,\n sessionReady: boolean,\n sessionIsError: boolean,\n sessionErrorMessage?: string,\n ownedQuery: QueryLikeState<OwnedProductResult>,\n selectMutation: MutationLikeState<AlacarteCheckoutResult>,\n checkoutQuery: QueryLikeState<AlacarteCheckoutResult>,\n productDetail: ProductDetail | null,\n /** Coupon (?discount_code=) applied right after the checkout is created —\n * when it succeeds, its checkout (with the coupon's discount reflected)\n * is shown in place of the pre-coupon one from selectMutation. */\n couponMutation?: MutationLikeState<AlacarteCheckoutResult>,\n /** True when a URL discount code still needs to be applied — the phase\n * stays 'loading' until the coupon mutation resolves so the user never sees\n * the pre-discount price flash. */\n urlCouponPending?: boolean,\n /** Latest successful manual update (coupon / acceptPrice / terms). Wins over\n * select + URL coupon when present. */\n checkoutOverride?: AlacarteCheckout | null,\n /** Course-runs lookup for a course selector. Empty `elements` is notFound. */\n courseRunLookup?: { pending: boolean, notFound: boolean },\n}\n\n/**\n * Pure decision function — no hooks, no React Query/nuqs types beyond plain\n * data — so every branch combination can be unit-tested directly.\n */\nexport function deriveAlacartePhase(input: DeriveAlacartePhaseInput): AlacartePhaseState {\n const {\n selector, sessionReady, sessionIsError, sessionErrorMessage,\n ownedQuery, selectMutation, checkoutQuery, productDetail, couponMutation,\n checkoutOverride = null, urlCouponPending: urlCouponPendingProp = false,\n courseRunLookup = { pending: false, notFound: false },\n } = input;\n\n const ownedProductName = ownedQuery.data?.product?.name ?? null;\n\n const empty: Omit<AlacartePhaseState, 'phase'> = {\n selector,\n checkout: null,\n line: null,\n productDetail: null,\n error: null,\n priceChanged: null,\n priceAccepted: false,\n isAlreadyOwned: false,\n ownedProductName: null,\n };\n\n const withCheckout = (\n checkout: AlacarteCheckout | null,\n priceChanged: AlacartePriceChanged | null = null,\n isAlreadyOwned = false,\n ): AlacartePhaseState => ({\n phase: isAlreadyOwned ? 'alreadyOwned' : 'ready',\n selector,\n checkout,\n line: checkout?.line ?? null,\n productDetail,\n error: null,\n priceChanged: priceChanged ?? null,\n priceAccepted: checkout?.priceAccepted === true,\n isAlreadyOwned,\n ownedProductName: isAlreadyOwned ? ownedProductName : null,\n });\n\n if (selector.kind === 'invalid') {\n return { phase: 'error', ...empty, error: 'CONFLICTING_SELECTION' };\n }\n if (sessionIsError) {\n return { phase: 'error', ...empty, error: sessionErrorMessage ?? 'Session error' };\n }\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n\n if (hasSelector) {\n if (selector.kind === 'course' && courseRunLookup.notFound) {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (!sessionReady || ownedQuery.isLoading || courseRunLookup.pending) {\n return { phase: 'loading', ...empty };\n }\n if (ownedQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(ownedQuery.error) };\n }\n\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n if (selectMutation.isIdle || selectMutation.isPending) {\n return { phase: 'loading', ...empty };\n }\n if (selectMutation.isError) {\n return { phase: 'error', ...empty, error: errorMessage(selectMutation.error) };\n }\n if (selectMutation.data && !selectMutation.data.ok) {\n // The backend may block ALREADY_OWNED at select time. When the\n // blocked response still includes checkout data (line, pricing), use\n // it so the overlay page shows the real totals. Fall back to the\n // standalone tCheckout query, then to an empty state.\n if (selectMutation.data.blocked?.reason === 'ALREADY_OWNED') {\n const blockedCheckout = selectMutation.data.checkout\n ?? (checkoutQuery.data?.ok ? checkoutQuery.data.checkout : null);\n if (blockedCheckout) {\n return withCheckout(blockedCheckout, selectMutation.data.priceChanged ?? null, true);\n }\n // Build a synthetic line from the owned-product pricing so the\n // overlay can show subtotal / deduction / total.\n const ownedProduct = ownedQuery.data?.product;\n const syntheticLine = ownedProduct ? buildLineFromOwnedProduct(ownedProduct) : null;\n return {\n phase: 'alreadyOwned',\n noticeMessageId: selectMutation.data.blocked.kind === 'course' ? 'alreadyOwnedCourse' : 'alreadyOwnedProgram',\n ...empty,\n line: syntheticLine,\n productDetail,\n isAlreadyOwned: true,\n ownedProductName,\n };\n }\n if (selectMutation.data.blocked?.reason === 'NOT_PURCHASABLE') {\n return {\n phase: 'notPurchasable',\n ...empty,\n productDetail,\n error: selectMutation.data.blocked.kind === 'program'\n ? 'This program is not eligible for checkout.'\n : 'This course is not eligible for checkout.',\n };\n }\n const selectError = selectMutation.data.error;\n if (selectError === 'COURSE_NOT_FOUND' || selectError === 'PRODUCT_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This course could not be found.',\n };\n }\n if (selectError === 'PROGRAM_NOT_FOUND') {\n return {\n phase: 'error',\n ...empty,\n error: 'This program could not be found.',\n };\n }\n const blockedDetail = selectMutation.data.blocked?.detail;\n return {\n phase: 'error',\n ...empty,\n error: blockedDetail ?? selectError ?? 'unknown',\n };\n }\n\n // When a URL discount code still needs to be applied, stay in 'loading'\n // so the user never sees the pre-discount price flash.\n if (urlCouponPendingProp && !checkoutOverride) {\n return { phase: 'loading', ...empty };\n }\n\n // Once the coupon-apply (?discount_code=) mutation succeeds, its checkout\n // (with the discount reflected) supersedes the pre-coupon one. Manual\n // updates (override) win over both.\n const finalCheckout = checkoutOverride\n ?? (couponMutation?.data?.ok\n ? couponMutation.data.checkout\n : selectMutation.data?.checkout ?? null);\n\n // When select succeeds but the owned-products query says the learner\n // already has this product, show the full checkout under an overlay.\n return withCheckout(\n finalCheckout,\n selectMutation.data?.priceChanged\n ?? (couponMutation?.data?.ok ? couponMutation.data.priceChanged : undefined)\n ?? null,\n isOwned,\n );\n }\n\n // No selector: fall back to the learner's existing open checkout, if any.\n if (!sessionReady || checkoutQuery.isLoading) {\n return { phase: 'loading', ...empty };\n }\n if (checkoutQuery.isError) {\n return { phase: 'error', ...empty, error: errorMessage(checkoutQuery.error) };\n }\n if (checkoutOverride || checkoutQuery.data?.checkout) {\n const checkout = checkoutOverride ?? checkoutQuery.data!.checkout;\n return withCheckout(checkout, checkoutQuery.data?.priceChanged ?? null);\n }\n\n return { phase: 'noActiveCheckout', noticeMessageId: 'noActiveCheckout', ...empty, isAlreadyOwned: false, ownedProductName: null };\n}\n\n/** amountDue with coupon/automatic discount removed (price − program deduction). */\nfunction amountDueWithoutDiscount(line: AlacarteLine): AlacarteMoney | null {\n if (!line.price) return null;\n if (line.kind === 'program' && line.deduction) {\n return {\n amount: line.price.amount - line.deduction.amount,\n currency: line.price.currency,\n };\n }\n return line.price;\n}\n\n/** amountDue after applying a discount on top of price (− program deduction). */\nfunction amountDueWithDiscount(\n line: AlacarteLine,\n discount: AlacarteMoney,\n): AlacarteMoney | null {\n const base = amountDueWithoutDiscount(line);\n if (!base) return null;\n return { amount: base.amount - discount.amount, currency: base.currency };\n}\n\n/**\n * Checkout to show once a coupon removal succeeds. The backend may return a\n * line that still carries the old coupon discount/amountDue, so that line is\n * patched to clear it. An automatic offer (bundle / first-order) the backend\n * re-applied once the coupon is gone is the real state and is kept as-is.\n *\n * When the backend clears the coupon but does not re-apply the automatic\n * offer that was present before the coupon, `priorCheckout` (typically the\n * pre-coupon select response) is used to restore that offer.\n */\nexport function checkoutWithoutCoupon(\n checkout: AlacarteCheckout,\n priorCheckout?: AlacarteCheckout | null,\n): AlacarteCheckout {\n const { line } = checkout;\n if (!line) {\n return { ...checkout, couponCode: null };\n }\n if (line.discountSource === 'automatic') {\n return { ...checkout, couponCode: null };\n }\n\n const priorLine = priorCheckout?.line;\n const priorAutomatic = priorLine?.discountSource === 'automatic' && priorLine.discount\n ? priorLine\n : null;\n\n const clearedLine = {\n ...line,\n discount: null,\n discountSource: null,\n discountName: null,\n amountDue: amountDueWithoutDiscount(line),\n } as typeof line;\n\n if (priorAutomatic?.discount) {\n return {\n ...checkout,\n couponCode: null,\n line: {\n ...clearedLine,\n discount: priorAutomatic.discount,\n discountSource: 'automatic',\n discountName: priorAutomatic.discountName ?? null,\n amountDue: amountDueWithDiscount(clearedLine, priorAutomatic.discount),\n } as typeof line,\n };\n }\n\n return { ...checkout, couponCode: null, line: clearedLine };\n}\n\nexport function useAlacarteCheckout(\n options: {\n apiUrl?: string,\n edxSessionUrl?: string,\n /**\n * When true, skip GET /api/subscription/course_runs/ and call Viax with a\n * course key derived from ?course_run_key= instead.\n */\n skipSubscriptionCourseRuns?: boolean,\n },\n): UseAlacarteCheckoutResult {\n const { apiUrl, edxSessionUrl, skipSubscriptionCourseRuns = false } = options;\n const queryClient = useQueryClient();\n const selector = useProductSelector();\n const discountCode = useDiscountCode();\n const [orderBiId, setOrderBiId] = useQueryState('order_bi_id', parseAsString);\n\n // Reuses the same query key as useCheckout's session exchange — React\n // Query dedupes the network call regardless of how many hooks read it.\n const sessionQuery = useViaxSessionQuery(edxSessionUrl ?? null);\n const sessionReady = !!sessionQuery.data;\n const refreshSession = useRefreshViaxSession(edxSessionUrl ?? null);\n\n // Stable ref so the onRefreshToken callback always uses the latest\n // refreshSession without recreating the client on every render.\n const refreshSessionRef = useRef(refreshSession);\n refreshSessionRef.current = refreshSession;\n\n const client = useMemo(\n () => (apiUrl ? createAlacarteCheckoutClient({\n apiUrl,\n onRefreshToken: () => viaxTokenForRejectedCall(() => refreshSessionRef.current()),\n }) : null),\n [apiUrl],\n );\n\n useEffect(() => {\n if (sessionQuery.data && client) {\n client.setToken(sessionQuery.data.viaxToken);\n }\n }, [sessionQuery.data, client]);\n\n const hasSelector = selector.kind === 'course' || selector.kind === 'program';\n const productId = selector.kind === 'course'\n ? selector.courseUid\n : selector.kind === 'program' ? selector.programUid : null;\n\n const ownedQuery = useOwnedProductQuery(client, sessionReady && hasSelector, productId);\n const isOwned = ownedQuery.data?.ok === true && ownedQuery.data.product?.status === 'full';\n\n const selectMutation = useSelectProductMutation(client);\n const {\n isIdle: selectIsIdle, mutate: selectMutate, reset: selectReset,\n } = selectMutation;\n\n const courseRunKey = selector.kind === 'course' ? selector.runKey : null;\n const lmsBaseUrl = useMemo(\n () => lmsOriginFromSessionUrl(edxSessionUrl),\n [edxSessionUrl],\n );\n const courseLookupEnabled = !skipSubscriptionCourseRuns\n && selector.kind === 'course'\n && !!lmsBaseUrl\n && !!courseRunKey;\n const courseKeyQuery = useSubscriptionCourseKeyQuery(\n skipSubscriptionCourseRuns ? null : lmsBaseUrl,\n skipSubscriptionCourseRuns ? null : courseRunKey,\n );\n const courseKey = skipSubscriptionCourseRuns\n ? (courseRunKey ? courseKeyFromCourseRunKey(courseRunKey) : null)\n : (courseKeyQuery.data ?? null);\n const courseNotFound = courseLookupEnabled\n && courseKeyQuery.isError\n && isCourseNotFoundError(courseKeyQuery.error);\n\n // Mutations aren't called during render — fire once the owned-products\n // query resolves (regardless of result) so we always get checkout/line data.\n // A course is not selected until the course-runs lookup returns a course.\n // Pass viewedPrice from tOwnedProducts.amountDue (ALC-159) when available.\n useEffect(() => {\n if (!hasSelector || ownedQuery.isLoading || ownedQuery.isError) return;\n if (selector.kind === 'course' && !courseKey) return;\n if (!selectIsIdle) return;\n const amountDue = ownedQuery.data?.product?.price?.amountDue;\n selectMutate({\n selector,\n viewedPrice: typeof amountDue === 'number' ? amountDue : undefined,\n });\n }, [\n hasSelector,\n ownedQuery.isLoading,\n ownedQuery.isError,\n ownedQuery.data?.product?.price?.amountDue,\n selector,\n courseKey,\n selectIsIdle,\n selectMutate,\n ]);\n\n const productDetailEnabled = hasSelector && sessionReady && !ownedQuery.isLoading\n && (selector.kind !== 'course' || !!courseKey);\n const productDetailQuery = useProductDetailQuery(client, productDetailEnabled, selector, courseKey);\n\n // Run the checkout query when there's no selector (standard path) OR when\n // the product is already owned — after the select mutation is blocked with\n // ALREADY_OWNED the server may still have an open checkout with pricing data.\n const selectBlocked = !selectMutation.isIdle && !selectMutation.isPending\n && selectMutation.data && !selectMutation.data.ok;\n const checkoutQuery = useAlacarteCheckoutQuery(\n client,\n sessionReady && (!hasSelector || (isOwned && !!selectBlocked)),\n );\n\n // Apply ?discount_code= to the freshly-created checkout — fired once the\n // select mutation succeeds with a checkout that doesn't already carry it.\n const urlCouponMutation = useUpdateCheckoutMutation(client);\n const {\n isIdle: couponIsIdle, mutate: couponMutate, reset: urlCouponReset,\n } = urlCouponMutation;\n const createdCheckout = selectMutation.data?.ok ? selectMutation.data.checkout : null;\n\n useEffect(() => {\n if (!createdCheckout || !discountCode) return;\n if (createdCheckout.couponCode === discountCode) return;\n if (couponIsIdle) {\n couponMutate({ biId: createdCheckout.biId, couponCode: discountCode });\n }\n }, [createdCheckout, discountCode, couponIsIdle, couponMutate]);\n\n const [checkoutOverride, setCheckoutOverride] = useState<AlacarteCheckout | null>(null);\n const [couponError, setCouponError] = useState<string | null>(null);\n const [removedCouponCode, setRemovedCouponCode] = useState<string | null>(null);\n const [placeOrderError, setPlaceOrderError] = useState<string | null>(null);\n const [paymentInterrupted, setPaymentInterrupted] = useState(false);\n const [walletPaymentCancelled, setWalletPaymentCancelled] = useState(false);\n const [placingOrder, setPlacingOrder] = useState(false);\n const [paymentTimedOut, setPaymentTimedOut] = useState(false);\n const [sanctionsBlocked, setSanctionsBlocked] = useState<{ referenceCode: string } | null>(null);\n // biId of a checkout that's locked (CART_PAYMENT_PENDING) from a prior\n // tCheckoutPlaceOrder call whose Stripe confirmation was rejected\n // client-side. The next attempt must skip tCheckoutUpdate (it would fail\n // with CHECKOUT_NOT_OPEN) and go straight to tCheckoutPlaceOrder again.\n const [cardRetryBiId, setCardRetryBiId] = useState<string | null>(null);\n // Last checkout that carried an automatic offer — restored after a custom\n // coupon is removed if the backend does not re-apply it.\n const automaticBaselineRef = useRef<AlacarteCheckout | null>(null);\n // Tracks the payment method/processor used for the last place-order attempt,\n // so the Order Completed event can include them.\n const lastPaymentInfoRef = useRef<{ method: string, processor: string }>({ method: 'card', processor: 'stripe' });\n // Ref for product detail so trackEvent inside useCallback always reads the\n // latest value instead of a stale closure capture.\n const productDetailRef = useRef<ProductDetail | null>(null);\n productDetailRef.current = productDetailQuery.data ?? null;\n\n // Reset local overrides and in-flight select/coupon when the product changes\n // so viewedPrice / couponRecheck run again for the new selection.\n useEffect(() => {\n setCheckoutOverride(null);\n setCouponError(null);\n setRemovedCouponCode(null);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n setPaymentTimedOut(false);\n setSanctionsBlocked(null);\n setCardRetryBiId(null);\n automaticBaselineRef.current = null;\n selectReset();\n urlCouponReset();\n }, [selector, selectReset, urlCouponReset]);\n\n // Surface couponRecheck from product switch (section 2 of the API doc).\n useEffect(() => {\n const result = selectMutation.data;\n if (!result?.ok) return;\n const message = getCouponRecheckMessage(\n result.couponRecheck,\n result.checkout?.line?.discountSource,\n );\n if (message) setCouponError(message);\n }, [selectMutation.data]);\n\n // Surface ?discount_code= apply failures (domain ok:false or transport error).\n useEffect(() => {\n if (!discountCode) return;\n if (urlCouponMutation.isIdle || urlCouponMutation.isPending) return;\n if (urlCouponMutation.isError) {\n setCouponError(errorMessage(urlCouponMutation.error));\n return;\n }\n const result = urlCouponMutation.data;\n if (result && !result.ok) {\n setCouponError(getCouponErrorMessage(result.error, discountCode));\n }\n }, [\n discountCode,\n urlCouponMutation.isIdle,\n urlCouponMutation.isPending,\n urlCouponMutation.isError,\n urlCouponMutation.error,\n urlCouponMutation.data,\n ]);\n\n // Segment: Coupon Applied for ?discount_code= auto-apply.\n const urlCouponTrackedRef = useRef(false);\n useEffect(() => {\n if (urlCouponTrackedRef.current) return;\n const result = urlCouponMutation.data;\n if (!result?.ok || !result.checkout?.line) return;\n urlCouponTrackedRef.current = true;\n const line = result.checkout.line;\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? discountCode ?? '',\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }, [urlCouponMutation.data, discountCode, productDetailQuery.data]);\n\n const manualUpdateMutation = useUpdateCheckoutMutation(client);\n\n const placedOrderQuery = usePlacedOrderQuery(\n client,\n orderBiId,\n sessionReady && !!orderBiId,\n );\n\n const derived = deriveAlacartePhase({\n selector,\n sessionReady,\n sessionIsError: sessionQuery.isError,\n sessionErrorMessage: sessionQuery.error?.message,\n ownedQuery: {\n isLoading: ownedQuery.isLoading,\n isError: ownedQuery.isError,\n error: ownedQuery.error,\n data: ownedQuery.data,\n },\n selectMutation: {\n isIdle: selectMutation.isIdle,\n isPending: selectMutation.isPending,\n isError: selectMutation.isError,\n error: selectMutation.error,\n data: selectMutation.data,\n },\n checkoutQuery: {\n isLoading: checkoutQuery.isLoading,\n isError: checkoutQuery.isError,\n error: checkoutQuery.error,\n data: checkoutQuery.data,\n },\n productDetail: productDetailQuery.data ?? null,\n courseRunLookup: {\n pending: courseLookupEnabled && courseKeyQuery.isLoading,\n notFound: courseNotFound,\n },\n couponMutation: {\n isIdle: urlCouponMutation.isIdle,\n isPending: urlCouponMutation.isPending,\n isError: urlCouponMutation.isError,\n error: urlCouponMutation.error,\n data: urlCouponMutation.data,\n },\n checkoutOverride,\n // The URL coupon is pending only when the checkout exists, doesn't already\n // carry the code, and the mutation hasn't completed yet. When the backend\n // returns the coupon pre-applied (couponCode === discountCode) or when\n // there's no discount_code param at all, this is false from the start.\n urlCouponPending: !!discountCode\n && !!createdCheckout\n && createdCheckout.couponCode !== discountCode\n && (urlCouponMutation.isIdle || urlCouponMutation.isPending),\n });\n\n const applyCoupon = useCallback((code: string) => {\n const biId = derived.checkout?.biId;\n if (!biId || !client) return;\n const trimmed = code.trim();\n if (!trimmed) return;\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId, couponCode: trimmed },\n {\n onSuccess: (result) => {\n if (result.ok && result.checkout) {\n setCheckoutOverride(result.checkout);\n setCouponError(null);\n setRemovedCouponCode(null);\n // Segment: Coupon Applied (track_plan_id 30)\n const line = result.checkout.line;\n if (line) {\n trackEvent('Coupon Applied', {\n checkoutType: 'a_la_carte',\n track_plan_id: 30,\n trigger_source: 'client-side',\n cart_id: result.checkout.biId,\n checkout_id: result.checkout.biId,\n coupon_name: result.checkout.couponCode ?? trimmed,\n discount: line.discount?.amount ?? 0,\n currency: line.discount?.currency ?? line.amountDue?.currency ?? 'USD',\n products: buildProductsFromLine(line, productDetailQuery.data ?? null),\n });\n }\n } else {\n setCouponError(getCouponErrorMessage(result.error, trimmed));\n }\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout?.biId, client, manualUpdateMutation]);\n\n // Remember the latest automatic offer so removeCoupon can restore it.\n useEffect(() => {\n const checkout = derived.checkout;\n if (\n checkout?.line?.discountSource === 'automatic'\n && checkout.line.discount\n ) {\n automaticBaselineRef.current = checkout;\n }\n }, [derived.checkout]);\n\n const removeCoupon = useCallback(() => {\n const currentCheckout = derived.checkout;\n if (!currentCheckout?.biId || !client) return;\n const removedCode = currentCheckout.couponCode?.trim() || null;\n // Prefer the remembered automatic offer; fall back to the pre-coupon\n // select response when the baseline was never captured.\n const priorCheckout = automaticBaselineRef.current\n ?? (selectMutation.data?.ok ? selectMutation.data.checkout : null);\n\n setCouponError(null);\n manualUpdateMutation.mutate(\n { biId: currentCheckout.biId, couponCode: '' },\n {\n onSuccess: (result) => {\n if (!result.ok) {\n setCouponError(getCouponErrorMessage(result.error));\n return;\n }\n setCheckoutOverride(\n checkoutWithoutCoupon(result.checkout ?? currentCheckout, priorCheckout),\n );\n setCouponError(null);\n if (removedCode) setRemovedCouponCode(removedCode);\n },\n onError: (err) => {\n setCouponError(errorMessage(err));\n },\n },\n );\n }, [derived.checkout, client, manualUpdateMutation, selectMutation.data]);\n\n const placeOrderCore = useCallback(async (opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n // A timed-out attempt may still complete — never start a second one.\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'card', processor: 'stripe' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'card',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated } = await placeAlacarteOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing) => client.placeCheckoutOrder(biId, billing),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n confirmCardPayment: opts.confirmCardPayment,\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n\n setCardRetryBiId(null);\n setCheckoutOverride(updated);\n await setOrderBiId(updated.biId);\n } catch (err: unknown) {\n if (err instanceof CardValidationError) {\n // tCheckoutPlaceOrder already succeeded and locked the checkout\n // (CART_PAYMENT_PENDING); Stripe rejected the card before it ever\n // reached the backend. Next attempt must retry tCheckoutPlaceOrder\n // directly, not tCheckoutUpdate.\n setCardRetryBiId(checkout.biId);\n } else {\n setCardRetryBiId(null);\n }\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n // The timeout warning and sanctions modal replace the generic error banner.\n const errMsg = err instanceof Error ? err.message : '';\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isSanctionsBlockedError(err)) {\n // TODO: use the backend reference code once tCheckoutPlaceOrder returns one.\n setSanctionsBlocked({ referenceCode: 'REF-8F2K-40QX-1177' });\n } else if (isCouponError(errMsg)) {\n // Coupon errors show inline below the promo code input, not as a top banner.\n setCouponError(getCouponErrorMessage(errMsg));\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [derived.checkout, client, setOrderBiId, cardRetryBiId, paymentTimedOut]);\n\n /** Fire-and-forget wrapper for card payments. */\n const placeOrder = useCallback((opts: {\n billing: BillingInfo,\n confirmCardPayment: (clientSecret: string) => Promise<void>,\n }) => {\n if (placingOrder || paymentTimedOut) return;\n placeOrderCore(opts).catch(() => { /* error already in state */ });\n }, [placeOrderCore, placingOrder, paymentTimedOut]);\n\n // biId of the checkout the open PayPal order belongs to — capture/cancel need it.\n const paypalBiIdRef = useRef<string | null>(null);\n\n const reloadCheckout = useCallback(async () => {\n if (!client) return;\n try {\n const fresh = await client.getCheckout();\n if (fresh.ok && fresh.checkout) {\n setCheckoutOverride(fresh.checkout);\n queryClient.setQueryData(alacarteKeys.checkout(), fresh);\n }\n } catch {\n // The learner can still retry from the current checkout.\n }\n }, [client, queryClient]);\n\n const startPaypalOrder = useCallback(async (opts: { billing: BillingInfo }) => {\n const checkout = derived.checkout;\n if (!checkout || !client) throw new Error('Checkout not ready');\n if (paymentTimedOut) throw new RequestTimeoutError();\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n lastPaymentInfoRef.current = { method: 'paypal', processor: 'paypal' };\n\n // Segment: Payment Info Entered (track_plan_id 31)\n if (checkout.line) {\n await trackEvent('Payment Info Entered', {\n checkoutType: 'a_la_carte',\n track_plan_id: 31,\n trigger_source: 'client-side',\n cart_id: checkout.biId,\n checkout_id: checkout.biId,\n currency: checkout.line.amountDue?.currency ?? 'USD',\n revenue: checkout.line.amountDue?.amount ?? 0,\n payment_method: 'paypal',\n discount: checkout.line.discount?.amount ?? 0,\n products: buildProductsFromLine(checkout.line, productDetailRef.current),\n });\n }\n\n try {\n const { checkout: updated, paypalOrderId } = await startAlacartePaypalOrder({\n updateCheckout: (args) => client.updateCheckout(args),\n placeCheckoutOrder: (biId, billing, paymentMethod) => (\n client.placeCheckoutOrder(biId, billing, paymentMethod)\n ),\n checkout,\n billing: toAlacarteBillingAddress(opts.billing),\n skipPrepare: cardRetryBiId === checkout.biId,\n });\n // tCheckoutPlaceOrder locked the checkout (CART_PAYMENT_PENDING) until\n // the PayPal order is captured or cancelled; a retry must skip tCheckoutUpdate.\n setCardRetryBiId(updated.biId);\n setCheckoutOverride(updated);\n paypalBiIdRef.current = updated.biId;\n return paypalOrderId;\n } catch (err: unknown) {\n if (err instanceof AlacartePlaceOrderError && err.checkout) {\n setCheckoutOverride(err.checkout);\n }\n const paypalErrMsg = err instanceof Error ? err.message : '';\n if (isRequestTimeoutError(err)) {\n setPaymentTimedOut(true);\n } else if (isCouponError(paypalErrMsg)) {\n setCouponError(getCouponErrorMessage(paypalErrMsg));\n } else {\n setPlaceOrderError(errorMessage(err));\n }\n setPlacingOrder(false);\n throw err;\n }\n }, [derived.checkout, client, cardRetryBiId, paymentTimedOut]);\n\n const cancelPaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) {\n setPlacingOrder(false);\n return;\n }\n try {\n const result = await client.cancelPaypalOrder(biId, paypalOrderId);\n if (result.ok) {\n // Settled as a failed payment — the checkout is open again.\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n setPaymentInterrupted(true);\n }\n await reloadCheckout();\n } catch {\n // Leave cardRetryBiId set so the next attempt reuses the locked checkout.\n } finally {\n setPlacingOrder(false);\n }\n }, [client, reloadCheckout]);\n\n const approvePaypalOrder = useCallback(async (paypalOrderId: string) => {\n const biId = paypalBiIdRef.current;\n if (!biId || !client) throw new Error('Checkout not ready');\n\n setPlacingOrder(true);\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n\n try {\n const result = await client.capturePaypalOrder(biId, paypalOrderId);\n // PAYMENT_IN_PROGRESS: another capture holds the lock and will settle the\n // order — poll getTwouOrder like a COMPLETED / PENDING capture.\n const placed = result.ok\n ? result.status === 'COMPLETED' || result.status === 'PENDING'\n : result.error === 'PAYMENT_IN_PROGRESS';\n if (!placed) {\n throw toPlaceOrderError(result.ok ? 'PAYPAL_PAYMENT_DECLINED' : (result.error ?? 'CAPTURE_FAILED'));\n }\n paypalBiIdRef.current = null;\n setCardRetryBiId(null);\n await setOrderBiId(biId);\n } catch (err: unknown) {\n setPlaceOrderError(errorMessage(err));\n // A declined/failed capture leaves the order settled as failed — reload so\n // the learner can retry (paymentDecline comes back on tCheckout).\n setCardRetryBiId(null);\n await reloadCheckout();\n throw err;\n } finally {\n setPlacingOrder(false);\n }\n }, [client, setOrderBiId, reloadCheckout]);\n\n const clearPaymentAlerts = useCallback(() => {\n setPlaceOrderError(null);\n setPaymentInterrupted(false);\n setWalletPaymentCancelled(false);\n }, []);\n\n const placedView = derivePlacedOrderView({\n orderBiId,\n result: placedOrderQuery.data,\n pollTimedOut: placedOrderQuery.pollTimedOut,\n isLoading: placedOrderQuery.isLoading,\n isFetching: placedOrderQuery.isFetching,\n });\n const { placedOrder } = placedView;\n const placedOrderPlacedAt = placedOrder?.placedAt ?? null;\n\n // Segment: Order Completed (track_plan_id 32), deduplicated by order number.\n useEffect(() => {\n if (!placedOrder || !orderBiId) return;\n const { method, processor } = lastPaymentInfoRef.current;\n trackEventOnce('Order Completed', {\n checkoutType: 'a_la_carte',\n track_plan_id: 32,\n trigger_source: 'client-side',\n order_id: placedOrder.orderNumber,\n checkout_id: orderBiId,\n total: placedOrder.totals.paid,\n revenue: placedOrder.totals.paid,\n currency: placedOrder.totals.currency,\n tax: placedOrder.totals.discount === 0 && placedOrder.totals.paid === 0 ? 0 : placedOrder.totals.deduction,\n coupon: placedOrder.couponCode ?? null,\n coupon_name: [],\n discount: placedOrder.totals.discount,\n processor_name: processor,\n payment_method: method,\n products: derived.line\n ? buildProductsFromLine(derived.line, productDetailRef.current)\n : buildProductsFromOrder(placedOrder.lines, productDetailRef.current),\n });\n }, [placedOrder, orderBiId, productDetailQuery.data, derived.line]);\n\n // NOT_PLACED / poll timeout: the payment either failed or we couldn't confirm\n // it in time. Reload tCheckout and drop ?order_bi_id= so the learner can\n // retry 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 if (placedView.returnedByPollTimeout) {\n // ALC-452 #6: the poll window expired without a payment outcome.\n // Show a retry-friendly error instead of the \"payment interrupted\"\n // message, which implies \"you haven't been charged\".\n setPlaceOrderError(POLL_TIMEOUT_MESSAGE);\n } else {\n // NOT_PLACED: the backend confirmed the payment did not go through.\n setPaymentInterrupted(true);\n }\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, placedView.returnedByPollTimeout, client, setOrderBiId, queryClient]);\n\n return {\n ...derived,\n couponError,\n couponApplying: manualUpdateMutation.isPending,\n applyCoupon,\n removeCoupon,\n clearCouponError: () => setCouponError(null),\n removedCouponCode,\n clearRemovedCouponCode: () => setRemovedCouponCode(null),\n placingOrder,\n placeOrderError,\n paymentInterrupted,\n walletPaymentCancelled,\n placeOrder,\n placeOrderAsync: placeOrderCore,\n startPaypalOrder,\n approvePaypalOrder,\n cancelPaypalOrder,\n clearPlaceOrderError: () => setPlaceOrderError(null),\n clearPaymentInterrupted: () => setPaymentInterrupted(false),\n markWalletPaymentCancelled: () => setWalletPaymentCancelled(true),\n clearWalletPaymentCancelled: () => setWalletPaymentCancelled(false),\n clearPaymentAlerts,\n paymentTimedOut,\n sanctionsBlocked,\n paymentDecline: derived.checkout?.paymentDecline ?? null,\n placedOrder,\n awaitingPlacedOrder: placedView.awaitingPlacedOrder,\n placedOrderError: placedView.placedOrderError,\n placedOrderPlacedAt,\n };\n}\n\nexport default useAlacarteCheckout;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alacarte.js","sourceRoot":"","sources":["../../src/types/alacarte.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * types/alacarte.ts — domain types for the à la carte checkout flow\n * (tCheckout / tCheckoutSelect / tCheckoutUpdate / tOwnedProducts), a separate\n * bounded context from the subscription checkout modeled in ../types.ts.\n * See alacarte-checkout-api.md and alacarte-owned-products-api.md at the repo\n * root for the full contract.\n */\nimport type { GqlRunner, CourseDetail } from '../types';\n\nexport type { GqlRunner };\n\n// --- Checkout status -----------------------------------------------------------\nexport type AlacarteStatus =\n | 'CART_CREATED'\n | 'CART_SANCTION_PASSED'\n | 'CART_PAYMENT_FAILED';\n\n// --- Money -----------------------------------------------------------------------\nexport interface AlacarteMoney {\n amount: number,\n currency: string,\n}\n\n// --- Checkout line (discriminated union on `kind`) --------------------------------\n/** Where the line discount came from — coupon code vs automatic offer (bundle / first-order). */\nexport type AlacarteDiscountSource = 'coupon' | 'automatic';\n\nexport interface AlacarteCourseLine {\n biiId: string,\n kind: 'course',\n courseName: string,\n courseUid: string,\n courseRunKey: string,\n /** The seat being bought on that run, e.g. \"verified\". */\n seatType: string | null,\n price: AlacarteMoney | null,\n /** Taken off by an applied coupon or automatic offer; absent when neither applies. */\n discount: AlacarteMoney | null,\n /** `\"coupon\"` or `\"automatic\"`; absent with no discount. */\n discountSource?: AlacarteDiscountSource | null,\n /** Discount name for the order summary, e.g. \"First order discount\". */\n discountName?: string | null,\n /** price less discount. */\n amountDue: AlacarteMoney | null,\n billingAddressSet: boolean,\n}\n\n/** Owned member course on a program checkout line (simpler than OwnedCourseRef). */\nexport interface AlacarteProgramOwnedCourse {\n courseId: string,\n name: string,\n via: 'order' | 'program' | 'enrollment',\n}\n\nexport interface AlacarteProgramLine {\n biiId: string,\n kind: 'program',\n programId: string,\n programName: string,\n price: AlacarteMoney | null,\n /** Taken off for member courses the learner already owns; absent when they own none. */\n deduction: AlacarteMoney | null,\n /**\n * Member courses the learner already owns — explains the deduction\n * (\"Already yours: …\"). Empty/absent when they own none.\n */\n ownedCourses?: AlacarteProgramOwnedCourse[] | null,\n /** Taken off by an applied coupon or automatic offer; absent when neither applies. */\n discount: AlacarteMoney | null,\n /** `\"coupon\"` or `\"automatic\"`; absent with no discount. */\n discountSource?: AlacarteDiscountSource | null,\n /** Discount name for the order summary, e.g. \"Bundle discount\". */\n discountName?: string | null,\n /** price less deduction less discount. */\n amountDue: AlacarteMoney | null,\n billingAddressSet: boolean,\n}\n\nexport type AlacarteLine = AlacarteCourseLine | AlacarteProgramLine;\n\n/** Present when the learner switches product while a coupon is on the cart. */\nexport type AlacarteCouponRecheckOutcome = 'kept' | 'rejected' | 'unverified';\n\nexport interface AlacarteCouponRecheck {\n outcome: AlacarteCouponRecheckOutcome,\n /** Coupon error code when outcome is `rejected`. */\n reason?: AlacarteErrorCode | string | null,\n}\n\n/** Last card-decline details; cleared when the next payment attempt starts. */\nexport interface AlacartePaymentDecline {\n code?: string | null,\n /** Ready to show the learner. */\n message: string,\n}\n\n/** Why a selection was refused — see section 5 of alacarte-checkout-api.md. */\nexport interface AlacarteBlocked {\n reason: 'ALREADY_OWNED' | 'NOT_PURCHASABLE',\n productId: string,\n kind: 'course' | 'program',\n /** ALREADY_OWNED only — where to send the learner (the learner dashboard). */\n route?: string,\n /** ALREADY_OWNED only. */\n ownedCourses?: OwnedCourseRef[],\n /** NOT_PURCHASABLE only — the catalog's reason, e.g. \"program_not_one_click_eligible\". */\n detail?: string,\n}\n\n/** Present when the price the learner saw (viewedPrice) differs from what checkout resolves now. */\nexport interface AlacartePriceChanged {\n viewed: AlacarteMoney,\n current: AlacarteMoney,\n}\n\n// --- Checkout envelope -------------------------------------------------------------\nexport interface AlacarteCheckout {\n biId: string,\n uid: string,\n status: AlacarteStatus,\n // Not always present in real responses (absent, not null, when no coupon was entered).\n couponCode?: string | null,\n termsAcceptedAt: string | null,\n acceptedAmount?: AlacarteMoney | null,\n priceAccepted?: boolean,\n /** True when this is the learner's first à-la-carte order (first-order offer applies). */\n firstOrder?: boolean,\n /** Present after the card was declined on the last attempt. */\n paymentDecline?: AlacartePaymentDecline | null,\n line: AlacarteLine | null,\n}\n\nexport type AlacarteErrorCode =\n | 'NOT_AUTHENTICATED'\n | 'RUN_KEY_REQUIRED'\n | 'CONFLICTING_SELECTION'\n | 'NOTHING_SELECTED'\n | 'COURSE_NOT_FOUND'\n | 'PROGRAM_NOT_FOUND'\n | 'CHECKOUT_NOT_FOUND'\n | 'CHECKOUT_NOT_YOURS'\n | 'PRODUCT_NOT_FOUND'\n // Blocked selection — details in the `blocked` envelope field.\n | 'ALREADY_OWNED'\n | 'NOT_PURCHASABLE'\n // No price can be resolved for the product right now.\n | 'PRICING_UNAVAILABLE'\n // Coupon errors — returned from tCheckoutUpdate, checkout left unchanged.\n | 'COUPON_INVALID'\n | 'COUPON_NOT_ACTIVE'\n | 'COUPON_EXPIRED'\n | 'COUPON_CAP_REACHED'\n | 'COUPON_PRODUCT_NOT_ELIGIBLE'\n | 'COUPON_PARTY_NOT_ELIGIBLE'\n | 'COUPON_PER_CUSTOMER_LIMIT'\n | 'COUPON_REJECTED'\n // tPlacedOrder errors.\n | 'ORDER_ID_REQUIRED'\n | 'ORDER_NOT_FOUND'\n | 'NOT_PLACED'\n | 'ORDER_READ_FAILED'\n // Payment is still being confirmed, including a 3D Secure check. Poll; not a failure yet.\n | 'PAYMENT_PENDING';\n\nexport interface AlacarteReplaced {\n courseName?: string,\n courseUid?: string,\n courseRunKey?: string,\n programId?: string,\n programName?: string,\n}\n\n/** Shared response envelope for tCheckout / tCheckoutSelect / tCheckoutUpdate. */\nexport interface AlacarteCheckoutResult {\n ok: boolean,\n checkout: AlacarteCheckout | null,\n replaced?: AlacarteReplaced,\n priceChanged?: AlacartePriceChanged,\n blocked?: AlacarteBlocked,\n /** Present when select switches product while a coupon was applied. */\n couponRecheck?: AlacarteCouponRecheck,\n error?: AlacarteErrorCode | string,\n}\n\n// --- Owned products ------------------------------------------------------------------\nexport type OwnedProductStatus = 'full' | 'partial' | 'none';\n\nexport interface OwnedCourseRef {\n courseId: string,\n via: 'order' | 'program' | 'enrollment',\n orderBiId?: string,\n enrollmentBiId?: string,\n programId?: string,\n name: string,\n slug: string,\n}\n\nexport interface OwnedProductPrice {\n full: number,\n deduction: number,\n amountDue: number,\n currency: string,\n}\n\nexport interface OwnedProduct {\n productId: string,\n kind: 'course' | 'program',\n name: string,\n slug: string,\n status: OwnedProductStatus,\n memberCount?: number,\n ownedCourses: OwnedCourseRef[],\n /** Pricing breakdown — available when the backend returns it (e.g. for\n * already-owned products where the checkout line is not created). */\n price?: OwnedProductPrice | null,\n}\n\nexport interface OwnedProductResult {\n ok: boolean,\n product: OwnedProduct | null,\n error?: AlacarteErrorCode | string,\n}\n\nexport interface OwnedProgramRef {\n programId: string,\n orderBiId: string,\n}\n\nexport interface OwnedProductsSummary {\n courses: OwnedCourseRef[],\n programs: OwnedProgramRef[],\n}\n\nexport interface AllOwnedProductsResult {\n ok: boolean,\n owned: OwnedProductsSummary | null,\n error?: AlacarteErrorCode | string,\n}\n\n// --- Program details (filterTwouProgram, by tProgramUuid) -----------------------------\nexport interface ProgramCourseRef {\n id: string,\n uid: string | null,\n maName: string | null,\n maDescription: string | null,\n tShortDescription: string | null,\n imageUrl: string | null,\n tBrandText: string | null,\n tOrgLogoUrl: string | null,\n tUrlCourse: string | null,\n tMarketingSlug: string | null,\n tStatus: { code: string } | null,\n}\n\nexport interface ProgramDetail {\n uid: string,\n tEffortLow: number | null,\n tEnrollmentCount: number | null,\n tMarketingSlug: string | null,\n tSkills: string[] | null,\n tFaq: string | null,\n tLevelType: string | null,\n tCourses: ProgramCourseRef[],\n}\n\n/** Course or program detail, depending on which was selected. */\nexport type ProductDetail = CourseDetail | ProgramDetail;\n\n// --- Banner details (PDP banner before checkout) ---------------------------------\n\nexport interface BannerCourseInstructor {\n tGivenName: string | null,\n tFamilyName: string | null,\n tOrganization: string | null,\n tInstructorUuid: string | null,\n tSortValue: number | null,\n}\n\nexport interface BannerCourseDetail {\n uid: string,\n id: string | null,\n maName: string,\n tEnrollmentCount: number | null,\n tAlacartePurchasable: boolean | null,\n tCourseKey: string | null,\n tShortDescription: string | null,\n maDescription: string | null,\n tBrandText: string | null,\n tOrgLogoUrl: string | null,\n imageUrl: string | null,\n tUrlCourse: string | null,\n tMarketingSlug: string | null,\n tLevelType: string | null,\n tPacingType: string | null,\n tDurationLow: number | null,\n tDurationHigh: number | null,\n tDurationUnit: string | null,\n tEffortLow: number | null,\n tEffortHigh: number | null,\n tEffortUnit: string | null,\n tLanguage: string | null,\n tExpectedLearningItems: string | null,\n tSkills: string[] | null,\n tPrerequisites: string | null,\n tSyllabus: string | null,\n tFaq: string | null,\n tTestimonials: string | null,\n tTranscriptLanguages: string[] | null,\n tInstructors: BannerCourseInstructor[],\n}\n\nexport interface BannerProgramCourse {\n id: string,\n uid: string | null,\n maName: string | null,\n tShortDescription: string | null,\n maDescription: string | null,\n tBrandText: string | null,\n tOrgLogoUrl: string | null,\n tCourseKey: string | null,\n imageUrl: string | null,\n tUrlCourse: string | null,\n tMarketingSlug: string | null,\n tStatus: { code: string } | null,\n}\n\nexport interface BannerProgramDetail {\n uid: string,\n tEffortLow: number | null,\n tEnrollmentCount: number | null,\n tMarketingSlug: string | null,\n tAlacartePurchasable: boolean | null,\n tSkills: string[] | null,\n tFaq: string | null,\n tLevelType: string | null,\n imageUrl: string | null,\n tBannerImageUrl: string | null,\n tCourses: BannerProgramCourse[],\n}\n\nexport type BannerData =\n | { kind: 'course', data: BannerCourseDetail }\n | { kind: 'program', data: BannerProgramDetail };\n\n// --- Placed order (getTwouOrder, confirmation page) ------------------------------------\nexport interface PlacedOrderAmounts {\n price: number,\n deduction: number,\n discount: number,\n paid: number,\n currency: string,\n}\n\nexport interface PlacedOrderLine {\n lineId: string,\n kind: 'course' | 'program',\n productId?: string,\n productUid?: string,\n name: string,\n /** Present on course lines and on each course line of a program order. */\n courseRunKey?: string | null,\n seatType?: string | null,\n /** Set on every line of a program order (one line per course bought). */\n programId?: string,\n bundleRef?: string,\n discountRuleId?: string,\n amounts: PlacedOrderAmounts,\n}\n\nexport interface PlacedOrder {\n orderId: string,\n /** `biId` from getTwouOrder — the order number shown on the confirmation page. */\n orderNumber: string,\n status: string,\n couponCode: string | null,\n /** `card` covers Stripe cards and Apple Pay / Google Pay (named in `wallet`); `paypal` has no card. */\n paymentMethod: { type: 'card' | 'paypal', brand?: string, last4?: string, wallet?: string } | null,\n lines: PlacedOrderLine[],\n totals: PlacedOrderAmounts,\n /** ISO timestamp from tPlacedAt, falling back to biCreatedAt. */\n placedAt?: string | null,\n}\n\nexport interface PlacedOrderResult {\n ok: boolean,\n order: PlacedOrder | null,\n error?: AlacarteErrorCode | string,\n}\n\n/** Billing for tCheckoutPlaceOrder. Only `country` (ISO-2) is required;\n * name/line/city/etc. are optional when the UI doesn't collect a full address. */\nexport interface AlacarteBillingAddress {\n country: string,\n firstName?: string,\n lastName?: string,\n line1?: string,\n line2?: string,\n city?: string,\n state?: string,\n postcode?: string,\n}\n\n/** Stripe payment details returned by a successful tCheckoutPlaceOrder. */\nexport interface AlacartePlaceOrderPayment {\n clientSecret: string,\n paymentIntentId: string,\n /** Amount in cents. */\n amount: number,\n currency: string,\n}\n\nexport type AlacartePlaceOrderErrorCode =\n | 'TERMS_NOT_ACCEPTED'\n | 'PRICE_NOT_ACCEPTED'\n | 'BILLING_ADDRESS_REQUIRED'\n | 'SANCTIONS_BLOCKED'\n | 'COUPON_UNAVAILABLE'\n | 'PAYMENT_NOT_STARTED'\n | 'CHECKOUT_NOT_FOUND'\n | 'NOT_AUTHENTICATED';\n\n/** PayPal order returned by tCheckoutPlaceOrder(paymentMethod: \"PAYPAL\"). */\nexport interface AlacartePaypalPayment {\n paypalOrderId: string,\n /** Amount in cents. */\n amount: number,\n currency: string,\n}\n\n/** paymentMethod argument of tCheckoutPlaceOrder — omitted means STRIPE. */\nexport type AlacartePaymentMethod = 'STRIPE' | 'PAYPAL';\n\n/** tCheckoutCapturePaypalOrder / tCheckoutCancelPaypalOrder response. */\nexport interface AlacartePaypalOrderResult {\n ok: boolean,\n status?: 'COMPLETED' | 'PENDING' | 'FAILED' | 'CANCELLED',\n orderNumber?: string,\n error?: string,\n}\n\n/** Immediate placement from tCheckoutPlaceOrder (e.g. $0 — no PaymentIntent). */\nexport interface AlacartePlacedOrderRef {\n orderNumber: string,\n}\n\nexport interface AlacartePlaceOrderApiResult {\n ok: boolean,\n payment: AlacartePlaceOrderPayment | null,\n /** Set instead of `payment` when placed with paymentMethod \"PAYPAL\". */\n paypal?: AlacartePaypalPayment | null,\n /** Set when the order was placed immediately without a Stripe/PayPal charge. */\n placed?: AlacartePlacedOrderRef | null,\n /** True when amount due is 0 and no payment processor was started. */\n noChargeRequired?: boolean,\n /** Present on some failures (e.g. PRICE_NOT_ACCEPTED, COUPON_UNAVAILABLE). */\n checkout?: AlacarteCheckout | null,\n error?: AlacartePlaceOrderErrorCode | string,\n}\n\n// --- Product selector (derived from query params) --------------------------------------\nexport type ProductSelector =\n | { kind: 'course', courseUid: string, runKey: string }\n | { kind: 'program', programUid: string }\n | { kind: 'invalid' }\n | { kind: 'none' };\n\n// --- Client surface --------------------------------------------------------------------\nexport interface AlacarteCheckoutClient {\n gql: GqlRunner,\n setToken: (token: string) => void,\n getCheckout: () => Promise<AlacarteCheckoutResult>,\n /** viewedPrice: the amount the learner saw on the page before checkout (USD, before any coupon). */\n selectCourse: (courseUid: string, runKey: string, viewedPrice?: number) => Promise<AlacarteCheckoutResult>,\n selectProgram: (programUid: string, viewedPrice?: number) => Promise<AlacarteCheckoutResult>,\n updateCheckout: (args: {\n biId?: string, couponCode?: string, termsAccepted?: boolean, acceptPrice?: boolean,\n }) => Promise<AlacarteCheckoutResult>,\n getOwnedProduct: (productId: string) => Promise<OwnedProductResult>,\n getAllOwnedProducts: () => Promise<AllOwnedProductsResult>,\n getProgramDetail: (programUid: string) => Promise<ProgramDetail | null>,\n getCourseDetail: (courseKey: string) => Promise<CourseDetail | null>,\n getPlacedOrder: (biId: string) => Promise<PlacedOrderResult>,\n /** One-call place order — returns Stripe client secret (section 5a). */\n placeCheckoutOrder: (\n biId: string,\n billing?: AlacarteBillingAddress,\n paymentMethod?: AlacartePaymentMethod,\n ) => Promise<AlacartePlaceOrderApiResult>,\n capturePaypalOrder: (biId: string, paypalOrderId: string) => Promise<AlacartePaypalOrderResult>,\n cancelPaypalOrder: (biId: string, paypalOrderId: string) => Promise<AlacartePaypalOrderResult>,\n}\n"]}
|
|
1
|
+
{"version":3,"file":"alacarte.js","sourceRoot":"","sources":["../../src/types/alacarte.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * types/alacarte.ts — domain types for the à la carte checkout flow\n * (tCheckout / tCheckoutSelect / tCheckoutUpdate / tOwnedProducts), a separate\n * bounded context from the subscription checkout modeled in ../types.ts.\n * See alacarte-checkout-api.md and alacarte-owned-products-api.md at the repo\n * root for the full contract.\n */\nimport type { GqlRunner, CourseDetail } from '../types';\n\nexport type { GqlRunner };\n\n// --- Checkout status -----------------------------------------------------------\nexport type AlacarteStatus =\n | 'CART_CREATED'\n | 'CART_SANCTION_PASSED'\n | 'CART_PAYMENT_FAILED';\n\n// --- Money -----------------------------------------------------------------------\nexport interface AlacarteMoney {\n amount: number,\n currency: string,\n}\n\n// --- Checkout line (discriminated union on `kind`) --------------------------------\n/** Where the line discount came from — coupon code vs automatic offer (bundle / first-order). */\nexport type AlacarteDiscountSource = 'coupon' | 'automatic';\n\nexport interface AlacarteCourseLine {\n biiId: string,\n kind: 'course',\n courseName: string,\n courseUid: string,\n courseRunKey: string,\n /** The seat being bought on that run, e.g. \"verified\". */\n seatType: string | null,\n price: AlacarteMoney | null,\n /** Taken off by an applied coupon or automatic offer; absent when neither applies. */\n discount: AlacarteMoney | null,\n /** `\"coupon\"` or `\"automatic\"`; absent with no discount. */\n discountSource?: AlacarteDiscountSource | null,\n /** Discount name for the order summary, e.g. \"First order discount\". */\n discountName?: string | null,\n /** price less discount. */\n amountDue: AlacarteMoney | null,\n billingAddressSet: boolean,\n}\n\n/** Owned member course on a program checkout line (simpler than OwnedCourseRef). */\nexport interface AlacarteProgramOwnedCourse {\n courseId: string,\n name: string,\n via: 'order' | 'program' | 'enrollment',\n}\n\nexport interface AlacarteProgramLine {\n biiId: string,\n kind: 'program',\n programId: string,\n programName: string,\n price: AlacarteMoney | null,\n /** Taken off for member courses the learner already owns; absent when they own none. */\n deduction: AlacarteMoney | null,\n /**\n * Member courses the learner already owns — explains the deduction\n * (\"Already yours: …\"). Empty/absent when they own none.\n */\n ownedCourses?: AlacarteProgramOwnedCourse[] | null,\n /** Taken off by an applied coupon or automatic offer; absent when neither applies. */\n discount: AlacarteMoney | null,\n /** `\"coupon\"` or `\"automatic\"`; absent with no discount. */\n discountSource?: AlacarteDiscountSource | null,\n /** Discount name for the order summary, e.g. \"Bundle discount\". */\n discountName?: string | null,\n /** price less deduction less discount. */\n amountDue: AlacarteMoney | null,\n billingAddressSet: boolean,\n}\n\nexport type AlacarteLine = AlacarteCourseLine | AlacarteProgramLine;\n\n/** Present when the learner switches product while a coupon is on the cart. */\nexport type AlacarteCouponRecheckOutcome = 'kept' | 'rejected' | 'unverified';\n\nexport interface AlacarteCouponRecheck {\n outcome: AlacarteCouponRecheckOutcome,\n /** Coupon error code when outcome is `rejected`. */\n reason?: AlacarteErrorCode | string | null,\n}\n\n/** Last card-decline details; cleared when the next payment attempt starts. */\nexport interface AlacartePaymentDecline {\n code?: string | null,\n /** Ready to show the learner. */\n message: string,\n}\n\n/** Why a selection was refused — see section 5 of alacarte-checkout-api.md. */\nexport interface AlacarteBlocked {\n reason: 'ALREADY_OWNED' | 'NOT_PURCHASABLE',\n productId: string,\n kind: 'course' | 'program',\n /** ALREADY_OWNED only — where to send the learner (the learner dashboard). */\n route?: string,\n /** ALREADY_OWNED only. */\n ownedCourses?: OwnedCourseRef[],\n /** NOT_PURCHASABLE only — the catalog's reason, e.g. \"program_not_one_click_eligible\". */\n detail?: string,\n}\n\n/** Present when the price the learner saw (viewedPrice) differs from what checkout resolves now. */\nexport interface AlacartePriceChanged {\n viewed: AlacarteMoney,\n current: AlacarteMoney,\n}\n\n// --- Checkout envelope -------------------------------------------------------------\nexport interface AlacarteCheckout {\n biId: string,\n uid: string,\n status: AlacarteStatus,\n // Not always present in real responses (absent, not null, when no coupon was entered).\n couponCode?: string | null,\n termsAcceptedAt: string | null,\n acceptedAmount?: AlacarteMoney | null,\n priceAccepted?: boolean,\n /** True when this is the learner's first à-la-carte order (first-order offer applies). */\n firstOrder?: boolean,\n /** Present after the card was declined on the last attempt. */\n paymentDecline?: AlacartePaymentDecline | null,\n line: AlacarteLine | null,\n}\n\nexport type AlacarteErrorCode =\n | 'NOT_AUTHENTICATED'\n | 'RUN_KEY_REQUIRED'\n | 'CONFLICTING_SELECTION'\n | 'NOTHING_SELECTED'\n | 'COURSE_NOT_FOUND'\n | 'PROGRAM_NOT_FOUND'\n | 'CHECKOUT_NOT_FOUND'\n | 'CHECKOUT_NOT_YOURS'\n | 'PRODUCT_NOT_FOUND'\n // Blocked selection — details in the `blocked` envelope field.\n | 'ALREADY_OWNED'\n | 'NOT_PURCHASABLE'\n // No price can be resolved for the product right now.\n | 'PRICING_UNAVAILABLE'\n // Coupon errors — returned from tCheckoutUpdate, checkout left unchanged.\n | 'COUPON_INVALID'\n | 'COUPON_NOT_ACTIVE'\n | 'COUPON_EXPIRED'\n | 'COUPON_CAP_REACHED'\n | 'COUPON_PRODUCT_NOT_ELIGIBLE'\n | 'COUPON_PARTY_NOT_ELIGIBLE'\n | 'COUPON_PER_CUSTOMER_LIMIT'\n | 'COUPON_REJECTED'\n // getTwouOrder (placed order) errors.\n | 'ORDER_ID_REQUIRED'\n | 'ORDER_NOT_FOUND'\n | 'NOT_PLACED'\n | 'ORDER_READ_FAILED'\n // Payment is still being confirmed, including a 3D Secure check. Poll; not a failure yet.\n | 'PAYMENT_PENDING';\n\nexport interface AlacarteReplaced {\n courseName?: string,\n courseUid?: string,\n courseRunKey?: string,\n programId?: string,\n programName?: string,\n}\n\n/** Shared response envelope for tCheckout / tCheckoutSelect / tCheckoutUpdate. */\nexport interface AlacarteCheckoutResult {\n ok: boolean,\n checkout: AlacarteCheckout | null,\n replaced?: AlacarteReplaced,\n priceChanged?: AlacartePriceChanged,\n blocked?: AlacarteBlocked,\n /** Present when select switches product while a coupon was applied. */\n couponRecheck?: AlacarteCouponRecheck,\n error?: AlacarteErrorCode | string,\n}\n\n// --- Owned products ------------------------------------------------------------------\nexport type OwnedProductStatus = 'full' | 'partial' | 'none';\n\nexport interface OwnedCourseRef {\n courseId: string,\n via: 'order' | 'program' | 'enrollment',\n orderBiId?: string,\n enrollmentBiId?: string,\n programId?: string,\n name: string,\n slug: string,\n}\n\nexport interface OwnedProductPrice {\n full: number,\n deduction: number,\n amountDue: number,\n currency: string,\n}\n\nexport interface OwnedProduct {\n productId: string,\n kind: 'course' | 'program',\n name: string,\n slug: string,\n status: OwnedProductStatus,\n memberCount?: number,\n ownedCourses: OwnedCourseRef[],\n /** Pricing breakdown — available when the backend returns it (e.g. for\n * already-owned products where the checkout line is not created). */\n price?: OwnedProductPrice | null,\n}\n\nexport interface OwnedProductResult {\n ok: boolean,\n product: OwnedProduct | null,\n error?: AlacarteErrorCode | string,\n}\n\nexport interface OwnedProgramRef {\n programId: string,\n orderBiId: string,\n}\n\nexport interface OwnedProductsSummary {\n courses: OwnedCourseRef[],\n programs: OwnedProgramRef[],\n}\n\nexport interface AllOwnedProductsResult {\n ok: boolean,\n owned: OwnedProductsSummary | null,\n error?: AlacarteErrorCode | string,\n}\n\n// --- Program details (filterTwouProgram, by tProgramUuid) -----------------------------\nexport interface ProgramCourseRef {\n id: string,\n uid: string | null,\n maName: string | null,\n maDescription: string | null,\n tShortDescription: string | null,\n imageUrl: string | null,\n tBrandText: string | null,\n tOrgLogoUrl: string | null,\n tUrlCourse: string | null,\n tMarketingSlug: string | null,\n tStatus: { code: string } | null,\n}\n\nexport interface ProgramDetail {\n uid: string,\n tEffortLow: number | null,\n tEnrollmentCount: number | null,\n tMarketingSlug: string | null,\n tSkills: string[] | null,\n tFaq: string | null,\n tLevelType: string | null,\n tCourses: ProgramCourseRef[],\n}\n\n/** Course or program detail, depending on which was selected. */\nexport type ProductDetail = CourseDetail | ProgramDetail;\n\n// --- Banner details (PDP banner before checkout) ---------------------------------\n\nexport interface BannerCourseInstructor {\n tGivenName: string | null,\n tFamilyName: string | null,\n tOrganization: string | null,\n tInstructorUuid: string | null,\n tSortValue: number | null,\n}\n\nexport interface BannerCourseDetail {\n uid: string,\n id: string | null,\n maName: string,\n tEnrollmentCount: number | null,\n tAlacartePurchasable: boolean | null,\n tCourseKey: string | null,\n tShortDescription: string | null,\n maDescription: string | null,\n tBrandText: string | null,\n tOrgLogoUrl: string | null,\n imageUrl: string | null,\n tUrlCourse: string | null,\n tMarketingSlug: string | null,\n tLevelType: string | null,\n tPacingType: string | null,\n tDurationLow: number | null,\n tDurationHigh: number | null,\n tDurationUnit: string | null,\n tEffortLow: number | null,\n tEffortHigh: number | null,\n tEffortUnit: string | null,\n tLanguage: string | null,\n tExpectedLearningItems: string | null,\n tSkills: string[] | null,\n tPrerequisites: string | null,\n tSyllabus: string | null,\n tFaq: string | null,\n tTestimonials: string | null,\n tTranscriptLanguages: string[] | null,\n tInstructors: BannerCourseInstructor[],\n}\n\nexport interface BannerProgramCourse {\n id: string,\n uid: string | null,\n maName: string | null,\n tShortDescription: string | null,\n maDescription: string | null,\n tBrandText: string | null,\n tOrgLogoUrl: string | null,\n tCourseKey: string | null,\n imageUrl: string | null,\n tUrlCourse: string | null,\n tMarketingSlug: string | null,\n tStatus: { code: string } | null,\n}\n\nexport interface BannerProgramDetail {\n uid: string,\n tEffortLow: number | null,\n tEnrollmentCount: number | null,\n tMarketingSlug: string | null,\n tAlacartePurchasable: boolean | null,\n tSkills: string[] | null,\n tFaq: string | null,\n tLevelType: string | null,\n imageUrl: string | null,\n tBannerImageUrl: string | null,\n tCourses: BannerProgramCourse[],\n}\n\nexport type BannerData =\n | { kind: 'course', data: BannerCourseDetail }\n | { kind: 'program', data: BannerProgramDetail };\n\n// --- Placed order (getTwouOrder, confirmation page) ------------------------------------\nexport interface PlacedOrderAmounts {\n price: number,\n deduction: number,\n discount: number,\n paid: number,\n currency: string,\n}\n\nexport interface PlacedOrderLine {\n lineId: string,\n kind: 'course' | 'program',\n productId?: string,\n productUid?: string,\n name: string,\n /** Present on course lines and on each course line of a program order. */\n courseRunKey?: string | null,\n seatType?: string | null,\n /** Set on every line of a program order (one line per course bought). */\n programId?: string,\n bundleRef?: string,\n discountRuleId?: string,\n amounts: PlacedOrderAmounts,\n}\n\nexport interface PlacedOrder {\n orderId: string,\n /** `biId` from getTwouOrder — the order number shown on the confirmation page. */\n orderNumber: string,\n status: string,\n couponCode: string | null,\n /** `card` covers Stripe cards and Apple Pay / Google Pay (named in `wallet`); `paypal` has no card. */\n paymentMethod: { type: 'card' | 'paypal', brand?: string, last4?: string, wallet?: string } | null,\n lines: PlacedOrderLine[],\n totals: PlacedOrderAmounts,\n /** ISO timestamp from tPlacedAt, falling back to biCreatedAt. */\n placedAt?: string | null,\n}\n\nexport interface PlacedOrderResult {\n ok: boolean,\n order: PlacedOrder | null,\n error?: AlacarteErrorCode | string,\n}\n\n/** Billing for tCheckoutPlaceOrder. Only `country` (ISO-2) is required;\n * name/line/city/etc. are optional when the UI doesn't collect a full address. */\nexport interface AlacarteBillingAddress {\n country: string,\n firstName?: string,\n lastName?: string,\n line1?: string,\n line2?: string,\n city?: string,\n state?: string,\n postcode?: string,\n}\n\n/** Stripe payment details returned by a successful tCheckoutPlaceOrder. */\nexport interface AlacartePlaceOrderPayment {\n clientSecret: string,\n paymentIntentId: string,\n /** Amount in cents. */\n amount: number,\n currency: string,\n}\n\nexport type AlacartePlaceOrderErrorCode =\n | 'TERMS_NOT_ACCEPTED'\n | 'PRICE_NOT_ACCEPTED'\n | 'BILLING_ADDRESS_REQUIRED'\n | 'SANCTIONS_BLOCKED'\n | 'COUPON_UNAVAILABLE'\n | 'PAYMENT_NOT_STARTED'\n | 'CHECKOUT_NOT_FOUND'\n | 'NOT_AUTHENTICATED';\n\n/** PayPal order returned by tCheckoutPlaceOrder(paymentMethod: \"PAYPAL\"). */\nexport interface AlacartePaypalPayment {\n paypalOrderId: string,\n /** Amount in cents. */\n amount: number,\n currency: string,\n}\n\n/** paymentMethod argument of tCheckoutPlaceOrder — omitted means STRIPE. */\nexport type AlacartePaymentMethod = 'STRIPE' | 'PAYPAL';\n\n/** tCheckoutCapturePaypalOrder / tCheckoutCancelPaypalOrder response. */\nexport interface AlacartePaypalOrderResult {\n ok: boolean,\n status?: 'COMPLETED' | 'PENDING' | 'FAILED' | 'CANCELLED',\n orderNumber?: string,\n error?: string,\n}\n\n/** Immediate placement from tCheckoutPlaceOrder (e.g. $0 — no PaymentIntent). */\nexport interface AlacartePlacedOrderRef {\n orderNumber: string,\n}\n\nexport interface AlacartePlaceOrderApiResult {\n ok: boolean,\n payment: AlacartePlaceOrderPayment | null,\n /** Set instead of `payment` when placed with paymentMethod \"PAYPAL\". */\n paypal?: AlacartePaypalPayment | null,\n /** Set when the order was placed immediately without a Stripe/PayPal charge. */\n placed?: AlacartePlacedOrderRef | null,\n /** True when amount due is 0 and no payment processor was started. */\n noChargeRequired?: boolean,\n /** Present on some failures (e.g. PRICE_NOT_ACCEPTED, COUPON_UNAVAILABLE). */\n checkout?: AlacarteCheckout | null,\n error?: AlacartePlaceOrderErrorCode | string,\n}\n\n// --- Product selector (derived from query params) --------------------------------------\nexport type ProductSelector =\n | { kind: 'course', courseUid: string, runKey: string }\n | { kind: 'program', programUid: string }\n | { kind: 'invalid' }\n | { kind: 'none' };\n\n// --- Client surface --------------------------------------------------------------------\nexport interface AlacarteCheckoutClient {\n gql: GqlRunner,\n setToken: (token: string) => void,\n getCheckout: () => Promise<AlacarteCheckoutResult>,\n /** viewedPrice: the amount the learner saw on the page before checkout (USD, before any coupon). */\n selectCourse: (courseUid: string, runKey: string, viewedPrice?: number) => Promise<AlacarteCheckoutResult>,\n selectProgram: (programUid: string, viewedPrice?: number) => Promise<AlacarteCheckoutResult>,\n updateCheckout: (args: {\n biId?: string, couponCode?: string, termsAccepted?: boolean, acceptPrice?: boolean,\n }) => Promise<AlacarteCheckoutResult>,\n getOwnedProduct: (productId: string) => Promise<OwnedProductResult>,\n getAllOwnedProducts: () => Promise<AllOwnedProductsResult>,\n getProgramDetail: (programUid: string) => Promise<ProgramDetail | null>,\n getCourseDetail: (courseKey: string) => Promise<CourseDetail | null>,\n getPlacedOrder: (biId: string) => Promise<PlacedOrderResult>,\n /** One-call place order — returns Stripe client secret (section 5a). */\n placeCheckoutOrder: (\n biId: string,\n billing?: AlacarteBillingAddress,\n paymentMethod?: AlacartePaymentMethod,\n ) => Promise<AlacartePlaceOrderApiResult>,\n capturePaypalOrder: (biId: string, paypalOrderId: string) => Promise<AlacartePaypalOrderResult>,\n cancelPaypalOrder: (biId: string, paypalOrderId: string) => Promise<AlacartePaypalOrderResult>,\n}\n"]}
|
|
@@ -7,6 +7,8 @@ export declare class AlacartePlaceOrderError extends Error {
|
|
|
7
7
|
checkout: AlacarteCheckout | null;
|
|
8
8
|
constructor(code: string, message: string, checkout?: AlacarteCheckout | null);
|
|
9
9
|
}
|
|
10
|
+
/** Learner-facing message for the poll-timeout return-to-checkout (ALC-452 #6). */
|
|
11
|
+
export declare const POLL_TIMEOUT_MESSAGE: string;
|
|
10
12
|
export declare function getPlaceOrderErrorMessage(error?: string | null): string;
|
|
11
13
|
export declare function toPlaceOrderError(code: string, checkout?: AlacarteCheckout | null): AlacartePlaceOrderError;
|
|
12
14
|
/** The learner failed sanctions screening at place order — no charge was
|
|
@@ -12,6 +12,8 @@ const PLACE_ORDER_MESSAGES = {
|
|
|
12
12
|
CANCEL_FAILED: 'Your PayPal payment could not be cancelled. Please refresh and try again.',
|
|
13
13
|
PAYMENT_RECONCILIATION_REQUIRED: 'We could not confirm your PayPal payment. Please contact support.',
|
|
14
14
|
PAYPAL_PAYMENT_DECLINED: 'Your PayPal payment was declined. Please try again or use another payment method.',
|
|
15
|
+
// ALC-452 #6: poll timeout — the learner waited ~30s without a confirmed outcome.
|
|
16
|
+
POLL_TIMEOUT: "Your payment could not be confirmed. Please try again — you won't be charged twice.",
|
|
15
17
|
};
|
|
16
18
|
export class AlacartePlaceOrderError extends Error {
|
|
17
19
|
constructor(code, message, checkout = null) {
|
|
@@ -21,6 +23,8 @@ export class AlacartePlaceOrderError extends Error {
|
|
|
21
23
|
this.checkout = checkout;
|
|
22
24
|
}
|
|
23
25
|
}
|
|
26
|
+
/** Learner-facing message for the poll-timeout return-to-checkout (ALC-452 #6). */
|
|
27
|
+
export const POLL_TIMEOUT_MESSAGE = PLACE_ORDER_MESSAGES.POLL_TIMEOUT;
|
|
24
28
|
export function getPlaceOrderErrorMessage(error) {
|
|
25
29
|
var _a;
|
|
26
30
|
if (!error)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placeOrderErrors.js","sourceRoot":"","sources":["../../src/utils/placeOrderErrors.ts"],"names":[],"mappings":"AAKA,MAAM,oBAAoB,GAA2B;IACnD,kBAAkB,EAAE,sCAAsC;IAC1D,kBAAkB,EAAE,mEAAmE;IACvF,wBAAwB,EAAE,kCAAkC;IAC5D,iBAAiB,EAAE,yCAAyC;IAC5D,kBAAkB,EAChB,wFAAwF;IAC1F,mBAAmB,EAAE,iDAAiD;IACtE,kBAAkB,EAAE,iEAAiE;IACrF,iBAAiB,EAAE,iDAAiD;IACpE,4DAA4D;IAC5D,cAAc,EAAE,6FAA6F;IAC7G,aAAa,EAAE,2EAA2E;IAC1F,+BAA+B,EAAE,mEAAmE;IACpG,uBAAuB,EAAE,mFAAmF;
|
|
1
|
+
{"version":3,"file":"placeOrderErrors.js","sourceRoot":"","sources":["../../src/utils/placeOrderErrors.ts"],"names":[],"mappings":"AAKA,MAAM,oBAAoB,GAA2B;IACnD,kBAAkB,EAAE,sCAAsC;IAC1D,kBAAkB,EAAE,mEAAmE;IACvF,wBAAwB,EAAE,kCAAkC;IAC5D,iBAAiB,EAAE,yCAAyC;IAC5D,kBAAkB,EAChB,wFAAwF;IAC1F,mBAAmB,EAAE,iDAAiD;IACtE,kBAAkB,EAAE,iEAAiE;IACrF,iBAAiB,EAAE,iDAAiD;IACpE,4DAA4D;IAC5D,cAAc,EAAE,6FAA6F;IAC7G,aAAa,EAAE,2EAA2E;IAC1F,+BAA+B,EAAE,mEAAmE;IACpG,uBAAuB,EAAE,mFAAmF;IAC5G,kFAAkF;IAClF,YAAY,EAAE,qFAAqF;CACpG,CAAC;AAEF,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAKhD,YAAY,IAAY,EAAE,OAAe,EAAE,WAAoC,IAAI;QACjF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAED,mFAAmF;AACnF,MAAM,CAAC,MAAM,oBAAoB,GAAG,oBAAoB,CAAC,YAAY,CAAC;AAEtE,MAAM,UAAU,yBAAyB,CAAC,KAAqB;;IAC7D,IAAI,CAAC,KAAK;QAAE,OAAO,4DAA4D,CAAC;IAChF,OAAO,MAAA,oBAAoB,CAAC,KAAK,CAAC,mCAAI,KAAK,CAAC;AAC9C,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,IAAY,EACZ,WAAoC,IAAI;IAExC,OAAO,IAAI,uBAAuB,CAAC,IAAI,EAAE,yBAAyB,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;AACtF,CAAC;AAED;8EAC8E;AAC9E,MAAM,UAAU,uBAAuB,CAAC,GAAY;IAClD,OAAO,GAAG,YAAY,uBAAuB,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB,CAAC;AACpF,CAAC","sourcesContent":["/**\n * Learner-facing messages for tCheckoutPlaceOrder errors (section 5a).\n */\nimport type { AlacarteCheckout } from '../types/alacarte';\n\nconst PLACE_ORDER_MESSAGES: Record<string, string> = {\n TERMS_NOT_ACCEPTED: 'Please accept the terms to continue.',\n PRICE_NOT_ACCEPTED: 'The price has changed. Please review the new total and try again.',\n BILLING_ADDRESS_REQUIRED: 'Please select a billing country.',\n SANCTIONS_BLOCKED: \"We're unable to complete this purchase.\",\n COUPON_UNAVAILABLE:\n 'This promo code can no longer be used. Review the new total and accept it to continue.',\n PAYMENT_NOT_STARTED: 'Payment could not be started. Please try again.',\n CHECKOUT_NOT_FOUND: 'Your checkout could not be found. Please refresh and try again.',\n NOT_AUTHENTICATED: 'Please sign in again to complete your purchase.',\n // tCheckoutCapturePaypalOrder / tCheckoutCancelPaypalOrder.\n CAPTURE_FAILED: 'Your PayPal payment could not be completed. Please try again or use another payment method.',\n CANCEL_FAILED: 'Your PayPal payment could not be cancelled. Please refresh and try again.',\n PAYMENT_RECONCILIATION_REQUIRED: 'We could not confirm your PayPal payment. Please contact support.',\n PAYPAL_PAYMENT_DECLINED: 'Your PayPal payment was declined. Please try again or use another payment method.',\n // ALC-452 #6: poll timeout — the learner waited ~30s without a confirmed outcome.\n POLL_TIMEOUT: \"Your payment could not be confirmed. Please try again — you won't be charged twice.\",\n};\n\nexport class AlacartePlaceOrderError extends Error {\n code: string;\n\n checkout: AlacarteCheckout | null;\n\n constructor(code: string, message: string, checkout: AlacarteCheckout | null = null) {\n super(message);\n this.name = 'AlacartePlaceOrderError';\n this.code = code;\n this.checkout = checkout;\n }\n}\n\n/** Learner-facing message for the poll-timeout return-to-checkout (ALC-452 #6). */\nexport const POLL_TIMEOUT_MESSAGE = PLACE_ORDER_MESSAGES.POLL_TIMEOUT;\n\nexport function getPlaceOrderErrorMessage(error?: string | null): string {\n if (!error) return 'Something went wrong placing your order. Please try again.';\n return PLACE_ORDER_MESSAGES[error] ?? error;\n}\n\nexport function toPlaceOrderError(\n code: string,\n checkout: AlacarteCheckout | null = null,\n): AlacartePlaceOrderError {\n return new AlacartePlaceOrderError(code, getPlaceOrderErrorMessage(code), checkout);\n}\n\n/** The learner failed sanctions screening at place order — no charge was\n * made and retrying won't help, so the UI shows a blocking modal instead. */\nexport function isSanctionsBlockedError(err: unknown): err is AlacartePlaceOrderError {\n return err instanceof AlacartePlaceOrderError && err.code === 'SANCTIONS_BLOCKED';\n}\n"]}
|