All files / src/componentsV2/Payment Payment.tsx

89.28% Statements 25/28
87.09% Branches 27/31
76.92% Functions 10/13
92.3% Lines 24/26

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                                                                          13x                 217x 217x   217x         217x           217x 217x 217x   217x 31x 2x     217x 34x 11x     217x                                                                                                                                             1085x                           912x                 912x                                                   13x             34x   117x           234x             230x                               224x                  
import { Box, Collapse, Stack } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
 
import { Grid } from "@mui/material";
import GiveText from "@shared/Text/GiveText";
import GiveRadio from "@shared/Radio/GiveRadio";
import { getCardBrandIcon } from "@sections/Checkout/Payment/inputs/CardNumberInput";
import { GiveInput, InputProps } from "@shared/GiveInputs/GiveInput";
import { Controller, useFormContext } from "react-hook-form";
import { useAppTheme } from "@theme/v2/Provider";
import { HiddenComponent } from "@containers/HiddenComponent";
import CVVField from "./components/CVVField";
import WithCheckoutTooltip from "@sections/PayBuilder/Checkout/components/CheckoutTooltip";
import ExpirationDateField from "./components/ExpirationDateField";
import CardNumberField from "./components/CardNumberField";
 
type PaymentField = {
  label?: string;
  name?: string;
  md: number;
  Component: (props: InputProps) => JSX.Element;
  hidden?: boolean;
};
interface IPayment {
  isMobileView?: boolean;
  isDeclined?: boolean;
  isDisabledFields?: boolean;
  styles?: {
    checkoutInputStyles?: any;
    paymentSectionStyles?: any;
    rootContainerSx?: any;
  };
  customInputFields?: PaymentField[];
  HeaderComponent?: JSX.Element;
  showTooltip?: boolean;
}
 
const Payment = ({
  isMobileView,
  isDeclined,
  isDisabledFields,
  styles,
  customInputFields,
  HeaderComponent,
  showTooltip = true,
}: IPayment) => {
  const { palette } = useAppTheme();
  const methods = useFormContext();
 
  const [isPaymentOptionOpen, setIsPaymentOptionOpen] = useState(true);
  const {
    paymentSectionStyles = {},
    checkoutInputStyles = {},
    rootContainerSx = {},
  } = styles || {};
 
  const {
    setFocus,
    watch,
    formState: { errors },
  } = methods;
  const values = watch();
  const expiration = values.payment?.expirationDate?.length || 0;
 
  useEffect(() => {
    if (expiration >= 7 && !(errors as any).payment?.expirationDate)
      setFocus("payment.cvv");
  }, [expiration, !(errors as any).payment?.expirationDate]);
 
  const formFields = useMemo(() => {
    if (customInputFields) return customInputFields;
    return getPaymentFields({ isDisabledFields, isDeclined });
  }, [isDeclined, isDisabledFields, customInputFields]);
 
  return (
    <Stack spacing="20px">
      {HeaderComponent && HeaderComponent}
      <Stack
        width="100%"
        height="100%"
        sx={{
          border: `1px solid ${palette.border?.secondary}`,
          backgroundColor: `transparent`,
          borderTopRightRadius: "12px",
          borderTopLeftRadius: "12px",
          ...(!isPaymentOptionOpen && {
            borderBottomRightRadius: "12px",
            borderBottomLeftRadius: "12px",
          }),
          ...(isPaymentOptionOpen &&
            rootContainerSx?.borderColor && {
              borderColor: rootContainerSx.borderColor,
            }),
          ...rootContainerSx,
        }}
        padding="16px"
      >
        <Stack
          direction="row"
          justifyContent="space-between"
          alignItems="center"
        >
          <Stack direction="row" spacing={1}>
            <Box display="inline-flex">
              <GiveRadio
                onClick={() => {
                  setIsPaymentOptionOpen((prev) => !prev);
                }}
                checked={isPaymentOptionOpen}
                disabled={isDisabledFields}
                iconStyles={{
                  backgroundColor: "transparent !important",
                  borderColor: `${palette?.border?.tertiary} !important`,
                }}
              />
            </Box>
 
            <GiveText variant="bodyS">Credit or Debit Card</GiveText>
          </Stack>
          <Stack direction="row">
            {getCardBrandIcon(
              "",
              true,
              { width: 40, height: 26 },
              isMobileView,
              palette,
            )}
          </Stack>
        </Stack>
      </Stack>
      <Collapse
        orientation="vertical"
        in={isPaymentOptionOpen}
        style={{
          marginTop: "0px",
          borderBottomLeftRadius: "12px",
          borderBottomRightRadius: "12px",
          borderStyle: "solid",
          borderWidth: "0 1px 1px 1px",
          borderColor: palette.border?.secondary,
          ...paymentSectionStyles,
        }}
      >
        <Grid container rowSpacing="24px" columnSpacing={3} padding="16px">
          {formFields.map(({ Component, name, label, md, hidden }, index) => {
            return (
              <HiddenComponent key={index} hidden={hidden || false}>
                <Grid item key={index} xs={12} md={isMobileView ? 12 : md}>
                  {/* if name or options don't exist it means it's not an input */}
                  {!name ? (
                    <Component />
                  ) : (
                    <Controller
                      control={methods.control}
                      name={name as any}
                      render={({
                        field: { onChange, value, ref },
                        fieldState: { error },
                      }) => {
                        const baseProps = {
                          name,
                          value,
                          label,
                          onChange,
                          helperText: error?.message,
                          inputRef: ref,
                        };
 
                        return (
                          <WithCheckoutTooltip
                            disabled={showTooltip && isDisabledFields}
                          >
                            <Component
                              {...baseProps}
                              fullWidth
                              error={Boolean(error)}
                              disabled={isDisabledFields}
                              sx={checkoutInputStyles}
                            />
                          </WithCheckoutTooltip>
                        );
                      }}
                    />
                  )}
                </Grid>
              </HiddenComponent>
            );
          })}
        </Grid>
      </Collapse>
    </Stack>
  );
};
 
export const getPaymentFields = ({
  isDisabledFields = false,
  isDeclined = false,
}: {
  isDisabledFields?: boolean;
  isDeclined?: boolean;
}): PaymentField[] => {
  return [
    {
      Component: (props: InputProps) => <CardNumberField {...props} />,
      label: "Card Number",
      name: "payment.cardNumber",
      md: 12,
    },
    {
      Component: (props: InputProps) => <ExpirationDateField {...props} />,
      label: "Expiration Date (MM/YY)",
      name: "payment.expirationDate",
      md: 6,
    },
    {
      Component: (props: InputProps) => (
        <CVVField {...props} hideTooltip={isDisabledFields} />
      ),
      label: "Security Code",
      name: "payment.cvv",
      md: 6,
    },
    {
      Component: () => (
        <GiveText variant="bodyXS" color="error">
          Your card was declined. Try again or use different card.
        </GiveText>
      ),
      md: 12,
      hidden: !isDeclined,
    },
    {
      Component: (props: InputProps) => <GiveInput {...props} />,
      label: "Name on Card",
      name: "payment.nameOnCard",
      md: 12,
    },
  ];
};
 
export default Payment;