Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const StatefulProvisioningButton = () => {
const queryClient = useQueryClient();
const { authenticatedUser }: AppContextValue = useContext(AppContext);
const { data: polledCheckoutIntent } = usePolledCheckoutIntent();
const { data: successContext, refetch } = useBFFSuccess();
const { data: successContext, refetch } = useBFFSuccess(authenticatedUser.userId ?? null);
const { checkoutIntent } = successContext || {};
const [buttonState, setButtonState] = useState('pending');
const intl = useIntl();
Expand Down
46 changes: 33 additions & 13 deletions src/components/StatefulButton/StatefulSubscribeButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import { CheckoutContextValue, useCheckout } from '@stripe/react-stripe-js';
import { StripeCheckoutStatus } from '@stripe/stripe-js';
import { useQueryClient } from '@tanstack/react-query';
import { useContext, useEffect, useState } from 'react';
import { useCallback, useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { useCheckoutIntent, usePolledCheckoutIntent } from '@/components/app/data';
import { termsAndConditions } from '@/components/app/data/constants';
import { queryBffContext, queryBffSuccess } from '@/components/app/data/queries/queries';
import { patchCheckoutIntent } from '@/components/app/data/services/checkout-intent';
import { determineExistingSuccessfulCheckoutIntent } from '@/components/app/data/services/context';
import { CheckoutPageRoute, CheckoutSubstepKey, DataStoreKey } from '@/constants/checkout';
Expand Down Expand Up @@ -73,17 +74,12 @@
confirm: CheckoutContextValue['confirm'],
} = useCheckout();
const billingDetailsData = useCheckoutFormStore((state) => state.formData[DataStoreKey.BillingDetails]);
const setCheckoutSessionStatus = useCheckoutFormStore((state) => state.setCheckoutSessionStatus);
const { setCheckoutSessionStatus, setCheckoutSessionClientSecret } = useCheckoutFormStore((state) => state);

const hasInvalidTerms = Object.values(billingDetailsData).some((value) => !value);
const isFormValid = canConfirm && !hasInvalidTerms;

const onClickHandler = async () => {
// Sets the button to pending state and then calls confirm()
setStatefulButtonState('pending');

// Calls confirm() to start the Stripe checkout flow.
let response;
const patchCheckoutIntentCallback = useCallback(async () => {
try {
if (checkoutIntent) {
const { id, country, state } = checkoutIntent;
Expand All @@ -95,12 +91,20 @@
};
await patchCheckoutIntent(tncCheckoutUpdateRequest);
}
} catch (patchError) {
logError(patchError);
}
}, [checkoutIntent]);

const purchaseStripeCheckout = useCallback(async () => {
let response;
try {
response = await confirm({
redirect: 'if_required',
returnUrl: `${window.location.href}/${CheckoutSubstepKey.Success}`,
});
} catch (error) {
response = error;
} catch (stripeError) {
response = stripeError;
}
// Set the button to the appropriate state based on the response.
// Stripe responses map 1:1 to button states except for 'default' which is the initial state.
Expand All @@ -110,7 +114,16 @@
`[BillingDetails] Error during self service purchasing Stripe checkout for checkoutIntent: ${JSON.stringify(checkoutIntent)}, ${JSON.stringify(response.error)}`,
);
}
};
}, [checkoutIntent, confirm]);

const onClickHandler = useCallback(async () => {
// Sets the button to pending state and then calls confirm()
setStatefulButtonState('pending');

// Calls confirm() to start the Stripe checkout flow.
await patchCheckoutIntentCallback();
await purchaseStripeCheckout();
}, [patchCheckoutIntentCallback, purchaseStripeCheckout]);

// Visually alter the Subscribe button to a "successful" appearance if the polled intent state becomes successful.
useEffect(() => {
Expand All @@ -124,6 +137,13 @@
// If the payment succeeded from the stripe API, update the checkout session status.
if (status.type === 'complete' && status.paymentStatus === 'paid') {
setCheckoutSessionStatus(status);
setCheckoutSessionClientSecret('');
queryClient.invalidateQueries({
queryKey: queryBffSuccess(authenticatedUser.userId ?? null).queryKey,
}).then(data => data).catch(error => logError(error));
queryClient.invalidateQueries({
queryKey: queryBffContext(authenticatedUser.userId ?? null).queryKey,
}).then(data => data).catch(error => logError(error));
sendEnterpriseCheckoutTrackingEvent({
checkoutIntentId: checkoutIntent?.id ?? null,
eventName: EVENT_NAMES.SUBSCRIPTION_CHECKOUT.PAYMENT_PROCESSED_SUCCESSFULLY,
Expand All @@ -136,14 +156,14 @@
setErrorMessageKey('fallback');
}
}
}, [

Check failure on line 159 in src/components/StatefulButton/StatefulSubscribeButton.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useEffect has a missing dependency: 'setCheckoutSessionClientSecret'. Either include it or remove the dependency array
statefulButtonState,
status,
setCheckoutSessionStatus,
queryClient,
authenticatedUser,
navigate,
checkoutIntent?.id,
queryClient,
authenticatedUser.userId,
]);

const props = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ const determineBannerMessage = (state?: string | null) => {

const BillingDetailsSuccessContent = () => {
const { authenticatedUser }:AppContextValue = useContext(AppContext);
const { data: successBFFContext } = useBFFSuccess(authenticatedUser?.id);
const { data: successBFFContext, refetch } = useBFFSuccess(authenticatedUser?.userId || null);
const { checkoutIntent } = successBFFContext || {};
const bannerElement = useMemo(
() => determineBannerMessage(checkoutIntent?.state),
[checkoutIntent?.state],
);

refetch().catch(error => error);
return (
<>
<BillingDetailsHeadingMessage>
Expand Down
21 changes: 14 additions & 7 deletions src/components/Stepper/Steps/BillingDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
import { AppContext } from '@edx/frontend-platform/react';
import { Stack, Stepper } from '@openedx/paragon';
import { useContext } from 'react';
import { Helmet } from 'react-helmet';

import { useCheckoutSessionClientSecret } from '@/components/app/data';
import { useBFFSuccess, useCheckoutSessionClientSecret } from '@/components/app/data';
import { BillingDetailsPage } from '@/components/billing-details-pages';
import { useStepperContent } from '@/components/Stepper/Steps/hooks';
import { BillingDetailsSuccessContent } from '@/components/Stepper/StepperContent';
import { StripeProvider } from '@/components/StripeProvider';
import { CheckoutStepKey } from '@/constants/checkout';
import { useCheckoutFormStore } from '@/hooks/useCheckoutFormStore';

const BillingDetails = () => {
const { authenticatedUser }: AppContextValue = useContext(AppContext);
const checkoutSessionClientSecret = useCheckoutSessionClientSecret();
const StepperContent = useStepperContent();

if (!checkoutSessionClientSecret) {
const { data: successContext } = useBFFSuccess(authenticatedUser.userId || null);
const state = useCheckoutFormStore(s => s.checkoutSessionStatus);
const successfulCheckout = state.type === 'complete' && state.paymentStatus === 'paid';
console.log({

Check warning on line 19 in src/components/Stepper/Steps/BillingDetails.tsx

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
successfulCheckout, successContext, checkoutSessionClientSecret, state,
});
if ((successfulCheckout && successContext?.checkoutIntent?.existingSuccessfulCheckoutIntent) || !checkoutSessionClientSecret) {

Check failure on line 22 in src/components/Stepper/Steps/BillingDetails.tsx

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 129. Maximum allowed is 120
return (
<>
<Helmet title="Billing Details" />
<Stepper.Step eventKey={CheckoutStepKey.BillingDetails} title="Billing Details">
<Stack gap={4}>
<StepperContent />
<BillingDetailsSuccessContent />
</Stack>
</Stepper.Step>
</>

);
}
return (
Expand Down
2 changes: 1 addition & 1 deletion src/components/app/routes/loaders/checkoutStepperLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ async function billingDetailsSuccessLoader(queryClient: QueryClient): Promise<Re
}

const contextMetadata: CheckoutContextResponse = await queryClient.ensureQueryData(
queryBffContext(authenticatedUser?.userId || null),
queryBffSuccess(authenticatedUser?.userId || null),
);
const { checkoutIntent } = contextMetadata;

Expand Down
Loading