All files / src/shared/GiveExportModal/hooks useManageExportApi.ts

60.97% Statements 25/41
65.62% Branches 21/32
35.71% Functions 5/14
60% Lines 24/40

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                      25x       25x   25x             86x 86x   86x 86x   86x       6x                                                               86x       6x                                                         86x                 86x 86x 86x         86x                                   86x                             86x 49x 49x 42x 2x         42x     86x            
import { DEFAULT_QUERY_CONFIG } from "@components/VirtualList/hooks/queries";
import { customInstance } from "@services/api";
import { addSizeToImage } from "@utils/image.helpers";
import { useCallback, useMemo, useState } from "react";
import { useInfiniteQuery } from "react-query";
import { ContextOptionsApi } from "../giveExportTypes";
import { useGetProcessors } from "@hooks/acquirer-api/merchants/useGetProcessors";
import { useGetCurrentMerchantId } from "@hooks/common";
import { exportType, selectOptions, TableType } from "../const";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { processorMap } from "@features/Merchants/MerchantSidePanel/constants";
const defaultSearch = {
  merchantsSearchQuery: "",
  reasonsSearchQuery: "",
};
const pageSize = 20;
 
const processorEnabledTypes: TableType[] = [exportType.ACQUIRE_DISPUTE];
 
export default function useManageExportApi({
  fieldTypes,
}: {
  fieldTypes?: TableType;
}) {
  const { merchantId, isSponsor } = useGetCurrentMerchantId();
  const { isMerchantProcessorEnabled } = useGetFeatureFlagValues();
  const [{ merchantsSearchQuery, reasonsSearchQuery }, setSearchQuery] =
    useState(defaultSearch);
  const disputesApiEnabled = fieldTypes === exportType.ACQUIRE_DISPUTE;
 
  const merchantsQuery = useInfiniteQuery({
    queryKey: ["get-merchants", merchantsSearchQuery],
    enabled: disputesApiEnabled,
    queryFn: async ({ pageParam = 1 }) => {
      const response = await customInstance({
        url: `/disputes/merchants?page=${pageParam}&max=${pageSize}&q=${merchantsSearchQuery}`,
      });
 
      const data = response?.data || [];
      const _data = data.map(
        (merchant: { accID: number; name: string; imageURL: string }) => {
          return {
            label: merchant.name,
            value: merchant.accID,
            ImageURL: addSizeToImage(merchant.imageURL, "thumb"),
            checkedIcon: "Check",
            hideImage: false,
          };
        },
      );
 
      return {
        data: _data,
        total: response.total,
        currentPage: pageParam,
        hasNextPage: pageParam * pageSize < response.total, // Determine if more pages exist
      };
    },
 
    getNextPageParam: (lastPage: any) =>
      lastPage.hasNextPage ? lastPage.currentPage + 1 : undefined,
    ...DEFAULT_QUERY_CONFIG,
 
    keepPreviousData: true,
  });
 
  const reasonsQuery = useInfiniteQuery({
    queryKey: ["get-reasons", reasonsSearchQuery],
    enabled: disputesApiEnabled,
    queryFn: async ({ pageParam = 1 }) => {
      const response = await customInstance({
        url: `/disputes/reasons?page=${pageParam}&max=${pageSize}&q=${reasonsSearchQuery}`,
      });
 
      const data = response?.data || [];
      const _data = data.map((reason: { reason: string }) => {
        return {
          label: reason.reason,
          value: reason.reason,
          ImageURL: "",
          checkedIcon: "Check",
          hideImage: true,
        };
      });
 
      return {
        data: _data,
        total: response.total,
        currentPage: pageParam,
        hasNextPage: pageParam * pageSize < response.total, // Determine if more pages exist
      };
    },
 
    getNextPageParam: (lastPage: any) =>
      lastPage.hasNextPage ? lastPage.currentPage + 1 : undefined,
    ...DEFAULT_QUERY_CONFIG,
    keepPreviousData: true,
  });
 
  const { data: processorsData } = useGetProcessors(
    merchantId,
    fieldTypes &&
      processorEnabledTypes.includes(fieldTypes) &&
      isMerchantProcessorEnabled &&
      !isSponsor,
  );
 
  const isLoadingMerchants =
    merchantsQuery.isLoading || merchantsQuery?.isRefetching;
  const isLoadingReasons = reasonsQuery.isLoading || reasonsQuery?.isRefetching;
  const clearSearchMerchant = useCallback(() => {
    setSearchQuery(defaultSearch);
    merchantsQuery.remove();
  }, [merchantsQuery]);
 
  const merchants: ContextOptionsApi = {
    optionsList: isLoadingMerchants
      ? []
      : merchantsQuery.data?.pages.flatMap((p) => {
          return p.data;
        }) ?? [],
    fetchNextPage: merchantsQuery?.hasNextPage
      ? merchantsQuery.fetchNextPage
      : undefined,
    hasNextPage: merchantsQuery.hasNextPage,
    isLoading: isLoadingMerchants,
    searchQuery: merchantsSearchQuery,
    setSearchQuery: (val: string) => {
      setSearchQuery({ ...defaultSearch, merchantsSearchQuery: val });
    },
    clearSearch: clearSearchMerchant,
  };
 
  const reasons: ContextOptionsApi = {
    optionsList: isLoadingReasons
      ? []
      : reasonsQuery.data?.pages.flatMap((p) => p.data) ?? [],
    fetchNextPage: reasonsQuery.hasNextPage
      ? reasonsQuery.fetchNextPage
      : undefined,
    hasNextPage: reasonsQuery.hasNextPage,
    isLoading: isLoadingReasons,
    searchQuery: reasonsSearchQuery,
    setSearchQuery: (val: string) =>
      setSearchQuery({ ...defaultSearch, reasonsSearchQuery: val }),
    clearSearch: clearSearchMerchant,
  };
 
  const processorOptions = useMemo(() => {
    const baseOptions = [selectOptions[0]];
    if (!processorsData) return baseOptions;
    const options = processorsData.map((processorItem) => {
      return {
        label: processorMap[processorItem.name],
        value: processorItem.name,
      };
    });
    return [...baseOptions, ...options];
  }, [processorsData]);
 
  return {
    merchants,
    reasons,
    processorOptions,
  };
}