All files / app/payment/hostedCreditCard withHostedCreditCardFieldset.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  28x 28x     28x 28x   28x 28x 28x 28x     28x 28x 28x 28x                                           148x                 120x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x   97x   97x 110x     97x 8x 8x 8x 8x       8x                                                                             8x 8x 8x 8x 8x   1x 1x       1x 1x     1x 1x   1x 1x   1x 4x 4x   4x   4x 1x                                       97x 18x 18x   18x                         97x 79x           18x                                       120x             28x 98x     98x 98x   98x   98x 98x   98x 1x     97x             97x                  
import { CardInstrument, HostedFormOptions, Instrument, PaymentMethod } from '@bigcommerce/checkout-sdk';
import { compact, forIn } from 'lodash';
import React, { useCallback, useState, ComponentType, FunctionComponent, ReactNode } from 'react';
import { ObjectSchema } from 'yup';
 
import { withCheckout, CheckoutContextProps } from '../../checkout';
import { connectFormik, ConnectFormikProps } from '../../common/form';
import { MapToPropsFactory } from '../../common/hoc';
import { withLanguage, WithLanguageProps } from '../../locale';
import { withForm, WithFormProps } from '../../ui/form';
import { getCreditCardInputStyles, CreditCardCustomerCodeField, CreditCardInputStylesType } from '../creditCard';
import { isInstrumentCardCodeRequiredSelector, isInstrumentCardNumberRequiredSelector, isInstrumentFeatureAvailable } from '../storedInstrument';
import { PaymentFormValues } from '../PaymentForm';
 
import getHostedCreditCardValidationSchema, { HostedCreditCardValidationSchemaShape } from './getHostedCreditCardValidationSchema';
import getHostedInstrumentValidationSchema, { HostedInstrumentValidationSchemaShape } from './getHostedInstrumentValidationSchema';
import HostedCreditCardFieldset from './HostedCreditCardFieldset';
import HostedCreditCardValidation from './HostedCreditCardValidation';
 
export interface WithHostedCreditCardFieldsetProps {
    isUsingMultiShipping?: boolean;
    method: PaymentMethod;
}
 
export interface WithInjectedHostedCreditCardFieldsetProps {
    hostedFieldset: ReactNode;
    hostedStoredCardValidationSchema: ObjectSchema<HostedInstrumentValidationSchemaShape>;
    hostedValidationSchema: ObjectSchema<HostedCreditCardValidationSchemaShape>;
    getHostedFormOptions(selectedInstrument?: CardInstrument): Promise<HostedFormOptions>;
    getHostedStoredCardValidationFieldset(selectedInstrument?: CardInstrument): ReactNode;
}
 
interface WithCheckoutContextProps {
    isCardCodeRequired: boolean;
    isInstrumentFeatureAvailable: boolean;
    isInstrumentCardCodeRequired(instrument: Instrument, method: PaymentMethod): boolean;
    isInstrumentCardNumberRequired(instrument: Instrument): boolean;
}
 
export default function withHostedCreditCardFieldset<TProps extends WithHostedCreditCardFieldsetProps>(
    OriginalComponent: ComponentType<TProps & Partial<WithInjectedHostedCreditCardFieldsetProps>>
): ComponentType<Omit<TProps, keyof WithInjectedHostedCreditCardFieldsetProps>> {
    const Component: FunctionComponent<
        WithHostedCreditCardFieldsetProps &
        WithCheckoutContextProps &
        WithLanguageProps &
        WithFormProps &
        ConnectFormikProps<PaymentFormValues>
    > = ({
        formik: { setFieldValue, setFieldTouched, submitForm },
        isCardCodeRequired,
        isInstrumentCardCodeRequired: isInstrumentCardCodeRequiredProp,
        isInstrumentCardNumberRequired: isInstrumentCardNumberRequiredProp,
        isInstrumentFeatureAvailable: isInstrumentFeatureAvailableProp,
        isSubmitted,
        language,
        method,
        setSubmitted,
        ...rest
    }) => {
        const [focusedFieldType, setFocusedFieldType] = useState<string>();
 
        const getHostedFieldId: (name: string) => string = useCallback(name => {
            return `${compact([method.gateway, method.id]).join('-')}-${name}`;
        }, [method]);
 
        const getHostedFormOptions: (selectedInstrument?: CardInstrument) => Promise<HostedFormOptions> = useCallback(async selectedInstrument => {
            const styleProps = ['color', 'fontFamily', 'fontSize', 'fontWeight'];
            const isInstrumentCardNumberRequired = selectedInstrument ? isInstrumentCardNumberRequiredProp(selectedInstrument) : false;
            const isInstrumentCardCodeRequired = selectedInstrument ? isInstrumentCardCodeRequiredProp(selectedInstrument, method) : false;
            const styleContainerId = selectedInstrument ?
                (isInstrumentCardCodeRequired ? getHostedFieldId('ccCvv') : undefined) :
                getHostedFieldId('ccNumber');
 
            return {
                fields: selectedInstrument ?
                    {
                        cardCodeVerification: isInstrumentCardCodeRequired && selectedInstrument ?
                            {
                                accessibilityLabel: language.translate('payment.credit_card_cvv_label'),
                                containerId: getHostedFieldId('ccCvv'),
                                instrumentId: selectedInstrument.bigpayToken,
                            } :
                            undefined,
                        cardNumberVerification: isInstrumentCardNumberRequired && selectedInstrument ?
                            {
                                accessibilityLabel: language.translate('payment.credit_card_number_label'),
                                containerId: getHostedFieldId('ccNumber'),
                                instrumentId: selectedInstrument.bigpayToken,
                            } :
                            undefined,
                    } :
                    {
                        cardCode: isCardCodeRequired ?
                            {
                                accessibilityLabel: language.translate('payment.credit_card_cvv_label'),
                                containerId: getHostedFieldId('ccCvv'),
                            } :
                            undefined,
                        cardExpiry: {
                            accessibilityLabel: language.translate('payment.credit_card_expiration_label'),
                            containerId: getHostedFieldId('ccExpiry'),
                            placeholder: language.translate('payment.credit_card_expiration_placeholder_text'),
                        },
                        cardName: {
                            accessibilityLabel: language.translate('payment.credit_card_name_label'),
                            containerId: getHostedFieldId('ccName'),
                        },
                        cardNumber: {
                            accessibilityLabel: language.translate('payment.credit_card_number_label'),
                            containerId: getHostedFieldId('ccNumber'),
                        },
                    },
                styles: IstyleContainerId ?
                    {
                        default: await getCreditCardInputStyles(styleContainerId, styleProps),
                        error: await getCreditCardInputStyles(styleContainerId, styleProps, CreditCardInputStylesType.Error),
                        focus: await getCreditCardInputStyles(styleContainerId, styleProps, CreditCardInputStylesType.Focus),
                    } : {},
                onBlur: ({ fieldType }) => {
                    Iif (focusedFieldType === fieldType) {
                        setFocusedFieldType(undefined);
                    }
                },
                onCardTypeChange: ({ cardType }) => {
                    setFieldValue('hostedForm.cardType', cardType);
                },
                onEnter: () => {
                    setSubmitted(true);
                    submitForm();
                },
                onFocus: ({ fieldType }) => {
                    setFocusedFieldType(fieldType);
                },
                onValidate: ({ errors = {} }) => {
                    forIn(errors, (IfieldErrors = [], fieldType) => {
                        const errorKey = `hostedForm.errors.${fieldType}`;
 
                        setFieldValue(errorKey, fieldErrors[0]?.type ?? '');
 
                        if (fieldErrors[0]) {
                            setFieldTouched(errorKey);
                        }
                    });
                },
            };
        }, [
            focusedFieldType,
            getHostedFieldId,
            isCardCodeRequired,
            isInstrumentCardCodeRequiredProp,
            isInstrumentCardNumberRequiredProp,
            language,
            method,
            setFieldValue,
            setFieldTouched,
            setFocusedFieldType,
            setSubmitted,
            submitForm,
        ]);
 
        const getHostedStoredCardValidationFieldset: (selectedInstrument: CardInstrument) => ReactNode = useCallback(selectedInstrument => {
            const isInstrumentCardNumberRequired = selectedInstrument ? isInstrumentCardNumberRequiredProp(selectedInstrument) : false;
            const isInstrumentCardCodeRequired = selectedInstrument ? isInstrumentCardCodeRequiredProp(selectedInstrument, method) : false;
 
            return <HostedCreditCardValidation
                cardCodeId={ isInstrumentCardCodeRequired ? getHostedFieldId('ccCvv') : undefined }
                cardNumberId={ isInstrumentCardNumberRequired ? getHostedFieldId('ccNumber') : undefined }
                focusedFieldType={ focusedFieldType }
            />;
        }, [
            focusedFieldType,
            getHostedFieldId,
            isInstrumentCardCodeRequiredProp,
            isInstrumentCardNumberRequiredProp,
            method,
        ]);
 
        if (!method.config.isHostedFormEnabled) {
            return <OriginalComponent
                { ...rest as TProps }
                method={ method }
            />;
        }
 
        return <OriginalComponent
            { ...rest as TProps }
            getHostedFormOptions={ getHostedFormOptions }
            getHostedStoredCardValidationFieldset={ getHostedStoredCardValidationFieldset }
            hostedFieldset={
                <HostedCreditCardFieldset
                    additionalFields={ method.config.requireCustomerCode && <CreditCardCustomerCodeField name="ccCustomerCode" /> }
                    cardCodeId={ isCardCodeRequired ? getHostedFieldId('ccCvv') : undefined }
                    cardExpiryId={ getHostedFieldId('ccExpiry') }
                    cardNameId={ getHostedFieldId('ccName') }
                    cardNumberId={ getHostedFieldId('ccNumber') }
                    focusedFieldType={ focusedFieldType }
                />
            }
            hostedStoredCardValidationSchema={ getHostedInstrumentValidationSchema({ language }) }
            hostedValidationSchema={ getHostedCreditCardValidationSchema({ language }) }
            method={ method }
        />;
    };
 
    return connectFormik(withForm(withLanguage(withCheckout(mapFromCheckoutProps)(Component)))) as ComponentType<Omit<TProps, keyof WithInjectedHostedCreditCardFieldsetProps>>;
}
 
const mapFromCheckoutProps: MapToPropsFactory<
    CheckoutContextProps,
    WithCheckoutContextProps,
    WithHostedCreditCardFieldsetProps & ConnectFormikProps<PaymentFormValues>
> = () => {
    return ({ checkoutState }, { isUsingMultiShipping = false, method }) => {
        const {
            data: {
                getConfig,
                getCustomer,
            },
        } = checkoutState;
 
        const config = getConfig();
        const customer = getCustomer();
 
        if (!config || !customer) {
            return null;
        }
 
        const isInstrumentFeatureAvailableProp = isInstrumentFeatureAvailable({
            config,
            customer,
            isUsingMultiShipping,
            paymentMethod: method,
        });
 
        return {
            method,
            isCardCodeRequired: method.config.cardCode || method.config.cardCode === null,
            isInstrumentCardCodeRequired: isInstrumentCardCodeRequiredSelector(checkoutState),
            isInstrumentCardNumberRequired: isInstrumentCardNumberRequiredSelector(checkoutState),
            isInstrumentFeatureAvailable: isInstrumentFeatureAvailableProp,
        };
    };
};