All files / app/shipping SingleShippingForm.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  5x 5x 5x 5x   5x 5x 5x 5x   5x 5x 5x 5x 5x                                                                               5x   5x 5x   39x                 39x   39x   39x   12x             6x 5x     6x         5x   95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x     95x 95x 95x 95x   95x 188x   95x                                                                                   39x   95x 95x 95x 95x       95x   95x 6x     89x     39x   13x     13x           22x   9x   9x   9x   9x 2x     7x     5x   7x 7x 7x   7x   7x       7x 7x     39x                                                         39x 2x             2x     2x 1x               1x   2x       5x     96x   96x   5x   5x 7x 7x   39x                 92x 92x 92x 92x             30x 30x 30x 30x                     60x                
import { Address, CheckoutParams, CheckoutSelectors, Consignment, Country, CustomerAddress, CustomerRequestOptions, FormField, RequestOptions, ShippingInitializeOptions, ShippingRequestOptions } from '@bigcommerce/checkout-sdk';
import { withFormik, FormikProps } from 'formik';
import { debounce, noop } from 'lodash';
import React, { PureComponent, ReactNode } from 'react';
import { lazy, object } from 'yup';
 
import { getAddressFormFieldsValidationSchema, getTranslateAddressError, isEqualAddress, mapAddressFromFormValues, mapAddressToFormValues, AddressFormValues } from '../address';
import { getCustomFormFieldsValidationSchema } from '../formFields';
import { withLanguage, WithLanguageProps } from '../locale';
import { Fieldset, Form, FormContext } from '../ui/form';
 
import hasSelectedShippingOptions from './hasSelectedShippingOptions';
import BillingSameAsShippingField from './BillingSameAsShippingField';
import ShippingAddress from './ShippingAddress';
import { SHIPPING_ADDRESS_FIELDS } from './ShippingAddressFields';
import ShippingFormFooter from './ShippingFormFooter';
 
export interface SingleShippingFormProps {
    addresses: CustomerAddress[];
    isBillingSameAsShipping: boolean;
    cartHasChanged: boolean;
    consignments: Consignment[];
    countries: Country[];
    countriesWithAutocomplete: string[];
    customerMessage: string;
    googleMapsApiKey?: string;
    isLoading: boolean;
    isShippingStepPending: boolean;
    isMultiShippingMode: boolean;
    methodId?: string;
    shippingAddress?: Address;
    shouldShowSaveAddress?: boolean;
    shouldShowOrderComments: boolean;
    deinitialize(options: ShippingRequestOptions): Promise<CheckoutSelectors>;
    deleteConsignments(): Promise<Address | undefined>;
    getFields(countryCode?: string): FormField[];
    initialize(options: ShippingInitializeOptions): Promise<CheckoutSelectors>;
    onSubmit(values: SingleShippingFormValues): void;
    onUnhandledError?(error: Error): void;
    signOut(options?: CustomerRequestOptions): void;
    updateAddress(address: Partial<Address>, options?: RequestOptions<CheckoutParams>): Promise<CheckoutSelectors>;
}
 
export interface SingleShippingFormValues {
    billingSameAsShipping: boolean;
    shippingAddress?: AddressFormValues;
    orderComment: string;
}
 
interface SingleShippingFormState {
    isResettingAddress: boolean;
    isUpdatingShippingData: boolean;
    hasRequestedShippingOptions: boolean;
}
 
export const SHIPPING_AUTOSAVE_DELAY = 1700;
 
class SingleShippingForm extends PureComponent<SingleShippingFormProps & WithLanguageProps & FormikProps<SingleShippingFormValues>> {
    static contextType = FormContext;
 
    state: SingleShippingFormState = {
        isResettingAddress: false,
        isUpdatingShippingData: false,
        hasRequestedShippingOptions: false,
    };
 
    private debouncedUpdateAddress: any;
 
    constructor(props: SingleShippingFormProps & WithLanguageProps & FormikProps<SingleShippingFormValues>) {
        super(props);
 
        const { updateAddress } = this.props;
 
        this.debouncedUpdateAddress = debounce(async (address: Address, includeShippingOptions: boolean) => {
            try {
                await updateAddress(address, {
                    params: {
                        include: {
                            'consignments.availableShippingOptions': includeShippingOptions,
                        },
                    },
                });
                if (includeShippingOptions) {
                    this.setState({ hasRequestedShippingOptions: true });
                }
            } finally {
                this.setState({ isUpdatingShippingData: false });
            }
        }, SHIPPING_AUTOSAVE_DELAY);
    }
 
    render(): ReactNode {
        const {
            addresses,
            cartHasChanged,
            isLoading,
            onUnhandledError,
            methodId,
            shouldShowSaveAddress,
            countries,
            countriesWithAutocomplete,
            googleMapsApiKey,
            shippingAddress,
            consignments,
            shouldShowOrderComments,
            initialize,
            isValid,
            deinitialize,
            values: { shippingAddress: addressForm },
            isShippingStepPending,
        } = this.props;
 
        const {
            isResettingAddress,
            isUpdatingShippingData,
            hasRequestedShippingOptions,
        } = this.state;
 
        const PAYMENT_METHOD_VALID = ['amazon', 'amazonpay'];
        const shouldShowBillingSameAsShipping = !PAYMENT_METHOD_VALID.some(method => method === methodId);
 
        return (
            <Form autoComplete="on">
                <Fieldset>
                    <ShippingAddress
                        addresses={ addresses }
                        consignments={ consignments }
                        countries={ countries }
                        countriesWithAutocomplete={ countriesWithAutocomplete }
                        deinitialize={ deinitialize }
                        formFields={ this.getFields(addressForm && addressForm.countryCode) }
                        googleMapsApiKey={ googleMapsApiKey }
                        hasRequestedShippingOptions={ hasRequestedShippingOptions }
                        initialize={ initialize }
                        isLoading={ isResettingAddress }
                        isShippingStepPending={ isShippingStepPending }
                        methodId={ methodId }
                        onAddressSelect={ this.handleAddressSelect }
                        onFieldChange={ this.handleFieldChange }
                        onUnhandledError={ onUnhandledError }
                        onUseNewAddress={ this.onUseNewAddress }
                        shippingAddress={ shippingAddress }
                        shouldShowSaveAddress={ shouldShowSaveAddress }
                    />
                    {
                        shouldShowBillingSameAsShipping && <div className="form-body">
                            <BillingSameAsShippingField />
                        </div>
                    }
                </Fieldset>
 
                <ShippingFormFooter
                    cartHasChanged={ cartHasChanged }
                    isLoading={ isLoading || isUpdatingShippingData }
                    isMultiShippingMode={ false }
                    shouldDisableSubmit={ this.shouldDisableSubmit() }
                    shouldShowOrderComments={ shouldShowOrderComments }
                    shouldShowShippingOptions={ isValid }
                />
            </Form>
        );
    }
 
    private shouldDisableSubmit: () => boolean = () => {
        const {
            isLoading,
            consignments,
            isValid,
        } = this.props;
 
        const {
            isUpdatingShippingData,
        } = this.state;
 
        if (!isValid) {
            return false;
        }
 
        return isLoading || isUpdatingShippingData || !hasSelectedShippingOptions(consignments);
    };
 
    private handleFieldChange: (name: string) => void = async name => {
        const {
            setFieldValue,
        } = this.props;
 
        Iif (name === 'countryCode') {
            setFieldValue('shippingAddress.stateOrProvince', '');
            setFieldValue('shippingAddress.stateOrProvinceCode', '');
        }
 
        // Enqueue the following code to run after Formik has run validation
        await new Promise(resolve => setTimeout(resolve));
 
        const isShippingField = SHIPPING_ADDRESS_FIELDS.includes(name);
 
        const { hasRequestedShippingOptions } = this.state;
 
        const { isValid } = this.props;
 
        if (!isValid) {
            return;
        }
 
        this.updateAddressWithFormData(isShippingField || !hasRequestedShippingOptions);
    };
 
    private updateAddressWithFormData(includeShippingOptions: boolean) {
        const {
            shippingAddress,
            values: { shippingAddress: addressForm },
        } = this.props;
 
        const updatedShippingAddress = addressForm && mapAddressFromFormValues(addressForm);
 
        Iif (!updatedShippingAddress || isEqualAddress(updatedShippingAddress, shippingAddress)) {
            return;
        }
 
        this.setState({ isUpdatingShippingData: true });
        this.debouncedUpdateAddress(updatedShippingAddress, includeShippingOptions);
    }
 
    private handleAddressSelect: (
        address: Address
    ) => void = async address => {
        const {
            updateAddress,
            onUnhandledError = noop,
            values,
            setValues,
        } = this.props;
 
        this.setState({ isResettingAddress: true });
 
        try {
            await updateAddress(address);
 
            setValues({
                ...values,
                shippingAddress: mapAddressToFormValues(
                    this.getFields(address.countryCode),
                    address
                ),
            });
        } catch (error) {
            onUnhandledError(error);
        } finally {
            this.setState({ isResettingAddress: false });
        }
    };
 
    private onUseNewAddress: () => void = async () => {
        const {
            deleteConsignments,
            onUnhandledError = noop,
            setValues,
            values,
        } = this.props;
 
        this.setState({ isResettingAddress: true });
 
        try {
            const address = await deleteConsignments();
            setValues({
                ...values,
                shippingAddress: mapAddressToFormValues(
                    this.getFields(address && address.countryCode),
                    address
                ),
            });
        } catch (e) {
            onUnhandledError(e);
        } finally {
            this.setState({ isResettingAddress: false });
        }
    };
 
    private getFields(countryCode: string | undefined): FormField[] {
        const {
            getFields,
        } = this.props;
 
        return getFields(countryCode);
    }
}
 
export default withLanguage(withFormik<SingleShippingFormProps & WithLanguageProps, SingleShippingFormValues>({
    handleSubmit: (values, { props: { onSubmit } }) => {
        onSubmit(values);
    },
    mapPropsToValues: ({ getFields, shippingAddress, isBillingSameAsShipping, customerMessage }) => ({
        billingSameAsShipping: isBillingSameAsShipping,
        orderComment: customerMessage,
        shippingAddress: mapAddressToFormValues(
            getFields(shippingAddress && shippingAddress.countryCode),
            shippingAddress
        ),
    }),
    isInitialValid: ({
        shippingAddress,
        getFields,
        language,
    }) => (
        !!shippingAddress && getAddressFormFieldsValidationSchema({
            language,
            formFields: getFields(shippingAddress.countryCode),
        }).isValidSync(shippingAddress)
    ),
    validationSchema: ({
        language,
        getFields,
        methodId,
    }: SingleShippingFormProps & WithLanguageProps) => methodId ?
        object({
            shippingAddress: lazy<Partial<AddressFormValues>>(formValues =>
                getCustomFormFieldsValidationSchema({
                    translate: getTranslateAddressError(language),
                    formFields: getFields(formValues && formValues.countryCode),
                })
            ),
        }) :
        object({
            shippingAddress: lazy<Partial<AddressFormValues>>(formValues =>
                getAddressFormFieldsValidationSchema({
                    language,
                    formFields: getFields(formValues && formValues.countryCode),
                })
            ),
        }),
    enableReinitialize: false,
})(SingleShippingForm));