All files / app/payment/paymentMethod CreditCardPaymentMethod.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  26x 26x 26x     26x 26x   26x 26x 26x   26x   26x 26x   26x                                                                       78x                 78x       26x 78x                 78x 78x     139x 34x     156x         34x       26x 1x             1x     2x                 26x 26x               26x         26x   50x     4x         4x                   26x   104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x   104x   104x 104x 104x 104x 104x   104x                                                                     26x 240x 240x   240x     26x 240x   240x 8x     232x   232x       232x     26x   104x 104x 104x 104x 104x 104x 104x 104x 104x   104x 48x     56x   56x 7x                 49x           78x 1x           78x             78x 1x 1x   1x 1x         1x                 26x           26x 79x   78x   103x   206x   206x       103x 103x 103x 103x         206x   103x 103x   103x       103x 103x             103x                             26x  
import { CardInstrument, CheckoutSelectors, HostedFieldType, Instrument, PaymentInitializeOptions, PaymentInstrument, PaymentMethod, PaymentRequestOptions } from '@bigcommerce/checkout-sdk';
import { memoizeOne } from '@bigcommerce/memoize';
import { find, noop } from 'lodash';
import React, { Component, 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 { LoadingOverlay } from '../../ui/loading';
import { DocumentOnlyCustomFormFieldsetValues, FawryCustomFormFieldsetValues, IdealCustomFormFieldsetValues, SepaCustomFormFieldsetValues } from '../checkoutcomFieldsets/';
import { configureCardValidator, getCreditCardValidationSchema, CreditCardFieldset, CreditCardFieldsetValues } from '../creditCard';
import { HostedCreditCardFieldsetValues } from '../hostedCreditCard';
import { getInstrumentValidationSchema, isCardInstrument, isInstrumentCardCodeRequiredSelector, isInstrumentCardNumberRequiredSelector, isInstrumentFeatureAvailable, CardInstrumentFieldset, CardInstrumentFieldsetValues, CreditCardValidation } from '../storedInstrument';
import withPayment, { WithPaymentProps } from '../withPayment';
import { PaymentFormValues } from '../PaymentForm';
import StoreInstrumentFieldset from '../StoreInstrumentFieldset';
 
export interface CreditCardPaymentMethodProps {
    isInitializing?: boolean;
    isUsingMultiShipping?: boolean;
    method: PaymentMethod;
    cardFieldset?: ReactNode;
    cardValidationSchema?: ObjectSchema<CreditCardPaymentMethodValues>;
    storedCardValidationSchema?: ObjectSchema<CreditCardPaymentMethodValues>;
    deinitializePayment(options: PaymentRequestOptions): Promise<CheckoutSelectors>;
    getStoredCardValidationFieldset?(selectedInstrument?: CardInstrument): ReactNode;
    initializePayment(options: PaymentInitializeOptions, selectedInstrument?: CardInstrument): Promise<CheckoutSelectors>;
    onUnhandledError?(error: Error): void;
}
 
export type CreditCardPaymentMethodValues = CreditCardFieldsetValues | CardInstrumentFieldsetValues | HostedCreditCardFieldsetValues | DocumentOnlyCustomFormFieldsetValues | SepaCustomFormFieldsetValues | FawryCustomFormFieldsetValues | IdealCustomFormFieldsetValues;
 
interface WithCheckoutCreditCardPaymentMethodProps {
    instruments: CardInstrument[];
    isCardCodeRequired: boolean;
    isCustomerCodeRequired: boolean;
    isInstrumentFeatureAvailable: boolean;
    isLoadingInstruments: boolean;
    isPaymentDataRequired: boolean;
    shouldShowInstrumentFieldset: boolean;
    isInstrumentCardCodeRequired(instrument: Instrument, method: PaymentMethod): boolean;
    isInstrumentCardNumberRequired(instrument: Instrument): boolean;
    loadInstruments(): Promise<CheckoutSelectors>;
}
 
interface CreditCardPaymentMethodState {
    focusedHostedFieldType?: HostedFieldType;
    isAddingNewCard: boolean;
    selectedInstrumentId?: string;
}
 
class CreditCardPaymentMethod extends Component<
    CreditCardPaymentMethodProps &
        WithCheckoutCreditCardPaymentMethodProps &
        WithFormProps &
        WithPaymentProps &
        WithLanguageProps &
        ConnectFormikProps<PaymentFormValues>,
    CreditCardPaymentMethodState
> {
    state: CreditCardPaymentMethodState = {
        isAddingNewCard: false,
    };
 
    async componentDidMount(): Promise<void> {
        const {
            initializePayment,
            isInstrumentFeatureAvailable: isInstrumentFeatureAvailableProp,
            loadInstruments,
            method,
            onUnhandledError = noop,
            setValidationSchema,
        } = this.props;
 
        setValidationSchema(method, this.getValidationSchema());
        configureCardValidator();
 
        try {
            if (isInstrumentFeatureAvailableProp) {
                await loadInstruments();
            }
 
            await initializePayment({
                gatewayId: method.gateway,
                methodId: method.id,
            }, this.getSelectedInstrument());
        } catch (error) {
            onUnhandledError(error);
        }
    }
 
    async componentWillUnmount(): Promise<void> {
        const {
            deinitializePayment,
            method,
            onUnhandledError = noop,
            setValidationSchema,
        } = this.props;
 
        setValidationSchema(method, null);
 
        try {
            await deinitializePayment({
                gatewayId: method.gateway,
                methodId: method.id,
            });
        } catch (error) {
            onUnhandledError(error);
        }
    }
 
    async componentDidUpdate(_prevProps: Readonly<CreditCardPaymentMethodProps>, prevState: Readonly<CreditCardPaymentMethodState>): Promise<void> {
        const {
            deinitializePayment,
            initializePayment,
            method,
            onUnhandledError = noop,
            setValidationSchema,
        } = this.props;
 
        const {
            isAddingNewCard,
            selectedInstrumentId,
        } = this.state;
 
        setValidationSchema(method, this.getValidationSchema());
 
        if (selectedInstrumentId !== prevState.selectedInstrumentId ||
            isAddingNewCard !== prevState.isAddingNewCard) {
            try {
                await deinitializePayment({
                    gatewayId: method.gateway,
                    methodId: method.id,
                });
 
                await initializePayment({
                    gatewayId: method.gateway,
                    methodId: method.id,
                }, this.getSelectedInstrument());
            } catch (error) {
                onUnhandledError(error);
            }
        }
    }
 
    render(): ReactNode {
        const {
            cardFieldset,
            getStoredCardValidationFieldset,
            instruments,
            isInitializing,
            isInstrumentCardCodeRequired: isInstrumentCardCodeRequiredProp,
            isInstrumentCardNumberRequired: isInstrumentCardNumberRequiredProp,
            isInstrumentFeatureAvailable: isInstrumentFeatureAvailableProp,
            isLoadingInstruments,
            shouldShowInstrumentFieldset,
            method,
        } = this.props;
 
        const { isAddingNewCard } = this.state;
 
        const selectedInstrument = this.getSelectedInstrument();
        const shouldShowCreditCardFieldset = !shouldShowInstrumentFieldset || isAddingNewCard;
        const isLoading = isInitializing || isLoadingInstruments;
        const shouldShowNumberField = selectedInstrument ? isInstrumentCardNumberRequiredProp(selectedInstrument) : false;
        const shouldShowCardCodeField = selectedInstrument ? isInstrumentCardCodeRequiredProp(selectedInstrument, method) : false;
 
        return (
            <LoadingOverlay
                hideContentWhenLoading
                isLoading={ isLoading }
            >
                <div className="paymentMethod paymentMethod--creditCard">
                    { shouldShowInstrumentFieldset && <CardInstrumentFieldset
                        instruments={ instruments }
                        onDeleteInstrument={ this.handleDeleteInstrument }
                        onSelectInstrument={ this.handleSelectInstrument }
                        onUseNewInstrument={ this.handleUseNewCard }
                        selectedInstrumentId={ selectedInstrument && selectedInstrument.bigpayToken }
                        validateInstrument={ getStoredCardValidationFieldset ?
                            getStoredCardValidationFieldset(selectedInstrument) :
                            <CreditCardValidation
                                shouldShowCardCodeField={ shouldShowCardCodeField }
                                shouldShowNumberField={ shouldShowNumberField }
                            /> }
                    /> }
 
                    { shouldShowCreditCardFieldset && !cardFieldset && <CreditCardFieldset
                        shouldShowCardCodeField={ method.config.cardCode || method.config.cardCode === null }
                        shouldShowCustomerCodeField={ method.config.requireCustomerCode }
                    /> }
 
                    { shouldShowCreditCardFieldset && cardFieldset }
 
                    { isInstrumentFeatureAvailableProp && <StoreInstrumentFieldset
                        instrumentId={ selectedInstrument && selectedInstrument.bigpayToken }
                    /> }
                </div>
            </LoadingOverlay>
        );
    }
 
    private getSelectedInstrument(): CardInstrument | undefined {
        const { instruments } = this.props;
        const { selectedInstrumentId = this.getDefaultInstrumentId() } = this.state;
 
        return find(instruments, { bigpayToken: selectedInstrumentId });
    }
 
    private getDefaultInstrumentId(): string | undefined {
        const { isAddingNewCard } = this.state;
 
        if (isAddingNewCard) {
            return;
        }
 
        const { instruments } = this.props;
        const defaultInstrument = (
            instruments.find(instrument => instrument.defaultInstrument) ||
            instruments[0]
        );
 
        return defaultInstrument && defaultInstrument.bigpayToken;
    }
 
    private getValidationSchema(): ObjectSchema<CreditCardPaymentMethodValues> | null {
        const {
            cardValidationSchema,
            isInstrumentCardCodeRequired: isInstrumentCardCodeRequiredProp,
            isInstrumentCardNumberRequired: isInstrumentCardNumberRequiredProp,
            isInstrumentFeatureAvailable: isInstrumentFeatureAvailableProp,
            isPaymentDataRequired,
            language,
            method,
            storedCardValidationSchema,
        } = this.props;
 
        if (!isPaymentDataRequired) {
            return null;
        }
 
        const selectedInstrument = this.getSelectedInstrument();
 
        if (isInstrumentFeatureAvailableProp && selectedInstrument) {
            return storedCardValidationSchema || getInstrumentValidationSchema({
                instrumentBrand: selectedInstrument.brand,
                instrumentLast4: selectedInstrument.last4,
                isCardCodeRequired: isInstrumentCardCodeRequiredProp(selectedInstrument, method),
                isCardNumberRequired: isInstrumentCardNumberRequiredProp(selectedInstrument),
                language,
            });
        }
 
        return cardValidationSchema || getCreditCardValidationSchema({
            isCardCodeRequired: method.config.cardCode === true,
            language,
        });
    }
 
    private handleUseNewCard: () => void = () => {
        this.setState({
            isAddingNewCard: true,
            selectedInstrumentId: undefined,
        });
    };
 
    private handleSelectInstrument: (id: string) => void = id => {
        this.setState({
            isAddingNewCard: false,
            selectedInstrumentId: id,
        });
    };
 
    private handleDeleteInstrument: (id: string) => void = id => {
        const { instruments, formik: { setFieldValue } } = this.props;
        const { selectedInstrumentId } = this.state;
 
        Eif (instruments.length === 0) {
            this.setState({
                isAddingNewCard: true,
                selectedInstrumentId: undefined,
            });
 
            setFieldValue('instrumentId', '');
        } else if (selectedInstrumentId === id) {
            this.setState({
                selectedInstrumentId: this.getDefaultInstrumentId(),
            });
 
            setFieldValue('instrumentId', this.getDefaultInstrumentId());
        }
    };
}
 
const mapFromCheckoutProps: MapToPropsFactory<
    CheckoutContextProps,
    WithCheckoutCreditCardPaymentMethodProps,
    CreditCardPaymentMethodProps & ConnectFormikProps<PaymentFormValues>
> = () => {
    const filterInstruments = memoizeOne((Iinstruments: PaymentInstrument[] = []) => instruments.filter(isCardInstrument));
 
    return (context, props) => {
        const {
            isUsingMultiShipping = false,
            method,
        } = props;
 
        const { checkoutService, checkoutState } = context;
 
        const {
            data: {
                getConfig,
                getCustomer,
                getInstruments,
                isPaymentDataRequired,
            },
            statuses: {
                isLoadingInstruments,
            },
        } = checkoutState;
 
        const config = getConfig();
        const customer = getCustomer();
 
        Iif (!config || !customer || !method) {
            return null;
        }
 
        const instruments = filterInstruments(getInstruments(method));
        const isInstrumentFeatureAvailableProp = isInstrumentFeatureAvailable({
            config,
            customer,
            isUsingMultiShipping,
            paymentMethod: method,
        });
 
        return {
            instruments,
            isCardCodeRequired: method.config.cardCode || method.config.cardCode === null,
            isCustomerCodeRequired: !!method.config.requireCustomerCode,
            isInstrumentCardCodeRequired: isInstrumentCardCodeRequiredSelector(checkoutState),
            isInstrumentCardNumberRequired: isInstrumentCardNumberRequiredSelector(checkoutState),
            isInstrumentFeatureAvailable: isInstrumentFeatureAvailableProp,
            isLoadingInstruments: isLoadingInstruments(),
            isPaymentDataRequired: isPaymentDataRequired(),
            loadInstruments: checkoutService.loadInstruments,
            shouldShowInstrumentFieldset: isInstrumentFeatureAvailableProp && instruments.length > 0,
        };
    };
};
 
export default connectFormik(withForm(withLanguage(withPayment(withCheckout(mapFromCheckoutProps)(CreditCardPaymentMethod)))));