All files / app/payment Payment.tsx

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563  2x 2x 2x     2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x                                                                                                   34x 34x                 34x 34x               2x 34x                   68x           68x 1x   33x 1x       34x 34x 34x     2x   69x 69x 69x   197x     2x       2x   103x 103x 103x 103x 103x 103x 103x 103x     103x 103x 103x 103x 103x 103x 103x     103x       103x                                                           2x   103x 103x 103x 103x 103x     103x   103x           90x     13x                   2x   103x 103x 103x   103x 293x                   103x     34x                                     34x                                       34x                                                                           34x     2x 2x       2x 2x   2x         2x 2x   2x 1x               3x 1x   2x       2x     34x 1x           2x           34x 4x                   4x         4x       4x         8x 3x   1x       1x       1x       34x                   34x                                     34x       33x 33x   33x       33x             2x   2x 44x 44x       44x 44x 44x 44x 44x 44x 44x 44x     44x 44x     44x 44x   132x   44x 44x 44x 44x 44x 44x   44x 9x       35x 35x 35x 35x 35x 35x   35x 35x   35x         35x 102x 33x     69x     35x 1x         1x 4x       35x 1x 1x   34x 34x     35x                                                             2x  
import { CartChangedError, CheckoutSelectors, CheckoutSettings, OrderRequestBody, PaymentMethod } from '@bigcommerce/checkout-sdk';
import { memoizeOne } from '@bigcommerce/memoize';
import { compact, find, isEmpty, noop } from 'lodash';
import React, { Component, ReactNode } from 'react';
import { ObjectSchema } from 'yup';
 
import { withCheckout, CheckoutContextProps } from '../checkout';
import { isCartChangedError, isRequestError, ErrorModal, ErrorModalOnCloseProps } from '../common/error';
import { EMPTY_ARRAY } from '../common/utility';
import { withLanguage, WithLanguageProps } from '../locale';
import { TermsConditionsType } from '../termsConditions';
import { LoadingOverlay } from '../ui/loading';
 
import mapSubmitOrderErrorMessage, { mapSubmitOrderErrorTitle } from './mapSubmitOrderErrorMessage';
import mapToOrderRequestBody from './mapToOrderRequestBody';
import { getUniquePaymentMethodId, PaymentMethodId, PaymentMethodProviderType } from './paymentMethod';
import PaymentContext from './PaymentContext';
import PaymentForm, { PaymentFormValues } from './PaymentForm';
 
export interface PaymentProps {
    isEmbedded?: boolean;
    isUsingMultiShipping?: boolean;
    checkEmbeddedSupport?(methodIds: string[]): void; // TODO: We're currently doing this check in multiple places, perhaps we should move it up so this check get be done in a single place instead.
    onCartChangedError?(error: CartChangedError): void;
    onFinalize?(): void;
    onFinalizeError?(error: Error): void;
    onReady?(): void;
    onSubmit?(): void;
    onSubmitError?(error: Error): void;
    onUnhandledError?(error: Error): void;
}
 
interface WithCheckoutPaymentProps {
    availableStoreCredit: number;
    cartUrl: string;
    defaultMethod?: PaymentMethod;
    finalizeOrderError?: Error;
    isInitializingPayment: boolean;
    isSubmittingOrder: boolean;
    isStoreCreditApplied: boolean;
    isTermsConditionsRequired: boolean;
    methods: PaymentMethod[];
    shouldExecuteSpamCheck: boolean;
    shouldLocaliseErrorMessages: boolean;
    submitOrderError?: Error;
    termsConditionsText?: string;
    termsConditionsUrl?: string;
    usableStoreCredit: number;
    applyStoreCredit(useStoreCredit: boolean): Promise<CheckoutSelectors>;
    clearError(error: Error): void;
    finalizeOrderIfNeeded(): Promise<CheckoutSelectors>;
    isPaymentDataRequired(): boolean;
    loadCheckout(): Promise<CheckoutSelectors>;
    loadPaymentMethods(): Promise<CheckoutSelectors>;
    submitOrder(values: OrderRequestBody): Promise<CheckoutSelectors>;
}
 
interface PaymentState {
    didExceedSpamLimit: boolean;
    isReady: boolean;
    selectedMethod?: PaymentMethod;
    shouldDisableSubmit: { [key: string]: boolean };
    shouldHidePaymentSubmitButton: { [key: string]: boolean };
    submitFunctions: { [key: string]: ((values: PaymentFormValues) => void) | null };
    validationSchemas: { [key: string]: ObjectSchema<Partial<PaymentFormValues>> | null };
}
 
class Payment extends Component<PaymentProps & WithCheckoutPaymentProps & WithLanguageProps, PaymentState> {
    state: PaymentState = {
        didExceedSpamLimit: false,
        isReady: false,
        shouldDisableSubmit: {},
        shouldHidePaymentSubmitButton: {},
        validationSchemas: {},
        submitFunctions: {},
    };
 
    private getContextValue = memoizeOne(() => {
        return {
            disableSubmit: this.disableSubmit,
            setSubmit: this.setSubmit,
            setValidationSchema: this.setValidationSchema,
            hidePaymentSubmitButton: this.hidePaymentSubmitButton,
        };
    });
 
    async componentDidMount(): Promise<void> {
        const {
            finalizeOrderIfNeeded,
            loadPaymentMethods,
            onFinalize = noop,
            onFinalizeError = noop,
            onReady = noop,
            onUnhandledError = noop,
        } = this.props;
 
        try {
            await loadPaymentMethods();
        } catch (error) {
            onUnhandledError(error);
        }
 
        try {
            await finalizeOrderIfNeeded();
            onFinalize();
        } catch (error) {
            if (error.type !== 'order_finalization_not_required') {
                onFinalizeError(error);
            }
        }
 
        window.addEventListener('beforeunload', this.handleBeforeUnload);
        this.setState({ isReady: true });
        onReady();
    }
 
    componentDidUpdate(): void {
        const {
            checkEmbeddedSupport = noop,
            methods,
        } = this.props;
 
        checkEmbeddedSupport(methods.map(({ id }) => id));
    }
 
    componentWillUnmount(): void {
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
    }
 
    render(): ReactNode {
        const {
            defaultMethod,
            finalizeOrderError,
            isInitializingPayment,
            isUsingMultiShipping,
            methods,
            applyStoreCredit,
            ...rest
        } = this.props;
 
        const {
            didExceedSpamLimit,
            isReady,
            selectedMethod = defaultMethod,
            shouldDisableSubmit,
            validationSchemas,
            shouldHidePaymentSubmitButton,
        } = this.state;
 
        const uniqueSelectedMethodId = (
            selectedMethod &&
            getUniquePaymentMethodId(selectedMethod.id, selectedMethod.gateway)
        );
 
        return (
            <PaymentContext.Provider value={ this.getContextValue() }>
                <LoadingOverlay
                    isLoading={ !isReady }
                    unmountContentWhenLoading
                >
                    { !isEmpty(methods) && defaultMethod && <PaymentForm
                        { ...rest }
                        defaultGatewayId={ defaultMethod.gateway }
                        defaultMethodId={ defaultMethod.id }
                        didExceedSpamLimit={ didExceedSpamLimit }
                        isInitializingPayment={ isInitializingPayment }
                        isUsingMultiShipping={ isUsingMultiShipping }
                        methods={ methods }
                        onMethodSelect={ this.setSelectedMethod }
                        onStoreCreditChange={ this.handleStoreCreditChange }
                        onSubmit={ this.handleSubmit }
                        selectedMethod={ selectedMethod }
                        shouldDisableSubmit={ uniqueSelectedMethodId && shouldDisableSubmit[uniqueSelectedMethodId] || undefined }
                        shouldHidePaymentSubmitButton={ uniqueSelectedMethodId && shouldHidePaymentSubmitButton[uniqueSelectedMethodId] || undefined }
                        validationSchema={ uniqueSelectedMethodId && validationSchemas[uniqueSelectedMethodId] || undefined }
                    /> }
                </LoadingOverlay>
 
                { this.renderOrderErrorModal() }
                { this.renderEmbeddedSupportErrorModal() }
            </PaymentContext.Provider>
        );
    }
 
    private renderOrderErrorModal(): ReactNode {
        const {
            finalizeOrderError,
            language,
            shouldLocaliseErrorMessages,
            submitOrderError,
        } = this.props;
 
        // FIXME: Export correct TS interface
        const error: any = submitOrderError || finalizeOrderError;
 
        if (!error ||
            error.type === 'order_finalization_not_required' ||
            error.type === 'payment_cancelled' ||
            error.type === 'payment_invalid_form' ||
            error.type === 'spam_protection_not_completed' ||
            error.type === 'invalid_hosted_form_value') {
            return null;
        }
 
        return (
            <ErrorModal
                error={ error }
                message={ mapSubmitOrderErrorMessage(error, language.translate.bind(language), shouldLocaliseErrorMessages) }
                onClose={ this.handleCloseModal }
                title={ mapSubmitOrderErrorTitle(error, language.translate.bind(language)) }
            />
        );
    }
 
    private renderEmbeddedSupportErrorModal(): ReactNode {
        const {
            checkEmbeddedSupport = noop,
            methods,
        } = this.props;
 
        try {
            checkEmbeddedSupport(methods.map(({ id }) => id));
        } catch (error) {
            return (
                <ErrorModal
                    error={ error }
                    onClose={ this.handleCloseModal }
                />
            );
        }
 
        return null;
    }
 
    private disableSubmit: (
        method: PaymentMethod,
        disabled?: boolean
    ) => void = (method, disabled = true) => {
        const uniqueId = getUniquePaymentMethodId(method.id, method.gateway);
        const { shouldDisableSubmit } = this.state;
 
        if (shouldDisableSubmit[uniqueId] === disabled) {
            return;
        }
 
        this.setState({
            shouldDisableSubmit: {
                ...shouldDisableSubmit,
                [uniqueId]: disabled,
            },
        });
    };
 
    private hidePaymentSubmitButton: (
        method: PaymentMethod,
        disabled?: boolean
    ) => void = (method, disabled = true) => {
        const uniqueId = getUniquePaymentMethodId(method.id, method.gateway);
        const { shouldHidePaymentSubmitButton } = this.state;
 
        if (shouldHidePaymentSubmitButton[uniqueId] === disabled) {
            return;
        }
 
        this.setState({
            shouldHidePaymentSubmitButton: {
                ...shouldHidePaymentSubmitButton,
                [uniqueId]: disabled,
            },
        });
    };
 
    // tslint:disable:cyclomatic-complexity
    private handleBeforeUnload: (event: BeforeUnloadEvent) => string | undefined = event => {
        const { defaultMethod, isSubmittingOrder, language } = this.props;
        const { selectedMethod = defaultMethod } = this.state;
 
        // TODO: Perhaps there is a better way to handle `adyen`, `afterpay`, `amazon`,
        // `checkout.com`, `converge`, `sagepay`, `stripev3` and `sezzle`. They require
        //  a redirection to another website during the payment flow but are not
        //  categorised as hosted payment methods.
        if (!isSubmittingOrder ||
            !selectedMethod ||
            selectedMethod.type === PaymentMethodProviderType.Hosted ||
            selectedMethod.type === PaymentMethodProviderType.PPSDK ||
            selectedMethod.id === PaymentMethodId.Amazon ||
            selectedMethod.id === PaymentMethodId.AmazonPay ||
            selectedMethod.id === PaymentMethodId.Checkoutcom ||
            selectedMethod.id === PaymentMethodId.Converge ||
            selectedMethod.id === PaymentMethodId.Laybuy ||
            selectedMethod.id === PaymentMethodId.Quadpay ||
            selectedMethod.id === PaymentMethodId.SagePay ||
            selectedMethod.id === PaymentMethodId.Sezzle ||
            selectedMethod.id === PaymentMethodId.Zip ||
            selectedMethod.gateway === PaymentMethodId.AdyenV2 ||
            selectedMethod.gateway === PaymentMethodId.AdyenV2GooglePay ||
            selectedMethod.gateway === PaymentMethodId.Afterpay ||
            selectedMethod.gateway === PaymentMethodId.Clearpay ||
            selectedMethod.gateway === PaymentMethodId.Checkoutcom ||
            selectedMethod.gateway === PaymentMethodId.Mollie ||
            selectedMethod.gateway === PaymentMethodId.StripeV3) {
            return;
        }
 
        const message = language.translate('common.leave_warning');
 
        event.returnValue = message;
 
        return message;
    };
 
    private handleCloseModal: (
        event: Event,
        props: ErrorModalOnCloseProps
    ) => Promise<void> = async (_, { error }) => {
        Iif (!error) {
            return;
        }
 
        const { cartUrl, clearError, loadCheckout } = this.props;
        const { type: errorType } = error as any; // FIXME: Export correct TS interface
 
        Iif (errorType === 'provider_fatal_error' ||
            errorType === 'order_could_not_be_finalized_error') {
            window.location.replace(cartUrl || '/');
        }
 
        if (IisRequestError(error)) {
            const { body, headers, status } = error;
 
            if (body.type === 'provider_error' && headers.location) {
                window.top.location.assign(headers.location);
            }
 
            // Reload the checkout object to get the latest `shouldExecuteSpamCheck` value,
            // which will in turn make `SpamProtectionField` visible again.
            // NOTE: As a temporary fix, we're checking the status code instead of the error
            // type because of an issue with Nginx config, which causes the server to return
            // HTML page instead of JSON response when there is a 429 error.
            if (status === 429 || body.type === 'spam_protection_expired' || body.type === 'spam_protection_failed') {
                this.setState({ didExceedSpamLimit: true });
 
                await loadCheckout();
            }
        }
 
        clearError(error);
    };
 
    private handleStoreCreditChange: (useStoreCredit: boolean) => void = async useStoreCredit => {
        const {
            applyStoreCredit,
            onUnhandledError = noop,
        } = this.props;
 
        try {
            await applyStoreCredit(useStoreCredit);
        } catch (e) {
            onUnhandledError(e);
        }
    };
 
    private handleSubmit: (values: PaymentFormValues) => void = async values => {
        const {
            defaultMethod,
            loadPaymentMethods,
            isPaymentDataRequired,
            onCartChangedError = noop,
            onSubmit = noop,
            onSubmitError = noop,
            submitOrder,
        } = this.props;
 
        const {
            selectedMethod = defaultMethod,
            submitFunctions,
        } = this.state;
 
        const customSubmit = selectedMethod && submitFunctions[
            getUniquePaymentMethodId(selectedMethod.id, selectedMethod.gateway)
        ];
 
        Iif (customSubmit) {
            return customSubmit(values);
        }
 
        try {
            await submitOrder(mapToOrderRequestBody(values, isPaymentDataRequired()));
            onSubmit();
        } catch (error) {
            Iif (error.type === 'payment_method_invalid') {
                return loadPaymentMethods();
            }
 
            Iif (isCartChangedError(error)) {
                return onCartChangedError(error);
            }
 
            onSubmitError(error);
        }
    };
 
    private setSelectedMethod: (method?: PaymentMethod) => void = method => {
        const { selectedMethod } = this.state;
 
        if (selectedMethod === method) {
            return;
        }
 
        this.setState({ selectedMethod: method });
    };
 
    private setSubmit: (
        method: PaymentMethod,
        fn: (values: PaymentFormValues) => void | null
    ) => void = (method, fn) => {
        const uniqueId = getUniquePaymentMethodId(method.id, method.gateway);
        const { submitFunctions } = this.state;
 
        if (submitFunctions[uniqueId] === fn) {
            return;
        }
 
        this.setState({
            submitFunctions: {
                ...submitFunctions,
                [uniqueId]: fn,
            },
        });
    };
 
    private setValidationSchema: (
        method: PaymentMethod,
        schema: ObjectSchema<Partial<PaymentFormValues>> | null
    ) => void = (method, schema) => {
        const uniqueId = getUniquePaymentMethodId(method.id, method.gateway);
        const { validationSchemas } = this.state;
 
        Iif (validationSchemas[uniqueId] === schema) {
            return;
        }
 
        this.setState({
            validationSchemas: {
                ...validationSchemas,
                [uniqueId]: schema,
            },
        });
    };
}
 
export function mapToPaymentProps({
    checkoutService,
    checkoutState,
}: CheckoutContextProps): WithCheckoutPaymentProps | null {
    const {
        data: {
            getCheckout,
            getConfig,
            getCustomer,
            getConsignments,
            getOrder,
            getPaymentMethod,
            getPaymentMethods,
            isPaymentDataRequired,
        },
        errors: {
            getFinalizeOrderError,
            getSubmitOrderError,
        },
        statuses: {
            isInitializingPayment,
            isSubmittingOrder,
        },
    } = checkoutState;
 
    const checkout = getCheckout();
    const config = getConfig();
    const customer = getCustomer();
    const consignments = getConsignments();
    const { isComplete = false } = getOrder() || {};
    const methods = getPaymentMethods() || EMPTY_ARRAY;
 
    if (!checkout || !config || !customer || isComplete) {
        return null;
    }
 
    const {
        enableTermsAndConditions: isTermsConditionsEnabled,
        features,
        orderTermsAndConditionsType: termsConditionsType,
        orderTermsAndConditions: termsCondtitionsText,
        orderTermsAndConditionsLink: termsCondtitionsUrl,
    } = config.checkoutSettings as CheckoutSettings & { orderTermsAndConditionsLocation: string };
 
    const isTermsConditionsRequired = isTermsConditionsEnabled;
    const selectedPayment = find(checkout.payments, { providerType: PaymentMethodProviderType.Hosted });
 
    const { isStoreCreditApplied } = checkout;
 
    let selectedPaymentMethod;
    let filteredMethods;
 
    filteredMethods = methods.filter((method: PaymentMethod) => {
        if (method.id === PaymentMethodId.Bolt && method.initializationData) {
            return !!method.initializationData.showInCheckout;
        }
 
        return true;
    });
 
    if (consignments && consignments.length > 1) {
        const multiShippingIncompatibleMethodIds: string[] = [
            PaymentMethodId.AmazonPay,
            PaymentMethodId.Amazon,
        ];
 
        filteredMethods = methods.filter((method: PaymentMethod) => {
            return multiShippingIncompatibleMethodIds.indexOf(method.id) === -1;
        });
    }
 
    if (selectedPayment) {
        selectedPaymentMethod = getPaymentMethod(selectedPayment.providerId, selectedPayment.gatewayId);
        filteredMethods = selectedPaymentMethod ? compact([selectedPaymentMethod]) : filteredMethods;
    } else {
        selectedPaymentMethod = find(filteredMethods, { config: { hasDefaultStoredInstrument: true } });
        filteredMethods = filteredMethods;
    }
 
    return {
        applyStoreCredit: checkoutService.applyStoreCredit,
        availableStoreCredit: customer.storeCredit,
        cartUrl: config.links.cartLink,
        clearError: checkoutService.clearError,
        defaultMethod: selectedPaymentMethod ? selectedPaymentMethod : filteredMethods[0],
        finalizeOrderError: getFinalizeOrderError(),
        finalizeOrderIfNeeded: checkoutService.finalizeOrderIfNeeded,
        loadCheckout: checkoutService.loadCheckout,
        isInitializingPayment: isInitializingPayment(),
        isPaymentDataRequired,
        isStoreCreditApplied,
        isSubmittingOrder: isSubmittingOrder(),
        isTermsConditionsRequired,
        loadPaymentMethods: checkoutService.loadPaymentMethods,
        methods: filteredMethods,
        shouldExecuteSpamCheck: checkout.shouldExecuteSpamCheck,
        shouldLocaliseErrorMessages: features['PAYMENTS-6799.localise_checkout_payment_error_messages'],
        submitOrder: checkoutService.submitOrder,
        submitOrderError: getSubmitOrderError(),
        termsConditionsText: isTermsConditionsRequired && termsConditionsType === TermsConditionsType.TextArea ?
            termsCondtitionsText :
            undefined,
        termsConditionsUrl: isTermsConditionsRequired && termsConditionsType === TermsConditionsType.Link ?
            termsCondtitionsUrl :
            undefined,
        usableStoreCredit: checkout.grandTotal > 0 ?
            Math.min(checkout.grandTotal, customer.storeCredit || 0) : 0,
    };
}
 
export default withLanguage(withCheckout(mapToPaymentProps)(Payment));