All files / src/components/common/BusinessProfileInputs CustomTaxSsnInput.tsx

72.61% Statements 61/84
65.9% Branches 58/88
57.14% Functions 16/28
75.3% Lines 61/81

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                                                                                        45x 45x   45x 45x 45x   45x 45x 5x   40x 40x           45x 6x     45x     45x 45x   45x 45x         45x                   45x       45x   6x                 45x 6x 6x 6x     6x     45x   45x 6x     45x           49x             49x 49x                                                                                                 49x                                             98x                                                         98x             1x                                                                                                               19x           175x     175x 175x 161x   14x       175x     19x 49x 49x   49x 1x 1x   49x 49x 49x 49x 49x 49x 49x     19x   19x 803x 49x                          
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 { Text } from "@common/Text";
import DropdownIcon from "@assets/icons/dropDownIcon";
import { TextField, styled } from "@mui/material";
import { isEmpty, isFunction } from "lodash";
import { palette } from "@palette";
interface Props {
  taxIdName?: string;
  ssnName?: string;
  businessTypeName?: string;
  disabled?: boolean;
  isBusiness?: boolean;
  tinType?: string;
  helperText?: string;
  customError?: (msg: string) => JSX.Element;
  isCustomErrorArray?: string[];
  forceSSN?: boolean;
}
 
function CustomTaxSsnInput({
  ssnName = "ssn",
  taxIdName = "taxId",
  businessTypeName = "",
  disabled = false,
  isBusiness = true,
  tinType = "tinType",
  helperText,
  customError,
  isCustomErrorArray,
  forceSSN,
}: Props) {
  const {
    control,
    setValue,
    watch,
    formState: { isDirty },
    trigger,
  } = useFormContext();
  const values = watch();
 
  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;
    }
  }
 
  if (forceSSN) {
    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 || forceSSN;
  const handleChange = (event: any) => {
    setSelectValue(event.target.value);
    setIsHovered(false);
  };
 
  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
    Iif (isDirty && businessType) {
      if (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]);
  const inputName = isSSN ? ssnName : taxIdName;
 
  useEffect(() => {
    setValue(tinType, isSSN ? "ssn" : "ein");
  }, [isSSN, tinType]);
 
  return (
    <Controller
      name={inputName}
      key={inputName}
      control={control}
      render={({ field: { ref, ...rest }, fieldState: { error } }) => {
        const borderColor = error
          ? palette.filled.red
          : isFocused
          ? `${palette.gray[300]}`
          : isHovered && !disabled
          ? `${palette.gray.main}`
          : `${palette?.liftedWhite[200]}`;
        const errorMessage = error?.message || helperText || "";
        return (
          <>
            <Box
              width="100%"
              sx={{
                display: "flex",
                alignItems: "center",
                borderRight: "none",
              }}
              onMouseOver={() => setIsHovered(true)}
              onMouseOut={() => setIsHovered(false)}
            >
              <FormControl
                sx={{
                  minWidth: "100px",
                  borderRadius: 0,
                  "& fieldset": { border: "none" },
                }}
              >
                <Select
                  open={open}
                  onClose={() => setOpen(false)}
                  onOpen={() => setOpen(true)}
                  value={selectValue}
                  onChange={handleChange}
                  disabled={disabled || !isChangeAllowed}
                  label="Select"
                  sx={{
                    bgcolor: "#F8F8F6",
                    ...(!disabled && {
                      "&:hover": {
                        bgcolor: `${palette.neutral[20]} !important`,
                      },
                    }),
                    border: `2px solid ${borderColor}`,
                    height: "54.13px",
                    borderRightWidth: "1px !important",
                    borderRadius: "8px 0 0 8px",
                    "& .MuiSelect-select": {
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      paddingRight: "8px !important",
                      paddingLeft: "8px !important",
                      width: "auto",
                      minWidth: "60px",
                    },
                  }}
                  IconComponent={() => (
                    <Box
                      sx={{
                        cursor: disabled ? "default" : "pointer",
                        width: "100%",
                        height: "100%",
                        display: "flex",
                        alignItems: "center",
                      }}
                      onClick={() =>
                        !disabled && isChangeAllowed && setOpen((prev) => !prev)
                      }
                    >
                      {isChangeAllowed && (
                        <DropdownIcon
                          width={11.5}
                          height={8.5}
                          fill={palette.gray[300]}
                        />
                      )}
                    </Box>
                  )}
                >
                  {Object.values(options).map((text) => (
                    <MenuItem
                      key={text}
                      value={text}
                      sx={{ display: text === selectValue ? "none" : "block" }}
                    >
                      <Text
                        color={palette.black[100]}
                        fontWeight="regular"
                        textAlign="left"
                        fontSize="14px"
                      >
                        {text}
                      </Text>
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
 
              <Box flex={4} sx={{ height: "54.13px" }}>
                <PatternFormat
                  className="taxid-input"
                  format={isSSN ? "###-##-####" : "##-#######"}
                  fullWidth
                  onKeyDown={(event) => handleKeyDown(event, rest.value)}
                  customInput={CustomTextField}
                  pattern="\d*"
                  placeholder={isSSN ? "XXX-XX-XXXX" : "XX-XXXXXXX"}
                  {...rest}
                  ref={(inputRef) => {
                    ref({
                      ...inputRef,
                      focus: () => setIsFocused(true),
                    });
                  }}
                  error={!!error}
                  disabled={disabled}
                  onFocus={() => setIsFocused(true)}
                  onBlur={() => setIsFocused(false)}
                  sx={{
                    height: "100%",
                    letterSpacing: "6px",
                    "& .MuiFormHelperText-root": {
                      letterSpacing: "0px",
                    },
                    "&  .MuiInputBase-root": {
                      borderRadius: "0 8px 8px 0",
                      borderLeft: "none",
                    },
                    "& .css-1a7prda-MuiInputBase-root-MuiOutlinedInput-root": {
                      padding: 0,
                      paddingLeft: "5px",
                    },
                    "& .MuiInputBase-root": {
                      borderColor: borderColor,
                      height: "100%",
                    },
                    "& .MuiInputBase-root input ": {
                      marginTop: "0 !important",
                      height: "100%",
                    },
                  }}
                />
              </Box>
            </Box>
 
            {!isEmpty(errorMessage) && (
              <>
                {isCustomErrorArray?.includes(errorMessage) && customError ? (
                  customError(errorMessage)
                ) : (
                  <Text
                    fontWeight="regular"
                    paddingInline="12px"
                    fontSize="12px"
                    color={palette.gray[300]}
                    marginTop="4px"
                    textAlign="left"
                  >
                    {errorMessage}
                  </Text>
                )}
              </>
            )}
          </>
        );
      }}
    />
  );
}
 
export default memo(CustomTaxSsnInput);
 
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 [hasTouched, setHasTouched] = useState(false);
 
  const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
    setHasTouched(true);
    e?.onChange(event);
  };
  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 && !hasTouched ? ssnEIN : e?.value;
  return <Input {...e} value={val} onChange={handleInput} />;
};
 
const sole_proprietorship = "individual_sole_proprietorship";
 
const Input = styled(TextField, {
  shouldForwardProp: (prop) => prop !== "disabledTextcolor",
})(({ disabledTextcolor }: any) => ({
  "& .MuiInputBase-root.Mui-disabled": {
    backgroundColor: palette.liftedWhite[200],
    boxShadow: "none",
    border: "none",
 
    "& input": {
      marginTop: "18px",
      WebkitTextFillColor: disabledTextcolor || palette.gray[300],
      color: disabledTextcolor || palette.gray[300],
    },
  },
}));