All files / src/hooks/enterprise-api/merchants useGetLEsInfinitely.tsx

74.46% Statements 35/47
46.15% Branches 18/39
50% Functions 6/12
79.54% Lines 35/44

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                      34x                     216x 216x 216x 216x 216x 216x 216x   216x 216x   216x                                   216x             216x 19x 19x     216x 19x 19x 19x         19x   19x     216x             216x                                           34x                             216x                   24x 24x   24x   24x       24x                                   216x     34x 24x     24x     24x    
import React, { useEffect, useRef, useState } from "react";
import { ROWS_PER_PAGE } from "@hooks/common/usePagination";
import { UseQueryOptions, useQuery } from "react-query";
import { getLegalEntities } from "@services/api/businessProfile";
import { useAppSelector } from "@redux/hooks";
import { selectSelectedAccount } from "@redux/slices/auth/accounts";
import { checkPortals } from "@utils/routing";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { uniqBy } from "lodash";
import { DIGITS_ONLY_REGEX } from "@validation/regex";
 
export const useListLEsInfinitely = ({
  q,
  merchantId: selectedMerchantId,
  outOfTree,
  useGlobalEndpoint,
}: {
  q?: string;
  merchantId?: number;
  outOfTree?: boolean;
  useGlobalEndpoint?: boolean;
}) => {
  const searchQuery = q;
  const loadingRef = useRef<boolean>(false);
  const [page, setPage] = useState(1);
  const [allData, setAllData] = useState<any>([]);
  const searchQueryRef = useRef(false);
  const { isAcquirerEnterprises, isEnterprisePortal } = checkPortals();
  const { isOnboardingLinkBPEnabled } = useGetFeatureFlagValues();
 
  const selectedUser = useAppSelector(selectSelectedAccount);
  const merchantId = selectedUser?.id;
 
  const { data, isLoading, isError, isFetching } = useListLEs(
    {
      page,
      searchQuery: q,
      onlyApproved: !isOnboardingLinkBPEnabled || (!q && isEnterprisePortal),
      addOutOfMerchantTree:
        !isAcquirerEnterprises && outOfTree && isOnboardingLinkBPEnabled,
      selectedMerchantId,
      useGlobalEndpoint,
    },
    {
      refetchOnWindowFocus: false,
      onSuccess() {
        loadingRef.current = false;
      },
    },
  );
 
  const handlePageChange = (
    event: React.ChangeEvent<unknown>,
    value: number,
  ) => {
    setPage(value);
  };
 
  useEffect(() => {
    setPage(1);
    searchQueryRef.current = true;
  }, [searchQuery, merchantId]);
 
  useEffect(() => {
    let newData = [];
    if (searchQueryRef.current) {
      newData = [...(data?.data || [])];
    } else E{
      newData = [...allData, ...(data?.data || [])];
    }
 
    setAllData(uniqBy(newData, "id"));
 
    searchQueryRef.current = false;
  }, [data]);
 
  const loadNextPage = () => {
    if (isLoading) return;
    if (data?.total > allData.length) {
      setPage((prev) => prev + 1);
    }
  };
 
  return {
    isError,
    isFetching,
    page,
    rowsPerPage: ROWS_PER_PAGE,
    currentPageRows: allData,
    handlePageChange,
    totalRows: data?.total ?? 0,
    setPage: () => setPage((current) => current + 1),
    allRows: allData,
    loadingRef,
    isLoading,
    setPageDispatcher: setPage,
    setAllData,
    state: {
      isEmpty: !searchQuery && data?.total === 0,
      isError,
    },
    loadNextPage,
  };
};
 
const useListLEs = (
  {
    page,
    searchQuery,
    merchantId,
    onlyApproved = true,
    addOutOfMerchantTree,
    selectedMerchantId,
    useGlobalEndpoint,
  }: any,
  options: Omit<
    UseQueryOptions<any, any, any, any>,
    "queryKey" | "queryFn"
  > = {},
) => {
  const { data, isLoading, isError, isFetching } = useQuery(
    [
      "list-le-infinitely",
      page,
      searchQuery,
      merchantId,
      selectedMerchantId,
      addOutOfMerchantTree,
    ],
    async () => {
      const approvedFilter = onlyApproved ? `statusName:"approved"%3B` : "";
      const searchedTaxID = getOutOfMerchantTreeTaxID(searchQuery);
      const outOfMerchantTreeTaxID =
        addOutOfMerchantTree && searchedTaxID ? `&tax_id=${searchedTaxID}` : "";
      const checkedIfDeclinedPreviously =
        addOutOfMerchantTree && searchedTaxID && selectedMerchantId
          ? `&subject_merchant_acc_id="${selectedMerchantId}"`
          : "";
 
      const data = await getLegalEntities(
        merchantId,
        {
          filter: `${approvedFilter}allowMultipleMerchants:true&sort=name${
            searchQuery ? `&q="${searchQuery}"` : ""
          }&page=${page}&max=${ROWS_PER_PAGE}${outOfMerchantTreeTaxID}${checkedIfDeclinedPreviously}`,
        },
        useGlobalEndpoint,
      );
 
      return data;
    },
    {
      cacheTime: 0,
      ...options,
    },
  );
 
  return { data, isLoading, isError, isFetching };
};
 
const getOutOfMerchantTreeTaxID = (searchQuery: string) => {
  const nonFormattedTaxID = searchQuery?.replace(/(\s|-)/g, "");
 
  // only digits and has exactly 9 digits
  Iif (DIGITS_ONLY_REGEX.test(nonFormattedTaxID) && nonFormattedTaxID?.length === 9)
    return nonFormattedTaxID;
 
  return "";
};