All files / src/components/Disputes/DisputesList/hooks useDisputesTable.tsx

71.87% Statements 46/64
45.65% Branches 21/46
56.25% Functions 9/16
73.01% Lines 46/63

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                                            263x   263x 12x 12x   12x 3x 3x                     12x 12x 12x 12x 12x 12x 18x   12x   12x       12x 18x   12x 12x   12x 12x   12x   12x       12x         12x       12x   12x 18x               12x                       6x                                         12x                                                 12x       12x     12x       12x               12x                   12x                       12x       12x 3x                           12x 3x       12x           12x     21x                              
import { useEffect, useRef, useState } from "react";
import { useInfiniteQuery, useQuery, useQueryClient } from "react-query";
import { queryBuilder } from "@components/VirtualList/api";
import { items } from "@components/VirtualList/components/VirtualizedList";
import { selectQueryString } from "@redux/slices/search";
import { useAppSelector } from "@redux/hooks";
import { GIVE_DISPUTE_PANEL } from "modals/modal_names";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { useIterator } from "@common/Table/hooks";
import { selectSelectedMerchant } from "@redux/slices/merchantFilters";
import { useDisputesQueryString } from "./useDisputesQueryString";
import { useSearchParams } from "react-router-dom";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import {
  selectDisputeTab,
  selectQueryFilters,
} from "@redux/slices/transactions";
import { useFormattedFilters } from "@shared/GiveFilter/hooks/useFormattedFilters";
import { sortingKey } from "@redux/slices/fundraisers";
import { useRowsPerPage } from "componentsV2/Table/hooks/useRowsPerPage";
import { STORED_MERCHANTS_ROWS_PER_PAGE } from "@constants/stringConstants";
 
export const DISPUTES_QUERY_KEY = "get-disputes-list";
 
export const useDisputesTable = () => {
  const [params] = useSearchParams();
  const { isMediumSmallView } = useCustomTheme();
 
  useEffect(() => {
    const disputeID = params.get("id");
    Iif (disputeID) {
      NiceModal.show(GIVE_DISPUTE_PANEL, {
        id: disputeID,
        isFirst: true,
        isLast: true,
        setSelectedRow: onChangeSelectedRowItem,
        isLoading: isFetchingNextPage,
      });
    }
  }, []);
  const scrollToTop =
    useRef<(index?: number, align?: "center" | "start" | "end") => void>(null);
  const page = useRef(1);
  const sort = useRef("-createdAt");
  const queryClient = useQueryClient();
  const [paginatedPage, setPaginatedPage] = useState(1);
  const searchQuery = useAppSelector((state) =>
    selectQueryString(state, DISPUTES_QUERY_KEY),
  );
  const { queryString } = useDisputesQueryString();
  // for rebranded filter
  const { formattedFilterString } = useFormattedFilters({
    queryKey: DISPUTES_QUERY_KEY,
  });
 
  const selectedMerchant = useAppSelector((state) =>
    selectSelectedMerchant(state, DISPUTES_QUERY_KEY),
  );
  const tab = useAppSelector(selectDisputeTab);
  const { rowsPerPage } = useRowsPerPage(STORED_MERCHANTS_ROWS_PER_PAGE);
 
  const queryFilters = useAppSelector(selectQueryFilters);
  const selectedMerchantID = selectedMerchant?.accID;
 
  const isInfiniteDataEnabled = isMediumSmallView;
 
  const isPaginatedDataEnabled = !isMediumSmallView;
  // for now in closed tab the default filter is prevented (also considered closed) and closed status,
  // so when filtering with outcome (won or lost) we need to make sure to update that default filter to remove prevented
  // in order to display correct data as a FE wise solution for now
  const filterWithoutPrevented = queryFilters.disputeStatus.replace(
    /,status:"prevented"/,
    "",
  );
  const usedFilters =
    tab === "-closed" && queryString.includes("outcome")
      ? filterWithoutPrevented
      : queryFilters.disputeStatus;
 
  const usedQueryString = formattedFilterString || queryString;
 
  const sorting = useAppSelector((state) =>
    sortingKey(state, DISPUTES_QUERY_KEY),
  );
 
  const {
    data: paginatedData,
    isLoading: paginatedDataLoading,
    isFetching,
    isRefetching,
  } = useQuery(
    [
      DISPUTES_QUERY_KEY,
      paginatedPage,
      searchQuery,
      usedQueryString,
      selectedMerchantID,
      usedFilters,
      sorting,
      rowsPerPage,
    ],
    () =>
      queryBuilder({
        queryString: usedQueryString,
        searchQuery,
        rowsPerPage: rowsPerPage,
        path: "disputes",
        sorting: sorting || sort.current,
        merchantId: selectedMerchantID,
        page: paginatedPage,
        filter: usedFilters,
      })({ pageParam: paginatedPage }),
    {
      enabled: isPaginatedDataEnabled,
    },
  );
 
  const {
    data: infiniteData,
    isFetchingNextPage,
    fetchNextPage,
    hasNextPage,
    isLoading,
  } = useInfiniteQuery(
    [
      DISPUTES_QUERY_KEY,
      searchQuery,
      usedQueryString,
      selectedMerchantID,
      usedFilters,
    ],
    queryBuilder({
      queryString: usedQueryString,
      searchQuery,
      rowsPerPage: rowsPerPage,
      path: "disputes",
      sorting: sort.current,
      merchantId: selectedMerchantID,
      filter: usedFilters,
    }),
    {
      enabled: isInfiniteDataEnabled,
      getNextPageParam: (lastPage: any) => {
        return lastPage.nextCursor;
      },
    },
  );
 
  const uiData = isPaginatedDataEnabled
    ? paginatedData?.data || []
    : infiniteData?.pages?.flatMap((p: any) => p.data) || [];
 
  const modal = useModal(GIVE_DISPUTE_PANEL);
 
  const { selectedRowIdx, onChangeSelectedRowItem, setSelectedRowIdx } =
    useIterator({
      dataLen: uiData.length,
    });
 
  const handleOnClick = async () => {
    if (isFetchingNextPage || isLoading) return;
 
    items.clear();
 
    queryClient.removeQueries([DISPUTES_QUERY_KEY, paginatedPage]);
  };
 
  const handleOnSort = (newSort: any) => {
    if (scrollToTop.current) {
      scrollToTop.current();
    }
    sort.current = newSort;
    page.current = 1;
 
    handleOnClick();
  };
 
  const onEndReached = async () => {
    if (!isFetchingNextPage && hasNextPage && isInfiniteDataEnabled) {
      fetchNextPage({
        pageParam: ++page.current,
      }).then(() => {
        if (scrollToTop.current) {
          scrollToTop.current((infiniteData?.pages?.length ?? 1) * rowsPerPage);
        }
      });
    }
  };
 
  const handleOpenSidePanel = ({ index }: { index: number }) => {
    setSelectedRowIdx(index);
  };
 
  useEffect(() => {
    Iif (
      (modal.visible || (!modal.visible && selectedRowIdx >= 0)) &&
      uiData[selectedRowIdx]?.id
    ) {
      NiceModal.show(GIVE_DISPUTE_PANEL, {
        id: uiData[selectedRowIdx]?.id,
        isFirst: selectedRowIdx === 0,
        isLast: uiData[selectedRowIdx + 1] === undefined && !hasNextPage,
        setSelectedRow: onChangeSelectedRowItem,
        isLoading: isFetchingNextPage,
      });
    }
  }, [selectedRowIdx, modal.visible, isFetchingNextPage]);
 
  useEffect(() => {
    setPaginatedPage(1);
  }, [searchQuery, usedQueryString, tab]);
 
  const loading =
    isFetchingNextPage ||
    isLoading ||
    paginatedDataLoading ||
    isRefetching ||
    isFetching;
 
  return {
    handleOnSort,
    // filter out nullish items
    uiData: uiData?.filter((item: any) => item),
    scrollToTop,
    loading,
    onEndReached,
    isFetchingNextPage,
    clickRow: handleOpenSidePanel,
    selectedIndex: selectedRowIdx,
    totalRows: paginatedData?.total || 0,
    setPaginatedPage,
    paginatedPage,
    tab,
    nextCursor: page.current + 1,
    rowsPerPage,
  };
};