Skip to content

Commit

Permalink
Refactored a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
rupertbates committed Feb 26, 2025
1 parent 9088316 commit 75f7253
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import {
PaymentTsAndCs,
SummaryTsAndCs,
} from 'pages/supporter-plus-landing/components/paymentTsAndCs';
import { appropriateErrorMessage } from '../../../helpers/forms/errorReasons';
import { formatUserDate } from '../../../helpers/utilities/dateConversions';
import { getTierThreeDeliveryDate } from '../../weekly-subscription-checkout/helpers/deliveryDays';
import { PersonalDetailsFields } from '../checkout/components/PersonalDetailsFields';
Expand All @@ -101,7 +102,10 @@ import {
} from './form';
import { submitForm } from './formOnSubmit';
import type { PaymentMethod } from './paymentFields';
import { FormSubmissionError } from './paymentFields';
import {
FormSubmissionError,
getPaymentFieldsForPaymentMethod,
} from './paymentFields';
import {
checkedRadioLabelColour,
defaultRadioLabelColour,
Expand Down Expand Up @@ -346,6 +350,51 @@ export function CheckoutComponent({

const { supportInternationalisationId } = countryGroups[countryGroupId];

const onFormSubmit = async (formData: FormData) => {
if (paymentMethod === undefined) {
setPaymentMethodError('Please select a payment method');
return;
}
setIsProcessingPayment(true);
try {
const paymentFields = await getPaymentFieldsForPaymentMethod(
paymentMethod,
stripeExpressCheckoutPaymentType,
stripe,
elements,
isTestUser,
stripePublicKey,
recaptchaToken,
formData,
);
if (paymentFields === undefined) {
throw new Error('paymentFields is undefined');
}
await submitForm({
geoId,
productKey,
ratePlanKey,
formData,
paymentMethod,
paymentFields,
productFields,
hasDeliveryAddress: !!productDescription.deliverableTo,
abParticipations,
promotion,
contributionAmount,
});
} catch (error) {
if (error instanceof FormSubmissionError) {
setErrorMessage(error.message);
setErrorContext(error.context);
} else {
setErrorMessage('Sorry, something went wrong');
setErrorContext(appropriateErrorMessage('internal_error'));
}
}
setIsProcessingPayment(false);
};

useAbandonedBasketCookie(
productKey,
originalAmount,
Expand Down Expand Up @@ -457,44 +506,9 @@ export function CheckoutComponent({
ref={formRef}
onSubmit={(event) => {
event.preventDefault();
if (paymentMethod === undefined) {
setPaymentMethodError('Please select a payment method');
} else {
const form = event.currentTarget;
const formData = new FormData(form);
setIsProcessingPayment(true);
try {
/** we defer this to an external function as a lot of the payment methods use async */
void submitForm({
formData,
hasDeliveryAddress: !!productDescription.deliverableTo,
isTestUser,
stripePublicKey,
stripeExpressCheckoutPaymentType,
stripe,
stripeElements: elements,
productKey,
promotion,
geoId,
abParticipations,
productFields,
ratePlanKey,
paymentMethod,
recaptchaToken,
contributionAmount,
}).then(() => {
setIsProcessingPayment(false);
});
} catch (error) {
if (error instanceof FormSubmissionError) {
setErrorMessage(error.message);
setErrorContext(error.context);
}
setIsProcessingPayment(false);
}
}

return false;
const form = event.currentTarget;
const formData = new FormData(form);
void onFormSubmit(formData);
}}
>
<Box
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import type {
ExpressPaymentType,
Stripe,
StripeElements,
} from '@stripe/stripe-js';
import type { Promotion } from 'helpers/productPrice/promotions';
import type { GeoId } from 'pages/geoIdConfig';
import type { Participations } from '../../../helpers/abTests/models';
import type { ErrorReason } from '../../../helpers/forms/errorReasons';
import { appropriateErrorMessage } from '../../../helpers/forms/errorReasons';
import type {
ProductFields,
RegularPaymentFields,
RegularPaymentRequest,
StatusResponse,
} from '../../../helpers/forms/paymentIntegrations/readerRevenueApis';
Expand All @@ -30,10 +26,7 @@ import {
} from '../checkout/helpers/formDataExtractors';
import { setThankYouOrder } from '../checkout/helpers/sessionStorage';
import type { PaymentMethod } from './paymentFields';
import {
FormSubmissionError,
getPaymentFieldsForPaymentMethod,
} from './paymentFields';
import { FormSubmissionError } from './paymentFields';
import type { ProcessPaymentResponse } from './retryPaymentStatus';
import { processPaymentWithRetries } from './retryPaymentStatus';

Expand All @@ -42,62 +35,35 @@ type CreateSubscriptionResponse = StatusResponse & {
};

export const submitForm = async ({
geoId,
productKey,
ratePlanKey,
formData,
paymentMethod,
paymentFields,
productFields,
hasDeliveryAddress,
isTestUser,
stripePublicKey,
stripeExpressCheckoutPaymentType,
stripe,
stripeElements,
promotion,
geoId,
abParticipations,
productFields,
paymentMethod,
recaptchaToken,
promotion,
contributionAmount,
}: {
geoId: GeoId;
productKey: ActiveProductKey;
ratePlanKey: string;
formData: FormData;
paymentMethod: PaymentMethod;
paymentFields: RegularPaymentFields;
productFields: ProductFields;
hasDeliveryAddress: boolean;
isTestUser: boolean;
stripePublicKey: string;
stripeExpressCheckoutPaymentType: ExpressPaymentType | undefined;
stripe: Stripe | null;
stripeElements: StripeElements | null;
promotion: Promotion | undefined;
geoId: GeoId;
abParticipations: Participations;
productFields: ProductFields;
paymentMethod: PaymentMethod;
recaptchaToken: string | undefined;
contributionAmount?: number;
promotion: Promotion | undefined;
contributionAmount: number | undefined;
}) => {
const personalData = extractPersonalDataFromForm(formData);
const { billingAddress, deliveryAddress } = hasDeliveryAddress
? extractDeliverableAddressDataFromForm(formData)
: extractNonDeliverableAddressDataFromForm(formData);

const paymentFields = await getPaymentFieldsForPaymentMethod(
paymentMethod,
stripeExpressCheckoutPaymentType,
stripe,
stripeElements,
isTestUser,
stripePublicKey,
recaptchaToken,
formData,
);

if (paymentFields === undefined) {
// TODO: show error message to user?
console.error('paymentFields is undefined');
return;
}

const ophanIds = getOphanIds();
const referrerAcquisitionData = {
...getReferrerAcquisitionData(),
Expand Down Expand Up @@ -234,7 +200,5 @@ const goToThankYouPage = (
userType && thankYouUrlSearchParams.set('userType', userType);
contributionAmount &&
thankYouUrlSearchParams.set('contribution', contributionAmount.toString());
setTimeout(() => {
window.location.href = `/${geoId}/thank-you?${thankYouUrlSearchParams.toString()}`;
}, 50); // 50ms delay ensures the change is registered
window.location.href = `/${geoId}/thank-you?${thankYouUrlSearchParams.toString()}`;
};
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,6 @@ export const getPaymentFieldsForPaymentMethod = async (
recaptchaToken: string | undefined,
formData: FormData,
): Promise<RegularPaymentFields | undefined> => {
console.log('paymentMethod', paymentMethod, recaptchaToken);
if (paymentMethod === 'Stripe') {
return getStripePaymentFields(
stripe,
Expand Down

0 comments on commit 75f7253

Please sign in to comment.