All files / app/cart Redeemable.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  8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x   8x                                                     8x 79x 79x 79x 79x   85x                                             8x 21x 21x 21x 21x   21x   4x 4x         4x 1x 1x 1x                 21x   2x 2x       21x           21x 21x   4x       17x       21x                                                                     21x                     21x             8x   68x         2x 2x     4x   2x 2x       6x 6x            
import { CheckoutSelectors, RequestError } from '@bigcommerce/checkout-sdk';
import { memoizeOne } from '@bigcommerce/memoize';
import { withFormik, FieldProps, FormikProps } from 'formik';
import { noop } from 'lodash';
import React, { memo, useCallback, Fragment, FunctionComponent, KeyboardEvent } from 'react';
import { object, string } from 'yup';
 
import { preventDefault } from '../common/dom';
import { withLanguage, TranslatedString, WithLanguageProps } from '../locale';
import { Alert, AlertType } from '../ui/alert';
import { Button, ButtonVariant } from '../ui/button';
import { FormContextType, FormField, FormProvider, Label, TextInput } from '../ui/form';
import { Toggle } from '../ui/toggle';
 
import AppliedRedeemables, { AppliedRedeemablesProps } from './AppliedRedeemables';
 
export interface RedeemableFormValues {
    redeemableCode: string;
}
 
export type ReedemableChildrenProps = Pick<RedeemableProps,
    'onRemovedCoupon' |
    'onRemovedGiftCertificate' |
    'isRemovingGiftCertificate' |
    'isRemovingCoupon' |
    'coupons' |
    'giftCertificates'
>;
 
export type RedeemableProps = {
    appliedRedeemableError?: RequestError;
    isApplyingRedeemable?: boolean;
    isRemovingRedeemable?: boolean;
    removedRedeemableError?: RequestError;
    showAppliedRedeemables?: boolean;
    shouldCollapseCouponCode?: boolean;
    applyCoupon(code: string): Promise<CheckoutSelectors>;
    applyGiftCertificate(code: string): Promise<CheckoutSelectors>;
    clearError(error: Error): void;
} & AppliedRedeemablesProps;
 
const Redeemable: FunctionComponent<RedeemableProps & WithLanguageProps & FormikProps<RedeemableFormValues>> = ({
    shouldCollapseCouponCode,
    showAppliedRedeemables,
    ...formProps
}) => (
    <Toggle openByDefault={ !shouldCollapseCouponCode }>
        { ({ toggle, isOpen }) => (
            <Fragment>
                { shouldCollapseCouponCode && <a
                    className="redeemable-label"
                    data-test="redeemable-label"
                    href="#"
                    onClick={ preventDefault(toggle) }
                >
                    <TranslatedString id="redeemable.toggle_action" />
                </a> }
                { !shouldCollapseCouponCode && <div className="redeemable-label">
                    <TranslatedString id="redeemable.toggle_action" />
                </div> }
                { (isOpen || !shouldCollapseCouponCode) && <div data-test="redeemable-collapsable">
                    <RedeemableForm { ...formProps } />
                    { showAppliedRedeemables &&
                        <AppliedRedeemables { ...formProps } /> }
                </div> }
            </Fragment>
        ) }
    </Toggle>
);
 
const RedeemableForm: FunctionComponent<Partial<RedeemableProps> & FormikProps<RedeemableFormValues>> = ({
    appliedRedeemableError,
    isApplyingRedeemable,
    clearError = noop,
    submitForm,
}) => {
    const handleKeyDown = useCallback(memoizeOne((setSubmitted: FormContextType['setSubmitted']) => (
        (event: KeyboardEvent) => {
            Eif (appliedRedeemableError) {
                clearError(appliedRedeemableError);
            }
 
            // note: to prevent submitting main form, we manually intercept
            // the enter key event and submit the "subform".
            if (event.keyCode === 13) {
                setSubmitted(true);
                submitForm();
                event.preventDefault();
            }
        }
    )), [
        appliedRedeemableError,
        clearError,
        submitForm,
    ]);
 
    const handleSubmit = useCallback(memoizeOne((setSubmitted: FormContextType['setSubmitted']) => (
        () => {
            setSubmitted(true);
            submitForm();
        }
    )), []);
 
    const renderLabel = useCallback((name: string) => (
        <Label hidden htmlFor={ name }>
            <TranslatedString id="redeemable.code_label" />
        </Label>
    ), []);
 
    const renderErrorMessage = useCallback((errorCode: string) => {
        switch (errorCode) {
        case 'min_purchase':
            return <TranslatedString id="redeemable.coupon_min_order_total" />;
        case 'not_applicable':
            return <TranslatedString id="redeemable.coupon_location_error" />;
        default:
            return <TranslatedString id="redeemable.code_invalid_error" />;
        }
    }, []);
 
    const renderInput = useCallback((setSubmitted: FormContextType['setSubmitted']) => ({ field }: FieldProps) => (
        <Fragment>
            { appliedRedeemableError && appliedRedeemableError.errors && appliedRedeemableError.errors[0] &&
                <Alert type={ AlertType.Error }>
                    { renderErrorMessage(appliedRedeemableError.errors[0].code) }
                </Alert> }
 
            <div className="form-prefixPostfix">
                <TextInput
                    { ...field }
                    className="form-input optimizedCheckout-form-input"
                    onKeyDown={ handleKeyDown(setSubmitted) }
                    testId="redeemableEntry-input"
                />
 
                <Button
                    className="form-prefixPostfix-button--postfix"
                    id="applyRedeemableButton"
                    isLoading={ isApplyingRedeemable }
                    onClick={ handleSubmit(setSubmitted) }
                    testId="redeemableEntry-submit"
                    variant={ ButtonVariant.Secondary }
                >
                    <TranslatedString id="redeemable.apply_action" />
                </Button>
            </div>
        </Fragment>
    ), [
        appliedRedeemableError,
        handleKeyDown,
        handleSubmit,
        isApplyingRedeemable,
        renderErrorMessage,
    ]);
 
    const renderContent = useCallback(memoizeOne(({ setSubmitted }: FormContextType) => (
        <FormField
            input={ renderInput(setSubmitted) }
            label={ renderLabel }
            name="redeemableCode"
        />
    )), [
        renderLabel,
        renderInput,
    ]);
 
    return <fieldset className="form-fieldset redeemable-entry">
        <FormProvider>
            { renderContent }
        </FormProvider>
    </fieldset>;
};
 
export default withLanguage(withFormik<RedeemableProps & WithLanguageProps, RedeemableFormValues>({
    mapPropsToValues() {
        return {
            redeemableCode: '',
        };
    },
 
    async handleSubmit({ redeemableCode }, { props: { applyCoupon, applyGiftCertificate, clearError } }) {
        const code = redeemableCode.trim();
 
        try {
            await applyGiftCertificate(code);
        } catch (error) {
            clearError(error);
            applyCoupon(code);
        }
    },
 
    validationSchema({ language }: RedeemableProps & WithLanguageProps) {
        return object({
            redeemableCode: string()
                .required(language.translate('redeemable.code_required_error')),
        });
    },
})(memo(Redeemable)));