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

88% Statements 66/75
84.33% Branches 70/83
92.85% Functions 13/14
91.3% Lines 63/69

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                                                89x                       216x 216x 216x 216x 216x   216x   216x   216x 38x 38x 38x   38x     216x 27x 10x 10x           216x                   216x 34x 140x         34x     216x                   34x       34x 34x 1x 1x         33x       216x 713x 29x   684x         12x   672x 72x           600x     216x 38x     216x 16x         16x       16x                   216x 27x 27x 22x   4x     4x     2x     2x   16x             216x     216x                                 876x 789x 741x         2x                                                                       89x 216x       12x                   204x     89x                
import React, { useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import { Stack } from "@mui/material";
import { sleep } from "@utils/index";
import { isEmpty } from "lodash";
import GiveOwnershipTab from "./GiveOwnershipTab";
import { HFGiveInput } from "@shared/HFInputs/HFGiveInput/HFGiveInput";
import GiveText from "@shared/Text/GiveText";
import { getMatchInfoMessage } from "@components/Merchants/MerchantPreview/utils";
import { useAppTheme } from "@theme/v2/Provider";
 
type GiveOwnershipInputProps = {
  name: string;
  label: string;
  placeholder: string;
  disabled?: boolean;
  labelProps?: any;
  isFullyDisabled?: boolean;
  disableWithoutReset?: boolean;
  leType?: string;
  matchInfo?: any;
  overrideTooltip?: boolean;
};
 
const GiveOwnershipTabsInput = ({
  name,
  label,
  placeholder,
  disabled,
  labelProps,
  isFullyDisabled,
  disableWithoutReset,
  leType,
  matchInfo,
  overrideTooltip,
}: GiveOwnershipInputProps) => {
  const { setValue, watch, formState } = useFormContext();
  const [tabs, setTabs] = useState(getInitialTabs(leType));
  const { isOFACMatch, isOFACPossibleMatch, isPEPMatch } = matchInfo ?? {};
  const showMatchinfo = Object.values(matchInfo ?? {}).some(Boolean);
  const isSole = leType === "individual_sole_proprietorship";
  const isTaxExemptOrGovtAgency =
    leType && ["tax_exempt_organization", "government_agency"].includes(leType);
 
  const theme = useAppTheme();
 
  const normalizeInput = (value: string) => {
    Iif (isEmpty(value)) return value;
    const currentValue = value?.replace(/[^\d.]/g, "");
    Iif (parseFloat(currentValue) > 100) return "100";
 
    return currentValue;
  };
 
  useEffect(() => {
    if (isFullyDisabled && !disableWithoutReset) {
      setValue(name, "100");
      handleSelectTab({
        value: "100",
      });
    }
  }, [isFullyDisabled]);
 
  const handleBlur = () => {
    const value = normalizeInput(watch(name));
    if (
      leType &&
      ["tax_exempt_organization", "government_agency"].includes(leType)
    )
      return;
    if (parseFloat(value) < 10) setValue(name, "10");
  };
 
  const selectTab = (value: string) => {
    const updatedTabs = tabs.map((tab) => {
      return {
        ...tab,
        selected: tab.value === value,
      };
    });
    setTabs(updatedTabs);
  };
 
  const handleSelectTab = async ({
    value,
    custom,
    shouldDirty = true,
  }: {
    value: string;
    custom?: string;
    shouldDirty?: boolean;
  }) => {
    const val =
      formState && formState.defaultValues
        ? formState?.defaultValues[name]
        : normalizeInput(watch(name));
 
    selectTab(value);
    if (value === "Custom") {
      await sleep(50);
      setValue(name, custom || val || "33", {
        shouldValidate: true,
        shouldDirty,
      });
    } else {
      setValue(name, value, { shouldValidate: true, shouldDirty });
    }
  };
 
  const getTooltip = (tab: string) => {
    if (leType === "individual_sole_proprietorship") {
      return "A sole proprietor owns 100% of the business";
    }
    if (
      leType &&
      tab === "0" &&
      ["tax_exempt_organization", "government_agency"].includes(leType)
    ) {
      return "Tax-exempt organizations and government agencies do not possess ownership percentages";
    }
    if (showMatchinfo) {
      return getMatchInfoMessage({
        isOFACPossibleMatch,
        isPEPMatch,
        isOFACMatch,
      });
    }
    return "";
  };
 
  React.useEffect(() => {
    setValue(name, normalizeInput(watch(name)));
  }, [watch(name)]);
 
  const setInitialValue = (value: string, shouldDirty = false) => {
    switch (value.toString()) {
      case "0":
      case "10":
      case "25":
      case "100":
        handleSelectTab({
          value: value.toString(),
          shouldDirty,
        });
        break;
      default:
        handleSelectTab({
          value: "Custom",
          custom: value,
          shouldDirty,
        });
    }
  };
 
  React.useEffect(() => {
    const value = watch(name);
    if (leType) {
      switch (leType) {
        case "individual_sole_proprietorship":
          handleSelectTab({
            value: "100",
          });
          break;
        case "tax_exempt_organization":
        case "government_agency":
          handleSelectTab({
            value: "0",
          });
          break;
        default:
          if (value) setInitialValue(value);
          else EsetValue(name, "10");
      }
    }
  }, []);
 
  const showCustomPercentageInput =
    tabs?.slice(-1)?.[0]?.selected &&
    leType !== "individual_sole_proprietorship";
 
  return (
    <Stack spacing={1}>
      <GiveText fontSize={"14px"} {...labelProps}>
        Ownership
      </GiveText>
      <Stack
        direction="row"
        spacing={1}
        sx={{
          marginBottom: showCustomPercentageInput ? "16px!important" : "0px",
          overflowX: "auto",
          "&::-webkit-scrollbar": {
            display: "none",
          },
        }}
      >
        {tabs.map(({ value, flex, selected }) => {
          if (isSole && value !== "100") return;
          if (isTaxExemptOrGovtAgency && value !== "0") return;
          return (
            <GiveOwnershipTab
              key={value}
              selected={isSole || selected}
              disabled={isFullyDisabled}
              onClick={() => handleSelectTab({ value })}
              flex={flex}
              value={value}
              tooltip={overrideTooltip ? "" : getTooltip(value)}
              label={value !== "Custom" ? `${value}%` : value}
              dataTestId={`ownership-${value}`}
              sx={{
                maxWidth: "164px",
                ...(isFullyDisabled &&
                  (isSole || isTaxExemptOrGovtAgency) && {
                    button: {
                      backgroundColor: `${theme.palette.buttons?.default} !important`,
                      color: `${theme.palette.text?.invert} !important`,
                    },
                  }),
              }}
            />
          );
        })}
      </Stack>
      {showCustomPercentageInput && (
        <HFGiveInput
          label={label}
          name={name}
          placeholder={placeholder}
          onBlur={handleBlur}
          fullWidth
          rightContent="%"
          size="medium"
          disabled={disabled || isFullyDisabled}
        />
      )}
    </Stack>
  );
};
 
const getInitialTabs = (leType?: string) => {
  if (
    leType &&
    ["tax_exempt_organization", "government_agency"].includes(leType)
  ) {
    return [
      {
        flex: 1,
        value: "0",
        selected: true,
      },
      ...initTabs,
    ];
  }
 
  return initTabs;
};
 
const initTabs = [
  { value: "10", selected: true },
  { value: "25", selected: false, flex: 1 },
  { value: "100", selected: false, flex: 1 },
  { value: "Custom", selected: false },
];
 
export default GiveOwnershipTabsInput;