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

55.26% Statements 21/38
23.8% Branches 5/21
28.57% Functions 4/14
55.26% Lines 21/38

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                                68x 68x   68x                     30x 30x 30x 30x 30x           30x           30x   2x             30x       30x             30x   30x 2x                                     30x           30x               30x                                                                                                                 30x                                                                                                                       68x                              
import { CaretDown } from "@assets/icons";
import { RHFInput } from "@common/Input";
import Selector from "@common/TableFilters/Selector";
import { Text, TruncateText } from "@common/Text";
import useGetEnterpriseCategoryCodes from "@hooks/enterprise-api/merchants/useGetEnterpriseCategoryCodes";
import { InputAdornment, Stack } from "@mui/material";
import { palette } from "@palette";
import { debounce } from "lodash";
import { useCallback, useMemo, useRef, useState } from "react";
import { useFormContext } from "react-hook-form";
import { TCategoriSelectorWithSearch, TCategory } from "./types";
import * as Sentry from "@sentry/react";
import { EmptyState } from "@common/AssignMenu/AssignMenu";
import { TagIcon } from "@phosphor-icons/react";
import { CustomToolTip } from "@common/BusinessOwners/CustomToolTip";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
const BOTTOM_OFFSET_PX = 3;
const TOOLTIP_BOTTOM_MARGIN = 20;
 
const CategoriSelectorWithSearch = ({
  width,
  fullWidth = false,
  name,
  placeholder,
  label,
  providerId,
  isAcquirer,
  disabled,
  saveWithCodeProperty = false,
}: TCategoriSelectorWithSearch) => {
  const { setValue, watch } = useFormContext();
  const [searchValue, setSearchValue] = useState("");
  const value = watch(name);
  const { isMobileView } = useCustomTheme();
  const scrollRef = useRef<HTMLDivElement | null>(null);
 
  const {
    data: fetchedCategories,
    isLoading,
    onEndReached,
  } = useGetEnterpriseCategoryCodes({
    id: providerId,
    searchKey: searchValue,
    sorting: "categoryCodes.riskLevelSortOrder,categoryCodes.code",
  });
 
  const selectedCategory = useMemo(
    () =>
      fetchedCategories?.find(
        (category: TCategory) =>
          category?.categoryCodes?.code === value ||
          category?.categoryCodes?.id === value,
      ),
    [fetchedCategories, value],
  );
  const selectedValue = selectedCategory?.categoryCodes.code
    ? `${selectedCategory?.categoryCodes.code} - ${selectedCategory?.categoryCodes.title}`
    : "";
 
  const debouncedSetSearchValue = useCallback(
    debounce((value) => {
      setSearchValue(value);
    }, 300),
    [],
  );
 
  const [isOpen, setIsOpen] = useState<boolean>(false);
 
  const categoriesOptions = useMemo(() => {
    return fetchedCategories
      ?.filter((category: TCategory) => {
        if (!category?.categoryCodes) {
          //This log should be removed after a while if we're unable to reproduce a scenario that triggers it no longer
          Sentry.captureMessage("Error: Category without category codes found");
          return false;
        }
        return true;
      })
      .map((category: TCategory) => ({
        id: category.categoryCodes.id,
        value: saveWithCodeProperty
          ? category.categoryCodes.code
          : category.categoryCodes.id,
        label: `${category.categoryCodes.code} - ${category.categoryCodes.title}`,
        riskStatus: category.categoryCodes.merchantRiskStatus,
      }));
  }, [fetchedCategories]);
 
  const onChange = (value: any) => {
    setValue(name, value.value, {
      shouldDirty: true,
    });
  };
 
  const handleScroll = (e: React.UIEvent<HTMLElement>) => {
    const { scrollTop, clientHeight, scrollHeight } = e.currentTarget;
    const isNearBottom =
      scrollHeight - (scrollTop + clientHeight) <= BOTTOM_OFFSET_PX;
    if (isNearBottom) {
      onEndReached();
    }
  };
  return (
    <Selector
      options={categoriesOptions}
      value={value}
      searchedWord={searchValue}
      loading={isLoading}
      handleChange={(val) => onChange(val)}
      handleSearch={debouncedSetSearchValue}
      width={width}
      isOpen={setIsOpen}
      multiSelect
      closeOnClick
      ignoreMobileView
      showApplyAction={false}
      fullWidth={fullWidth}
      onScroll={handleScroll}
      scrollBoxRef={scrollRef}
      renderCustomElement={(option: any) => {
        const {
          item: { label, riskStatus, disabled, tooltipTitle },
        } = option;
        return (
          <CustomToolTip
            showToolTip={disabled}
            message={tooltipTitle}
            scrollRef={scrollRef}
            placement="top"
            PopperProps={{
              container: scrollRef.current,
              ...(isMobileView && {
                anchorEl: {
                  getBoundingClientRect: () =>
                    ({
                      top: window.innerHeight - TOOLTIP_BOTTOM_MARGIN,
                      left: window.innerWidth / 2,
                      width: 0,
                      height: 0,
                    } as any),
                },
              }),
            }}
          >
            <Stack
              padding="4px 8px"
              gap="4px"
              sx={{
                pointerEvents: disabled ? "none" : "auto",
              }}
            >
              <TruncateText flex={1} height="40px" lineClamp={1}>
                {label}
              </TruncateText>
            </Stack>
          </CustomToolTip>
        );
      }}
      renderCustomParent={({ onClick }) => (
        <RHFInput
          value={selectedValue}
          disabled={(isAcquirer && !providerId) || disabled}
          onClick={onClick}
          placeholder={placeholder}
          name={name}
          label={label}
          fullWidth
          InputProps={{
            readOnly: true,
            endAdornment: (
              <InputAdornment sx={{ cursor: "pointer" }} position="end">
                <CaretDown rotate={isOpen ? 180 : 0} />
              </InputAdornment>
            ),
          }}
        />
      )}
      searchBarProps={{
        placeholder: "Search",
        customDeleteIcon: <CustomDeleteIcon />,
      }}
      customNoResultsEmptyState={
        <EmptyState
          title="No MCC"
          Icon={
            <>
              <svg width="0" height="0">
                <linearGradient
                  id="gp-gradient"
                  x1="100%"
                  y1="100%"
                  x2="0%"
                  y2="0%"
                >
                  <stop stopColor="#528DDF" offset="0%" />
                  <stop stopColor="#72ECF0" offset="100%" />
                </linearGradient>
              </svg>
              <TagIcon
                size={48}
                style={{ fill: "url(#gp-gradient)", marginBottom: 12 }}
              />
            </>
          }
          subTitle={
            <>
              The selected provider does not
              <br />
              have a MCC assigned
            </>
          }
        />
      }
    />
  );
};
 
export default CategoriSelectorWithSearch;
 
const CustomDeleteIcon = () => {
  return (
    <Text
      sx={{
        color: palette.accent[3],
        marginRight: "15px",
        fontFamily: "Give Whyte",
        fontSize: "14px",
        fontWeight: 350,
        lineHeight: "16.8px",
      }}
    >
      Clear
    </Text>
  );
};