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

69.04% Statements 87/126
48.95% Branches 47/96
62.06% Functions 18/29
73.04% Lines 84/115

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                                                                                                    98x   98x                 1311x 1532x   1311x 1311x           1311x                 1311x   1311x 128x 128x 128x     1311x 150x 26x 26x 26x                 150x       1311x                   1311x           1311x     98x                                   203x 203x 203x 203x 203x   203x     15x 15x 2x     203x 203x 203x 203x 203x 203x                                   203x 20x 20x 20x     203x               203x   203x 1x 1x     1x       1x   1x   1x 1x     1x 1x     1x 1x     1x 1x   1x                   203x     1x   1x                           1x       203x 20x 4x   20x     203x   5x   5x                       203x 17x 17x             17x         17x                                                       203x                                                       203x 76x     203x   37x 37x   37x       37x                             203x                     1x                                              
import { RHFSelect } from "@common/Select";
import { useListAllEnterprises } from "@hooks/acquirer-api/merchants/useListAllEnterprises";
import { useListEnterpriseCategoryCodes } from "@hooks/enterprise-api/merchants/useListEnterpriseCategoryCodes";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import { selectSelectedAccount } from "@redux/slices/auth/accounts";
import {
  resetSearchQueryByKey,
  selectQueryString,
  setSearchQueryByKey,
} from "@redux/slices/search";
import { QKEY_LIST_ENTERPRISES } from "@constants/queryKeys";
import NiceModal from "@ebay/nice-modal-react";
import { GIVE_CONFIRMATION_POP_UP } from "modals/modal_names";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import { debounce } from "lodash";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { addSizeToImage } from "@utils/image.helpers";
import { Stack } from "@mui/material";
import GiveText from "@shared/Text/GiveText";
import ContextualMenuHeader from "@shared/ContextualMenu/ContextualMenuHeader";
import GiveThumbnail from "@shared/Thumbnail/GiveThumbnail";
 
type EnterpriseType = {
  accID: number;
  name: string;
  imageURL?: string;
};
 
type EnterprisesSelectProps = {
  id?: string;
  name: string;
  label?: string;
  disabled?: boolean;
  slug?: string;
  phone?: string;
  imageUrl?: string;
  enterpriseName?: string;
  focusViewColor?: string;
  isConfirmModal?: boolean;
  isRebranded?: boolean;
  placeholder?: string;
  useContextualMenuHeader?: boolean;
  tabFilter?: string;
  filter?: string;
  cacheTime?: number;
  staleTime?: number;
};
 
const BOTTOM_OFFSET_PX = 3;
 
export const useInfiniteEnterprises = (arg?: {
  searchText?: string;
  filter?: string;
  enabled?: boolean;
  hasLoadingOnSearch?: boolean;
  tabFilter?: string;
  cacheTime?: number;
  staleTime?: number;
}) => {
  const searchText = useAppSelector((state) =>
    selectQueryString(state, QKEY_LIST_ENTERPRISES),
  );
  const [data, setData] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const {
    data: pageData,
    isLoading,
    error,
    isFetching,
  } = useListAllEnterprises({
    page: data.length > 20 && searchText ? 1 : page,
    searchText: searchText,
    filter: arg?.filter,
    enabled: arg?.enabled,
    tabFilter: arg?.tabFilter,
    cacheTime: arg?.cacheTime,
    staleTime: arg?.staleTime,
  });
  const searchQueryRef = useRef(false);
 
  useEffect(() => {
    setPage(1);
    searchQueryRef.current = true;
    if (arg?.hasLoadingOnSearch) setData([]);
  }, [searchText]);
 
  useEffect(() => {
    if (pageData?.data) {
      if (searchQueryRef.current) {
        setData([...(pageData?.data || [])]);
        searchQueryRef.current = false;
      } else E{
        if (data.length === 0 && pageData?.data) {
          setData(pageData.data);
        } else if (data.length > 0) {
          setData((prev) => [...prev, ...pageData.data]);
        }
      }
    }
    Iif (pageData?.data === null && pageData?.total < 1 && !isLoading)
      setData([]);
  }, [pageData]);
 
  const handleScroll = (e: React.UIEvent<HTMLElement>) => {
    if (isLoading) return;
    const { scrollTop, clientHeight, scrollHeight } = e.currentTarget;
    const isNearBottom =
      scrollHeight - (scrollTop + clientHeight) <= BOTTOM_OFFSET_PX;
    if (isNearBottom && pageData?.total > data.length) {
      setPage((prev) => prev + 1);
    }
  };
 
  const loadNextPage = () => {
    if (isLoading) return;
    if (pageData?.total > data.length) {
      setPage((prev) => prev + 1);
    }
  };
  return { handleScroll, loadNextPage, data, isLoading, error, isFetching };
};
 
const EnterprisesSelect = ({
  name,
  disabled,
  slug,
  phone,
  isConfirmModal,
  enterpriseName,
  imageUrl,
  isRebranded = false,
  label = "Provider",
  placeholder = "Select an option",
  useContextualMenuHeader = false,
  tabFilter,
  filter = "",
  cacheTime,
  staleTime,
  ...rest
}: EnterprisesSelectProps) => {
  const { setValue, watch, getValues } = useFormContext();
  const { isMobileView } = useCustomThemeV2();
  const [selectedEnterprise, setSelectedEnterprise] = useState(0);
  const watchedValue = watch(name);
  const linkedBankAccountID = watch("linkedBankAccountID");
 
  useEffect(() => {
    // Keep internal selected state in sync with form value, including clearing.
    // NOTE: watchedValue can be "" when reset programmatically.
    const next = watchedValue ? Number(watchedValue) : 0;
    if (next !== selectedEnterprise) {
      setSelectedEnterprise(next);
    }
  }, [watchedValue, selectedEnterprise]);
  const searchBarValueRef = useRef("");
  const searchedEnterprise = useRef<any>(null);
  const selectRef = useRef<{ closeMenu: () => void } | null>(null);
  const dispatch = useAppDispatch();
  const [searchValue, setSearchValue] = useState<string>("");
  const debouncedSetSearchValue = useCallback(
    debounce((value, reason) => {
      if (reason === "onChange" || reason == "keyDown") {
        searchBarValueRef.current = value;
        dispatch(
          setSearchQueryByKey({
            queryKey: QKEY_LIST_ENTERPRISES,
            params: {
              value: value,
            },
          }),
        );
      }
      setSearchValue(value);
    }, 500),
    [],
  );
 
  const handleClearSearch = () => {
    searchBarValueRef.current = "";
    dispatch(resetSearchQueryByKey(QKEY_LIST_ENTERPRISES));
    setSearchValue("");
  };
  const { data, handleScroll, loadNextPage, isFetching } =
    useInfiniteEnterprises({
      tabFilter,
      filter,
      cacheTime,
      staleTime,
    });
 
  const { servicePhoneNumber, slug: enterpriseSlug } =
    useListEnterpriseCategoryCodes(watch(name));
 
  const handleChangeEnterprise = (enterpriseID: string) => {
    const selectedEnterprise = data.find(
      (value) => Number(value.accID) === Number(enterpriseID),
    );
 
    Iif (searchBarValueRef.current && selectedEnterprise) {
      searchedEnterprise.current = selectedEnterprise;
    }
 
    setSelectedEnterprise(Number(enterpriseID));
 
    setValue(name, enterpriseID, { shouldDirty: true, shouldValidate: true });
 
    Eif (slug && data) {
      setValue(slug, enterpriseSlug);
    }
 
    Eif (phone) {
      setValue(phone, servicePhoneNumber);
    }
 
    Eif (enterpriseName) {
      setValue(enterpriseName, selectedEnterprise?.name);
    }
 
    Eif (imageUrl) {
      setValue(imageUrl, selectedEnterprise?.imageURL ?? "");
    }
    Iif (linkedBankAccountID) {
      const bankAccounts = getValues("bankAccounts");
      const filteredAccounts = bankAccounts?.filter(
        (item: any) => item.id !== linkedBankAccountID,
      );
      setValue("linkedBankAccountID", null);
      setValue("bankAccounts", filteredAccounts);
    }
  };
 
  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const enterpriseID = e.target.value;
 
    Iif (isConfirmModal) {
      NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
        modalType: "discard-warning",
        title: "Change Provider",
        description:
          "Changing the provider will remove the bank account currently linked to this merchant.",
        customSubmitBtnText: "Yes, Change",
        actions: {
          handleSuccess: {
            onClick: () => handleChangeEnterprise(enterpriseID),
          },
        },
      });
    } else {
      handleChangeEnterprise(enterpriseID);
    }
  };
 
  useEffect(() => {
    if (slug && data) {
      setValue(slug, enterpriseSlug);
    }
    return handleClearSearch();
  }, [enterpriseSlug]);
 
  const createProviderImage = useCallback(
    (imageURL?: string, name?: string) => {
      const imageUrl = imageURL ? addSizeToImage(imageURL, "thumb") : undefined;
 
      return (
        <GiveThumbnail
          imageUrl={imageUrl}
          name={name}
          size="extra_extra_small"
          type="provider"
        />
      );
    },
    [],
  );
 
  const enterpriseOptions = useMemo(() => {
    Iif (!data) return [];
    const allEnterprises = data.map((provider: EnterpriseType) => ({
      value: provider.accID,
      label: provider.name,
      Image: createProviderImage(provider.imageURL, provider.name),
      imageURL: provider.imageURL,
    }));
 
    Eif (
      !searchedEnterprise.current ||
      !selectedEnterprise ||
      searchedEnterprise.current?.accID !== selectedEnterprise
    )
      return allEnterprises;
 
    const isSearchedEnterpriseExisting = data.find(
      (value) =>
        Number(value.accID) === Number(searchedEnterprise.current?.accID),
    );
 
    if (isSearchedEnterpriseExisting) return allEnterprises;
 
    return [
      ...allEnterprises,
      {
        value: searchedEnterprise.current?.accID,
        label: searchedEnterprise.current?.name,
        Image: createProviderImage(
          searchedEnterprise.current?.imageURL,
          searchedEnterprise.current?.name,
        ),
        imageURL: searchedEnterprise.current?.imageURL,
      },
    ];
  }, [
    data,
    searchedEnterprise.current,
    selectedEnterprise,
    createProviderImage,
  ]);
 
  const ctxMenuProps = {
    isFetchingNextPage: isFetching,
    searchBarProps: {
      handleChange: (val: string, type: string) =>
        debouncedSetSearchValue(val, type),
      value: searchValue || searchBarValueRef?.current,
      handleClearSearch,
      resetOnClose: false,
    },
    onCloseEmptyState: handleClearSearch,
    showEmptySectionWhenNoData: true,
    emptySection: "empty-search",
    ...(!isMobileView && {
      color: "tertiary",
      texture: "blurred",
    }),
    ...(isMobileView &&
      useContextualMenuHeader && {
        Header: (
          <ContextualMenuHeader
            title="Select Provider"
            onBackClick={() => selectRef.current?.closeMenu()}
          />
        ),
      }),
    onEndReached: loadNextPage,
  };
 
  const selectedOption = enterpriseOptions.find(
    (opt) => opt.value === selectedEnterprise,
  );
 
  const renderSelectedValue = useCallback(
    (value: string | number) => {
      const option = enterpriseOptions.find((opt) => opt.value === value);
      Iif (!option) return null;
 
      const imageUrl = option.imageURL
        ? addSizeToImage(option.imageURL, "thumb")
        : undefined;
 
      return (
        <Stack direction="row" alignItems="center" gap="8px">
          <GiveThumbnail
            imageUrl={imageUrl}
            name={option.label}
            size="extra_extra_small"
            type="provider"
          />
          <GiveText variant="bodyS">{option.label}</GiveText>
        </Stack>
      );
    },
    [enterpriseOptions],
  );
 
  return isRebranded ? (
    <HFGiveSelect
      ref={selectRef}
      label={label}
      name={name}
      options={enterpriseOptions}
      placeholder={placeholder}
      useContextualMenu
      withIconOffset={false}
      contextualMenuProps={ctxMenuProps as any}
      disabled={disabled}
      onChange={(e) => handleChange(e as any)}
      renderValue={selectedOption ? renderSelectedValue : undefined}
      value={selectedEnterprise}
      data-testid="provider-select-rebranded"
      {...rest}
    />
  ) : (
    <RHFSelect
      label={label}
      name={name}
      placeholder="Choose Merchant’s Provider"
      options={enterpriseOptions}
      onChange={handleChange}
      fullWidth
      disabled={disabled}
      onScroll={handleScroll}
      sxMenu={{ maxWidth: "300px" }}
      {...rest}
    />
  );
};
 
export default EnterprisesSelect;