All files / src/shared/GiveInputs GiveTaxIdInput.tsx

84.78% Statements 78/92
83.33% Branches 95/114
77.14% Functions 27/35
86.36% Lines 76/88

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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460                                                                                            548x 548x 548x 548x 548x 548x   548x 548x 127x   421x 421x           548x     548x 548x   548x 548x           548x 25x 25x 25x   223x 5x       548x       548x   80x 1x     1x         548x 78x 78x 78x     78x       548x 78x     548x   548x           611x           611x                               4x                                                                         611x                             611x                               1222x                                                                         25x             1222x             8x 1x                                                                                                 57x           2065x     2065x 2065x 1628x   437x       2065x     57x 638x 618x 618x 618x 618x 618x 618x 618x   618x                             57x   618x                           57x   11671x             828x                                         57x 4808x   828x                                             57x 57x                                 57x 1890x 611x              
import React, { memo, useEffect, useState } from "react";
import Box from "@mui/material/Box";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import MenuItem from "@mui/material/MenuItem";
import PatternFormat from "react-number-format";
import { useFormContext, Controller } from "react-hook-form";
import { navigationKeys } from "@constants/constants";
import GiveText from "@shared/Text/GiveText";
import { FormLabel, TextField } from "@mui/material";
import { styled } from "@theme/v2/Provider";
import { isEmpty } from "lodash";
import { useAppTheme } from "@theme/v2/Provider";
import { CheckIcon, CaretDownIcon } from "@phosphor-icons/react";
import { SxProps } from "@mui/system";
 
interface Props {
  taxIdName?: string;
  ssnName?: string;
  businessTypeName?: string;
  disabled?: boolean;
  isBusiness?: boolean;
  tinType?: string;
  helperText?: string;
  sx?: SxProps;
  isSSNOnly?: boolean;
  label?: string;
}
 
function GiveTaxIdInput({
  ssnName = "ssn",
  taxIdName = "taxId",
  businessTypeName = "",
  disabled = false,
  isBusiness = true,
  tinType = "tinType",
  helperText,
  sx,
  isSSNOnly = false,
  label,
}: Props) {
  const {
    control,
    setValue,
    watch,
    formState: { isDirty },
  } = useFormContext();
  const values = watch();
  const theme = useAppTheme();
  const [open, setOpen] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const [isHovered, setIsHovered] = useState(false);
 
  let presSelected = "";
  if (accessObjectProperty(values, tinType) === options.SSN.toLowerCase()) {
    presSelected = options.SSN;
  } else {
    if (!isEmpty(accessObjectProperty(values, taxIdName)) || isBusiness) {
      presSelected = options.EIN;
    } else E{
      presSelected = options.SSN;
    }
  }
 
  const [selectValue, setSelectValue] = useState(presSelected);
 
  const isSoleProp =
    accessObjectProperty(values, businessTypeName) === sole_proprietorship;
  const isChangeAllowed = (isBusiness && isSoleProp) || !isBusiness;
 
  const isSSN = selectValue === options.SSN || isSSNOnly;
  const handleChange = (event: any) => {
    setSelectValue(event.target.value);
    setIsHovered(false);
    setValue(inputName, "", { shouldDirty: true });
  };
 
  const handleKeyDown = (event: any, value: string) => {
    const key = event.key;
    const count = isSSN ? 11 : 10;
    const isMaxLength = value?.replace(/\s/g, "").length === count;
 
    if (!navigationKeys.some((item) => item === key) && isMaxLength) {
      event.preventDefault();
    }
  };
 
  const businessType = accessObjectProperty(values, businessTypeName);
 
  //TODO: REFACTOR!!! these useEffects and the code related to it, we should properly use the form setValue instead of relying on these
 
  useEffect(() => {
    // reset ein/ssn dropdown if business type is changed
    if (isDirty && businessType) {
      Iif (businessType === sole_proprietorship) {
        setSelectValue(options.SSN);
      } else {
        setSelectValue(options.EIN);
      }
    }
  }, [businessType]);
 
  useEffect(() => {
    Iif (isDirty) return;
    setSelectValue((prev) => {
      Iif (prev != presSelected) {
        return presSelected;
      }
      return prev;
    });
  }, [presSelected]);
 
  useEffect(() => {
    setValue(tinType, isSSN ? "ssn" : "ein");
  }, [isSSN, tinType]);
 
  const inputName = isSSN ? ssnName : taxIdName;
 
  return (
    <Controller
      name={inputName}
      key={inputName}
      control={control}
      render={({ field: { ref, ...rest }, fieldState: { error, isDirty } }) => {
        const borderColor = error
          ? `${theme.palette.primitive?.error[50]}`
          : isHovered && !disabled
          ? `${theme.palette.border?.active}`
          : `${theme.palette.border?.secondary}`;
 
        return (
          <>
            {label && (
              <GiveText
                color={error ? "error" : "primary"}
                sx={{
                  fontSize: "14px",
                  marginBottom: "8px",
                }}
              >
                {label}
              </GiveText>
            )}
            <InputContainer
              isFocused={isFocused}
              isError={!!error}
              onMouseOver={() => setIsHovered(true)}
              onMouseOut={() => setIsHovered(false)}
              sx={sx}
            >
              <FormControl
                sx={{
                  minWidth: "50px",
                  borderRadius: 0,
                  "& fieldset": { border: "none" },
                  boxSizing: "border-box",
                }}
              >
                <StyledSelect
                  borderColor={borderColor}
                  isFocused={isFocused}
                  isBaseInputDisabled={disabled}
                  open={open}
                  onClose={() => setOpen(false)}
                  onOpen={() => setOpen(true)}
                  value={selectValue}
                  onChange={handleChange}
                  disabled={disabled || !isChangeAllowed}
                  label="Select"
                  MenuProps={{
                    PaperProps: {
                      sx: {
                        display: "flex",
                        flexDirection: "column",
                        width: "250px",
                        background: `${theme.palette.surface?.["tertiary-transparent"]} !important`,
                        backdropFilter: "blur(8px)",
                        padding: "8px !important",
                        borderRadius: "16px !important",
                      },
                    },
                  }}
                  IconComponent={() => (
                    <IconContainer
                      disabled={disabled}
                      onClick={() =>
                        !disabled && isChangeAllowed && setOpen((prev) => !prev)
                      }
                    >
                      {isChangeAllowed && !disabled && (
                        <CaretDownIcon
                          size={20}
                          color={theme.palette.icon?.["icon-secondary"]}
                        />
                      )}
                    </IconContainer>
                  )}
                  renderValue={(selected) => (
                    <GiveText
                      fontWeight="regular"
                      textAlign="left"
                      fontSize="14px"
                      color="secondary"
                      data-testid="tax-id-selected-option"
                      sx={{
                        opacity: "1 !important",
                        WebkitTextFillColor: `${theme.palette.text.secondary} !important`,
                      }}
                    >
                      {String(selected)}
                    </GiveText>
                  )}
                >
                  {Object.values(options).map((text) => (
                    <StyledMenuItem
                      key={text}
                      value={text}
                      isSelected={selectValue === text}
                    >
                      <GiveText
                        color="secondary"
                        fontWeight="regular"
                        textAlign="left"
                        fontSize="14px"
                      >
                        {text}
                      </GiveText>
                      {open && text === selectValue && (
                        <CheckIcon
                          fill={theme.palette.icon?.["icon-secondary"]}
                          size="20px"
                        />
                      )}
                    </StyledMenuItem>
                  ))}
                </StyledSelect>
              </FormControl>
 
              <Box
                flex={4}
                sx={{
                  height: isFocused ? "46px" : "48px",
                  boxSizing: "border-box",
                }}
                display="flex"
                alignItems="center"
              >
                <PatternFormat
                  className="taxid-input"
                  format={isSSN ? "###-##-####" : "##-#######"}
                  fullWidth
                  onKeyDown={(event) => handleKeyDown(event, rest.value)}
                  customInput={CustomTextField}
                  pattern="\d*"
                  placeholder={isSSN ? "XXX-XX-XXXX" : "XX-XXXXXXX"}
                  isDirty={isDirty}
                  {...rest}
                  ref={(inputRef) => {
                    ref({
                      ...inputRef,
                      focus: () => setIsFocused(true),
                    });
                  }}
                  error={!!error}
                  disabled={disabled}
                  onFocus={() => setIsFocused(true)}
                  onBlur={() => setIsFocused(false)}
                  sx={{
                    letterSpacing: "6px",
                    "& .MuiFormHelperText-root": {
                      letterSpacing: "0px",
                    },
                    "& .css-1a7prda-MuiInputBase-root-MuiOutlinedInput-root": {
                      padding: 0,
                      paddingLeft: "5px",
                    },
                    "& .MuiInputBase-root": {
                      border: isFocused ? "none" : `1.5px solid`,
                      borderRadius: "0 12px 12px 0",
                      borderLeft: "none",
                      borderColor: borderColor,
                      height: isFocused ? "43px !important" : "48px",
                      "&:hover": {
                        borderColor: borderColor,
                      },
                    },
                    "& .MuiInputBase-root input ": {
                      marginTop: "0 !important",
                      color: theme.palette.text.primary,
                    },
                  }}
                />
              </Box>
            </InputContainer>
            {(error?.message || helperText) && (
              <GiveText
                fontWeight="regular"
                paddingInline={0}
                fontSize="12px"
                color="error1"
                marginTop="4px"
                textAlign="left"
              >
                {error?.message || helperText}
              </GiveText>
            )}
          </>
        );
      }}
    />
  );
}
 
export default memo(GiveTaxIdInput);
 
const options = {
  EIN: "EIN",
  SSN: "SSN",
};
function accessObjectProperty(obj: any, path: string) {
  // Split the path by dot
  const parts = path.split(".");
 
  // Access the property dynamically
  const result = parts.reduce((acc, part) => {
    if (acc && typeof acc === "object" && part in acc) {
      return acc[part];
    } else {
      return undefined;
    }
  }, obj);
 
  return result;
}
 
const CustomTextField = (e: any) => {
  const { watch } = useFormContext();
  const { isDirty } = e;
  const values = watch();
  const isSSN = values?.tinType === "ssn";
  const digits = e.value.replace(/[^0-9]/g, "");
  const isLast4 = digits?.length === 4;
  const ssnEIN = isSSN ? `XXX-XX-${digits}` : `XX-XXX${digits}`;
  const val = isLast4 && !isDirty ? ssnEIN : e?.value;
 
  return (
    <Input
      {...e}
      value={val}
      InputProps={{
        ...e?.InputProps,
        inputProps: {
          ...e?.InputProps?.inputProps,
          "data-testid": "custom-input-taxid",
        },
      }}
    />
  );
};
 
const sole_proprietorship = "individual_sole_proprietorship";
 
const Input = styled(TextField)(({ theme, disabledTextcolor }: any) => ({
  "& .MuiInputBase-root.Mui-disabled": {
    backgroundColor: theme.palette.surface?.secondary,
    boxShadow: "none",
    border: `1.5px solid ${theme.palette.border?.secondary}`,
    borderLeftWidth: 0,
    "& input": {
      marginTop: "18px",
      WebkitTextFillColor: disabledTextcolor || theme.palette.text.secondary,
      color: disabledTextcolor || theme.palette.text.secondary,
    },
  },
}));
 
export const StyledSelect = styled(Select, {
  shouldForwardProp: (prop) =>
    prop !== "borderColor" &&
    prop !== "isFocused" &&
    prop !== "isBaseInputDisabled",
})<{
  borderColor: string;
  isFocused: boolean;
  isBaseInputDisabled: boolean;
}>(({ borderColor, isFocused, isBaseInputDisabled, theme }) => ({
  boxSizing: "border-box",
  border: isFocused ? "none" : `1.5px solid ${borderColor}`,
  borderRightWidth: 0,
  borderRadius: "12px 0 0 12px",
  height: isFocused ? "46px" : "48px",
  backgroundColor: isBaseInputDisabled
    ? `${theme.palette.surface?.secondary}`
    : "inherit",
  "& .MuiSelect-select": {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    paddingRight: "8px !important",
    paddingLeft: "16px !important",
    paddingBlock: "14px !important",
    width: "auto",
    minWidth: "30px",
  },
}));
 
export const InputContainer = styled(Box, {
  shouldForwardProp: (prop) => prop !== "isFocused" && prop !== "isError",
})<{ isFocused: boolean; isError: boolean }>(
  ({ isFocused, isError, theme }) => ({
    width: "100%",
    height: "46px",
    [theme.breakpoints.up("sm")]: {
      height: "50px",
    },
    display: "flex",
    alignItems: "center",
    borderRight: "none",
    background:
      isFocused && !isError
        ? "linear-gradient(#ffffffff, #ffffffff) padding-box, linear-gradient(85.95deg, #4F86D5 0%, #61C7E8 100%) border-box"
        : "inherit",
    border: isFocused
      ? isError
        ? `1.5px solid ${theme.palette.primitive?.error[50]}`
        : "1.5px solid transparent !important"
      : "none",
    borderRadius: "12px",
    boxSizing: "border-box",
  }),
);
 
export const StyledMenuItem = styled(MenuItem, {
  shouldForwardProp: (prop) => prop !== "isSelected",
})<{ isSelected: boolean }>(({ isSelected, theme }) => ({
  display: "flex",
  justifyContent: "space-between",
  alignItems: "center",
  flex: 1,
  backgroundColor: "transparent !important",
  borderRadius: "8px",
  paddingInline: "12px",
  "&:hover": {
    backgroundColor: isSelected
      ? "transparent !important"
      : `${theme.palette?.primitive?.transparent["darken-5"]} !important`,
    cursor: isSelected ? "default" : "pointer",
  },
}));
 
export const IconContainer = styled(Box, {
  shouldForwardProp: (prop) => prop !== "disabled",
})<{ disabled: boolean }>(({ disabled }) => ({
  cursor: disabled ? "default" : "pointer",
  width: "100%",
  height: "100%",
  display: "flex",
  alignItems: "center",
}));