@edx/frontend-app-subscription-checkout 1.4.0 → 1.6.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/app.js +2 -6
- package/dist/app.js.map +1 -1
- package/dist/checkoutPage/CheckoutPage.js +1 -2
- package/dist/checkoutPage/CheckoutPage.js.map +1 -1
- package/dist/components/CartSummary/CartSummary.d.ts +2 -7
- package/dist/components/CartSummary/CartSummary.js +4 -4
- package/dist/components/CartSummary/CartSummary.js.map +1 -1
- package/dist/components/Checkout/Checkout.d.ts +1 -6
- package/dist/components/Checkout/Checkout.js +4 -13
- package/dist/components/Checkout/Checkout.js.map +1 -1
- package/dist/components/PaymentForm/Messages.d.ts +10 -0
- package/dist/components/PaymentForm/Messages.js +11 -1
- package/dist/components/PaymentForm/Messages.js.map +1 -1
- package/dist/components/PaymentForm/PaymentForm.d.ts +7 -1
- package/dist/components/PaymentForm/PaymentForm.js +26 -13
- package/dist/components/PaymentForm/PaymentForm.js.map +1 -1
- package/dist/data/hooks/useCheckout.js +67 -17
- package/dist/data/hooks/useCheckout.js.map +1 -1
- package/dist/styles/components/paymentForm.scss +10 -0
- package/dist/utils/planQuery.d.ts +16 -0
- package/dist/utils/planQuery.js +57 -0
- package/dist/utils/planQuery.js.map +1 -0
- package/dist/utils/provision.js +2 -2
- package/dist/utils/provision.js.map +1 -1
- package/package.json +1 -1
package/dist/app.js
CHANGED
|
@@ -5,12 +5,8 @@ const app = {
|
|
|
5
5
|
appId,
|
|
6
6
|
routes,
|
|
7
7
|
slots,
|
|
8
|
-
// Environment-specific values (STRIPE_PUBLIC_KEY, VIAX_API_URL
|
|
9
|
-
//
|
|
10
|
-
// at site build time.
|
|
11
|
-
config: {
|
|
12
|
-
ENABLE_ANNUAL_BILLING: false,
|
|
13
|
-
},
|
|
8
|
+
// Environment-specific values (STRIPE_PUBLIC_KEY, VIAX_API_URL)
|
|
9
|
+
// are supplied by site.config.{dev,stage,prod}.tsx at site build time.
|
|
14
10
|
};
|
|
15
11
|
export default app;
|
|
16
12
|
//# sourceMappingURL=app.js.map
|
package/dist/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,KAAK,MAAM,YAAY,CAAC;AAE/B,MAAM,GAAG,GAAQ;IACf,KAAK;IACL,MAAM;IACN,KAAK;IACL,gEAAgE;IAChE,
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,KAAK,MAAM,YAAY,CAAC;AAE/B,MAAM,GAAG,GAAQ;IACf,KAAK;IACL,MAAM;IACN,KAAK;IACL,gEAAgE;IAChE,uEAAuE;CACxE,CAAC;AAEF,eAAe,GAAG,CAAC","sourcesContent":["import { App } from '@openedx/frontend-base';\nimport { appId } from '@src/constants';\nimport routes from '@src/routes';\nimport slots from '@src/slots';\n\nconst app: App = {\n appId,\n routes,\n slots,\n // Environment-specific values (STRIPE_PUBLIC_KEY, VIAX_API_URL)\n // are supplied by site.config.{dev,stage,prod}.tsx at site build time.\n};\n\nexport default app;\n"]}
|
|
@@ -10,7 +10,6 @@ const CheckoutPage = () => {
|
|
|
10
10
|
const LMS_BASE_URL = siteConfig.lmsBaseUrl.replace(/\/$/, '');
|
|
11
11
|
const stripePublishableKey = config.STRIPE_PUBLIC_KEY;
|
|
12
12
|
const apiUrl = config.VIAX_API_URL;
|
|
13
|
-
const enableAnnualBilling = Boolean(config.ENABLE_ANNUAL_BILLING);
|
|
14
13
|
const isDevelopment = siteConfig.environment === 'development';
|
|
15
14
|
const edxSessionUrl = `${isDevelopment ? 'https://courses.stage.edx.org' : LMS_BASE_URL}/api/edx-session`;
|
|
16
15
|
console.log('siteConfig ===> ', siteConfig);
|
|
@@ -21,7 +20,7 @@ const CheckoutPage = () => {
|
|
|
21
20
|
if (!stripePublishableKey || !apiUrl || !edxSessionUrl) {
|
|
22
21
|
return (_jsx(PageWrapper, { children: _jsxs(Alert, { variant: "danger", children: ["We're having trouble loading the checkout. Please refresh the page or try again in a few moments. If the problem persists,", ' ', _jsx("a", { href: "https://courses.edx.org/support/contact_us", children: "contact support" }), "."] }) }));
|
|
23
22
|
}
|
|
24
|
-
return (_jsx(PageWrapper, { children: _jsx(CheckoutGate, { stripePublishableKey: stripePublishableKey, apiUrl: apiUrl, edxSessionUrl: edxSessionUrl,
|
|
23
|
+
return (_jsx(PageWrapper, { children: _jsx(CheckoutGate, { stripePublishableKey: stripePublishableKey, apiUrl: apiUrl, edxSessionUrl: edxSessionUrl, learnerDashboardUrl: `${LMS_BASE_URL}/dashboard`, homeUrl: LMS_BASE_URL || '/', onComplete: (_subscriptionBiId) => {
|
|
25
24
|
console.log(_subscriptionBiId);
|
|
26
25
|
// window.location.href = `/checkout/confirmation?sub=${_subscriptionBiId ?? ''}`;
|
|
27
26
|
// Success screen.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CheckoutPage.js","sourceRoot":"","sources":["../../src/checkoutPage/CheckoutPage.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACrE,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,YAAY,MAAM,yCAAyC,CAAC;AAEnE,MAAM,WAAW,GAA4C,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAC7E,KAAC,SAAS,cAAE,QAAQ,GAAa,CAClC,CAAC;AAEF,MAAM,YAAY,GAA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AC;IAE1G,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,UAAU,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,4BAA4B,EAAE,oBAAoB,CAAC,CAAC;IAChE,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,qBAAqB,EAAE,aAAa,CAAC,CAAC;IAElD,IAAI,CAAC,oBAAoB,IAAI,CAAC,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;QACvD,OAAO,CACL,KAAC,WAAW,cACV,MAAC,KAAK,IAAC,OAAO,EAAC,QAAQ,2IAEwC,GAAG,EAChE,YAAG,IAAI,EAAC,4CAA4C,gCAEhD,SAEE,GACI,CACf,CAAC;IACJ,CAAC;IAED,OAAO,CACL,KAAC,WAAW,cACV,KAAC,YAAY,IACX,oBAAoB,EAAE,oBAAoB,EAC1C,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,aAAa,EAC5B,mBAAmB,EAAE,GAAG,YAAY,YAAY,EAChD,OAAO,EAAE,YAAY,IAAI,GAAG,EAC5B,UAAU,EAAE,CAAC,iBAAiB,EAAE,EAAE;gBAChC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;gBAC/B,kFAAkF;gBAClF,kBAAkB;YACpB,CAAC,GACD,GACU,CACf,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import React from 'react';\nimport { Alert, Container } from '@openedx/paragon';\nimport { getAppConfig, getSiteConfig } from '@openedx/frontend-base';\nimport { appId } from '@src/constants';\nimport CheckoutGate from '../components/CheckoutGate/CheckoutGate';\n\nconst PageWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (\n <Container>{children}</Container>\n);\n\nconst CheckoutPage: React.FC = () => {\n const config = getAppConfig(appId);\n const siteConfig = getSiteConfig();\n const LMS_BASE_URL = siteConfig.lmsBaseUrl.replace(/\\/$/, '');\n const stripePublishableKey = config.STRIPE_PUBLIC_KEY as string;\n const apiUrl = config.VIAX_API_URL as string;\n const isDevelopment = siteConfig.environment === 'development';\n const edxSessionUrl = `${isDevelopment ? 'https://courses.stage.edx.org' : LMS_BASE_URL}/api/edx-session`;\n\n console.log('siteConfig ===> ', siteConfig);\n console.log('config ====> ', config);\n console.log('stripePublishableKey ===> ', stripePublishableKey);\n console.log('apiURL ==> ', apiUrl);\n console.log('edxSessionUrl ===> ', edxSessionUrl);\n\n if (!stripePublishableKey || !apiUrl || !edxSessionUrl) {\n return (\n <PageWrapper>\n <Alert variant=\"danger\">\n We're having trouble loading the checkout. Please refresh the\n page or try again in a few moments. If the problem persists,{' '}\n <a href=\"https://courses.edx.org/support/contact_us\">\n contact support\n </a>\n .\n </Alert>\n </PageWrapper>\n );\n }\n\n return (\n <PageWrapper>\n <CheckoutGate\n stripePublishableKey={stripePublishableKey}\n apiUrl={apiUrl}\n edxSessionUrl={edxSessionUrl}\n learnerDashboardUrl={`${LMS_BASE_URL}/dashboard`}\n homeUrl={LMS_BASE_URL || '/'}\n onComplete={(_subscriptionBiId) => {\n console.log(_subscriptionBiId);\n // window.location.href = `/checkout/confirmation?sub=${_subscriptionBiId ?? ''}`;\n // Success screen.\n }}\n />\n </PageWrapper>\n );\n};\n\nexport default CheckoutPage;\n"]}
|
|
@@ -16,16 +16,11 @@ export interface CartSummaryProps {
|
|
|
16
16
|
defaultCycle?: BillingCycle;
|
|
17
17
|
monthlyRenewalLabel?: string;
|
|
18
18
|
annualRenewalLabel?: string;
|
|
19
|
-
/** Called when the learner switches monthly ↔ annual
|
|
19
|
+
/** Called when the learner switches monthly ↔ annual. */
|
|
20
20
|
onCycleChange?: (cycle: BillingCycle) => void;
|
|
21
|
-
/**
|
|
22
|
-
* When true, shows the Switch to annual/monthly control.
|
|
23
|
-
* Controlled via ENABLE_ANNUAL_BILLING in site.config.*.tsx.
|
|
24
|
-
*/
|
|
25
|
-
enableAnnualBilling?: boolean;
|
|
26
21
|
learnerCount?: number;
|
|
27
22
|
/** When set, shows the course enrollment preview card below the summary card. */
|
|
28
23
|
course?: CourseDetail | null;
|
|
29
24
|
}
|
|
30
|
-
declare const CartSummary: ({ productTitle, productBlurb, monthlyAmount, monthlyRegularAmount, promoMonths, annualAmount, currency, activeSubscriberCount, defaultCycle, onCycleChange,
|
|
25
|
+
declare const CartSummary: ({ productTitle, productBlurb, monthlyAmount, monthlyRegularAmount, promoMonths, annualAmount, currency, activeSubscriberCount, defaultCycle, onCycleChange, learnerCount: learnerCountProp, course, }: CartSummaryProps) => import("react/jsx-runtime").JSX.Element;
|
|
31
26
|
export default CartSummary;
|
|
@@ -5,14 +5,14 @@ import { useIntl } from '@openedx/frontend-base';
|
|
|
5
5
|
import { EdxUnlimitedLogo } from '../BrandMarks/BrandMarks';
|
|
6
6
|
import CourseEnrollmentCard from '../CourseEnrollmentCard/CourseEnrollmentCard';
|
|
7
7
|
import messages from './Messages';
|
|
8
|
-
const CartSummary = ({ productTitle = 'edX Subscription', productBlurb = 'Subscribe and get access to hundreds of courses and programs.', monthlyAmount = '39', monthlyRegularAmount = '59', promoMonths = 3, annualAmount = '299', currency = 'USD', activeSubscriberCount, defaultCycle = 'monthly', onCycleChange,
|
|
8
|
+
const CartSummary = ({ productTitle = 'edX Subscription', productBlurb = 'Subscribe and get access to hundreds of courses and programs.', monthlyAmount = '39', monthlyRegularAmount = '59', promoMonths = 3, annualAmount = '299', currency = 'USD', activeSubscriberCount, defaultCycle = 'monthly', onCycleChange, learnerCount: learnerCountProp = 2203, course = null, }) => {
|
|
9
9
|
const { formatMessage } = useIntl();
|
|
10
10
|
const isMonthly = defaultCycle === 'monthly';
|
|
11
|
-
const showCycleToggle =
|
|
11
|
+
const showCycleToggle = !!onCycleChange;
|
|
12
12
|
const learnerCount = (activeSubscriberCount != null ? activeSubscriberCount : learnerCountProp).toLocaleString();
|
|
13
13
|
return (_jsxs("div", { className: "cart-summary ", children: [_jsxs(Card, { className: "cart-summary__card p-3", children: [_jsxs(Card.Section, { className: "d-flex justify-content-between align-items-center p-0 pb-3", children: [_jsx("span", { className: "font-weight-bold text-gray-900", children: formatMessage(messages.summaryHeading) }), _jsxs(Badge, { variant: "light", className: "d-flex align-items-center px-2 py-1", children: [_jsx(Icon, { src: Group, className: "mr-1", style: { width: '1rem', height: '1rem' } }), formatMessage(messages.learnersSubscribed, {
|
|
14
14
|
count: learnerCount,
|
|
15
|
-
})] })] }), _jsx(Card.Divider, {}), _jsx(Card.Section, { className: "p-0 py-3", children: _jsxs("div", { className: "d-flex align-items-start", children: [_jsx(EdxUnlimitedLogo, {}), _jsxs("div", { children: [_jsx("p", { className: "font-weight-bold mb-0 text-primary-500", children: productTitle }), _jsx("p", { className: "small mb-0 text-gray-900", children: productBlurb })] })] }) }), _jsx(Card.Divider, {}), _jsxs(Card.Section, { className: "p-0
|
|
15
|
+
})] })] }), _jsx(Card.Divider, {}), _jsx(Card.Section, { className: "p-0 py-3", children: _jsxs("div", { className: "d-flex align-items-start", children: [_jsx(EdxUnlimitedLogo, {}), _jsxs("div", { children: [_jsx("p", { className: "font-weight-bold mb-0 text-primary-500", children: productTitle }), _jsx("p", { className: "small mb-0 text-gray-900", children: productBlurb })] })] }) }), _jsx(Card.Divider, {}), _jsxs(Card.Section, { className: "p-0 pt-3 pb-0", children: [_jsxs("div", { className: "d-flex justify-content-between align-items-start mb-1", children: [_jsx("span", { className: "small text-gray-900", children: isMonthly
|
|
16
16
|
? formatMessage(messages.monthlySubscription)
|
|
17
17
|
: formatMessage(messages.annualSubscription) }), _jsxs("div", { className: "cart-summary__pricing text-right", children: [_jsx("div", { className: "text-success font-weight-bold small", children: formatMessage(messages.trialLabel) }), isMonthly ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "small text-gray-900 font-weight-bold", children: formatMessage(messages.promotionalPrice, {
|
|
18
18
|
amount: monthlyAmount,
|
|
@@ -24,7 +24,7 @@ const CartSummary = ({ productTitle = 'edX Subscription', productBlurb = 'Subscr
|
|
|
24
24
|
amount: annualAmount,
|
|
25
25
|
frequency: 'year',
|
|
26
26
|
currency,
|
|
27
|
-
}) }))] })] }), showCycleToggle && (_jsx("div", { className: "mt-
|
|
27
|
+
}) }))] })] }), showCycleToggle && (_jsx("div", { className: "mt-1", children: _jsx(Button, { variant: "link", className: "cart-summary__cycle-toggle p-0", onClick: () => onCycleChange === null || onCycleChange === void 0 ? void 0 : onCycleChange(isMonthly ? 'annual' : 'monthly'), children: formatMessage(isMonthly ? messages.switchToAnnual : messages.switchToMonthly) }) }))] }), _jsxs(Card.Section, { className: "d-flex justify-content-between align-items-center p-0 pt-1", children: [_jsx("span", { className: "font-weight-bold text-gray-900", children: formatMessage(messages.todaysTotal) }), _jsx("span", { className: "font-weight-bold mb-0 text-gray-900", children: formatMessage(messages.todaysTotalValue) })] })] }), course && (_jsx(CourseEnrollmentCard, { course: course, variant: "checkout" })), _jsxs("div", { className: "cart-summary__stats d-none d-lg-flex mt-3", children: [_jsxs("div", { className: "cart-summary__stat d-flex align-items-center mr-4", children: [_jsx(Icon, { src: People, className: "mr-2 text-muted", style: { width: '1.5rem', height: '1.5rem' } }), _jsxs("div", { children: [_jsx("p", { className: "font-weight-bold mb-0", children: formatMessage(messages.learnersCount) }), _jsx("p", { className: "text-muted small mb-0", children: formatMessage(messages.learnersLabel) })] })] }), _jsxs("div", { className: "cart-summary__stat d-flex align-items-center", children: [_jsx(Icon, { src: Institution, className: "mr-2 text-muted", style: { width: '1.5rem', height: '1.5rem' } }), _jsxs("div", { children: [_jsx("p", { className: "font-weight-bold mb-0", children: formatMessage(messages.institutionsCount) }), _jsx("p", { className: "text-muted small mb-0", children: formatMessage(messages.institutionsLabel) })] })] })] })] }));
|
|
28
28
|
};
|
|
29
29
|
export default CartSummary;
|
|
30
30
|
//# sourceMappingURL=CartSummary.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CartSummary.js","s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QAAQ,EAAE,GAC5C,EACF,0BACE,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,GACpC,EACJ,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,GACpC,IACA,IACF,EACN,eAAK,SAAS,EAAC,8CAA8C,aAC3D,KAAC,IAAI,IACH,GAAG,EAAE,WAAW,EAChB,SAAS,EAAC,iBAAiB,EAC3B,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,GAC5C,EACF,0BACE,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,iBAAiB,CAAC,GACxC,EACJ,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,iBAAiB,CAAC,GACxC,IACA,IACF,IACF,IACF,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,WAAW,CAAC","sourcesContent":["import React from 'react';\nimport { Badge, Button, Card, Icon } from '@openedx/paragon';\nimport { Group, People, Institution } from '@openedx/paragon/icons';\nimport { useIntl } from '@openedx/frontend-base';\nimport { EdxUnlimitedLogo } from '../BrandMarks/BrandMarks';\nimport CourseEnrollmentCard from '../CourseEnrollmentCard/CourseEnrollmentCard';\nimport type { CourseDetail } from '../../types';\nimport messages from './Messages';\n\nexport type BillingCycle = 'monthly' | 'annual';\n\nexport interface CartSummaryProps {\n productTitle?: string,\n productBlurb?: string,\n /** Promotional monthly price amount e.g. \"39\" */\n monthlyAmount?: string,\n /** Regular monthly price after the promo period e.g. \"59\" */\n monthlyRegularAmount?: string,\n /** Length of the promotional period in months */\n promoMonths?: number,\n /** Annual price amount e.g. \"299\" */\n annualAmount?: string,\n currency?: string,\n activeSubscriberCount?: number | null,\n defaultCycle?: BillingCycle,\n monthlyRenewalLabel?: string,\n annualRenewalLabel?: string,\n /** Called when the learner switches monthly ↔ annual (requires enableAnnualBilling). */\n onCycleChange?: (cycle: BillingCycle) => void,\n /**\n * When true, shows the Switch to annual/monthly control.\n * Controlled via ENABLE_ANNUAL_BILLING in site.config.*.tsx.\n */\n enableAnnualBilling?: boolean,\n learnerCount?: number,\n /** When set, shows the course enrollment preview card below the summary card. */\n course?: CourseDetail | null,\n}\n\nconst CartSummary = ({\n productTitle = 'edX Subscription',\n productBlurb = 'Subscribe and get access to hundreds of courses and programs.',\n monthlyAmount = '39',\n monthlyRegularAmount = '59',\n promoMonths = 3,\n annualAmount = '299',\n currency = 'USD',\n activeSubscriberCount,\n defaultCycle = 'monthly',\n onCycleChange,\n enableAnnualBilling = false,\n learnerCount: learnerCountProp = 2203,\n course = null,\n}: CartSummaryProps) => {\n const { formatMessage } = useIntl();\n const isMonthly = defaultCycle === 'monthly';\n const showCycleToggle = enableAnnualBilling && !!onCycleChange;\n\n const learnerCount = (\n activeSubscriberCount != null ? activeSubscriberCount : learnerCountProp\n ).toLocaleString();\n\n return (\n <div className=\"cart-summary \">\n <Card className=\"cart-summary__card p-3\">\n <Card.Section className=\"d-flex justify-content-between align-items-center p-0 pb-3\">\n <span className=\"font-weight-bold text-gray-900\">\n {formatMessage(messages.summaryHeading)}\n </span>\n <Badge\n variant=\"light\"\n className=\"d-flex align-items-center px-2 py-1\"\n >\n <Icon\n src={Group}\n className=\"mr-1\"\n style={{ width: '1rem', height: '1rem' }}\n />\n {formatMessage(messages.learnersSubscribed, {\n count: learnerCount,\n })}\n </Badge>\n </Card.Section>\n\n <Card.Divider />\n\n <Card.Section className=\"p-0 py-3\">\n <div className=\"d-flex align-items-start\">\n <EdxUnlimitedLogo />\n <div>\n <p className=\"font-weight-bold mb-0 text-primary-500\">\n {productTitle}\n </p>\n <p className=\"small mb-0 text-gray-900\">{productBlurb}</p>\n </div>\n </div>\n </Card.Section>\n\n <Card.Divider />\n\n <Card.Section className=\"p-0 py-3\">\n <div className=\"d-flex justify-content-between align-items-start mb-1\">\n <span className=\"small text-gray-900\">\n {isMonthly\n ? formatMessage(messages.monthlySubscription)\n : formatMessage(messages.annualSubscription)}\n </span>\n <div className=\"cart-summary__pricing text-right\">\n <div className=\"text-success font-weight-bold small\">\n {formatMessage(messages.trialLabel)}\n </div>\n {isMonthly ? (\n <>\n <div className=\"small text-gray-900 font-weight-bold\">\n {formatMessage(messages.promotionalPrice, {\n amount: monthlyAmount,\n months: promoMonths,\n })}\n </div>\n <div className=\"small text-gray-900 font-weight-bold\">\n {formatMessage(messages.regularPrice, {\n amount: monthlyRegularAmount,\n currency,\n })}\n </div>\n </>\n ) : (\n <div className=\"small text-gray-900 font-weight-bold\">\n {formatMessage(messages.priceDisplay, {\n amount: annualAmount,\n frequency: 'year',\n currency,\n })}\n </div>\n )}\n </div>\n </div>\n {showCycleToggle && (\n <div className=\"mt-2\">\n <Button\n variant=\"link\"\n className=\"cart-summary__cycle-toggle p-0\"\n onClick={() => onCycleChange?.(isMonthly ? 'annual' : 'monthly')}\n >\n {formatMessage(\n isMonthly ? messages.switchToAnnual : messages.switchToMonthly,\n )}\n </Button>\n </div>\n )}\n </Card.Section>\n\n <Card.Section className=\"d-flex justify-content-between align-items-center px-0\">\n <span className=\"font-weight-bold text-gray-900\">\n {formatMessage(messages.todaysTotal)}\n </span>\n <span className=\"font-weight-bold mb-0 text-gray-900\">\n {formatMessage(messages.todaysTotalValue)}\n </span>\n </Card.Section>\n </Card>\n\n {course && (\n <CourseEnrollmentCard course={course} variant=\"checkout\" />\n )}\n\n {/* Stats row */}\n <div className=\"cart-summary__stats d-none d-lg-flex mt-3\">\n <div className=\"cart-summary__stat d-flex align-items-center mr-4\">\n <Icon\n src={People}\n className=\"mr-2 text-muted\"\n style={{ width: '1.5rem', height: '1.5rem' }}\n />\n <div>\n <p className=\"font-weight-bold mb-0\">\n {formatMessage(messages.learnersCount)}\n </p>\n <p className=\"text-muted small mb-0\">\n {formatMessage(messages.learnersLabel)}\n </p>\n </div>\n </div>\n <div className=\"cart-summary__stat d-flex align-items-center\">\n <Icon\n src={Institution}\n className=\"mr-2 text-muted\"\n style={{ width: '1.5rem', height: '1.5rem' }}\n />\n <div>\n <p className=\"font-weight-bold mb-0\">\n {formatMessage(messages.institutionsCount)}\n </p>\n <p className=\"text-muted small mb-0\">\n {formatMessage(messages.institutionsLabel)}\n </p>\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nexport default CartSummary;\n"]}
|
|
1
|
+
{"version":3,"file":"CartSummary.js","sourceRoot":"","sources":["../../../src/components/CartSummary/CartSummary.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,oBAAoB,MAAM,8CAA8C,CAAC;AAEhF,OAAO,QAAQ,MAAM,YAAY,CAAC;AA2BlC,MAAM,WAAW,GAAG,CAAC,EACnB,YAAY,GAAG,kBAAkB,EACjC,YAAY,GAAG,+DAA+D,EAC9E,aAAa,GAAG,IAAI,EACpB,oBAAoB,GAAG,IAAI,EAC3B,WAAW,GAAG,CAAC,EACf,YAAY,GAAG,KAAK,EACpB,QAAQ,GAAG,KAAK,EAChB,qBAAqB,EACrB,YAAY,GAAG,SAAS,EACxB,aAAa,EACb,YAAY,EAAE,gBAAgB,GAAG,IAAI,EACrC,MAAM,GAAG,IAAI,GACI,EAAE,EAAE;IACrB,MAAM,EAAE,aAAa,EAAE,GAAG,OAAO,EAAE,CAAC;IACpC,MAAM,SAAS,GAAG,YAAY,KAAK,SAAS,CAAC;IAC7C,MAAM,eAAe,GAAG,CAAC,CAAC,aAAa,CAAC;IAExC,MAAM,YAAY,GAAG,CACnB,qBAAqB,IAAI,IAAI,CAAC,CAAC,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M,EAAE,OAAO,EAAC,UAAU,GAAG,CAC5D,EAGD,eAAK,SAAS,EAAC,2CAA2C,aACxD,eAAK,SAAS,EAAC,mDAAmD,aAChE,KAAC,IAAI,IACH,GAAG,EAAE,MAAM,EACX,SAAS,EAAC,iBAAiB,EAC3B,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,GAC5C,EACF,0BACE,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,GACpC,EACJ,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,GACpC,IACA,IACF,EACN,eAAK,SAAS,EAAC,8CAA8C,aAC3D,KAAC,IAAI,IACH,GAAG,EAAE,WAAW,EAChB,SAAS,EAAC,iBAAiB,EAC3B,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,GAC5C,EACF,0BACE,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,iBAAiB,CAAC,GACxC,EACJ,YAAG,SAAS,EAAC,uBAAuB,YACjC,aAAa,CAAC,QAAQ,CAAC,iBAAiB,CAAC,GACxC,IACA,IACF,IACF,IACF,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,WAAW,CAAC","sourcesContent":["import React from 'react';\nimport { Badge, Button, Card, Icon } from '@openedx/paragon';\nimport { Group, People, Institution } from '@openedx/paragon/icons';\nimport { useIntl } from '@openedx/frontend-base';\nimport { EdxUnlimitedLogo } from '../BrandMarks/BrandMarks';\nimport CourseEnrollmentCard from '../CourseEnrollmentCard/CourseEnrollmentCard';\nimport type { CourseDetail } from '../../types';\nimport messages from './Messages';\n\nexport type BillingCycle = 'monthly' | 'annual';\n\nexport interface CartSummaryProps {\n productTitle?: string,\n productBlurb?: string,\n /** Promotional monthly price amount e.g. \"39\" */\n monthlyAmount?: string,\n /** Regular monthly price after the promo period e.g. \"59\" */\n monthlyRegularAmount?: string,\n /** Length of the promotional period in months */\n promoMonths?: number,\n /** Annual price amount e.g. \"299\" */\n annualAmount?: string,\n currency?: string,\n activeSubscriberCount?: number | null,\n defaultCycle?: BillingCycle,\n monthlyRenewalLabel?: string,\n annualRenewalLabel?: string,\n /** Called when the learner switches monthly ↔ annual. */\n onCycleChange?: (cycle: BillingCycle) => void,\n learnerCount?: number,\n /** When set, shows the course enrollment preview card below the summary card. */\n course?: CourseDetail | null,\n}\n\nconst CartSummary = ({\n productTitle = 'edX Subscription',\n productBlurb = 'Subscribe and get access to hundreds of courses and programs.',\n monthlyAmount = '39',\n monthlyRegularAmount = '59',\n promoMonths = 3,\n annualAmount = '299',\n currency = 'USD',\n activeSubscriberCount,\n defaultCycle = 'monthly',\n onCycleChange,\n learnerCount: learnerCountProp = 2203,\n course = null,\n}: CartSummaryProps) => {\n const { formatMessage } = useIntl();\n const isMonthly = defaultCycle === 'monthly';\n const showCycleToggle = !!onCycleChange;\n\n const learnerCount = (\n activeSubscriberCount != null ? activeSubscriberCount : learnerCountProp\n ).toLocaleString();\n\n return (\n <div className=\"cart-summary \">\n <Card className=\"cart-summary__card p-3\">\n <Card.Section className=\"d-flex justify-content-between align-items-center p-0 pb-3\">\n <span className=\"font-weight-bold text-gray-900\">\n {formatMessage(messages.summaryHeading)}\n </span>\n <Badge\n variant=\"light\"\n className=\"d-flex align-items-center px-2 py-1\"\n >\n <Icon\n src={Group}\n className=\"mr-1\"\n style={{ width: '1rem', height: '1rem' }}\n />\n {formatMessage(messages.learnersSubscribed, {\n count: learnerCount,\n })}\n </Badge>\n </Card.Section>\n\n <Card.Divider />\n\n <Card.Section className=\"p-0 py-3\">\n <div className=\"d-flex align-items-start\">\n <EdxUnlimitedLogo />\n <div>\n <p className=\"font-weight-bold mb-0 text-primary-500\">\n {productTitle}\n </p>\n <p className=\"small mb-0 text-gray-900\">{productBlurb}</p>\n </div>\n </div>\n </Card.Section>\n\n <Card.Divider />\n\n <Card.Section className=\"p-0 pt-3 pb-0\">\n <div className=\"d-flex justify-content-between align-items-start mb-1\">\n <span className=\"small text-gray-900\">\n {isMonthly\n ? formatMessage(messages.monthlySubscription)\n : formatMessage(messages.annualSubscription)}\n </span>\n <div className=\"cart-summary__pricing text-right\">\n <div className=\"text-success font-weight-bold small\">\n {formatMessage(messages.trialLabel)}\n </div>\n {isMonthly ? (\n <>\n <div className=\"small text-gray-900 font-weight-bold\">\n {formatMessage(messages.promotionalPrice, {\n amount: monthlyAmount,\n months: promoMonths,\n })}\n </div>\n <div className=\"small text-gray-900 font-weight-bold\">\n {formatMessage(messages.regularPrice, {\n amount: monthlyRegularAmount,\n currency,\n })}\n </div>\n </>\n ) : (\n <div className=\"small text-gray-900 font-weight-bold\">\n {formatMessage(messages.priceDisplay, {\n amount: annualAmount,\n frequency: 'year',\n currency,\n })}\n </div>\n )}\n </div>\n </div>\n {showCycleToggle && (\n <div className=\"mt-1\">\n <Button\n variant=\"link\"\n className=\"cart-summary__cycle-toggle p-0\"\n onClick={() => onCycleChange?.(isMonthly ? 'annual' : 'monthly')}\n >\n {formatMessage(\n isMonthly ? messages.switchToAnnual : messages.switchToMonthly,\n )}\n </Button>\n </div>\n )}\n </Card.Section>\n\n <Card.Section className=\"d-flex justify-content-between align-items-center p-0 pt-1\">\n <span className=\"font-weight-bold text-gray-900\">\n {formatMessage(messages.todaysTotal)}\n </span>\n <span className=\"font-weight-bold mb-0 text-gray-900\">\n {formatMessage(messages.todaysTotalValue)}\n </span>\n </Card.Section>\n </Card>\n\n {course && (\n <CourseEnrollmentCard course={course} variant=\"checkout\" />\n )}\n\n {/* Stats row */}\n <div className=\"cart-summary__stats d-none d-lg-flex mt-3\">\n <div className=\"cart-summary__stat d-flex align-items-center mr-4\">\n <Icon\n src={People}\n className=\"mr-2 text-muted\"\n style={{ width: '1.5rem', height: '1.5rem' }}\n />\n <div>\n <p className=\"font-weight-bold mb-0\">\n {formatMessage(messages.learnersCount)}\n </p>\n <p className=\"text-muted small mb-0\">\n {formatMessage(messages.learnersLabel)}\n </p>\n </div>\n </div>\n <div className=\"cart-summary__stat d-flex align-items-center\">\n <Icon\n src={Institution}\n className=\"mr-2 text-muted\"\n style={{ width: '1.5rem', height: '1.5rem' }}\n />\n <div>\n <p className=\"font-weight-bold mb-0\">\n {formatMessage(messages.institutionsCount)}\n </p>\n <p className=\"text-muted small mb-0\">\n {formatMessage(messages.institutionsLabel)}\n </p>\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nexport default CartSummary;\n"]}
|
|
@@ -2,11 +2,6 @@ import type { UseCheckoutOptions } from '../../data/hooks/useCheckout';
|
|
|
2
2
|
export type CheckoutProps = UseCheckoutOptions & {
|
|
3
3
|
/** Homepage URL for the country-unavailable modal CTA. */
|
|
4
4
|
homeUrl?: string;
|
|
5
|
-
/**
|
|
6
|
-
* When true, learners can switch between monthly and annual billing.
|
|
7
|
-
* Sourced from ENABLE_ANNUAL_BILLING in site.config.*.tsx.
|
|
8
|
-
*/
|
|
9
|
-
enableAnnualBilling?: boolean;
|
|
10
5
|
};
|
|
11
|
-
declare const Checkout: ({ homeUrl,
|
|
6
|
+
declare const Checkout: ({ homeUrl, ...props }: CheckoutProps) => import("react/jsx-runtime").JSX.Element;
|
|
12
7
|
export default Checkout;
|
|
@@ -10,7 +10,6 @@ var __rest = (this && this.__rest) || function (s, e) {
|
|
|
10
10
|
return t;
|
|
11
11
|
};
|
|
12
12
|
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
13
|
-
import { useEffect } from 'react';
|
|
14
13
|
import { Alert, Col, Row } from '@openedx/paragon';
|
|
15
14
|
import { Error as ErrorIcon } from '@openedx/paragon/icons';
|
|
16
15
|
import useCheckout from '../../data/hooks/useCheckout';
|
|
@@ -33,13 +32,8 @@ function resolvePurchasedCycle(selectedCycle, planName, renewalType) {
|
|
|
33
32
|
}
|
|
34
33
|
const Checkout = (_a) => {
|
|
35
34
|
var _b, _c, _d, _e, _f;
|
|
36
|
-
var { homeUrl = '/'
|
|
35
|
+
var { homeUrl = '/' } = _a, props = __rest(_a, ["homeUrl"]);
|
|
37
36
|
const c = useCheckout(props);
|
|
38
|
-
useEffect(() => {
|
|
39
|
-
if (!enableAnnualBilling && c.selectedCycle !== 'monthly') {
|
|
40
|
-
c.setCycle('monthly');
|
|
41
|
-
}
|
|
42
|
-
}, [enableAnnualBilling, c.selectedCycle, c.setCycle]);
|
|
43
37
|
const showForm = c.phase === 'init'
|
|
44
38
|
|| c.phase === 'ready'
|
|
45
39
|
|| c.phase === 'failed'
|
|
@@ -51,10 +45,7 @@ const Checkout = (_a) => {
|
|
|
51
45
|
const isBillingCountryBlocked = GATE_CHECK_COUNTRY
|
|
52
46
|
&& !!c.billing.country
|
|
53
47
|
&& !ALLOWED_CHECKOUT_COUNTRIES.includes(c.billing.country);
|
|
54
|
-
|
|
55
|
-
const selectedCycle = enableAnnualBilling
|
|
56
|
-
? c.selectedCycle
|
|
57
|
-
: 'monthly';
|
|
48
|
+
const selectedCycle = c.selectedCycle;
|
|
58
49
|
const purchasedCycle = resolvePurchasedCycle(selectedCycle, (_b = c.subscriptionDetails) === null || _b === void 0 ? void 0 : _b.planName, (_c = c.subscriptionDetails) === null || _c === void 0 ? void 0 : _c.renewalType);
|
|
59
50
|
const purchasedPrice = getPlanPrice(c.billingPlans, purchasedCycle);
|
|
60
51
|
const handleStartCourse = () => {
|
|
@@ -70,9 +61,9 @@ const Checkout = (_a) => {
|
|
|
70
61
|
? [c.course.tBrandText, c.course.maName].filter(Boolean).join(': ')
|
|
71
62
|
: null;
|
|
72
63
|
return (_jsxs(Row, { className: "checkout__container bg-light-200", children: [_jsx(CountryUnavailableModal, { isOpen: isBillingCountryBlocked, homeUrl: homeUrl }), _jsx(Col, { xs: 12, className: "d-lg-none", children: _jsx("h1", { className: "font-weight-bold text-primary-900", children: "Checkout" }) }), _jsx(Col, { xs: 12, children: _jsxs(Row, { className: "flex-column-reverse gap-5 flex-lg-row", children: [_jsx(Col, { xs: 12, lg: 7, xxl: 9, className: "payment__options", children: _jsxs("div", { children: [_jsx("h1", { className: "font-weight-bold text-primary-900 d-none d-lg-block", children: "Checkout" }), c.error && (_jsx(Alert, { variant: "danger", icon: ErrorIcon, dismissible: true, onClose: c.clearError, children: c.error })), showForm && (_jsxs(_Fragment, { children: [c.phase === 'failed' && (_jsx(Alert, { variant: "danger", icon: ErrorIcon, className: "mb-3", children: c.lastComment
|
|
73
|
-
|| 'Your payment could not be processed. Please check your card details and try again.' })), _jsx(PaymentForm, { billing: c.billing, setField: c.setField, numberMountRef: c.numberMountRef, expiryMountRef: c.expiryMountRef, cvcMountRef: c.cvcMountRef, cardError: c.cardError, stripeReady: c.stripeReady, sessionReady: c.sessionReady, submitting: isSubmitting, onPlaceOrder: c.placeOrder, trialEnd: displayEnd, priceToShow: selectedCycle === 'monthly' ? monthlyPrice : annualPrice, cycleToShow: selectedCycle === 'monthly' ? 'monthly' : 'annual', userCountry: c.userCountry })] })), c.phase === 'success' && (_jsx(SuccessScreen, { subscriptionBiId: ((_d = c.subscriptionDetails) === null || _d === void 0 ? void 0 : _d.biId) || '', cardLast4: ((_e = c.subscriptionDetails) === null || _e === void 0 ? void 0 : _e.cardLast4) || '', purchaseDate: displayStart, trialStart: displayStart, trialEnd: displayEnd, priceToShow: purchasedCycle === 'monthly'
|
|
64
|
+
|| 'Your payment could not be processed. Please check your card details and try again.' })), _jsx(PaymentForm, { billing: c.billing, setField: c.setField, numberMountRef: c.numberMountRef, expiryMountRef: c.expiryMountRef, cvcMountRef: c.cvcMountRef, cardError: c.cardError, stripeReady: c.stripeReady, sessionReady: c.sessionReady, submitting: isSubmitting, onPlaceOrder: c.placeOrder, trialEnd: displayEnd, priceToShow: selectedCycle === 'monthly' ? monthlyPrice : annualPrice, cycleToShow: selectedCycle === 'monthly' ? 'monthly' : 'annual', userCountry: c.userCountry, monthlyRegularAmount: monthlyPrice === null || monthlyPrice === void 0 ? void 0 : monthlyPrice.amount })] })), c.phase === 'success' && (_jsx(SuccessScreen, { subscriptionBiId: ((_d = c.subscriptionDetails) === null || _d === void 0 ? void 0 : _d.biId) || '', cardLast4: ((_e = c.subscriptionDetails) === null || _e === void 0 ? void 0 : _e.cardLast4) || '', purchaseDate: displayStart, trialStart: displayStart, trialEnd: displayEnd, priceToShow: purchasedCycle === 'monthly'
|
|
74
65
|
? monthlyPrice === null || monthlyPrice === void 0 ? void 0 : monthlyPrice.label
|
|
75
|
-
: annualPrice === null || annualPrice === void 0 ? void 0 : annualPrice.label, cycleToShow: purchasedCycle === 'monthly' ? 'monthly' : 'annual', courseLabel: courseLabel, onFindCourse: handleStartCourse })), c.phase === 'blocked' && (_jsx(BlockedScreen, { detail: c.lastComment }))] }) }), _jsx(Col, { xs: 12, lg: 5, xxl: 3, className: "payment__summary", children: c.phase === 'success' ? (_jsx(EnrollmentSummary, { amount: purchasedPrice === null || purchasedPrice === void 0 ? void 0 : purchasedPrice.amount, currency: purchasedPrice === null || purchasedPrice === void 0 ? void 0 : purchasedPrice.currency, cycleToShow: purchasedCycle, course: c.course, onStartCourse: handleStartCourse })) : (_jsx(CartSummary, { monthlyRegularAmount: monthlyPrice === null || monthlyPrice === void 0 ? void 0 : monthlyPrice.amount, annualAmount: annualPrice === null || annualPrice === void 0 ? void 0 : annualPrice.amount, currency: (_f = monthlyPrice === null || monthlyPrice === void 0 ? void 0 : monthlyPrice.currency) !== null && _f !== void 0 ? _f : annualPrice === null || annualPrice === void 0 ? void 0 : annualPrice.currency, monthlyRenewalLabel: getRenewalLabel(c.billingPlans, 'monthly'), annualRenewalLabel: getRenewalLabel(c.billingPlans, 'annual'), activeSubscriberCount: c.activeSubscriberCount, defaultCycle: selectedCycle, onCycleChange: c.setCycle,
|
|
66
|
+
: annualPrice === null || annualPrice === void 0 ? void 0 : annualPrice.label, cycleToShow: purchasedCycle === 'monthly' ? 'monthly' : 'annual', courseLabel: courseLabel, onFindCourse: handleStartCourse })), c.phase === 'blocked' && (_jsx(BlockedScreen, { detail: c.lastComment }))] }) }), _jsx(Col, { xs: 12, lg: 5, xxl: 3, className: "payment__summary", children: c.phase === 'success' ? (_jsx(EnrollmentSummary, { amount: purchasedPrice === null || purchasedPrice === void 0 ? void 0 : purchasedPrice.amount, currency: purchasedPrice === null || purchasedPrice === void 0 ? void 0 : purchasedPrice.currency, cycleToShow: purchasedCycle, course: c.course, onStartCourse: handleStartCourse })) : (_jsx(CartSummary, { monthlyRegularAmount: monthlyPrice === null || monthlyPrice === void 0 ? void 0 : monthlyPrice.amount, annualAmount: annualPrice === null || annualPrice === void 0 ? void 0 : annualPrice.amount, currency: (_f = monthlyPrice === null || monthlyPrice === void 0 ? void 0 : monthlyPrice.currency) !== null && _f !== void 0 ? _f : annualPrice === null || annualPrice === void 0 ? void 0 : annualPrice.currency, monthlyRenewalLabel: getRenewalLabel(c.billingPlans, 'monthly'), annualRenewalLabel: getRenewalLabel(c.billingPlans, 'annual'), activeSubscriberCount: c.activeSubscriberCount, defaultCycle: selectedCycle, onCycleChange: c.setCycle, course: c.course })) })] }) })] }));
|
|
76
67
|
};
|
|
77
68
|
export default Checkout;
|
|
78
69
|
//# sourceMappingURL=Checkout.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Checkout.js","sourceRoot":"","sources":["../../../src/components/Checkout/Checkout.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAc,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,WAAW,MAAM,8BAA8B,CAAC;AAEvD,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,iBAAiB,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,IAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,SAAS,EAAC,kBAAkB,YACrD,CAAC,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,CACvB,KAAC,iBAAiB,IAChB,MAAM,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,MAAM,EAC9B,QAAQ,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,QAAQ,EAClC,WAAW,EAAE,cAAc,EAC3B,MAAM,EAAE,CAAC,CAAC,MAAM,EAChB,aAAa,EAAE,iBAAiB,GAChC,CACH,CAAC,CAAC,CAAC,CACF,KAAC,WAAW,IACV,oBAAoB,EAAE,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,MAAM,EAC1C,YAAY,EAAE,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,MAAM,EACjC,QAAQ,EAAE,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,mCAAI,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,QAAQ,EACzD,mBAAmB,EAAE,eAAe,CAAC,CAAC,CAAC,YAAY,EAAE,SAAS,CAAC,EAC/D,kBAAkB,EAAE,eAAe,CAAC,CAAC,CAAC,YAAY,EAAE,QAAQ,CAAC,EAC7D,qBAAqB,EAAE,CAAC,CAAC,qBAAqB,EAC9C,YAAY,EAAE,aAAa,EAC3B,aAAa,EAAE,CAAC,CAAC,QAAQ,EACzB,mBAAmB,EAAE,mBAAmB,EACxC,MAAM,EAAE,CAAC,CAAC,MAAM,GAChB,CACH,GACG,IACF,GACF,IACF,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,QAAQ,CAAC","sourcesContent":["import React, { useEffect } from 'react';\nimport { Alert, Col, Row } from '@openedx/paragon';\nimport { Error as ErrorIcon } from '@openedx/paragon/icons';\nimport useCheckout from '../../data/hooks/useCheckout';\nimport type { UseCheckoutOptions } from '../../data/hooks/useCheckout';\nimport { ALLOWED_CHECKOUT_COUNTRIES, GATE_CHECK_COUNTRY } from '../../constants';\nimport CartSummary from '../CartSummary/CartSummary';\nimport EnrollmentSummary from '../EnrollmentSummary/EnrollmentSummary';\nimport PaymentForm from '../PaymentForm/PaymentForm';\nimport CountryUnavailableModal from '../CountryUnavailableModal/CountryUnavailableModal';\nimport { getPlanPrice, getRenewalLabel } from '../../utils/billingDetails';\nimport { getTrialDateRange } from '@src/utils';\nimport { SuccessScreen, BlockedScreen } from '../StatusScreens/StatusScreens';\nimport type { BillingCycle } from '../../types';\n\n/** Resolve purchased cycle from subscription details, falling back to checkout selection. */\nfunction resolvePurchasedCycle(\n selectedCycle: BillingCycle,\n planName?: string | null,\n renewalType?: string | null,\n): BillingCycle {\n const haystack = `${planName ?? ''} ${renewalType ?? ''}`.toLowerCase();\n if (haystack.includes('annual') || haystack.includes('year')) return 'annual';\n if (haystack.includes('month')) return 'monthly';\n return selectedCycle;\n}\n\nexport type CheckoutProps = UseCheckoutOptions & {\n /** Homepage URL for the country-unavailable modal CTA. */\n homeUrl?: string,\n /**\n * When true, learners can switch between monthly and annual billing.\n * Sourced from ENABLE_ANNUAL_BILLING in site.config.*.tsx.\n */\n enableAnnualBilling?: boolean,\n};\n\nconst Checkout = ({\n homeUrl = '/',\n enableAnnualBilling = false,\n ...props\n}: CheckoutProps) => {\n const c = useCheckout(props);\n\n useEffect(() => {\n if (!enableAnnualBilling && c.selectedCycle !== 'monthly') {\n c.setCycle('monthly');\n }\n }, [enableAnnualBilling, c.selectedCycle, c.setCycle]);\n\n const showForm\n = c.phase === 'init'\n || c.phase === 'ready'\n || c.phase === 'failed'\n || c.phase === 'processing';\n const monthlyPrice = getPlanPrice(c.billingPlans, 'monthly');\n const annualPrice = getPlanPrice(c.billingPlans, 'annual');\n const isSubmitting = c.processingSubscription;\n\n const { displayStart, displayEnd } = getTrialDateRange();\n\n const isBillingCountryBlocked = GATE_CHECK_COUNTRY\n && !!c.billing.country\n && !ALLOWED_CHECKOUT_COUNTRIES.includes(c.billing.country);\n\n // Keep annual selection only when the feature flag is on.\n const selectedCycle: BillingCycle = enableAnnualBilling\n ? c.selectedCycle\n : 'monthly';\n\n const purchasedCycle = resolvePurchasedCycle(\n selectedCycle,\n c.subscriptionDetails?.planName,\n c.subscriptionDetails?.renewalType,\n );\n const purchasedPrice = getPlanPrice(c.billingPlans, purchasedCycle);\n\n const handleStartCourse = () => {\n if (c.course?.tUrlCourse) {\n window.location.href = c.course.tUrlCourse;\n } else {\n window.location.href = '/subscription-search';\n }\n };\n\n const courseLabel = c.course\n ? [c.course.tBrandText, c.course.maName].filter(Boolean).join(': ')\n : null;\n\n return (\n <Row className=\"checkout__container bg-light-200\">\n <CountryUnavailableModal\n isOpen={isBillingCountryBlocked}\n homeUrl={homeUrl}\n />\n <Col xs={12} className=\"d-lg-none\">\n <h1 className=\"font-weight-bold text-primary-900\">Checkout</h1>\n </Col>\n <Col xs={12}>\n <Row className=\"flex-column-reverse gap-5 flex-lg-row\">\n {/* ── LEFT ── */}\n <Col xs={12} lg={7} xxl={9} className=\"payment__options\">\n <div>\n <h1 className=\"font-weight-bold text-primary-900 d-none d-lg-block\">\n Checkout\n </h1>\n {c.error && (\n <Alert\n variant=\"danger\"\n icon={ErrorIcon}\n dismissible\n onClose={c.clearError}\n >\n {c.error}\n </Alert>\n )}\n\n {showForm && (\n <>\n {c.phase === 'failed' && (\n <Alert variant=\"danger\" icon={ErrorIcon} className=\"mb-3\">\n {c.lastComment\n || 'Your payment could not be processed. Please check your card details and try again.'}\n </Alert>\n )}\n <PaymentForm\n billing={c.billing}\n setField={c.setField}\n numberMountRef={c.numberMountRef}\n expiryMountRef={c.expiryMountRef}\n cvcMountRef={c.cvcMountRef}\n cardError={c.cardError}\n stripeReady={c.stripeReady}\n sessionReady={c.sessionReady}\n submitting={isSubmitting}\n onPlaceOrder={c.placeOrder}\n trialEnd={displayEnd}\n priceToShow={\n selectedCycle === 'monthly' ? monthlyPrice : annualPrice\n }\n cycleToShow={\n selectedCycle === 'monthly' ? 'monthly' : 'annual'\n }\n userCountry={c.userCountry}\n />\n </>\n )}\n\n {c.phase === 'success' && (\n <SuccessScreen\n subscriptionBiId={c.subscriptionDetails?.biId || ''}\n cardLast4={c.subscriptionDetails?.cardLast4 || ''}\n purchaseDate={displayStart}\n trialStart={displayStart}\n trialEnd={displayEnd}\n priceToShow={\n purchasedCycle === 'monthly'\n ? monthlyPrice?.label\n : annualPrice?.label\n }\n cycleToShow={\n purchasedCycle === 'monthly' ? 'monthly' : 'annual'\n }\n courseLabel={courseLabel}\n onFindCourse={handleStartCourse}\n />\n )}\n\n {c.phase === 'blocked' && (\n <BlockedScreen detail={c.lastComment} />\n )}\n </div>\n </Col>\n\n {/* ── RIGHT — swaps to EnrollmentSummary on success ── */}\n <Col xs={12} lg={5} xxl={3} className=\"payment__summary\">\n {c.phase === 'success' ? (\n <EnrollmentSummary\n amount={purchasedPrice?.amount}\n currency={purchasedPrice?.currency}\n cycleToShow={purchasedCycle}\n course={c.course}\n onStartCourse={handleStartCourse}\n />\n ) : (\n <CartSummary\n monthlyRegularAmount={monthlyPrice?.amount}\n annualAmount={annualPrice?.amount}\n currency={monthlyPrice?.currency ?? annualPrice?.currency}\n monthlyRenewalLabel={getRenewalLabel(c.billingPlans, 'monthly')}\n annualRenewalLabel={getRenewalLabel(c.billingPlans, 'annual')}\n activeSubscriberCount={c.activeSubscriberCount}\n defaultCycle={selectedCycle}\n onCycleChange={c.setCycle}\n enableAnnualBilling={enableAnnualBilling}\n course={c.course}\n />\n )}\n </Col>\n </Row>\n </Col>\n </Row>\n );\n};\n\nexport default Checkout;\n"]}
|
|
1
|
+
{"version":3,"file":"Checkout.js","sourceRoot":"","sources":["../../../src/components/Checkout/Checkout.tsx"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,KAAK,IA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AAC,kBAAkB,YACrD,CAAC,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,CACvB,KAAC,iBAAiB,IAChB,MAAM,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,MAAM,EAC9B,QAAQ,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,QAAQ,EAClC,WAAW,EAAE,cAAc,EAC3B,MAAM,EAAE,CAAC,CAAC,MAAM,EAChB,aAAa,EAAE,iBAAiB,GAChC,CACH,CAAC,CAAC,CAAC,CACF,KAAC,WAAW,IACV,oBAAoB,EAAE,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,MAAM,EAC1C,YAAY,EAAE,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,MAAM,EACjC,QAAQ,EAAE,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,mCAAI,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,QAAQ,EACzD,mBAAmB,EAAE,eAAe,CAAC,CAAC,CAAC,YAAY,EAAE,SAAS,CAAC,EAC/D,kBAAkB,EAAE,eAAe,CAAC,CAAC,CAAC,YAAY,EAAE,QAAQ,CAAC,EAC7D,qBAAqB,EAAE,CAAC,CAAC,qBAAqB,EAC9C,YAAY,EAAE,aAAa,EAC3B,aAAa,EAAE,CAAC,CAAC,QAAQ,EACzB,MAAM,EAAE,CAAC,CAAC,MAAM,GAChB,CACH,GACG,IACF,GACF,IACF,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,QAAQ,CAAC","sourcesContent":["import React from 'react';\nimport { Alert, Col, Row } from '@openedx/paragon';\nimport { Error as ErrorIcon } from '@openedx/paragon/icons';\nimport useCheckout from '../../data/hooks/useCheckout';\nimport type { UseCheckoutOptions } from '../../data/hooks/useCheckout';\nimport { ALLOWED_CHECKOUT_COUNTRIES, GATE_CHECK_COUNTRY } from '../../constants';\nimport CartSummary from '../CartSummary/CartSummary';\nimport EnrollmentSummary from '../EnrollmentSummary/EnrollmentSummary';\nimport PaymentForm from '../PaymentForm/PaymentForm';\nimport CountryUnavailableModal from '../CountryUnavailableModal/CountryUnavailableModal';\nimport { getPlanPrice, getRenewalLabel } from '../../utils/billingDetails';\nimport { getTrialDateRange } from '@src/utils';\nimport { SuccessScreen, BlockedScreen } from '../StatusScreens/StatusScreens';\nimport type { BillingCycle } from '../../types';\n\n/** Resolve purchased cycle from subscription details, falling back to checkout selection. */\nfunction resolvePurchasedCycle(\n selectedCycle: BillingCycle,\n planName?: string | null,\n renewalType?: string | null,\n): BillingCycle {\n const haystack = `${planName ?? ''} ${renewalType ?? ''}`.toLowerCase();\n if (haystack.includes('annual') || haystack.includes('year')) return 'annual';\n if (haystack.includes('month')) return 'monthly';\n return selectedCycle;\n}\n\nexport type CheckoutProps = UseCheckoutOptions & {\n /** Homepage URL for the country-unavailable modal CTA. */\n homeUrl?: string,\n};\n\nconst Checkout = ({\n homeUrl = '/',\n ...props\n}: CheckoutProps) => {\n const c = useCheckout(props);\n\n const showForm\n = c.phase === 'init'\n || c.phase === 'ready'\n || c.phase === 'failed'\n || c.phase === 'processing';\n const monthlyPrice = getPlanPrice(c.billingPlans, 'monthly');\n const annualPrice = getPlanPrice(c.billingPlans, 'annual');\n const isSubmitting = c.processingSubscription;\n\n const { displayStart, displayEnd } = getTrialDateRange();\n\n const isBillingCountryBlocked = GATE_CHECK_COUNTRY\n && !!c.billing.country\n && !ALLOWED_CHECKOUT_COUNTRIES.includes(c.billing.country);\n\n const selectedCycle: BillingCycle = c.selectedCycle;\n\n const purchasedCycle = resolvePurchasedCycle(\n selectedCycle,\n c.subscriptionDetails?.planName,\n c.subscriptionDetails?.renewalType,\n );\n const purchasedPrice = getPlanPrice(c.billingPlans, purchasedCycle);\n\n const handleStartCourse = () => {\n if (c.course?.tUrlCourse) {\n window.location.href = c.course.tUrlCourse;\n } else {\n window.location.href = '/subscription-search';\n }\n };\n\n const courseLabel = c.course\n ? [c.course.tBrandText, c.course.maName].filter(Boolean).join(': ')\n : null;\n\n return (\n <Row className=\"checkout__container bg-light-200\">\n <CountryUnavailableModal\n isOpen={isBillingCountryBlocked}\n homeUrl={homeUrl}\n />\n <Col xs={12} className=\"d-lg-none\">\n <h1 className=\"font-weight-bold text-primary-900\">Checkout</h1>\n </Col>\n <Col xs={12}>\n <Row className=\"flex-column-reverse gap-5 flex-lg-row\">\n {/* ── LEFT ── */}\n <Col xs={12} lg={7} xxl={9} className=\"payment__options\">\n <div>\n <h1 className=\"font-weight-bold text-primary-900 d-none d-lg-block\">\n Checkout\n </h1>\n {c.error && (\n <Alert\n variant=\"danger\"\n icon={ErrorIcon}\n dismissible\n onClose={c.clearError}\n >\n {c.error}\n </Alert>\n )}\n\n {showForm && (\n <>\n {c.phase === 'failed' && (\n <Alert variant=\"danger\" icon={ErrorIcon} className=\"mb-3\">\n {c.lastComment\n || 'Your payment could not be processed. Please check your card details and try again.'}\n </Alert>\n )}\n <PaymentForm\n billing={c.billing}\n setField={c.setField}\n numberMountRef={c.numberMountRef}\n expiryMountRef={c.expiryMountRef}\n cvcMountRef={c.cvcMountRef}\n cardError={c.cardError}\n stripeReady={c.stripeReady}\n sessionReady={c.sessionReady}\n submitting={isSubmitting}\n onPlaceOrder={c.placeOrder}\n trialEnd={displayEnd}\n priceToShow={\n selectedCycle === 'monthly' ? monthlyPrice : annualPrice\n }\n cycleToShow={\n selectedCycle === 'monthly' ? 'monthly' : 'annual'\n }\n userCountry={c.userCountry}\n monthlyRegularAmount={monthlyPrice?.amount}\n />\n </>\n )}\n\n {c.phase === 'success' && (\n <SuccessScreen\n subscriptionBiId={c.subscriptionDetails?.biId || ''}\n cardLast4={c.subscriptionDetails?.cardLast4 || ''}\n purchaseDate={displayStart}\n trialStart={displayStart}\n trialEnd={displayEnd}\n priceToShow={\n purchasedCycle === 'monthly'\n ? monthlyPrice?.label\n : annualPrice?.label\n }\n cycleToShow={\n purchasedCycle === 'monthly' ? 'monthly' : 'annual'\n }\n courseLabel={courseLabel}\n onFindCourse={handleStartCourse}\n />\n )}\n\n {c.phase === 'blocked' && (\n <BlockedScreen detail={c.lastComment} />\n )}\n </div>\n </Col>\n\n {/* ── RIGHT — swaps to EnrollmentSummary on success ── */}\n <Col xs={12} lg={5} xxl={3} className=\"payment__summary\">\n {c.phase === 'success' ? (\n <EnrollmentSummary\n amount={purchasedPrice?.amount}\n currency={purchasedPrice?.currency}\n cycleToShow={purchasedCycle}\n course={c.course}\n onStartCourse={handleStartCourse}\n />\n ) : (\n <CartSummary\n monthlyRegularAmount={monthlyPrice?.amount}\n annualAmount={annualPrice?.amount}\n currency={monthlyPrice?.currency ?? annualPrice?.currency}\n monthlyRenewalLabel={getRenewalLabel(c.billingPlans, 'monthly')}\n annualRenewalLabel={getRenewalLabel(c.billingPlans, 'annual')}\n activeSubscriberCount={c.activeSubscriberCount}\n defaultCycle={selectedCycle}\n onCycleChange={c.setCycle}\n course={c.course}\n />\n )}\n </Col>\n </Row>\n </Col>\n </Row>\n );\n};\n\nexport default Checkout;\n"]}
|
|
@@ -39,6 +39,16 @@ declare const messages: {
|
|
|
39
39
|
defaultMessage: string;
|
|
40
40
|
description: string;
|
|
41
41
|
};
|
|
42
|
+
termsPricingMonthly: {
|
|
43
|
+
id: string;
|
|
44
|
+
defaultMessage: string;
|
|
45
|
+
description: string;
|
|
46
|
+
};
|
|
47
|
+
termsPricingAnnual: {
|
|
48
|
+
id: string;
|
|
49
|
+
defaultMessage: string;
|
|
50
|
+
description: string;
|
|
51
|
+
};
|
|
42
52
|
termsOfUse: {
|
|
43
53
|
id: string;
|
|
44
54
|
defaultMessage: string;
|
|
@@ -40,9 +40,19 @@ const messages = defineMessages({
|
|
|
40
40
|
// Terms
|
|
41
41
|
termsNotice: {
|
|
42
42
|
id: 'checkout.paymentForm.termsNotice',
|
|
43
|
-
defaultMessage: 'Your subscription will start today with a
|
|
43
|
+
defaultMessage: 'Your edX Plus subscription will start today with a {trialDays}-day free trial. Your subscription automatically renews on {date} for {pricing} (inclusive of applicable taxes). Cancel your subscription anytime from your dashboard. By clicking “Confirm subscription” you agree to our {termsLink}, and {refundLink}.',
|
|
44
44
|
description: 'Subscription terms notice shown before the confirm button',
|
|
45
45
|
},
|
|
46
|
+
termsPricingMonthly: {
|
|
47
|
+
id: 'checkout.paymentForm.termsPricingMonthly',
|
|
48
|
+
defaultMessage: '${promoAmount}/mo for {promoMonths} months then ${regularAmount}/mo',
|
|
49
|
+
description: 'Monthly promotional pricing in the terms notice e.g. $39/mo for 3 months then $59/mo',
|
|
50
|
+
},
|
|
51
|
+
termsPricingAnnual: {
|
|
52
|
+
id: 'checkout.paymentForm.termsPricingAnnual',
|
|
53
|
+
defaultMessage: '${amount}/{frequency}',
|
|
54
|
+
description: 'Annual plan pricing in the terms notice e.g. $299/year — no promotional pricing',
|
|
55
|
+
},
|
|
46
56
|
termsOfUse: {
|
|
47
57
|
id: 'checkout.paymentForm.termsOfUse',
|
|
48
58
|
defaultMessage: 'Terms of Use',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Messages.js","sourceRoot":"","sources":["../../../src/components/PaymentForm/Messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,QAAQ,GAAG,cAAc,CAAC;IAC9B,mBAAmB;IACnB,mBAAmB,EAAE;QACnB,EAAE,EAAE,0CAA0C;QAC9C,cAAc,EAAE,uBAAuB;QACvC,WAAW,EAAE,kDAAkD;KAChE;IACD,cAAc,EAAE;QACd,EAAE,EAAE,qCAAqC;QACzC,cAAc,EAAE,kBAAkB;QAClC,WAAW,EAAE,mBAAmB;KACjC;IACD,kBAAkB,EAAE;QAClB,EAAE,EAAE,yCAAyC;QAC7C,cAAc,EAAE,0DAA0D;QAC1E,WAAW,EAAE,yCAAyC;KACvD;IACD,iBAAiB,EAAE;QACjB,EAAE,EAAE,wCAAwC;QAC5C,cAAc,EAAE,qBAAqB;QACrC,WAAW,EAAE,+BAA+B;KAC7C;IAED,yBAAyB;IACzB,IAAI,EAAE;QACJ,EAAE,EAAE,2BAA2B;QAC/B,cAAc,EAAE,MAAM;QACtB,WAAW,EAAE,wCAAwC;KACtD;IACD,SAAS,EAAE;QACT,EAAE,EAAE,gCAAgC;QACpC,cAAc,EAAE,YAAY;QAC5B,WAAW,EAAE,iCAAiC;KAC/C;IACD,MAAM,EAAE;QACN,EAAE,EAAE,6BAA6B;QACjC,cAAc,EAAE,QAAQ;QACxB,WAAW,EAAE,6BAA6B;KAC3C;IAED,QAAQ;IACR,WAAW,EAAE;QACX,EAAE,EAAE,kCAAkC;QACtC,cAAc,EAAE,
|
|
1
|
+
{"version":3,"file":"Messages.js","sourceRoot":"","sources":["../../../src/components/PaymentForm/Messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,QAAQ,GAAG,cAAc,CAAC;IAC9B,mBAAmB;IACnB,mBAAmB,EAAE;QACnB,EAAE,EAAE,0CAA0C;QAC9C,cAAc,EAAE,uBAAuB;QACvC,WAAW,EAAE,kDAAkD;KAChE;IACD,cAAc,EAAE;QACd,EAAE,EAAE,qCAAqC;QACzC,cAAc,EAAE,kBAAkB;QAClC,WAAW,EAAE,mBAAmB;KACjC;IACD,kBAAkB,EAAE;QAClB,EAAE,EAAE,yCAAyC;QAC7C,cAAc,EAAE,0DAA0D;QAC1E,WAAW,EAAE,yCAAyC;KACvD;IACD,iBAAiB,EAAE;QACjB,EAAE,EAAE,wCAAwC;QAC5C,cAAc,EAAE,qBAAqB;QACrC,WAAW,EAAE,+BAA+B;KAC7C;IAED,yBAAyB;IACzB,IAAI,EAAE;QACJ,EAAE,EAAE,2BAA2B;QAC/B,cAAc,EAAE,MAAM;QACtB,WAAW,EAAE,wCAAwC;KACtD;IACD,SAAS,EAAE;QACT,EAAE,EAAE,gCAAgC;QACpC,cAAc,EAAE,YAAY;QAC5B,WAAW,EAAE,iCAAiC;KAC/C;IACD,M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S;QACzB,WAAW,EAAE,wBAAwB;KACtC;IACD,uBAAuB,EAAE;QACvB,EAAE,EAAE,8CAA8C;QAClD,cAAc,EAAE,SAAS;QACzB,WAAW,EAAE,4CAA4C;KAC1D;CACF,CAAC,CAAC;AAEH,eAAe,QAAQ,CAAC","sourcesContent":["import { defineMessages } from '@openedx/frontend-base';\n\nconst messages = defineMessages({\n // Section headings\n selectPaymentMethod: {\n id: 'checkout.paymentForm.selectPaymentMethod',\n defaultMessage: 'Select Payment Method',\n description: 'Heading for the payment method selection section',\n },\n needAssistance: {\n id: 'checkout.paymentForm.needAssistance',\n defaultMessage: 'Need assistance?',\n description: 'Help text heading',\n },\n needAssistanceBody: {\n id: 'checkout.paymentForm.needAssistanceBody',\n defaultMessage: 'Visit the {link} to review purchase and refund policies.',\n description: 'Help text with learner help center link',\n },\n learnerHelpCenter: {\n id: 'checkout.paymentForm.learnerHelpCenter',\n defaultMessage: 'Learner Help Center',\n description: 'Learner help center link text',\n },\n\n // Payment method options\n card: {\n id: 'checkout.paymentForm.card',\n defaultMessage: 'Card',\n description: 'Credit/debit card payment method label',\n },\n googlePay: {\n id: 'checkout.paymentForm.googlePay',\n defaultMessage: 'Google Pay',\n description: 'Google Pay payment method label',\n },\n paypal: {\n id: 'checkout.paymentForm.paypal',\n defaultMessage: 'PayPal',\n description: 'PayPal payment method label',\n },\n\n // Terms\n termsNotice: {\n id: 'checkout.paymentForm.termsNotice',\n defaultMessage: 'Your edX Plus subscription will start today with a {trialDays}-day free trial. Your subscription automatically renews on {date} for {pricing} (inclusive of applicable taxes). Cancel your subscription anytime from your dashboard. By clicking “Confirm subscription” you agree to our {termsLink}, and {refundLink}.',\n description: 'Subscription terms notice shown before the confirm button',\n },\n termsPricingMonthly: {\n id: 'checkout.paymentForm.termsPricingMonthly',\n defaultMessage: '${promoAmount}/mo for {promoMonths} months then ${regularAmount}/mo',\n description: 'Monthly promotional pricing in the terms notice e.g. $39/mo for 3 months then $59/mo',\n },\n termsPricingAnnual: {\n id: 'checkout.paymentForm.termsPricingAnnual',\n defaultMessage: '${amount}/{frequency}',\n description: 'Annual plan pricing in the terms notice e.g. $299/year — no promotional pricing',\n },\n termsOfUse: {\n id: 'checkout.paymentForm.termsOfUse',\n defaultMessage: 'Terms of Use',\n description: 'Terms of Use link text',\n },\n refundPolicy: {\n id: 'checkout.paymentForm.refundPolicy',\n defaultMessage: 'Refund Policy',\n description: 'Refund Policy link text',\n },\n\n // Checkboxes\n recurringConfirm: {\n id: 'checkout.paymentForm.recurringConfirm',\n defaultMessage: 'I agree to enroll in a recurring {cycle} subscription for {price}/{frequency} USD.',\n description: 'First checkbox confirming recurring charge',\n },\n ukCaResidentConfirm: {\n id: 'checkout.paymentForm.ukCaResidentConfirm',\n defaultMessage: 'Second checkbox only for UK and CA residents',\n description: 'Second checkbox for UK and CA residents',\n },\n\n // Submit button\n confirmSubscription: {\n id: 'checkout.paymentForm.confirmSubscription',\n defaultMessage: 'Confirm subscription',\n description: 'Submit button label',\n },\n processing: {\n id: 'checkout.paymentForm.processing',\n defaultMessage: 'Processing…',\n description: 'Submit button label while processing',\n },\n loadingPayment: {\n id: 'checkout.paymentForm.loadingPayment',\n defaultMessage: 'Loading payment…',\n description: 'Submit button label while Stripe loads',\n },\n country: {\n id: 'checkout.paymentForm.country',\n defaultMessage: 'Country',\n description: 'Country selector label',\n },\n spinnerScreenReaderText: {\n id: 'checkout.paymentForm.spinnerScreenReaderText',\n defaultMessage: 'Working',\n description: 'Screen reader text for the loading spinner',\n },\n});\n\nexport default messages;\n"]}
|
|
@@ -16,6 +16,12 @@ export interface PaymentFormProps {
|
|
|
16
16
|
cycleToShow: string;
|
|
17
17
|
trialEnd?: string;
|
|
18
18
|
userCountry?: string | null;
|
|
19
|
+
/** Promotional monthly price e.g. "39" — monthly plans only. */
|
|
20
|
+
promoAmount?: string;
|
|
21
|
+
/** Length of the promotional period in months. */
|
|
22
|
+
promoMonths?: number;
|
|
23
|
+
/** Regular monthly price after the promo period e.g. "59". */
|
|
24
|
+
monthlyRegularAmount?: string;
|
|
19
25
|
}
|
|
20
|
-
declare const PaymentForm: ({ billing, setField, numberMountRef, expiryMountRef, cvcMountRef, cardError, stripeReady, sessionReady, submitting, onPlaceOrder, priceToShow, cycleToShow, trialEnd, userCountry, }: PaymentFormProps) => import("react/jsx-runtime").JSX.Element;
|
|
26
|
+
declare const PaymentForm: ({ billing, setField, numberMountRef, expiryMountRef, cvcMountRef, cardError, stripeReady, sessionReady, submitting, onPlaceOrder, priceToShow, cycleToShow, trialEnd, userCountry, promoAmount, promoMonths, monthlyRegularAmount, }: PaymentFormProps) => import("react/jsx-runtime").JSX.Element;
|
|
21
27
|
export default PaymentForm;
|
|
@@ -5,8 +5,8 @@ import { useIntl } from '@openedx/frontend-base';
|
|
|
5
5
|
import PaymentFields from '../PaymentFields/PaymentFields';
|
|
6
6
|
import { COUNTRIES_REQUIRING_EXTRA_CONFIRM, BILLING_COUNTRIES } from '../../constants';
|
|
7
7
|
import messages from './Messages';
|
|
8
|
-
const PaymentForm = ({ billing, setField, numberMountRef, expiryMountRef, cvcMountRef, cardError, stripeReady, sessionReady, submitting, onPlaceOrder, priceToShow, cycleToShow, trialEnd, userCountry, }) => {
|
|
9
|
-
var _a;
|
|
8
|
+
const PaymentForm = ({ billing, setField, numberMountRef, expiryMountRef, cvcMountRef, cardError, stripeReady, sessionReady, submitting, onPlaceOrder, priceToShow, cycleToShow, trialEnd, userCountry, promoAmount = '39', promoMonths = 3, monthlyRegularAmount = '59', }) => {
|
|
9
|
+
var _a, _b;
|
|
10
10
|
const { formatMessage } = useIntl();
|
|
11
11
|
const [paymentMethod, setPaymentMethod] = useState('card');
|
|
12
12
|
const [confirmed, setConfirmed] = useState(false);
|
|
@@ -20,13 +20,25 @@ const PaymentForm = ({ billing, setField, numberMountRef, expiryMountRef, cvcMou
|
|
|
20
20
|
buttonLabel = formatMessage(messages.loadingPayment);
|
|
21
21
|
else if (!stripeReady)
|
|
22
22
|
buttonLabel = formatMessage(messages.loadingPayment);
|
|
23
|
-
const
|
|
23
|
+
const isMonthly = cycleToShow === 'monthly';
|
|
24
|
+
const amount = isMonthly ? promoAmount : ((_a = priceToShow === null || priceToShow === void 0 ? void 0 : priceToShow.amount) !== null && _a !== void 0 ? _a : '');
|
|
24
25
|
const frequency = cycleToShow === 'annual' ? 'year' : 'month';
|
|
26
|
+
const trialDays = 7;
|
|
27
|
+
const pricing = isMonthly
|
|
28
|
+
? formatMessage(messages.termsPricingMonthly, {
|
|
29
|
+
promoAmount,
|
|
30
|
+
promoMonths,
|
|
31
|
+
regularAmount: monthlyRegularAmount,
|
|
32
|
+
})
|
|
33
|
+
: formatMessage(messages.termsPricingAnnual, {
|
|
34
|
+
amount: (_b = priceToShow === null || priceToShow === void 0 ? void 0 : priceToShow.amount) !== null && _b !== void 0 ? _b : '',
|
|
35
|
+
frequency,
|
|
36
|
+
});
|
|
25
37
|
const buildConsent = () => {
|
|
26
38
|
const termsText = formatMessage(messages.termsNotice, {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
39
|
+
trialDays,
|
|
40
|
+
date: trialEnd !== null && trialEnd !== void 0 ? trialEnd : '{date}',
|
|
41
|
+
pricing,
|
|
30
42
|
termsLink: formatMessage(messages.termsOfUse),
|
|
31
43
|
refundLink: formatMessage(messages.refundPolicy),
|
|
32
44
|
});
|
|
@@ -48,14 +60,14 @@ const PaymentForm = ({ billing, setField, numberMountRef, expiryMountRef, cvcMou
|
|
|
48
60
|
};
|
|
49
61
|
return (_jsxs("div", { className: "payment-form bg-white", children: [_jsx("h2", { className: "payment-form__heading font-weight-bold mb-3 text-primary-500", children: formatMessage(messages.selectPaymentMethod) }), _jsxs("p", { className: "payment-form__help small mb-4", children: [_jsx("strong", { className: "d-block text-primary-500", children: formatMessage(messages.needAssistance) }), ' ', _jsx("span", { className: "text-gray-700", children: formatMessage(messages.needAssistanceBody, {
|
|
50
62
|
link: (_jsx("a", { href: "https://support.edx.org", target: "_blank", rel: "noreferrer", className: "text-gray-700", children: formatMessage(messages.learnerHelpCenter) })),
|
|
51
|
-
}) })] }), _jsxs("div", { className: "payment-form__methods mb-4", children: [_jsxs("div", { className: `payment-form__method${paymentMethod === 'card' ? ' payment-form__method--selected' : ''}`, children: [_jsxs("label", { htmlFor: "paymentMethod-card", className: "payment-form__method-header", children: [_jsx("input", { id: "paymentMethod-card", type: "radio", name: "paymentMethod", value: "card", checked: paymentMethod === 'card', onChange: () => setPaymentMethod('card'), className: "payment-form__radio" }), _jsx("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", children: _jsx("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M0 4C0 3.46957 0.210714 2.96086 0.585786 2.58579C0.960859 2.21071 1.46957 2 2 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4H0ZM0 6V12C0 12.5304 0.210714 13.0391 0.585786 13.4142C0.960859 13.7893 1.46957 14 2 14H14C14.5304 14 15.0391 13.7893 15.4142 13.4142C15.7893 13.0391 16 12.5304 16 12V6H0ZM3 11C3 10.7348 3.10536 10.4804 3.29289 10.2929C3.48043 10.1054 3.73478 10 4 10H5C5.26522 10 5.51957 10.1054 5.70711 10.2929C5.89464 10.4804 6 10.7348 6 11C6 11.2652 5.89464 11.5196 5.70711 11.7071C5.51957 11.8946 5.26522 12 5 12H4C3.73478 12 3.48043 11.8946 3.29289 11.7071C3.10536 11.5196 3 11.2652 3 11Z", fill: "#0270DE" }) }), _jsx("span", { className: "payment-form__method-name text-info-500", children: formatMessage(messages.card) })] }),
|
|
63
|
+
}) })] }), _jsxs("div", { className: "payment-form__methods mb-4", children: [_jsxs("div", { className: `payment-form__method${paymentMethod === 'card' ? ' payment-form__method--selected' : ''}`, children: [_jsxs("label", { htmlFor: "paymentMethod-card", className: "payment-form__method-header", children: [_jsx("input", { id: "paymentMethod-card", type: "radio", name: "paymentMethod", value: "card", checked: paymentMethod === 'card', onChange: () => setPaymentMethod('card'), className: "payment-form__radio" }), _jsx("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", children: _jsx("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M0 4C0 3.46957 0.210714 2.96086 0.585786 2.58579C0.960859 2.21071 1.46957 2 2 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4H0ZM0 6V12C0 12.5304 0.210714 13.0391 0.585786 13.4142C0.960859 13.7893 1.46957 14 2 14H14C14.5304 14 15.0391 13.7893 15.4142 13.4142C15.7893 13.0391 16 12.5304 16 12V6H0ZM3 11C3 10.7348 3.10536 10.4804 3.29289 10.2929C3.48043 10.1054 3.73478 10 4 10H5C5.26522 10 5.51957 10.1054 5.70711 10.2929C5.89464 10.4804 6 10.7348 6 11C6 11.2652 5.89464 11.5196 5.70711 11.7071C5.51957 11.8946 5.26522 12 5 12H4C3.73478 12 3.48043 11.8946 3.29289 11.7071C3.10536 11.5196 3 11.2652 3 11Z", fill: "#0270DE" }) }), _jsx("span", { className: "payment-form__method-name text-info-500", children: formatMessage(messages.card) })] }), _jsxs("div", { className: `payment-form__card-panel${paymentMethod === 'card' ? '' : ' payment-form__card-panel--collapsed'}`, "aria-hidden": paymentMethod !== 'card', children: [_jsx(PaymentFields, { numberMountRef: numberMountRef, expiryMountRef: expiryMountRef, cvcMountRef: cvcMountRef, cardError: cardError }), _jsxs(Form.Group, { controlId: "country", className: "mt-3 mb-0 payment__field--country", children: [_jsx(Form.Label, { className: "small m-0 x-small", children: formatMessage(messages.country) }), _jsx(Form.Control, { as: "select", value: billing.country, onChange: (e) => setField('country', e.target.value), children: BILLING_COUNTRIES.map((country) => {
|
|
52
64
|
return (_jsx("option", { value: country[0], children: country[1] }, country[0]));
|
|
53
|
-
}) })] })] })
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
termsLink: (_jsx("a", { className: "text-gray-700", href: "/terms",
|
|
58
|
-
refundLink: (_jsx("a", { className: "text-gray-700", href: "/refund-policy",
|
|
65
|
+
}) })] })] })] }), _jsx("div", { className: `my-3 payment-form__method payment-form__method--hidden${paymentMethod === 'googlepay' ? ' payment-form__method--selected' : ''}`, children: _jsxs("label", { htmlFor: "paymentMethod-googlepay", className: "payment-form__method-header", children: [_jsx("input", { id: "paymentMethod-googlepay", type: "radio", name: "paymentMethod", value: "googlepay", checked: paymentMethod === 'googlepay', onChange: () => setPaymentMethod('googlepay'), className: "payment-form__radio" }), _jsx("span", { className: "payment-form__method-icon payment-form__method-icon--gpay", "aria-hidden": "true", children: "G" }), _jsx("span", { className: "payment-form__method-name", children: formatMessage(messages.googlePay) })] }) }), _jsx("div", { className: `my-3 payment-form__method${paymentMethod === 'paypal' ? ' payment-form__method--selected' : ''}`, children: _jsxs("label", { htmlFor: "paymentMethod-paypal", className: "payment-form__method-header", children: [_jsx("input", { id: "paymentMethod-paypal", type: "radio", name: "paymentMethod", value: "paypal", checked: paymentMethod === 'paypal', onChange: () => setPaymentMethod('paypal'), className: "payment-form__radio" }), _jsx("span", { className: "payment-form__method-icon payment-form__method-icon--paypal", "aria-hidden": "true", children: "P" }), _jsx("span", { className: "payment-form__method-name", children: formatMessage(messages.paypal) })] }) })] }), _jsx("p", { className: "payment-form__terms text-gray-700 mb-3", children: formatMessage(messages.termsNotice, {
|
|
66
|
+
trialDays,
|
|
67
|
+
date: trialEnd !== null && trialEnd !== void 0 ? trialEnd : '{date}',
|
|
68
|
+
pricing,
|
|
69
|
+
termsLink: (_jsx("a", { className: "text-gray-700", href: "/edx-terms-service", children: formatMessage(messages.termsOfUse) })),
|
|
70
|
+
refundLink: (_jsx("a", { className: "text-gray-700", href: "/edx-terms-service#refund-policy", children: formatMessage(messages.refundPolicy) })),
|
|
59
71
|
}) }), _jsx(Form.Group, { controlId: "recurringConfirm", className: "mb-2", children: _jsx(Form.Checkbox, { id: "recurringConfirm", checked: confirmed, onChange: (e) => setConfirmed(e.target.checked), children: _jsx("span", { className: "text-gray-700", children: formatMessage(messages.recurringConfirm, {
|
|
60
72
|
cycle: cycleToShow,
|
|
61
73
|
price: amount,
|
|
@@ -63,6 +75,7 @@ const PaymentForm = ({ billing, setField, numberMountRef, expiryMountRef, cvcMou
|
|
|
63
75
|
}) }) }) }), showExtraConfirm && (_jsx(Form.Group, { controlId: "ukCaConfirm", className: "mb-4", children: _jsx(Form.Checkbox, { id: "ukCaConfirm", checked: ukCaConfirmed, onChange: (e) => setUkCaConfirmed(e.target.checked), children: _jsx("span", { className: "text-gray-700", children: formatMessage(messages.ukCaResidentConfirm) }) }) })), _jsxs(Button, { variant: "brand", className: "payment-form__submit", onClick: () => onPlaceOrder(buildConsent()), disabled: !stripeReady
|
|
64
76
|
|| submitting
|
|
65
77
|
|| !confirmed
|
|
78
|
+
|| paymentMethod === 'paypal'
|
|
66
79
|
|| (showExtraConfirm && !ukCaConfirmed), children: [busy && (_jsx(Spinner, { animation: "border", size: "sm", className: "mr-2", screenReaderText: formatMessage(messages.spinnerScreenReaderText) })), buttonLabel] })] }));
|
|
67
80
|
};
|
|
68
81
|
export default PaymentForm;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PaymentForm.js","sourceRoot":"","sources":["../../../src/components/PaymentForm/PaymentForm.tsx"],"names":[],"mappings":";AAAA,OAAc,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAExC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAG3D,OAAO,EAAE,iCAAiC,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACvF,OAAO,QAAQ,MAAM,YAAY,CAAC;AAqBlC,MAAM,WAAW,GAAG,CAAC,EACnB,OAAO,EACP,QAAQ,EACR,cAAc,EACd,cAAc,EACd,WAAW,EAC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AAE,MAAM;4BACb,SAAS;yBACV,CAAC,GACG,GACO,GACL,EAEZ,gBAAgB,IAAI,CACnB,KAAC,IAAI,CAAC,KAAK,IAAC,SAAS,EAAC,aAAa,EAAC,SAAS,EAAC,MAAM,YAClD,KAAC,IAAI,CAAC,QAAQ,IACZ,EAAE,EAAC,aAAa,EAChB,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,CAAC,CAAsC,EAAE,EAAE,CACnD,gBAAgB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,YAEpC,eAAM,SAAS,EAAC,eAAe,YAC5B,aAAa,CAAC,QAAQ,CAAC,mBAAmB,CAAC,GACvC,GACO,GACL,CACd,EAGD,MAAC,MAAM,IACL,OAAO,EAAC,OAAO,EACf,SAAS,EAAC,sBAAsB,EAChC,OAAO,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,YAAY,EAAE,CAAC,EAC3C,QAAQ,EACN,CAAC,WAAW;uBACT,UAAU;uBACV,CAAC,SAAS;uBACV,CAAC,gBAAgB,IAAI,CAAC,aAAa,CAAC,aAGxC,IAAI,IAAI,CACP,KAAC,OAAO,IACN,SAAS,EAAC,QAAQ,EAClB,IAAI,EAAC,IAAI,EACT,SAAS,EAAC,MAAM,EAChB,gBAAgB,EAAE,aAAa,CAAC,QAAQ,CAAC,uBAAuB,CAAC,GACjE,CACH,EACA,WAAW,IACL,IACL,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,WAAW,CAAC","sourcesContent":["import React, { useState } from 'react';\nimport type { Ref } from 'react';\nimport { Button, Form, Spinner } from '@openedx/paragon';\nimport { useIntl } from '@openedx/frontend-base';\nimport PaymentFields from '../PaymentFields/PaymentFields';\nimport type { BillingInfo, CheckoutConsent } from '../../types';\nimport type { PlanPrice } from '../../utils/billingDetails';\nimport { COUNTRIES_REQUIRING_EXTRA_CONFIRM, BILLING_COUNTRIES } from '../../constants';\nimport messages from './Messages';\n\ntype PaymentMethod = 'card' | 'googlepay' | 'paypal';\n\nexport interface PaymentFormProps {\n billing: BillingInfo,\n setField: (field: keyof BillingInfo, value: string) => void,\n numberMountRef: Ref<HTMLDivElement>,\n expiryMountRef: Ref<HTMLDivElement>,\n cvcMountRef: Ref<HTMLDivElement>,\n cardError: string,\n stripeReady: boolean,\n sessionReady: boolean,\n submitting: boolean,\n onPlaceOrder: (consent: CheckoutConsent) => void,\n priceToShow: PlanPrice | null,\n cycleToShow: string,\n trialEnd?: string,\n userCountry?: string | null,\n}\n\nconst PaymentForm = ({\n billing,\n setField,\n numberMountRef,\n expiryMountRef,\n cvcMountRef,\n cardError,\n stripeReady,\n sessionReady,\n submitting,\n onPlaceOrder,\n priceToShow,\n cycleToShow,\n trialEnd,\n userCountry,\n}: PaymentFormProps) => {\n const { formatMessage } = useIntl();\n const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('card');\n const [confirmed, setConfirmed] = useState(false);\n const [ukCaConfirmed, setUkCaConfirmed] = useState(false);\n\n const showExtraConfirm\n = !!userCountry && COUNTRIES_REQUIRING_EXTRA_CONFIRM.includes(userCountry);\n\n const busy = submitting || !stripeReady || !sessionReady;\n\n let buttonLabel = formatMessage(messages.confirmSubscription);\n if (submitting) buttonLabel = formatMessage(messages.processing);\n else if (!sessionReady) buttonLabel = formatMessage(messages.loadingPayment);\n else if (!stripeReady) buttonLabel = formatMessage(messages.loadingPayment);\n\n const amount = priceToShow?.amount ?? '';\n const frequency = cycleToShow === 'annual' ? 'year' : 'month';\n\n const buildConsent = (): CheckoutConsent => {\n const termsText = formatMessage(messages.termsNotice, {\n renewalDate: trialEnd ?? '{date}',\n price: amount,\n frequency,\n termsLink: formatMessage(messages.termsOfUse),\n refundLink: formatMessage(messages.refundPolicy),\n });\n const recurringText = formatMessage(messages.recurringConfirm, {\n cycle: cycleToShow,\n price: amount,\n frequency,\n });\n const consentParts = [termsText, recurringText];\n if (showExtraConfirm) {\n consentParts.push(formatMessage(messages.ukCaResidentConfirm));\n }\n return {\n tConsentRecurring: confirmed,\n tConsentUkCa: showExtraConfirm ? ukCaConfirmed : null,\n tConsentAt: new Date().toISOString(),\n tConsentText: consentParts.join('\\n\\n'),\n };\n };\n\n return (\n <div className=\"payment-form bg-white\">\n <h2 className=\"payment-form__heading font-weight-bold mb-3 text-primary-500\">\n {formatMessage(messages.selectPaymentMethod)}\n </h2>\n\n <p className=\"payment-form__help small mb-4\">\n <strong className=\"d-block text-primary-500\">\n {formatMessage(messages.needAssistance)}\n </strong>{' '}\n <span className=\"text-gray-700\">\n {formatMessage(messages.needAssistanceBody, {\n link: (\n <a\n href=\"https://support.edx.org\"\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-gray-700\"\n >\n {formatMessage(messages.learnerHelpCenter)}\n </a>\n ),\n })}\n </span>\n </p>\n\n {/* ── Payment method accordion ── */}\n <div className=\"payment-form__methods mb-4\">\n {/* ── Card ── */}\n <div\n className={`payment-form__method${paymentMethod === 'card' ? ' payment-form__method--selected' : ''}`}\n >\n {/* Header row — always visible */}\n <label\n htmlFor=\"paymentMethod-card\"\n className=\"payment-form__method-header\"\n >\n <input\n id=\"paymentMethod-card\"\n type=\"radio\"\n name=\"paymentMethod\"\n value=\"card\"\n checked={paymentMethod === 'card'}\n onChange={() => setPaymentMethod('card')}\n className=\"payment-form__radio\"\n />\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M0 4C0 3.46957 0.210714 2.96086 0.585786 2.58579C0.960859 2.21071 1.46957 2 2 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4H0ZM0 6V12C0 12.5304 0.210714 13.0391 0.585786 13.4142C0.960859 13.7893 1.46957 14 2 14H14C14.5304 14 15.0391 13.7893 15.4142 13.4142C15.7893 13.0391 16 12.5304 16 12V6H0ZM3 11C3 10.7348 3.10536 10.4804 3.29289 10.2929C3.48043 10.1054 3.73478 10 4 10H5C5.26522 10 5.51957 10.1054 5.70711 10.2929C5.89464 10.4804 6 10.7348 6 11C6 11.2652 5.89464 11.5196 5.70711 11.7071C5.51957 11.8946 5.26522 12 5 12H4C3.73478 12 3.48043 11.8946 3.29289 11.7071C3.10536 11.5196 3 11.2652 3 11Z\"\n fill=\"#0270DE\"\n />\n </svg>\n <span className=\"payment-form__method-name text-info-500\">\n {formatMessage(messages.card)}\n </span>\n </label>\n\n {/* Expanded panel — only when selected */}\n {paymentMethod === 'card' && (\n <div className=\"payment-form__card-panel\">\n <PaymentFields\n numberMountRef={numberMountRef}\n expiryMountRef={expiryMountRef}\n cvcMountRef={cvcMountRef}\n cardError={cardError}\n />\n <Form.Group\n controlId=\"country\"\n className=\"mt-3 mb-0 payment__field--country\"\n >\n <Form.Label className=\"small m-0 x-small\">\n {formatMessage(messages.country)}\n </Form.Label>\n <Form.Control\n as=\"select\"\n value={billing.country}\n onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>\n setField('country', e.target.value)}\n >\n {BILLING_COUNTRIES.map((country) => {\n return (\n <option key={country[0]} value={country[0]}>\n {country[1]}\n </option>\n );\n })}\n </Form.Control>\n </Form.Group>\n </div>\n )}\n </div>\n\n {/* ── Google Pay (hidden for now) ── */}\n <div\n className={`my-3 payment-form__method payment-form__method--hidden${paymentMethod === 'googlepay' ? ' payment-form__method--selected' : ''}`}\n >\n <label\n htmlFor=\"paymentMethod-googlepay\"\n className=\"payment-form__method-header\"\n >\n <input\n id=\"paymentMethod-googlepay\"\n type=\"radio\"\n name=\"paymentMethod\"\n value=\"googlepay\"\n checked={paymentMethod === 'googlepay'}\n onChange={() => setPaymentMethod('googlepay')}\n className=\"payment-form__radio\"\n />\n <span\n className=\"payment-form__method-icon payment-form__method-icon--gpay\"\n aria-hidden=\"true\"\n >\n G\n </span>\n <span className=\"payment-form__method-name\">\n {formatMessage(messages.googlePay)}\n </span>\n </label>\n </div>\n\n {/* ── PayPal (hidden for now) ── */}\n <div\n className={`payment-form__method payment-form__method--hidden${paymentMethod === 'paypal' ? ' payment-form__method--selected' : ''}`}\n >\n <label\n htmlFor=\"paymentMethod-paypal\"\n className=\"payment-form__method-header\"\n >\n <input\n id=\"paymentMethod-paypal\"\n type=\"radio\"\n name=\"paymentMethod\"\n value=\"paypal\"\n checked={paymentMethod === 'paypal'}\n onChange={() => setPaymentMethod('paypal')}\n className=\"payment-form__radio\"\n />\n <span\n className=\"payment-form__method-icon payment-form__method-icon--paypal\"\n aria-hidden=\"true\"\n >\n P\n </span>\n <span className=\"payment-form__method-name\">\n {formatMessage(messages.paypal)}\n </span>\n </label>\n </div>\n </div>\n\n {/* ── Terms ── */}\n <p className=\"payment-form__terms text-gray-700 mb-3\">\n {formatMessage(messages.termsNotice, {\n renewalDate: trialEnd ?? '{date}',\n price: amount,\n frequency,\n termsLink: (\n <a\n className=\"text-gray-700\"\n href=\"/terms\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n {formatMessage(messages.termsOfUse)}\n </a>\n ),\n refundLink: (\n <a\n className=\"text-gray-700\"\n href=\"/refund-policy\"\n target=\"_blank\"\n rel=\"noreferrer\"\n >\n {formatMessage(messages.refundPolicy)}\n </a>\n ),\n })}\n </p>\n\n {/* ── Checkboxes ── */}\n <Form.Group controlId=\"recurringConfirm\" className=\"mb-2\">\n <Form.Checkbox\n id=\"recurringConfirm\"\n checked={confirmed}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setConfirmed(e.target.checked)}\n >\n <span className=\"text-gray-700\">\n {formatMessage(messages.recurringConfirm, {\n cycle: cycleToShow,\n price: amount,\n frequency,\n })}\n </span>\n </Form.Checkbox>\n </Form.Group>\n\n {showExtraConfirm && (\n <Form.Group controlId=\"ukCaConfirm\" className=\"mb-4\">\n <Form.Checkbox\n id=\"ukCaConfirm\"\n checked={ukCaConfirmed}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setUkCaConfirmed(e.target.checked)}\n >\n <span className=\"text-gray-700\">\n {formatMessage(messages.ukCaResidentConfirm)}\n </span>\n </Form.Checkbox>\n </Form.Group>\n )}\n\n {/* ── Submit ── */}\n <Button\n variant=\"brand\"\n className=\"payment-form__submit\"\n onClick={() => onPlaceOrder(buildConsent())}\n disabled={\n !stripeReady\n || submitting\n || !confirmed\n || (showExtraConfirm && !ukCaConfirmed)\n }\n >\n {busy && (\n <Spinner\n animation=\"border\"\n size=\"sm\"\n className=\"mr-2\"\n screenReaderText={formatMessage(messages.spinnerScreenReaderText)}\n />\n )}\n {buttonLabel}\n </Button>\n </div>\n );\n};\n\nexport default PaymentForm;\n"]}
|
|
1
|
+
{"version":3,"file":"PaymentForm.js","sourceRoot":"","sources":["../../../src/components/PaymentForm/PaymentForm.tsx"],"names":[],"mappings":";AAAA,OAAc,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAExC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAG3D,OAAO,EAAE,iCAAiC,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACvF,OAAO,QAAQ,MAAM,YAAY,CAAC;AA2BlC,MAAM,WAAW,GAAG,CAAC,EACnB,OAAO,EACP,QAAQ,EACR,cAAc,EACd,cAAc,EACd,WAAW,EACX,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,QAAQ,EACR,WAAW,EACX,WAAW,GAAG,IAAI,EAClB,WAAW,GAAG,CAAC,EACf,oBAAoB,GAAG,IAAI,GACV,EAAE,EAAE;;IACrB,MAAM,EAAE,aAAa,EAAE,GAAG,OAAO,EAAE,CAAC;IACpC,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAAgB,MAAM,CAAC,CAAC;I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,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,YAEhC,eAAM,SAAS,EAAC,eAAe,YAC5B,aAAa,CAAC,QAAQ,CAAC,gBAAgB,EAAE;4BACxC,KAAK,EAAE,WAAW;4BAClB,KAAK,EAAE,MAAM;4BACb,SAAS;yBACV,CAAC,GACG,GACO,GACL,EAEZ,gBAAgB,IAAI,CACnB,KAAC,IAAI,CAAC,KAAK,IAAC,SAAS,EAAC,aAAa,EAAC,SAAS,EAAC,MAAM,YAClD,KAAC,IAAI,CAAC,QAAQ,IACZ,EAAE,EAAC,aAAa,EAChB,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,CAAC,CAAsC,EAAE,EAAE,CACnD,gBAAgB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,YAEpC,eAAM,SAAS,EAAC,eAAe,YAC5B,aAAa,CAAC,QAAQ,CAAC,mBAAmB,CAAC,GACvC,GACO,GACL,CACd,EAGD,MAAC,MAAM,IACL,OAAO,EAAC,OAAO,EACf,SAAS,EAAC,sBAAsB,EAChC,OAAO,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,YAAY,EAAE,CAAC,EAC3C,QAAQ,EACN,CAAC,WAAW;uBACT,UAAU;uBACV,CAAC,SAAS;uBACV,aAAa,KAAK,QAAQ;uBAC1B,CAAC,gBAAgB,IAAI,CAAC,aAAa,CAAC,aAGxC,IAAI,IAAI,CACP,KAAC,OAAO,IACN,SAAS,EAAC,QAAQ,EAClB,IAAI,EAAC,IAAI,EACT,SAAS,EAAC,MAAM,EAChB,gBAAgB,EAAE,aAAa,CAAC,QAAQ,CAAC,uBAAuB,CAAC,GACjE,CACH,EACA,WAAW,IACL,IACL,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,WAAW,CAAC","sourcesContent":["import React, { useState } from 'react';\nimport type { Ref } from 'react';\nimport { Button, Form, Spinner } from '@openedx/paragon';\nimport { useIntl } from '@openedx/frontend-base';\nimport PaymentFields from '../PaymentFields/PaymentFields';\nimport type { BillingInfo, CheckoutConsent } from '../../types';\nimport type { PlanPrice } from '../../utils/billingDetails';\nimport { COUNTRIES_REQUIRING_EXTRA_CONFIRM, BILLING_COUNTRIES } from '../../constants';\nimport messages from './Messages';\n\ntype PaymentMethod = 'card' | 'googlepay' | 'paypal';\n\nexport interface PaymentFormProps {\n billing: BillingInfo,\n setField: (field: keyof BillingInfo, value: string) => void,\n numberMountRef: Ref<HTMLDivElement>,\n expiryMountRef: Ref<HTMLDivElement>,\n cvcMountRef: Ref<HTMLDivElement>,\n cardError: string,\n stripeReady: boolean,\n sessionReady: boolean,\n submitting: boolean,\n onPlaceOrder: (consent: CheckoutConsent) => void,\n priceToShow: PlanPrice | null,\n cycleToShow: string,\n trialEnd?: string,\n userCountry?: string | null,\n /** Promotional monthly price e.g. \"39\" — monthly plans only. */\n promoAmount?: string,\n /** Length of the promotional period in months. */\n promoMonths?: number,\n /** Regular monthly price after the promo period e.g. \"59\". */\n monthlyRegularAmount?: string,\n}\n\nconst PaymentForm = ({\n billing,\n setField,\n numberMountRef,\n expiryMountRef,\n cvcMountRef,\n cardError,\n stripeReady,\n sessionReady,\n submitting,\n onPlaceOrder,\n priceToShow,\n cycleToShow,\n trialEnd,\n userCountry,\n promoAmount = '39',\n promoMonths = 3,\n monthlyRegularAmount = '59',\n}: PaymentFormProps) => {\n const { formatMessage } = useIntl();\n const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('card');\n const [confirmed, setConfirmed] = useState(false);\n const [ukCaConfirmed, setUkCaConfirmed] = useState(false);\n\n const showExtraConfirm\n = !!userCountry && COUNTRIES_REQUIRING_EXTRA_CONFIRM.includes(userCountry);\n\n const busy = submitting || !stripeReady || !sessionReady;\n\n let buttonLabel = formatMessage(messages.confirmSubscription);\n if (submitting) buttonLabel = formatMessage(messages.processing);\n else if (!sessionReady) buttonLabel = formatMessage(messages.loadingPayment);\n else if (!stripeReady) buttonLabel = formatMessage(messages.loadingPayment);\n\n const isMonthly = cycleToShow === 'monthly';\n const amount = isMonthly ? promoAmount : (priceToShow?.amount ?? '');\n const frequency = cycleToShow === 'annual' ? 'year' : 'month';\n const trialDays = 7;\n const pricing = isMonthly\n ? formatMessage(messages.termsPricingMonthly, {\n promoAmount,\n promoMonths,\n regularAmount: monthlyRegularAmount,\n })\n : formatMessage(messages.termsPricingAnnual, {\n amount: priceToShow?.amount ?? '',\n frequency,\n });\n\n const buildConsent = (): CheckoutConsent => {\n const termsText = formatMessage(messages.termsNotice, {\n trialDays,\n date: trialEnd ?? '{date}',\n pricing,\n termsLink: formatMessage(messages.termsOfUse),\n refundLink: formatMessage(messages.refundPolicy),\n });\n const recurringText = formatMessage(messages.recurringConfirm, {\n cycle: cycleToShow,\n price: amount,\n frequency,\n });\n const consentParts = [termsText, recurringText];\n if (showExtraConfirm) {\n consentParts.push(formatMessage(messages.ukCaResidentConfirm));\n }\n return {\n tConsentRecurring: confirmed,\n tConsentUkCa: showExtraConfirm ? ukCaConfirmed : null,\n tConsentAt: new Date().toISOString(),\n tConsentText: consentParts.join('\\n\\n'),\n };\n };\n\n return (\n <div className=\"payment-form bg-white\">\n <h2 className=\"payment-form__heading font-weight-bold mb-3 text-primary-500\">\n {formatMessage(messages.selectPaymentMethod)}\n </h2>\n\n <p className=\"payment-form__help small mb-4\">\n <strong className=\"d-block text-primary-500\">\n {formatMessage(messages.needAssistance)}\n </strong>{' '}\n <span className=\"text-gray-700\">\n {formatMessage(messages.needAssistanceBody, {\n link: (\n <a\n href=\"https://support.edx.org\"\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-gray-700\"\n >\n {formatMessage(messages.learnerHelpCenter)}\n </a>\n ),\n })}\n </span>\n </p>\n\n {/* ── Payment method accordion ── */}\n <div className=\"payment-form__methods mb-4\">\n {/* ── Card ── */}\n <div\n className={`payment-form__method${paymentMethod === 'card' ? ' payment-form__method--selected' : ''}`}\n >\n {/* Header row — always visible */}\n <label\n htmlFor=\"paymentMethod-card\"\n className=\"payment-form__method-header\"\n >\n <input\n id=\"paymentMethod-card\"\n type=\"radio\"\n name=\"paymentMethod\"\n value=\"card\"\n checked={paymentMethod === 'card'}\n onChange={() => setPaymentMethod('card')}\n className=\"payment-form__radio\"\n />\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M0 4C0 3.46957 0.210714 2.96086 0.585786 2.58579C0.960859 2.21071 1.46957 2 2 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4H0ZM0 6V12C0 12.5304 0.210714 13.0391 0.585786 13.4142C0.960859 13.7893 1.46957 14 2 14H14C14.5304 14 15.0391 13.7893 15.4142 13.4142C15.7893 13.0391 16 12.5304 16 12V6H0ZM3 11C3 10.7348 3.10536 10.4804 3.29289 10.2929C3.48043 10.1054 3.73478 10 4 10H5C5.26522 10 5.51957 10.1054 5.70711 10.2929C5.89464 10.4804 6 10.7348 6 11C6 11.2652 5.89464 11.5196 5.70711 11.7071C5.51957 11.8946 5.26522 12 5 12H4C3.73478 12 3.48043 11.8946 3.29289 11.7071C3.10536 11.5196 3 11.2652 3 11Z\"\n fill=\"#0270DE\"\n />\n </svg>\n <span className=\"payment-form__method-name text-info-500\">\n {formatMessage(messages.card)}\n </span>\n </label>\n\n {/* Keep Stripe host nodes mounted so Elements stay interactive after toggling methods. */}\n <div\n className={`payment-form__card-panel${paymentMethod === 'card' ? '' : ' payment-form__card-panel--collapsed'}`}\n aria-hidden={paymentMethod !== 'card'}\n >\n <PaymentFields\n numberMountRef={numberMountRef}\n expiryMountRef={expiryMountRef}\n cvcMountRef={cvcMountRef}\n cardError={cardError}\n />\n <Form.Group\n controlId=\"country\"\n className=\"mt-3 mb-0 payment__field--country\"\n >\n <Form.Label className=\"small m-0 x-small\">\n {formatMessage(messages.country)}\n </Form.Label>\n <Form.Control\n as=\"select\"\n value={billing.country}\n onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>\n setField('country', e.target.value)}\n >\n {BILLING_COUNTRIES.map((country) => {\n return (\n <option key={country[0]} value={country[0]}>\n {country[1]}\n </option>\n );\n })}\n </Form.Control>\n </Form.Group>\n </div>\n </div>\n\n {/* ── Google Pay (hidden for now) ── */}\n <div\n className={`my-3 payment-form__method payment-form__method--hidden${paymentMethod === 'googlepay' ? ' payment-form__method--selected' : ''}`}\n >\n <label\n htmlFor=\"paymentMethod-googlepay\"\n className=\"payment-form__method-header\"\n >\n <input\n id=\"paymentMethod-googlepay\"\n type=\"radio\"\n name=\"paymentMethod\"\n value=\"googlepay\"\n checked={paymentMethod === 'googlepay'}\n onChange={() => setPaymentMethod('googlepay')}\n className=\"payment-form__radio\"\n />\n <span\n className=\"payment-form__method-icon payment-form__method-icon--gpay\"\n aria-hidden=\"true\"\n >\n G\n </span>\n <span className=\"payment-form__method-name\">\n {formatMessage(messages.googlePay)}\n </span>\n </label>\n </div>\n\n {/* ── PayPal (UI only; backend wiring pending) ── */}\n <div\n className={`my-3 payment-form__method${paymentMethod === 'paypal' ? ' payment-form__method--selected' : ''}`}\n >\n <label\n htmlFor=\"paymentMethod-paypal\"\n className=\"payment-form__method-header\"\n >\n <input\n id=\"paymentMethod-paypal\"\n type=\"radio\"\n name=\"paymentMethod\"\n value=\"paypal\"\n checked={paymentMethod === 'paypal'}\n onChange={() => setPaymentMethod('paypal')}\n className=\"payment-form__radio\"\n />\n <span\n className=\"payment-form__method-icon payment-form__method-icon--paypal\"\n aria-hidden=\"true\"\n >\n P\n </span>\n <span className=\"payment-form__method-name\">\n {formatMessage(messages.paypal)}\n </span>\n </label>\n </div>\n </div>\n\n {/* ── Terms ── */}\n <p className=\"payment-form__terms text-gray-700 mb-3\">\n {formatMessage(messages.termsNotice, {\n trialDays,\n date: trialEnd ?? '{date}',\n pricing,\n termsLink: (\n <a\n className=\"text-gray-700\"\n href=\"/edx-terms-service\"\n >\n {formatMessage(messages.termsOfUse)}\n </a>\n ),\n refundLink: (\n <a\n className=\"text-gray-700\"\n href=\"/edx-terms-service#refund-policy\"\n >\n {formatMessage(messages.refundPolicy)}\n </a>\n ),\n })}\n </p>\n\n {/* ── Checkboxes ── */}\n <Form.Group controlId=\"recurringConfirm\" className=\"mb-2\">\n <Form.Checkbox\n id=\"recurringConfirm\"\n checked={confirmed}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setConfirmed(e.target.checked)}\n >\n <span className=\"text-gray-700\">\n {formatMessage(messages.recurringConfirm, {\n cycle: cycleToShow,\n price: amount,\n frequency,\n })}\n </span>\n </Form.Checkbox>\n </Form.Group>\n\n {showExtraConfirm && (\n <Form.Group controlId=\"ukCaConfirm\" className=\"mb-4\">\n <Form.Checkbox\n id=\"ukCaConfirm\"\n checked={ukCaConfirmed}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setUkCaConfirmed(e.target.checked)}\n >\n <span className=\"text-gray-700\">\n {formatMessage(messages.ukCaResidentConfirm)}\n </span>\n </Form.Checkbox>\n </Form.Group>\n )}\n\n {/* ── Submit ── */}\n <Button\n variant=\"brand\"\n className=\"payment-form__submit\"\n onClick={() => onPlaceOrder(buildConsent())}\n disabled={\n !stripeReady\n || submitting\n || !confirmed\n || paymentMethod === 'paypal'\n || (showExtraConfirm && !ukCaConfirmed)\n }\n >\n {busy && (\n <Spinner\n animation=\"border\"\n size=\"sm\"\n className=\"mr-2\"\n screenReaderText={formatMessage(messages.spinnerScreenReaderText)}\n />\n )}\n {buttonLabel}\n </Button>\n </div>\n );\n};\n\nexport default PaymentForm;\n"]}
|
|
@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
};
|
|
10
10
|
import { useCallback, useEffect, useMemo, useRef, useState, } from 'react';
|
|
11
11
|
import { createCheckoutClient } from '../../utils/checkout';
|
|
12
|
+
import { getPlanFromUrl, writePlanQueryParam } from '../../utils/planQuery';
|
|
12
13
|
import { loadStripe } from '../../utils/stripe';
|
|
13
14
|
import { STATUS, STATUS_LABELS, STRIPE_ELEMENT_OPTS, phaseFor, DEFAULTS, } from '../../constants';
|
|
14
15
|
import { useCartStatusQuery, useSubscriptionIdQuery, useBillingPlansQuery, useActiveSubscriptionsQuery, useViaxSessionQuery, useCourseDetailQuery, } from './useCheckoutQueries';
|
|
@@ -65,8 +66,12 @@ export default function useCheckout(options = {}) {
|
|
|
65
66
|
const [billing, setBilling] = useState({
|
|
66
67
|
firstName: '', lastName: '', city: '', zip: '', country: 'US', line1: '', state: '',
|
|
67
68
|
});
|
|
68
|
-
const [selectedCycle, setSelectedCycle] = useState(
|
|
69
|
+
const [selectedCycle, setSelectedCycle] = useState(getPlanFromUrl);
|
|
69
70
|
const [processingSubscription, setProcessingSubscription] = useState(false);
|
|
71
|
+
const setCycle = useCallback((cycle) => {
|
|
72
|
+
setSelectedCycle(cycle);
|
|
73
|
+
writePlanQueryParam(cycle);
|
|
74
|
+
}, []);
|
|
70
75
|
useEffect(() => {
|
|
71
76
|
if (sessionQuery.error) {
|
|
72
77
|
setError(sessionQuery.error.message);
|
|
@@ -77,12 +82,37 @@ export default function useCheckout(options = {}) {
|
|
|
77
82
|
// Stripe instances — written inside useEffect and mutations.
|
|
78
83
|
const stripeInstanceRef = useRef(null);
|
|
79
84
|
const cardNumberElementRef = useRef(null);
|
|
85
|
+
const cardExpiryElementRef = useRef(null);
|
|
86
|
+
const cardCvcElementRef = useRef(null);
|
|
80
87
|
const elementsRef = useRef(null);
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
const
|
|
85
|
-
const
|
|
88
|
+
// DOM mount targets — callback refs so we remount when hosts leave and return.
|
|
89
|
+
const numberMountNodeRef = useRef(null);
|
|
90
|
+
const expiryMountNodeRef = useRef(null);
|
|
91
|
+
const cvcMountNodeRef = useRef(null);
|
|
92
|
+
const [cardHostsEpoch, setCardHostsEpoch] = useState(0);
|
|
93
|
+
const assignCardHost = useCallback((store, node) => {
|
|
94
|
+
var _a, _b, _c, _d, _e, _f;
|
|
95
|
+
store.current = node;
|
|
96
|
+
if (numberMountNodeRef.current
|
|
97
|
+
&& expiryMountNodeRef.current
|
|
98
|
+
&& cvcMountNodeRef.current) {
|
|
99
|
+
setCardHostsEpoch((n) => n + 1);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
// Hosts are leaving the DOM — detach so Stripe is not bound to dead nodes.
|
|
103
|
+
(_b = (_a = cardNumberElementRef.current) === null || _a === void 0 ? void 0 : _a.unmount) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
104
|
+
(_d = (_c = cardExpiryElementRef.current) === null || _c === void 0 ? void 0 : _c.unmount) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
105
|
+
(_f = (_e = cardCvcElementRef.current) === null || _e === void 0 ? void 0 : _e.unmount) === null || _f === void 0 ? void 0 : _f.call(_e);
|
|
106
|
+
}, []);
|
|
107
|
+
const numberMountRef = useCallback((node) => {
|
|
108
|
+
assignCardHost(numberMountNodeRef, node);
|
|
109
|
+
}, [assignCardHost]);
|
|
110
|
+
const expiryMountRef = useCallback((node) => {
|
|
111
|
+
assignCardHost(expiryMountNodeRef, node);
|
|
112
|
+
}, [assignCardHost]);
|
|
113
|
+
const cvcMountRef = useCallback((node) => {
|
|
114
|
+
assignCardHost(cvcMountNodeRef, node);
|
|
115
|
+
}, [assignCardHost]);
|
|
86
116
|
const mountedRef = useRef(true);
|
|
87
117
|
const completedRef = useRef(false);
|
|
88
118
|
const sessionRef = useRef(null);
|
|
@@ -159,25 +189,43 @@ export default function useCheckout(options = {}) {
|
|
|
159
189
|
mountedRef.current = false;
|
|
160
190
|
};
|
|
161
191
|
}, [stripePublishableKey]);
|
|
162
|
-
// --- mount Stripe Elements once Stripe is loaded ---
|
|
192
|
+
// --- mount Stripe Elements once Stripe is loaded; remount if hosts return ---
|
|
163
193
|
useEffect(() => {
|
|
194
|
+
var _a, _b, _c, _d, _e, _f;
|
|
164
195
|
if (!stripe)
|
|
165
196
|
return;
|
|
166
|
-
|
|
197
|
+
const numberNode = numberMountNodeRef.current;
|
|
198
|
+
const expiryNode = expiryMountNodeRef.current;
|
|
199
|
+
const cvcNode = cvcMountNodeRef.current;
|
|
200
|
+
if (!numberNode || !expiryNode || !cvcNode)
|
|
167
201
|
return;
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
202
|
+
if (cardNumberElementRef.current && cardExpiryElementRef.current && cardCvcElementRef.current) {
|
|
203
|
+
try {
|
|
204
|
+
(_b = (_a = cardNumberElementRef.current).unmount) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
205
|
+
(_d = (_c = cardExpiryElementRef.current).unmount) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
206
|
+
(_f = (_e = cardCvcElementRef.current).unmount) === null || _f === void 0 ? void 0 : _f.call(_e);
|
|
207
|
+
cardNumberElementRef.current.mount(numberNode);
|
|
208
|
+
cardExpiryElementRef.current.mount(expiryNode);
|
|
209
|
+
cardCvcElementRef.current.mount(cvcNode);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
catch (_g) {
|
|
213
|
+
// Element is bound to a destroyed host — create a fresh Elements group.
|
|
214
|
+
cardNumberElementRef.current = null;
|
|
215
|
+
cardExpiryElementRef.current = null;
|
|
216
|
+
cardCvcElementRef.current = null;
|
|
217
|
+
elementsRef.current = null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
172
220
|
setCardReady(false);
|
|
173
221
|
const elements = stripe.elements();
|
|
174
222
|
elementsRef.current = elements;
|
|
175
223
|
const number = elements.create('cardNumber', Object.assign(Object.assign({}, STRIPE_ELEMENT_OPTS), { showIcon: true }));
|
|
176
224
|
const expiry = elements.create('cardExpiry', STRIPE_ELEMENT_OPTS);
|
|
177
225
|
const cvc = elements.create('cardCvc', STRIPE_ELEMENT_OPTS);
|
|
178
|
-
number.mount(
|
|
179
|
-
expiry.mount(
|
|
180
|
-
cvc.mount(
|
|
226
|
+
number.mount(numberNode);
|
|
227
|
+
expiry.mount(expiryNode);
|
|
228
|
+
cvc.mount(cvcNode);
|
|
181
229
|
number.on('ready', () => {
|
|
182
230
|
if (mountedRef.current)
|
|
183
231
|
setCardReady(true);
|
|
@@ -188,7 +236,9 @@ export default function useCheckout(options = {}) {
|
|
|
188
236
|
setCardError(((_a = e.error) === null || _a === void 0 ? void 0 : _a.message) || '');
|
|
189
237
|
});
|
|
190
238
|
cardNumberElementRef.current = number;
|
|
191
|
-
|
|
239
|
+
cardExpiryElementRef.current = expiry;
|
|
240
|
+
cardCvcElementRef.current = cvc;
|
|
241
|
+
}, [stripe, cardHostsEpoch]);
|
|
192
242
|
// --- on success ---
|
|
193
243
|
useEffect(() => {
|
|
194
244
|
var _a, _b;
|
|
@@ -245,7 +295,7 @@ export default function useCheckout(options = {}) {
|
|
|
245
295
|
billingPlans: (_j = (_h = billingPlansQuery.data) === null || _h === void 0 ? void 0 : _h.plans) !== null && _j !== void 0 ? _j : [],
|
|
246
296
|
activeSubscriberCount: (_l = (_k = activeSubscriptionsQuery.data) === null || _k === void 0 ? void 0 : _k.active) !== null && _l !== void 0 ? _l : null,
|
|
247
297
|
selectedCycle,
|
|
248
|
-
setCycle
|
|
298
|
+
setCycle,
|
|
249
299
|
sessionReady,
|
|
250
300
|
userCountry,
|
|
251
301
|
course: (_m = courseDetailQuery.data) !== null && _m !== void 0 ? _m : null,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCheckout.js","sourceRoot":"","sources":["../../../src/data/hooks/useCheckout.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EACL,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAClD,MAAM,OAAO,CAAC;AAGf,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAC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AAA,MAAA,iBAAiB,CAAC,IAAI,0CAAE,KAAK,mCAAI,EAAE;QACjD,qBAAqB,EAAE,MAAA,MAAA,wBAAwB,CAAC,IAAI,0CAAE,MAAM,mCAAI,IAAI;QACpE,aAAa;QACb,QAAQ,EAAE,gBAAgB;QAC1B,YAAY;QACZ,WAAW;QACX,MAAM,EAAE,MAAA,iBAAiB,CAAC,IAAI,mCAAI,IAAI;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import {\n useCallback, useEffect, useMemo, useRef, useState,\n} from 'react';\nimport type { Ref } from 'react';\nimport type { BillingCycle } from '../../types';\nimport { createCheckoutClient } from '../../utils/checkout';\nimport { loadStripe } from '../../utils/stripe';\nimport {\n STATUS, STATUS_LABELS, STRIPE_ELEMENT_OPTS, phaseFor, DEFAULTS,\n} from '../../constants';\nimport type {\n Status, Phase, Cart, BillingInfo, CheckoutClient, StripeLike, StripeElementLike,\n StripeElementsLike, BillingPlan, CheckoutConsent,\n} from '../../types';\nimport {\n useCartStatusQuery, useSubscriptionIdQuery, useBillingPlansQuery,\n useActiveSubscriptionsQuery, useViaxSessionQuery, useCourseDetailQuery,\n} from './useCheckoutQueries';\nimport type { EdxSessionResult } from '../../utils/provision';\nimport { useCheckoutMutations } from './useCheckoutMutations';\n\n/**\n * Read ?course_run_key= from the current URL.\n * Avoid URLSearchParams — it treats bare `+` as a space, which would turn\n * HarvardX+CS50+X into \"HarvardX CS50 X\". decodeURIComponent keeps `+` intact.\n */\nfunction getCourseRunKeyFromUrl(): string | null {\n if (typeof window === 'undefined') return null;\n const match = /[?&]course_run_key=([^&]*)/.exec(window.location.search);\n if (!match) return null;\n try {\n // Preserve literal `+` (treat as %2B) then decode %XX sequences.\n return decodeURIComponent(match[1].replace(/\\+/g, '%2B')).trim() || null;\n } catch {\n return match[1].trim() || null;\n }\n}\n\nexport interface UseCheckoutOptions {\n apiUrl?: string,\n edxSessionUrl?: string,\n stripePublishableKey?: string,\n onComplete?: (subscriptionBiId: string | null) => void,\n /** Country code resolved by CheckoutGate — used to show/hide the UK/CA extra checkbox. */\n userCountry?: string | null,\n /**\n * Course run key from the URL (e.g. course-v1:HarvardX+CS50+X).\n * When omitted, read from ?course_run_key=.\n */\n courseRunKey?: string | null,\n}\n\nexport interface UseCheckoutResult {\n phase: Phase,\n status: Status | null,\n statusLabel: string,\n stripeReady: boolean,\n /** True once the Stripe card Element iframe is fully initialised and interactive. */\n cardReady: boolean,\n notConfigured: boolean,\n showBanner: boolean,\n dismissBanner: () => void,\n error: string,\n clearError: () => void,\n cardError: string,\n lastComment: string,\n /** Full subscription details including card last 4 — available after SUBSCRIPTION_CREATED. */\n subscriptionDetails: import('../../types').SubscriptionDetails | null,\n billing: BillingInfo,\n setField: (field: keyof BillingInfo, value: string) => void,\n numberMountRef: Ref<HTMLDivElement>,\n expiryMountRef: Ref<HTMLDivElement>,\n cvcMountRef: Ref<HTMLDivElement>,\n submitting: boolean,\n /** True from Place order click until a terminal status is reached. */\n processingSubscription: boolean,\n placeOrder: (consent: CheckoutConsent) => void,\n /** Billing plans fetched on mount — includes prices for display in CartSummary. */\n billingPlans: BillingPlan[],\n /** Live active subscriber count for display in CartSummary. */\n activeSubscriberCount: number | null,\n /** Currently selected billing cycle. */\n selectedCycle: BillingCycle,\n /** Switch between monthly and annual billing. */\n setCycle: (cycle: BillingCycle) => void,\n /** True once GET /edx-session has returned and the viax token is set. */\n sessionReady: boolean,\n /** ISO 3166-1 alpha-2 country code — passed in from CheckoutGate for the UK/CA checkbox. */\n userCountry: string | null,\n /** Course details when arrived via ?course_run_key=; null for standard checkout. */\n course: import('../../types').CourseDetail | null,\n}\n\nexport default function useCheckout(options: UseCheckoutOptions = {}): UseCheckoutResult {\n const {\n apiUrl = DEFAULTS.apiUrl,\n edxSessionUrl,\n stripePublishableKey,\n onComplete,\n userCountry = null,\n courseRunKey: courseRunKeyProp,\n } = options;\n\n const courseRunKey = useMemo(\n () => courseRunKeyProp ?? getCourseRunKeyFromUrl(),\n [courseRunKeyProp],\n );\n\n const client = useMemo<CheckoutClient | null>(() => {\n if (!apiUrl) return null;\n return createCheckoutClient({ apiUrl });\n }, [apiUrl]);\n\n const notConfigured = !client || !stripePublishableKey || !edxSessionUrl;\n\n // Exchange edX session for viax token on page load.\n const sessionQuery = useViaxSessionQuery(notConfigured ? null : edxSessionUrl!);\n const sessionReady = !!sessionQuery.data;\n\n useEffect(() => {\n if (sessionQuery.data && client) {\n client.setToken(sessionQuery.data.viaxToken);\n }\n }, [sessionQuery.data, client]);\n\n // Fetch billing plans, subscriber count, and optional course once the viax session is ready.\n const billingPlansQuery = useBillingPlansQuery(client, sessionReady);\n const activeSubscriptionsQuery = useActiveSubscriptionsQuery(client, sessionReady);\n const courseDetailQuery = useCourseDetailQuery(client, sessionReady, courseRunKey);\n\n // --- state ---\n const [showBanner, setShowBanner] = useState(true);\n const [cart, setCart] = useState<Cart | null>(null);\n const [stripe, setStripe] = useState<StripeLike | null>(null);\n const [stripeReady, setStripeReady] = useState(false);\n const [cardReady, setCardReady] = useState(false);\n const [error, setError] = useState('');\n const [cardError, setCardError] = useState('');\n const [billing, setBilling] = useState<BillingInfo>({\n firstName: '', lastName: '', city: '', zip: '', country: 'US', line1: '', state: '',\n });\n const [selectedCycle, setSelectedCycle] = useState<BillingCycle>('monthly');\n const [processingSubscription, setProcessingSubscription] = useState(false);\n\n useEffect(() => {\n if (sessionQuery.error) {\n setError(sessionQuery.error.message);\n }\n }, [sessionQuery.error]);\n\n const setField = useCallback(\n (field: keyof BillingInfo, value: string) => setBilling((p: BillingInfo) => ({ ...p, [field]: value })),\n [],\n );\n\n // --- refs ---\n // Stripe instances — written inside useEffect and mutations.\n const stripeInstanceRef = useRef<StripeLike | null>(null);\n const cardNumberElementRef = useRef<StripeElementLike | null>(null);\n const elementsRef = useRef<StripeElementsLike | null>(null);\n const elementsMountedRef = useRef(false);\n // DOM mount targets — passed as ref={} to the Stripe Element host divs.\n const numberMountRef = useRef<HTMLDivElement | null>(null);\n const expiryMountRef = useRef<HTMLDivElement | null>(null);\n const cvcMountRef = useRef<HTMLDivElement | null>(null);\n const mountedRef = useRef(true);\n const completedRef = useRef(false);\n const sessionRef = useRef<EdxSessionResult | null>(null);\n\n useEffect(() => {\n sessionRef.current = sessionQuery.data ?? null;\n }, [sessionQuery.data]);\n\n // Mirror state into refs so mutations can read current values without stale closures.\n const cartRef = useRef<Cart | null>(null);\n const billingRef = useRef<BillingInfo>(billing);\n const selectedCycleRef = useRef<BillingCycle>(selectedCycle);\n useEffect(() => {\n cartRef.current = cart;\n }, [cart]);\n useEffect(() => {\n billingRef.current = billing;\n }, [billing]);\n useEffect(() => {\n selectedCycleRef.current = selectedCycle;\n }, [selectedCycle]);\n useEffect(() => {\n stripeInstanceRef.current = stripe;\n }, [stripe]);\n\n // --- server state ---\n const statusQuery = useCartStatusQuery(client, cart?.biId ?? null);\n const status: Status | null = statusQuery.data?.status ?? null;\n const lastComment = statusQuery.data?.lastComment ?? '';\n\n // Phase is 'ready' until a cart exists, then driven by bpStatus.\n const phase: Phase = cart ? phaseFor(status, status === STATUS.IN_CART) : 'ready';\n const subscriptionIdQuery = useSubscriptionIdQuery(\n client, cart?.biId ?? null, status === STATUS.SUBSCRIPTION_CREATED,\n );\n\n // --- mutations ---\n const { placeOrder: placeMutation } = useCheckoutMutations({\n client,\n sessionRef,\n stripeRef: stripeInstanceRef,\n cardNumberElRef: cardNumberElementRef,\n billingRef,\n selectedCycleRef,\n setError: (msg: string) => {\n setProcessingSubscription(false);\n setError(msg);\n },\n setCardError: (msg: string) => {\n setProcessingSubscription(false);\n setCardError(msg);\n },\n onCartCreated: (created: Cart) => {\n // Sync the ref immediately so any same-tick readers see the cart\n // before the setCart → useEffect mirror runs.\n cartRef.current = created;\n if (mountedRef.current) setCart(created);\n },\n });\n\n // --- load Stripe.js on mount ---\n useEffect(() => {\n mountedRef.current = true;\n if (!stripePublishableKey) return undefined;\n\n (async () => {\n try {\n const instance = await loadStripe(stripePublishableKey);\n if (mountedRef.current) {\n setStripe(instance);\n setStripeReady(true);\n }\n } catch (e: unknown) {\n if (mountedRef.current) setError((e as Error).message);\n }\n })();\n\n return () => {\n mountedRef.current = false;\n };\n }, [stripePublishableKey]);\n\n // --- mount Stripe Elements once Stripe is loaded ---\n useEffect(() => {\n if (!stripe) return;\n if (!numberMountRef.current || !expiryMountRef.current || !cvcMountRef.current) return;\n // Hard guard — never recreate elements once mounted, even if stripe reference changes.\n if (elementsMountedRef.current) return;\n elementsMountedRef.current = true;\n\n setCardReady(false);\n\n const elements = stripe.elements();\n elementsRef.current = elements;\n\n const number = elements.create('cardNumber', { ...STRIPE_ELEMENT_OPTS, showIcon: true });\n const expiry = elements.create('cardExpiry', STRIPE_ELEMENT_OPTS);\n const cvc = elements.create('cardCvc', STRIPE_ELEMENT_OPTS);\n\n number.mount(numberMountRef.current);\n expiry.mount(expiryMountRef.current);\n cvc.mount(cvcMountRef.current);\n\n number.on('ready', () => {\n if (mountedRef.current) setCardReady(true);\n });\n number.on('change', (e: { error?: { message?: string } }) => {\n if (mountedRef.current) setCardError(e.error?.message || '');\n });\n\n cardNumberElementRef.current = number;\n }, [stripe]);\n\n // --- on success ---\n useEffect(() => {\n if (status !== STATUS.SUBSCRIPTION_CREATED || completedRef.current) return;\n completedRef.current = true;\n if (onComplete) onComplete(subscriptionIdQuery.data?.biId ?? null);\n }, [status, subscriptionIdQuery.data, onComplete]);\n\n // --- actions ---\n const placeOrder = useCallback((consent: CheckoutConsent) => {\n setError('');\n setCardError('');\n if (phase === 'failed') setCart(null);\n setProcessingSubscription(true);\n placeMutation.mutate(consent);\n }, [placeMutation, phase]);\n\n // Turn off processingSubscription once we reach a terminal status.\n useEffect(() => {\n if (!status) return;\n const terminalStatuses: Status[] = [\n STATUS.SUBSCRIPTION_CREATED,\n STATUS.STRIPE_FAIL,\n STATUS.SANCTION_BLOCK,\n ];\n if (terminalStatuses.includes(status)) {\n setProcessingSubscription(false);\n }\n }, [status]);\n\n return {\n phase,\n status,\n statusLabel: (status && STATUS_LABELS[status]) || 'Processing your order…',\n stripeReady,\n cardReady,\n notConfigured,\n showBanner,\n dismissBanner: () => setShowBanner(false),\n error,\n clearError: () => setError(''),\n cardError,\n lastComment,\n subscriptionDetails: subscriptionIdQuery.data ?? null,\n billing,\n setField,\n numberMountRef,\n expiryMountRef,\n cvcMountRef,\n submitting: placeMutation.isPending,\n processingSubscription,\n placeOrder,\n billingPlans: billingPlansQuery.data?.plans ?? [],\n activeSubscriberCount: activeSubscriptionsQuery.data?.active ?? null,\n selectedCycle,\n setCycle: setSelectedCycle,\n sessionReady,\n userCountry,\n course: courseDetailQuery.data ?? null,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useCheckout.js","sourceRoot":"","sources":["../../../src/data/hooks/useCheckout.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EACL,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAClD,MAAM,OAAO,CAAC;AAGf,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACL,MAAM,EAAE,aAAa,EAAE,mBAAmB,EAAE,QAAQ,EAAE,QAAQ,GAC/D,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EACL,kBAAkB,EAAE,sBAAsB,EAAE,oBAAoB,EAChE,2BAA2B,EAAE,mBAAmB,EAAE,oBAAoB,GACvE,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAE9D;;;;GAIG;AACH,SAAS,sBAAsB;IAC7B,IAAI,OAAO,MAAM,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC/C,MAAM,KAAK,GAAG,4BAA4B,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAA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AC,MAAM,CAAC,CAAC,CAAC;IAEb,OAAO;QACL,KAAK;QACL,MAAM;QACN,WAAW,EAAE,CAAC,MAAM,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,wBAAwB;QAC1E,WAAW;QACX,SAAS;QACT,aAAa;QACb,UAAU;QACV,aAAa,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC;QACzC,KAAK;QACL,UAAU,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC9B,SAAS;QACT,WAAW;QACX,mBAAmB,EAAE,MAAA,mBAAmB,CAAC,IAAI,mCAAI,IAAI;QACrD,OAAO;QACP,QAAQ;QACR,cAAc;QACd,cAAc;QACd,WAAW;QACX,UAAU,EAAE,aAAa,CAAC,SAAS;QACnC,sBAAsB;QACtB,UAAU;QACV,YAAY,EAAE,MAAA,MAAA,iBAAiB,CAAC,IAAI,0CAAE,KAAK,mCAAI,EAAE;QACjD,qBAAqB,EAAE,MAAA,MAAA,wBAAwB,CAAC,IAAI,0CAAE,MAAM,mCAAI,IAAI;QACpE,aAAa;QACb,QAAQ;QACR,YAAY;QACZ,WAAW;QACX,MAAM,EAAE,MAAA,iBAAiB,CAAC,IAAI,mCAAI,IAAI;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import {\n useCallback, useEffect, useMemo, useRef, useState,\n} from 'react';\nimport type { Ref } from 'react';\nimport type { BillingCycle } from '../../types';\nimport { createCheckoutClient } from '../../utils/checkout';\nimport { getPlanFromUrl, writePlanQueryParam } from '../../utils/planQuery';\nimport { loadStripe } from '../../utils/stripe';\nimport {\n STATUS, STATUS_LABELS, STRIPE_ELEMENT_OPTS, phaseFor, DEFAULTS,\n} from '../../constants';\nimport type {\n Status, Phase, Cart, BillingInfo, CheckoutClient, StripeLike, StripeElementLike,\n StripeElementsLike, BillingPlan, CheckoutConsent,\n} from '../../types';\nimport {\n useCartStatusQuery, useSubscriptionIdQuery, useBillingPlansQuery,\n useActiveSubscriptionsQuery, useViaxSessionQuery, useCourseDetailQuery,\n} from './useCheckoutQueries';\nimport type { EdxSessionResult } from '../../utils/provision';\nimport { useCheckoutMutations } from './useCheckoutMutations';\n\n/**\n * Read ?course_run_key= from the current URL.\n * Avoid URLSearchParams — it treats bare `+` as a space, which would turn\n * HarvardX+CS50+X into \"HarvardX CS50 X\". decodeURIComponent keeps `+` intact.\n */\nfunction getCourseRunKeyFromUrl(): string | null {\n if (typeof window === 'undefined') return null;\n const match = /[?&]course_run_key=([^&]*)/.exec(window.location.search);\n if (!match) return null;\n try {\n // Preserve literal `+` (treat as %2B) then decode %XX sequences.\n return decodeURIComponent(match[1].replace(/\\+/g, '%2B')).trim() || null;\n } catch {\n return match[1].trim() || null;\n }\n}\n\nexport interface UseCheckoutOptions {\n apiUrl?: string,\n edxSessionUrl?: string,\n stripePublishableKey?: string,\n onComplete?: (subscriptionBiId: string | null) => void,\n /** Country code resolved by CheckoutGate — used to show/hide the UK/CA extra checkbox. */\n userCountry?: string | null,\n /**\n * Course run key from the URL (e.g. course-v1:HarvardX+CS50+X).\n * When omitted, read from ?course_run_key=.\n */\n courseRunKey?: string | null,\n}\n\nexport interface UseCheckoutResult {\n phase: Phase,\n status: Status | null,\n statusLabel: string,\n stripeReady: boolean,\n /** True once the Stripe card Element iframe is fully initialised and interactive. */\n cardReady: boolean,\n notConfigured: boolean,\n showBanner: boolean,\n dismissBanner: () => void,\n error: string,\n clearError: () => void,\n cardError: string,\n lastComment: string,\n /** Full subscription details including card last 4 — available after SUBSCRIPTION_CREATED. */\n subscriptionDetails: import('../../types').SubscriptionDetails | null,\n billing: BillingInfo,\n setField: (field: keyof BillingInfo, value: string) => void,\n numberMountRef: Ref<HTMLDivElement>,\n expiryMountRef: Ref<HTMLDivElement>,\n cvcMountRef: Ref<HTMLDivElement>,\n submitting: boolean,\n /** True from Place order click until a terminal status is reached. */\n processingSubscription: boolean,\n placeOrder: (consent: CheckoutConsent) => void,\n /** Billing plans fetched on mount — includes prices for display in CartSummary. */\n billingPlans: BillingPlan[],\n /** Live active subscriber count for display in CartSummary. */\n activeSubscriberCount: number | null,\n /** Currently selected billing cycle. */\n selectedCycle: BillingCycle,\n /** Switch between monthly and annual billing. */\n setCycle: (cycle: BillingCycle) => void,\n /** True once GET /edx-session has returned and the viax token is set. */\n sessionReady: boolean,\n /** ISO 3166-1 alpha-2 country code — passed in from CheckoutGate for the UK/CA checkbox. */\n userCountry: string | null,\n /** Course details when arrived via ?course_run_key=; null for standard checkout. */\n course: import('../../types').CourseDetail | null,\n}\n\nexport default function useCheckout(options: UseCheckoutOptions = {}): UseCheckoutResult {\n const {\n apiUrl = DEFAULTS.apiUrl,\n edxSessionUrl,\n stripePublishableKey,\n onComplete,\n userCountry = null,\n courseRunKey: courseRunKeyProp,\n } = options;\n\n const courseRunKey = useMemo(\n () => courseRunKeyProp ?? getCourseRunKeyFromUrl(),\n [courseRunKeyProp],\n );\n\n const client = useMemo<CheckoutClient | null>(() => {\n if (!apiUrl) return null;\n return createCheckoutClient({ apiUrl });\n }, [apiUrl]);\n\n const notConfigured = !client || !stripePublishableKey || !edxSessionUrl;\n\n // Exchange edX session for viax token on page load.\n const sessionQuery = useViaxSessionQuery(notConfigured ? null : edxSessionUrl!);\n const sessionReady = !!sessionQuery.data;\n\n useEffect(() => {\n if (sessionQuery.data && client) {\n client.setToken(sessionQuery.data.viaxToken);\n }\n }, [sessionQuery.data, client]);\n\n // Fetch billing plans, subscriber count, and optional course once the viax session is ready.\n const billingPlansQuery = useBillingPlansQuery(client, sessionReady);\n const activeSubscriptionsQuery = useActiveSubscriptionsQuery(client, sessionReady);\n const courseDetailQuery = useCourseDetailQuery(client, sessionReady, courseRunKey);\n\n // --- state ---\n const [showBanner, setShowBanner] = useState(true);\n const [cart, setCart] = useState<Cart | null>(null);\n const [stripe, setStripe] = useState<StripeLike | null>(null);\n const [stripeReady, setStripeReady] = useState(false);\n const [cardReady, setCardReady] = useState(false);\n const [error, setError] = useState('');\n const [cardError, setCardError] = useState('');\n const [billing, setBilling] = useState<BillingInfo>({\n firstName: '', lastName: '', city: '', zip: '', country: 'US', line1: '', state: '',\n });\n const [selectedCycle, setSelectedCycle] = useState<BillingCycle>(getPlanFromUrl);\n const [processingSubscription, setProcessingSubscription] = useState(false);\n\n const setCycle = useCallback((cycle: BillingCycle) => {\n setSelectedCycle(cycle);\n writePlanQueryParam(cycle);\n }, []);\n\n useEffect(() => {\n if (sessionQuery.error) {\n setError(sessionQuery.error.message);\n }\n }, [sessionQuery.error]);\n\n const setField = useCallback(\n (field: keyof BillingInfo, value: string) => setBilling((p: BillingInfo) => ({ ...p, [field]: value })),\n [],\n );\n\n // --- refs ---\n // Stripe instances — written inside useEffect and mutations.\n const stripeInstanceRef = useRef<StripeLike | null>(null);\n const cardNumberElementRef = useRef<StripeElementLike | null>(null);\n const cardExpiryElementRef = useRef<StripeElementLike | null>(null);\n const cardCvcElementRef = useRef<StripeElementLike | null>(null);\n const elementsRef = useRef<StripeElementsLike | null>(null);\n // DOM mount targets — callback refs so we remount when hosts leave and return.\n const numberMountNodeRef = useRef<HTMLDivElement | null>(null);\n const expiryMountNodeRef = useRef<HTMLDivElement | null>(null);\n const cvcMountNodeRef = useRef<HTMLDivElement | null>(null);\n const [cardHostsEpoch, setCardHostsEpoch] = useState(0);\n\n const assignCardHost = useCallback((\n store: { current: HTMLDivElement | null },\n node: HTMLDivElement | null,\n ) => {\n store.current = node;\n if (\n numberMountNodeRef.current\n && expiryMountNodeRef.current\n && cvcMountNodeRef.current\n ) {\n setCardHostsEpoch((n) => n + 1);\n return;\n }\n // Hosts are leaving the DOM — detach so Stripe is not bound to dead nodes.\n cardNumberElementRef.current?.unmount?.();\n cardExpiryElementRef.current?.unmount?.();\n cardCvcElementRef.current?.unmount?.();\n }, []);\n\n const numberMountRef = useCallback((node: HTMLDivElement | null) => {\n assignCardHost(numberMountNodeRef, node);\n }, [assignCardHost]);\n const expiryMountRef = useCallback((node: HTMLDivElement | null) => {\n assignCardHost(expiryMountNodeRef, node);\n }, [assignCardHost]);\n const cvcMountRef = useCallback((node: HTMLDivElement | null) => {\n assignCardHost(cvcMountNodeRef, node);\n }, [assignCardHost]);\n const mountedRef = useRef(true);\n const completedRef = useRef(false);\n const sessionRef = useRef<EdxSessionResult | null>(null);\n\n useEffect(() => {\n sessionRef.current = sessionQuery.data ?? null;\n }, [sessionQuery.data]);\n\n // Mirror state into refs so mutations can read current values without stale closures.\n const cartRef = useRef<Cart | null>(null);\n const billingRef = useRef<BillingInfo>(billing);\n const selectedCycleRef = useRef<BillingCycle>(selectedCycle);\n useEffect(() => {\n cartRef.current = cart;\n }, [cart]);\n useEffect(() => {\n billingRef.current = billing;\n }, [billing]);\n useEffect(() => {\n selectedCycleRef.current = selectedCycle;\n }, [selectedCycle]);\n useEffect(() => {\n stripeInstanceRef.current = stripe;\n }, [stripe]);\n\n // --- server state ---\n const statusQuery = useCartStatusQuery(client, cart?.biId ?? null);\n const status: Status | null = statusQuery.data?.status ?? null;\n const lastComment = statusQuery.data?.lastComment ?? '';\n\n // Phase is 'ready' until a cart exists, then driven by bpStatus.\n const phase: Phase = cart ? phaseFor(status, status === STATUS.IN_CART) : 'ready';\n const subscriptionIdQuery = useSubscriptionIdQuery(\n client, cart?.biId ?? null, status === STATUS.SUBSCRIPTION_CREATED,\n );\n\n // --- mutations ---\n const { placeOrder: placeMutation } = useCheckoutMutations({\n client,\n sessionRef,\n stripeRef: stripeInstanceRef,\n cardNumberElRef: cardNumberElementRef,\n billingRef,\n selectedCycleRef,\n setError: (msg: string) => {\n setProcessingSubscription(false);\n setError(msg);\n },\n setCardError: (msg: string) => {\n setProcessingSubscription(false);\n setCardError(msg);\n },\n onCartCreated: (created: Cart) => {\n // Sync the ref immediately so any same-tick readers see the cart\n // before the setCart → useEffect mirror runs.\n cartRef.current = created;\n if (mountedRef.current) setCart(created);\n },\n });\n\n // --- load Stripe.js on mount ---\n useEffect(() => {\n mountedRef.current = true;\n if (!stripePublishableKey) return undefined;\n\n (async () => {\n try {\n const instance = await loadStripe(stripePublishableKey);\n if (mountedRef.current) {\n setStripe(instance);\n setStripeReady(true);\n }\n } catch (e: unknown) {\n if (mountedRef.current) setError((e as Error).message);\n }\n })();\n\n return () => {\n mountedRef.current = false;\n };\n }, [stripePublishableKey]);\n\n // --- mount Stripe Elements once Stripe is loaded; remount if hosts return ---\n useEffect(() => {\n if (!stripe) return;\n const numberNode = numberMountNodeRef.current;\n const expiryNode = expiryMountNodeRef.current;\n const cvcNode = cvcMountNodeRef.current;\n if (!numberNode || !expiryNode || !cvcNode) return;\n\n if (cardNumberElementRef.current && cardExpiryElementRef.current && cardCvcElementRef.current) {\n try {\n cardNumberElementRef.current.unmount?.();\n cardExpiryElementRef.current.unmount?.();\n cardCvcElementRef.current.unmount?.();\n cardNumberElementRef.current.mount(numberNode);\n cardExpiryElementRef.current.mount(expiryNode);\n cardCvcElementRef.current.mount(cvcNode);\n return;\n } catch {\n // Element is bound to a destroyed host — create a fresh Elements group.\n cardNumberElementRef.current = null;\n cardExpiryElementRef.current = null;\n cardCvcElementRef.current = null;\n elementsRef.current = null;\n }\n }\n\n setCardReady(false);\n\n const elements = stripe.elements();\n elementsRef.current = elements;\n\n const number = elements.create('cardNumber', { ...STRIPE_ELEMENT_OPTS, showIcon: true });\n const expiry = elements.create('cardExpiry', STRIPE_ELEMENT_OPTS);\n const cvc = elements.create('cardCvc', STRIPE_ELEMENT_OPTS);\n\n number.mount(numberNode);\n expiry.mount(expiryNode);\n cvc.mount(cvcNode);\n\n number.on('ready', () => {\n if (mountedRef.current) setCardReady(true);\n });\n number.on('change', (e: { error?: { message?: string } }) => {\n if (mountedRef.current) setCardError(e.error?.message || '');\n });\n\n cardNumberElementRef.current = number;\n cardExpiryElementRef.current = expiry;\n cardCvcElementRef.current = cvc;\n }, [stripe, cardHostsEpoch]);\n\n // --- on success ---\n useEffect(() => {\n if (status !== STATUS.SUBSCRIPTION_CREATED || completedRef.current) return;\n completedRef.current = true;\n if (onComplete) onComplete(subscriptionIdQuery.data?.biId ?? null);\n }, [status, subscriptionIdQuery.data, onComplete]);\n\n // --- actions ---\n const placeOrder = useCallback((consent: CheckoutConsent) => {\n setError('');\n setCardError('');\n if (phase === 'failed') setCart(null);\n setProcessingSubscription(true);\n placeMutation.mutate(consent);\n }, [placeMutation, phase]);\n\n // Turn off processingSubscription once we reach a terminal status.\n useEffect(() => {\n if (!status) return;\n const terminalStatuses: Status[] = [\n STATUS.SUBSCRIPTION_CREATED,\n STATUS.STRIPE_FAIL,\n STATUS.SANCTION_BLOCK,\n ];\n if (terminalStatuses.includes(status)) {\n setProcessingSubscription(false);\n }\n }, [status]);\n\n return {\n phase,\n status,\n statusLabel: (status && STATUS_LABELS[status]) || 'Processing your order…',\n stripeReady,\n cardReady,\n notConfigured,\n showBanner,\n dismissBanner: () => setShowBanner(false),\n error,\n clearError: () => setError(''),\n cardError,\n lastComment,\n subscriptionDetails: subscriptionIdQuery.data ?? null,\n billing,\n setField,\n numberMountRef,\n expiryMountRef,\n cvcMountRef,\n submitting: placeMutation.isPending,\n processingSubscription,\n placeOrder,\n billingPlans: billingPlansQuery.data?.plans ?? [],\n activeSubscriberCount: activeSubscriptionsQuery.data?.active ?? null,\n selectedCycle,\n setCycle,\n sessionReady,\n userCountry,\n course: courseDetailQuery.data ?? null,\n };\n}\n"]}
|
|
@@ -58,6 +58,16 @@
|
|
|
58
58
|
&__card-panel {
|
|
59
59
|
padding: 0 1rem 1rem;
|
|
60
60
|
background: #fff;
|
|
61
|
+
|
|
62
|
+
// Hide without unmounting. Stripe Elements die if their host nodes leave the DOM.
|
|
63
|
+
// Avoid display:none so the iframes keep a layout box and stay interactive.
|
|
64
|
+
&--collapsed {
|
|
65
|
+
visibility: hidden;
|
|
66
|
+
max-height: 0;
|
|
67
|
+
padding: 0;
|
|
68
|
+
overflow: hidden;
|
|
69
|
+
pointer-events: none;
|
|
70
|
+
}
|
|
61
71
|
}
|
|
62
72
|
|
|
63
73
|
// Icon badges for Google Pay / PayPal
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { BillingCycle } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Map ?plan= values to the internal billing cycle.
|
|
4
|
+
* Accepts monthly, annual, and annually (the public query value).
|
|
5
|
+
*/
|
|
6
|
+
export declare function parsePlanParam(raw: string | null | undefined): BillingCycle | null;
|
|
7
|
+
export declare function getPlanFromSearch(search: string): BillingCycle;
|
|
8
|
+
export declare function getPlanFromUrl(): BillingCycle;
|
|
9
|
+
export declare function planToQueryValue(cycle: BillingCycle): 'monthly' | 'annually';
|
|
10
|
+
/**
|
|
11
|
+
* Set ?plan= while preserving other params.
|
|
12
|
+
* Avoid URLSearchParams — it treats bare `+` as a space and would break
|
|
13
|
+
* course_run_key values like HarvardX+CS50+X.
|
|
14
|
+
*/
|
|
15
|
+
export declare function withPlanQuery(search: string, cycle: BillingCycle): string;
|
|
16
|
+
export declare function writePlanQueryParam(cycle: BillingCycle): void;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const PLAN_QUERY_KEY = 'plan';
|
|
2
|
+
/**
|
|
3
|
+
* Map ?plan= values to the internal billing cycle.
|
|
4
|
+
* Accepts monthly, annual, and annually (the public query value).
|
|
5
|
+
*/
|
|
6
|
+
export function parsePlanParam(raw) {
|
|
7
|
+
if (!raw)
|
|
8
|
+
return null;
|
|
9
|
+
const value = raw.trim().toLowerCase();
|
|
10
|
+
if (value === 'monthly')
|
|
11
|
+
return 'monthly';
|
|
12
|
+
if (value === 'annual' || value === 'annually')
|
|
13
|
+
return 'annual';
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
export function getPlanFromSearch(search) {
|
|
17
|
+
var _a, _b;
|
|
18
|
+
const match = /[?&]plan=([^&]*)/i.exec(search);
|
|
19
|
+
if (!match)
|
|
20
|
+
return 'monthly';
|
|
21
|
+
try {
|
|
22
|
+
return (_a = parsePlanParam(decodeURIComponent(match[1]))) !== null && _a !== void 0 ? _a : 'monthly';
|
|
23
|
+
}
|
|
24
|
+
catch (_c) {
|
|
25
|
+
return (_b = parsePlanParam(match[1])) !== null && _b !== void 0 ? _b : 'monthly';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function getPlanFromUrl() {
|
|
29
|
+
if (typeof window === 'undefined')
|
|
30
|
+
return 'monthly';
|
|
31
|
+
return getPlanFromSearch(window.location.search);
|
|
32
|
+
}
|
|
33
|
+
export function planToQueryValue(cycle) {
|
|
34
|
+
return cycle === 'annual' ? 'annually' : 'monthly';
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Set ?plan= while preserving other params.
|
|
38
|
+
* Avoid URLSearchParams — it treats bare `+` as a space and would break
|
|
39
|
+
* course_run_key values like HarvardX+CS50+X.
|
|
40
|
+
*/
|
|
41
|
+
export function withPlanQuery(search, cycle) {
|
|
42
|
+
const planValue = planToQueryValue(cycle);
|
|
43
|
+
const raw = search.startsWith('?') ? search.slice(1) : search;
|
|
44
|
+
const parts = raw
|
|
45
|
+
.split('&')
|
|
46
|
+
.filter((part) => (part.length > 0
|
|
47
|
+
&& !part.toLowerCase().startsWith(`${PLAN_QUERY_KEY}=`)));
|
|
48
|
+
parts.push(`${PLAN_QUERY_KEY}=${planValue}`);
|
|
49
|
+
return `?${parts.join('&')}`;
|
|
50
|
+
}
|
|
51
|
+
export function writePlanQueryParam(cycle) {
|
|
52
|
+
if (typeof window === 'undefined')
|
|
53
|
+
return;
|
|
54
|
+
const next = `${window.location.pathname}${withPlanQuery(window.location.search, cycle)}${window.location.hash}`;
|
|
55
|
+
window.history.replaceState(window.history.state, '', next);
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=planQuery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planQuery.js","sourceRoot":"","sources":["../../src/utils/planQuery.ts"],"names":[],"mappings":"AAEA,MAAM,cAAc,GAAG,MAAM,CAAC;AAE9B;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,G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CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC9D,MAAM,KAAK,GAAG,GAAG;SACd,KAAK,CAAC,GAAG,CAAC;SACV,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAChB,IAAI,CAAC,MAAM,GAAG,CAAC;WACZ,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,GAAG,cAAc,GAAG,CAAC,CACxD,CAAC,CAAC;IACL,KAAK,CAAC,IAAI,CAAC,GAAG,cAAc,IAAI,SAAS,EAAE,CAAC,CAAC;IAC7C,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAC/B,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,KAAmB;IACrD,IAAI,OAAO,MAAM,KAAK,WAAW;QAAE,OAAO;IAC1C,MAAM,IAAI,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;IACjH,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import type { BillingCycle } from '../types';\n\nconst PLAN_QUERY_KEY = 'plan';\n\n/**\n * Map ?plan= values to the internal billing cycle.\n * Accepts monthly, annual, and annually (the public query value).\n */\nexport function parsePlanParam(raw: string | null | undefined): BillingCycle | null {\n if (!raw) return null;\n const value = raw.trim().toLowerCase();\n if (value === 'monthly') return 'monthly';\n if (value === 'annual' || value === 'annually') return 'annual';\n return null;\n}\n\nexport function getPlanFromSearch(search: string): BillingCycle {\n const match = /[?&]plan=([^&]*)/i.exec(search);\n if (!match) return 'monthly';\n try {\n return parsePlanParam(decodeURIComponent(match[1])) ?? 'monthly';\n } catch {\n return parsePlanParam(match[1]) ?? 'monthly';\n }\n}\n\nexport function getPlanFromUrl(): BillingCycle {\n if (typeof window === 'undefined') return 'monthly';\n return getPlanFromSearch(window.location.search);\n}\n\nexport function planToQueryValue(cycle: BillingCycle): 'monthly' | 'annually' {\n return cycle === 'annual' ? 'annually' : 'monthly';\n}\n\n/**\n * Set ?plan= while preserving other params.\n * Avoid URLSearchParams — it treats bare `+` as a space and would break\n * course_run_key values like HarvardX+CS50+X.\n */\nexport function withPlanQuery(search: string, cycle: BillingCycle): string {\n const planValue = planToQueryValue(cycle);\n const raw = search.startsWith('?') ? search.slice(1) : search;\n const parts = raw\n .split('&')\n .filter((part) => (\n part.length > 0\n && !part.toLowerCase().startsWith(`${PLAN_QUERY_KEY}=`)\n ));\n parts.push(`${PLAN_QUERY_KEY}=${planValue}`);\n return `?${parts.join('&')}`;\n}\n\nexport function writePlanQueryParam(cycle: BillingCycle): void {\n if (typeof window === 'undefined') return;\n const next = `${window.location.pathname}${withPlanQuery(window.location.search, cycle)}${window.location.hash}`;\n window.history.replaceState(window.history.state, '', next);\n}\n"]}
|
package/dist/utils/provision.js
CHANGED
|
@@ -20,8 +20,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
20
20
|
import { EnvironmentTypes, getSiteConfig } from '@openedx/frontend-base';
|
|
21
21
|
/** Hardcoded edX JWT used only for local/dev checkout against stage Viax. */
|
|
22
22
|
const DEV_SESSION_BODY = {
|
|
23
|
-
payload: 'eyJhbGciOiJSUzUxMiIsImtpZCI6Imxtc3N0YWdlMDAyIiwidHlwIjoiSldUIn0.
|
|
24
|
-
signature: '
|
|
23
|
+
payload: 'eyJhbGciOiJSUzUxMiIsImtpZCI6Imxtc3N0YWdlMDAyIiwidHlwIjoiSldUIn0.eyJhdWQiOiJJbmtvY3VqTGlreXVjc0Vkd2lXYXRkZWJyRWFja21ldkxha0R1aWZLb29zaGtha1dvdyIsImV4cCI6MTc4NzI2MDg0OSwiZ3JhbnRfdHlwZSI6InBhc3N3b3JkIiwiaWF0IjoxNzg3MjU3MjQ5LCJpc3MiOiJodHRwczovL2NvdXJzZXMuc3RhZ2UuZWR4Lm9yZy9vYXV0aDIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJKV18yNjA4X1VNQlkiLCJzY29wZXMiOlsidXNlcl9pZCIsImVtYWlsIiwicHJvZmlsZSJdLCJ2ZXJzaW9uIjoiMS4yLjAiLCJzdWIiOiI0Y2I4MDI0ODA3YmRiZWUzZGJiNTIyZmQ3NTc4Mzc1YSIsImZpbHRlcnMiOlsidXNlcjptZSJdLCJpc19yZXN0cmljdGVkIjpmYWxzZSwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJ1c2VyX2lkIjo1Mjg1MDI0LCJlbWFpbCI6ImdxaXpjZnZiY2FqcnBpcW9pc0BqYnN6ZS5jb20iLCJuYW1lIjoiSm9obiB3aWxsaXMiLCJmYW1pbHlfbmFtZSI6IiIsImdpdmVuX25hbWUiOiIiLCJhZG1pbmlzdHJhdG9yIjpmYWxzZSwic3VwZXJ1c2VyIjpmYWxzZX0',
|
|
24
|
+
signature: 'G7rbX6PhR1wwitQtmD5fySR7Wl7LCMoeUf4EDAngjErWfb0UM_G6cdaoVtHmAo6KpNU5692z024sIxlfdvSriJ_9Er_Sk3_XSr31we1IhbT9LjztgA-OL4LxuR_uNmkU6HJwhWLkTZ683LalkXmAqoghSw_Dx1HjT19Zfhgzcbd3VGcKBg7goI-FmiC8dDIImHrEw1AE1anLx-ocB-ayKQw-xS6xpckd8UxaWkW8631Xxhd7vT8C8bLpKD2fdWQj55Wykel5ws7vq32Heoqq-P7_SNZqNgAiMEvYqZaIuPLfrRuXHoeI4Obw8ejjaobPAsKQcMGQaKSiqO6MxaMGyQ'
|
|
25
25
|
};
|
|
26
26
|
function parseSessionResponse(data) {
|
|
27
27
|
var _a, _b, _c, _d;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provision.js","sourceRoot":"","sources":["../../src/utils/provision.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;;;;;;;;;;AAEH,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAWzE,6EAA6E;AAC7E,MAAM,gBAAgB,GAAG;IACvB,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"provision.js","sourceRoot":"","sources":["../../src/utils/provision.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;;;;;;;;;;AAEH,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAWzE,6EAA6E;AAC7E,MAAM,gBAAgB,GAAG;IACvB,OAAO,EAAE,ivBAAivB;IAC1vB,SAAS,EAAE,wVAAwV;CACpW,CAAC;AACF,SAAS,oBAAoB,CAAC,IAA6B;;IACzD,MAAM,SAAS,GAAG,CAChB,MAAA,MAAA,MAAA,IAAI,CAAC,SAAS,mCAAI,IAAI,CAAC,KAAK,mCAAI,IAAI,CAAC,YAAY,mCAAI,IAAI,CAAC,WAAW,CAChD,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,MAAA,IAAI,CAAC,WAAW,mCAAI,IAAI,CAAC,YAAY,CAAuB,CAAC;IAElF,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACxE,IAAI,CAAC,WAAW;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAE3E,OAAO;QACL,SAAS;QACT,WAAW;QACX,QAAQ,EAAE,IAAI,CAAC,QAA8B;QAC7C,SAAS,EAAE,IAAI,CAAC,SAA+B;QAC/C,QAAQ,EAAE,IAAI,CAAC,QAA8B;QAC7C,KAAK,EAAE,IAAI,CAAC,KAA2B;KACxC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAgB,gBAAgB,CAAC,UAAkB,EAAE,QAAgB;;QACzE,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC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CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAkD,CAAC;QAC9E,IAAI,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QAEpD,OAAO,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;CAAA","sourcesContent":["/**\n * api/provision.ts — exchange the edX session for a viax token.\n *\n * {LMS_BASE_URL}/api/edx-session\n * The LMS reads the edX JWT from browser cookies, exchanges it with viax,\n * and returns a per-user token for authenticated API calls.\n *\n * Dev uses POST with a hardcoded JWT payload (local LMS cookie exchange is\n * unavailable). Stage and prod use GET and rely on the browser session cookies.\n */\n\nimport { EnvironmentTypes, getSiteConfig } from '@openedx/frontend-base';\n\nexport interface EdxSessionResult {\n viaxToken: string, // raw JWT — add 'Bearer ' prefix before use\n customerUid: string,\n partyUid?: string,\n edxUserId?: string,\n username?: string,\n email?: string,\n}\n\n/** Hardcoded edX JWT used only for local/dev checkout against stage Viax. */\nconst DEV_SESSION_BODY = {\n payload: 'eyJhbGciOiJSUzUxMiIsImtpZCI6Imxtc3N0YWdlMDAyIiwidHlwIjoiSldUIn0.eyJhdWQiOiJJbmtvY3VqTGlreXVjc0Vkd2lXYXRkZWJyRWFja21ldkxha0R1aWZLb29zaGtha1dvdyIsImV4cCI6MTc4NzI2MDg0OSwiZ3JhbnRfdHlwZSI6InBhc3N3b3JkIiwiaWF0IjoxNzg3MjU3MjQ5LCJpc3MiOiJodHRwczovL2NvdXJzZXMuc3RhZ2UuZWR4Lm9yZy9vYXV0aDIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJKV18yNjA4X1VNQlkiLCJzY29wZXMiOlsidXNlcl9pZCIsImVtYWlsIiwicHJvZmlsZSJdLCJ2ZXJzaW9uIjoiMS4yLjAiLCJzdWIiOiI0Y2I4MDI0ODA3YmRiZWUzZGJiNTIyZmQ3NTc4Mzc1YSIsImZpbHRlcnMiOlsidXNlcjptZSJdLCJpc19yZXN0cmljdGVkIjpmYWxzZSwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJ1c2VyX2lkIjo1Mjg1MDI0LCJlbWFpbCI6ImdxaXpjZnZiY2FqcnBpcW9pc0BqYnN6ZS5jb20iLCJuYW1lIjoiSm9obiB3aWxsaXMiLCJmYW1pbHlfbmFtZSI6IiIsImdpdmVuX25hbWUiOiIiLCJhZG1pbmlzdHJhdG9yIjpmYWxzZSwic3VwZXJ1c2VyIjpmYWxzZX0',\n signature: 'G7rbX6PhR1wwitQtmD5fySR7Wl7LCMoeUf4EDAngjErWfb0UM_G6cdaoVtHmAo6KpNU5692z024sIxlfdvSriJ_9Er_Sk3_XSr31we1IhbT9LjztgA-OL4LxuR_uNmkU6HJwhWLkTZ683LalkXmAqoghSw_Dx1HjT19Zfhgzcbd3VGcKBg7goI-FmiC8dDIImHrEw1AE1anLx-ocB-ayKQw-xS6xpckd8UxaWkW8631Xxhd7vT8C8bLpKD2fdWQj55Wykel5ws7vq32Heoqq-P7_SNZqNgAiMEvYqZaIuPLfrRuXHoeI4Obw8ejjaobPAsKQcMGQaKSiqO6MxaMGyQ'\n};\nfunction parseSessionResponse(data: Record<string, unknown>): EdxSessionResult {\n const viaxToken = (\n data.viaxToken ?? data.token ?? data.access_token ?? data.accessToken\n ) as string | undefined;\n const customerUid = (data.customerUid ?? data.customer_uid) as string | undefined;\n\n if (!viaxToken) throw new Error('Session response missing viax token.');\n if (!customerUid) throw new Error('Session response missing customerUid.');\n\n return {\n viaxToken,\n customerUid,\n partyUid: data.partyUid as string | undefined,\n edxUserId: data.edxUserId as string | undefined,\n username: data.username as string | undefined,\n email: data.email as string | undefined,\n };\n}\n\n/**\n * Fetch the ISO 3166-1 alpha-2 country code from the user's edX account profile.\n * Returns null if the request fails or the field is absent.\n */\nexport async function fetchUserCountry(lmsBaseUrl: string, username: string): Promise<string | null> {\n try {\n const res = await fetch(`${lmsBaseUrl}/api/user/v1/accounts/${encodeURIComponent(username)}`, {\n credentials: 'include',\n });\n if (!res.ok) return null;\n const data = await res.json() as Record<string, unknown>;\n return typeof data.country === 'string' && data.country ? data.country : null;\n } catch {\n return null;\n }\n}\n\nfunction isDevelopment(): boolean {\n return getSiteConfig().environment === EnvironmentTypes.DEVELOPMENT;\n}\n\n/** Exchange the learner's edX session (cookies) for a viax token. */\nexport async function fetchEdxSession(sessionUrl: string): Promise<EdxSessionResult> {\n const headers: Record<string, string> = { Accept: 'application/json' };\n\n let res: Response;\n if (isDevelopment()) {\n res = await fetch(sessionUrl, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...headers,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(DEV_SESSION_BODY),\n });\n } else {\n res = await fetch(sessionUrl, {\n method: 'POST',\n credentials: 'include',\n headers,\n });\n }\n\n if (!res.ok) {\n throw new Error(\n `Failed to establish checkout session (${res.status}). Please log into edX and try again.`,\n );\n }\n\n const data = await res.json() as Record<string, unknown> & { error?: string };\n if (data.error) throw new Error(String(data.error));\n\n return parseSessionResponse(data);\n}\n"]}
|