All files / src/sections/PayBuilder/Checkout CheckoutFormPreview.tsx

78.72% Statements 37/47
65.74% Branches 71/108
57.14% Functions 4/7
78.72% Lines 37/47

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                                                                                  12x                                         113x   113x 113x 113x 113x               113x                 113x 113x   113x       113x 113x 113x     113x     113x   113x   113x 113x   113x 113x       113x         113x       113x         113x                           113x 16x                 113x 113x 113x                   113x 18x 18x       113x                                                                                                                                                                                                                                                                                                                                                                                                             12x         108x 72x     36x        
import NiceModal from "@ebay/nice-modal-react";
import { useGetCustomerFees } from "@hooks/merchant-api/cart/useGetCardInfos";
import { Box, Link, Stack, SxProps } from "@mui/material";
import CheckoutCart from "@pages/Checkout/components/CheckoutCart";
import { PaymentSuccessInfo } from "@pages/Checkout/components/PaymentSuccess";
import { useAppSelector } from "@redux/hooks";
import { selectCart } from "@redux/slices/cart";
import Payment from "@sections/PayBuilder/Checkout/components/PayBuilderPayment";
import { BreadcrumbItem } from "@shared/Breadcrumbs/GiveBreadcrumbs.types";
import GiveMotionWrapper from "@shared/Motion/GiveMotionWrapper";
import GiveText from "@shared/Text/GiveText";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { CustomTheme } from "@theme/v2/palette.interface";
import { useAppTheme } from "@theme/v2/Provider";
import { TERMS_OF_SERVICE_REBRAND_MODAL } from "modals/modal_names";
import React, { useEffect, useRef } from "react";
import { FormProvider } from "react-hook-form";
import { useParams } from "react-router-dom";
import { useDebouncedCallback } from "use-debounce";
import useCheckFormType from "../components/hooks/useCheckFormType";
import ProductPageLogoComponent from "../components/products/ProductPageContainer/ProductPageLogoComponent";
import { useCart } from "../provider/CartContext";
import { usePayBuilderContext } from "../provider/PayBuilderContext";
import { usePayBuilderForm } from "../provider/PayBuilderFormProvider";
import CheckoutSelector from "./CheckoutSelector";
import CheckoutAddressInputs from "./components/CheckoutAddressInputs";
import CheckoutButton from "./components/CheckoutButton";
import CheckoutFooter from "./components/CheckoutFooter";
import Contact from "./components/Contact";
import ParticipantDetails from "./components/ParticipantDetails";
import SupportPreview from "./components/SupportPreview";
import CustomFieldsPreview from "./components/CustomFieldsPreview";
import { FEE_PAYER_OPTIONS } from "./consts";
import { checkoutScrollbarStyles, isValidCardNumber } from "./helpers";
import useCheckoutPreview from "./hooks/useCheckoutPreview";
import { PayOut } from "./wrappers/WithOrderColumn/Order";
import { useGlobalGroupIdempotencyKey } from "@services/api/useGlobalGroupIdempotencyKey";
import { useIsMutating } from "react-query";
import GiveDisclaimer from "@features/Merchants/MerchantSidePanel/components/GiveDisclaimer/GiveDisclaimer";
import { PaymentErrorBoundary } from "@components/ErrorBoundary";
 
const CheckoutFormPreview = ({
  isPreviewMode = true,
  onPaymentSuccess,
  breadcrumbItems,
  sx = {},
  children,
  handleSubmit,
  isFromBottomSheet,
  bottomsheetCheckoutFormPreviewValues,
  previewHeader,
}: {
  isPreviewMode?: boolean;
  onPaymentSuccess?: (data: PaymentSuccessInfo) => void;
  breadcrumbItems?: BreadcrumbItem[];
  sx?: SxProps<CustomTheme>;
  children?: any;
  handleSubmit?: any;
  isFromBottomSheet?: boolean;
  bottomsheetCheckoutFormPreviewValues?: any;
  previewHeader?: React.ReactElement;
}) => {
  useGlobalGroupIdempotencyKey({ persist: true, condition: !isPreviewMode });
 
  const { isDesktopView, isMobileView, isTabletView } = useCustomThemeV2();
  const { setDisplayFees, setFees, cartItems } = useCart();
  const builderContext = usePayBuilderContext();
  const { palette } = useAppTheme();
  const {
    screenStates: {
      isMobileView: isMobileStateSelected,
      isTabletView: isTabletStateSelected,
      isDesktopView: isDesktopStateSelected,
    },
  } =
    Object.keys(builderContext)?.length > 0
      ? builderContext
      : {
          screenStates: {
            isMobileView: isMobileView,
            isTabletView: isTabletView,
            isDesktopView: isDesktopView,
          },
        };
  const isTabletOrMobile = isMobileStateSelected || isTabletStateSelected;
  const checkoutFormPreviewValues = useCheckoutPreview(onPaymentSuccess);
  const { methods, onSubmit, isLoading, isDeclined, isFailed, declineReason } =
    bottomsheetCheckoutFormPreviewValues || checkoutFormPreviewValues;
  const {
    methods: leftSidepanelMethods,
    parsedValues: { background, accentColor, logo, checkoutInputStyles },
  } = usePayBuilderForm();
  const { isCartLoading } = useAppSelector(selectCart);
  const checkoutClicked = useRef(false);
 
  const { render: isSupportEnabled } =
    leftSidepanelMethods.watch().Checkout.support;
 
  const { render: isBillingEnabled } =
    leftSidepanelMethods.watch().Checkout.billing;
 
  const payButtonValue = leftSidepanelMethods.watch().Checkout.payButtonText;
 
  const { isFundraiser, isSweepstake, isInvoice } = useCheckFormType();
  const { id } = useParams();
 
  const { methods: formValues } = usePayBuilderForm();
  const hasSelectedEntryError = Boolean(
    formValues.formState.errors.Entries?.selectedEntry,
  );
 
  const hasSelectedAmountError = Boolean(
    leftSidepanelMethods.formState.errors.Donations?.selectedAmount,
  );
 
  const isCustomerChoice =
    leftSidepanelMethods.watch().Checkout.feePayer ===
    FEE_PAYER_OPTIONS.CUSTOMER_CHOICE;
 
  const isCheckoutLoading =
    useIsMutating({
      mutationKey: "checkout-mutation",
    }) > 0;
 
  //  ----- CART UPDATE WAITING LOGIC ----
  const debouncedSubmit = useDebouncedCallback(
    async (data: any) => {
      if (isLoading || isCartLoading) {
        //if the user changes custom amount right before submission, we need to wait for cart to update
        checkoutClicked.current = true;
        return;
      }
      checkoutClicked.current = false;
      onSubmit(data);
    },
    500,
    { leading: false },
  );
 
  useEffect(() => {
    Iif (checkoutClicked.current && !isLoading && !isCartLoading) {
      //if the update finishes loading, and the user has pressed checkout previously,
      // we continue with checking the user out after the cart is processed
      checkoutClicked.current = false;
      debouncedSubmit(methods.getValues());
    }
  }, [isCartLoading]);
  // ----- CART UPDATE WAIT LOGIC END -----
  // ----- FEE LOGIC ------
  const passFees = !methods.watch("customerCoversFees");
  const cardNumber = methods.watch("payment.cardNumber");
  const { customerFees } = useGetCustomerFees({
    passFees,
    enabled:
      !(isPreviewMode || isLoading) &&
      isValidCardNumber(cardNumber) &&
      !isCheckoutLoading &&
      cartItems?.length > 0,
    cardNumber: cardNumber.replace(/\s+/g, ""),
  });
 
  useEffect(() => {
    setFees && setFees(customerFees / 100);
    !passFees && setDisplayFees(true);
  }, [customerFees]);
  // ----- FEE LOGIC END------
 
  return (
    <PaymentErrorBoundary
      isCritical={!isPreviewMode}
      formId={id}
      errorContext={{
        isPreviewMode,
        isFundraiser,
        isSweepstake,
        isInvoice,
        cartItemsCount: cartItems?.length || 0,
        isBottomSheet: isFromBottomSheet,
      }}
      onReset={() => {
        // Clear any temporary checkout state on reset
        if (!isPreviewMode) {
          methods.reset();
        }
      }}
    >
      <Box
        data-testid="form-preview"
        sx={{
          overflowY: "unset",
          width: "100%",
          maxWidth: "unset",
          height: "100%",
          backgroundColor: background,
          ...(!isFundraiser && {
            padding: isMobileView || isTabletOrMobile ? "16px" : "40px",
          }),
          ...(isPreviewMode && { marginTop: "20px" }),
          ...(isDesktopView && isPreviewMode && { borderRadius: "20px" }),
          ...sx,
          paddingTop: isSweepstake ? "40px" : 0,
          ...checkoutScrollbarStyles,
        }}
      >
        <CheckoutWrapper
          isCheckoutBottomsheetEnabled={!isFundraiser && !isInvoice}
          methods={methods}
        >
          {children && children}
          <Stack
            gap="24px"
            id="checkout-form"
            component="form"
            sx={{
              ...(isPreviewMode && {
                "& .MuiInputBase-root.Mui-disabled": {
                  backgroundColor: `${palette.surface?.primary} !important`,
                },
              }),
              ...checkoutInputStyles,
              maxWidth: "900px",
              marginX: "auto",
            }}
          >
            {!isFromBottomSheet &&
              !isFundraiser &&
              (isInvoice ? true : isPreviewMode) &&
              !isMobileView &&
              !isMobileStateSelected &&
              logo && (
                <ProductPageLogoComponent
                  logoUrl={logo}
                  isPreview={isPreviewMode}
                  boxSx={{
                    padding: 0,
                    paddingTop: "16px",
                    ...(isInvoice && {
                      width: "100%",
                      justifyContent: "flex-start",
                    }),
                  }}
                />
              )}
            {previewHeader}
            {!isInvoice && (
              <Box
                sx={{
                  paddingTop: isFromBottomSheet ? "32px" : 0,
                }}
              >
                <Contact isDisabledFields={isPreviewMode} />
              </Box>
            )}
            {/* Story 2 — between Contact and Payment (AC013). Self-gates on
                event, and AC059 keeps it read-only in live preview. */}
            <ParticipantDetails
              isDisabledFields={isPreviewMode}
              isPreviewMode={isPreviewMode}
            />
            <CheckoutSelector
              isMobileView={isMobileStateSelected}
              isDisabledFields={isPreviewMode || isLoading}
              isPreviewMode={isPreviewMode}
            />
            {isBillingEnabled && (
              <GiveMotionWrapper type="fadeInUp">
                <CheckoutAddressInputs
                  addressType="billingAddress"
                  isMobileView={isMobileView || isMobileStateSelected}
                  isDisabledFields={isPreviewMode || isLoading}
                  isPreviewMode={isPreviewMode}
                />
              </GiveMotionWrapper>
            )}
            <FormProvider {...methods}>
              <CustomFieldsPreview
                isDisabledFields={isPreviewMode || isLoading}
              />
            </FormProvider>
            <Payment
              isMobileView={isMobileStateSelected}
              isDeclined={isDeclined}
              isDisabledFields={isPreviewMode || isLoading}
              isPreviewMode={isPreviewMode}
            />
            {isSupportEnabled && isCustomerChoice && (
              <GiveMotionWrapper type="fadeInUp">
                <FormProvider {...methods}>
                  <SupportPreview
                    fees={customerFees}
                    isDisabledFields={isPreviewMode || isLoading}
                    isPreviewMode={isPreviewMode}
                  />
                </FormProvider>
              </GiveMotionWrapper>
            )}
            {(isFundraiser || (isSweepstake && isMobileView)) && (
              <CheckoutCart isFundraiser={isFundraiser} />
            )}
            {!isFundraiser && !isInvoice ? null : (
              <>
                <Stack gap="24px" direction="column">
                  {(isDeclined || isFailed) && (
                    <GiveDisclaimer
                      disclaimerType={
                        isDeclined ? "payment_declined" : "payment_failed"
                      }
                      mspResponseCode={declineReason}
                    />
                  )}
                  <CheckoutButton
                    isPreviewMode={isPreviewMode}
                    isLoading={isLoading || isCartLoading}
                    handleSubmit={methods.handleSubmit(debouncedSubmit)}
                    accentColor={accentColor}
                    isDisabled={
                      hasSelectedEntryError ||
                      hasSelectedAmountError ||
                      isCartLoading
                    }
                    title={payButtonValue}
                  />
                  <GiveText
                    variant="bodyS"
                    color="primary"
                    sx={{
                      textAlign: "center",
                    }}
                  >
                    {`By clicking '${payButtonValue}' you agree to GivePayments`}
                    &apos;{" "}
                    <Link
                      color="inherit"
                      onClick={() =>
                        NiceModal.show(TERMS_OF_SERVICE_REBRAND_MODAL)
                      }
                      sx={{ cursor: "pointer" }}
                    >
                      Terms & Conditions
                    </Link>
                  </GiveText>
                </Stack>
                <CheckoutFooter isDesktopView={isDesktopStateSelected} />
              </>
            )}
            {isTabletOrMobile && !isInvoice ? (
              <PayOut
                isPreviewMode={isPreviewMode}
                isLoading={isLoading}
                onSubmit={
                  typeof handleSubmit === "function"
                    ? handleSubmit(debouncedSubmit)
                    : null
                }
                isDeclined={isDeclined}
                isFailed={isFailed}
                declineReason={declineReason}
              />
            ) : null}
          </Stack>
        </CheckoutWrapper>
      </Box>
    </PaymentErrorBoundary>
  );
};
 
const CheckoutWrapper = ({
  children,
  methods,
  isCheckoutBottomsheetEnabled,
}: any) => {
  if (isCheckoutBottomsheetEnabled) {
    return <>{children}</>;
  }
 
  return <FormProvider {...methods}>{children}</FormProvider>;
};
 
export default CheckoutFormPreview;