All files / src/hooks/payment-forms useListPaymentForms.tsx

52.08% Statements 25/48
55% Branches 22/40
43.75% Functions 7/16
54.34% Lines 25/46

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                                                46x   46x                                                                                                                                                     46x       61x 61x       61x           46x 738x   738x 738x     61x     22x             22x           46x 738x   738x     65x     36x           46x 738x 738x 738x   738x     738x       738x                                            
import { QKEY_LIST_PAYMENT_FORMS } from "@constants/queryKeys";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useCachedList } from "@hooks/common/useCachedList";
import { ROWS_PER_PAGE, usePagination } from "@hooks/common/usePagination";
import { useStateEffect } from "@hooks/customReactCore";
import { QFORM_QUERY_KEY } from "@pages/AcquirerPortal/Enterprises/Modal/constants";
import { useAppSelector } from "@redux/hooks";
import {
  selectQueryFilters,
  sorting as sortingReducer,
} from "@redux/slices/fundraisers";
import { selectQueryString } from "@redux/slices/search";
import useGetCheckoutForms from "@sections/PayBuilder/Checkout/hooks/useGetCheckout";
import { useCart } from "@sections/PayBuilder/provider/CartContext";
import { customInstance } from "@services/api";
import { getPaymentFormVariants } from "@services/api/products/invoice";
import { useQueryFactory } from "@services/api/products/queryFactory";
import { buildMerchantEndpoints } from "@services/api/utils.api";
import { encodedQueryFilterMap } from "@services/filtering";
import { detectMobile } from "@utils/index";
import { checkPortals } from "@utils/routing";
import { useMemo, useRef } from "react";
import { useQuery, useQueryClient } from "react-query";
 
export const useGetPaymentForms = useQueryFactory("payment-form");
 
const useListPaymentForms = () => {
  const queryFilters = useAppSelector(selectQueryFilters);
  const sorting = useAppSelector(sortingReducer);
  const searchQuery = useAppSelector((state) =>
    selectQueryString(state, QKEY_LIST_PAYMENT_FORMS),
  );
 
  const queryFilter = useMemo(
    () => encodedQueryFilterMap(queryFilters),
    [queryFilters],
  );
 
  const loadingRef = useRef<boolean>(false);
 
  const { page, setPage } = usePagination(0, queryFilter.products);
  const queryString = queryFilter.products ? `%3B${queryFilter.products}` : "";
 
  const { allData, invalidateCache } = useCachedList(
    QKEY_LIST_PAYMENT_FORMS,
    false,
    page,
  );
 
  const { data, isError, isLoading, error } = useGetPaymentForms(
    {
      queryString,
      page,
      sorting,
      searchQuery,
    },
    {
      refetchOnWindowFocus: false,
 
      onSuccess(_data) {
        setTimeout(() => {
          loadingRef.current = false;
        }, 700);
      },
    },
  );
 
  const handlePageChange = (
    event: React.ChangeEvent<unknown>,
    value: number,
  ) => {
    setPage(value);
  };
 
  useStateEffect(() => {
    if (detectMobile()) invalidateCache();
    setPage(1);
  }, [sorting, searchQuery, queryString]);
 
  const usedData = detectMobile() ? allData : data?.data ?? [];
 
  return {
    isError,
    page,
    rowsPerPage: ROWS_PER_PAGE,
    currentPageRows: usedData,
    handlePageChange,
    totalRows: data?.total ?? 0,
    setPage: () => setPage((current) => current + 1),
    setPageDispatcher: setPage,
    allRows: usedData,
    loadingRef,
    isLoading,
    error,
    state: {
      isEmpty: !queryString && !searchQuery && data?.total === 0,
      isError,
    },
  };
};
 
export const getPaymentFormsById = (
  id: string,
  options?: { shouldWrap: boolean },
) => {
  const { shouldWrap = false } = options || {};
  const url = shouldWrap
    ? buildMerchantEndpoints(`products/${id}?filter=typeName:"standard"`)
    : `products/${id}?filter=typeName:"standard"`;
 
  return customInstance({
    url, // Dynamically constructed URL
    method: "GET", // HTTP method
  });
};
 
export const useGetPaymentFormById = (id: string) => {
  const { isPayBuilder, isMerchantPortal } = checkPortals();
 
  const queryClient = useQueryClient();
  return useQuery(
    ["get-payment-form-by-id", id],
    async () => {
      const data = await getPaymentFormsById(id, {
        shouldWrap: isPayBuilder || isMerchantPortal,
      });
      return data;
    },
    {
      cacheTime: 0,
      refetchOnWindowFocus: false,
      enabled: Boolean(id),
      onSuccess: (data) => {
        queryClient.setQueryData(QFORM_QUERY_KEY, { product: data });
      },
    },
  );
};
 
export const useGetPaymentFormVariants = (id: string) => {
  const { isMerchantPortal, isPayBuilder } = checkPortals();
 
  return useQuery({
    queryKey: ["get-payment-form-variants", id],
    queryFn: async () => {
      const data = await getPaymentFormVariants(id, {
        shouldWrap: isPayBuilder || isMerchantPortal,
      });
      return data;
    },
    enabled: Boolean(id),
  });
};
 
export const useGetPaymentFormInfos = (id: string) => {
  const { merchantId } = useGetCurrentMerchantId();
  const paymentFormResponse = useGetPaymentFormById(id);
  const paymentFormVariantsResponse = useGetPaymentFormVariants(id);
  // disable request for non-signed in users since we will need to read from paymentFormResponse
  const paymentFormCheckoutResponse = useGetCheckoutForms(merchantId ? id : "");
 
  // If user is not logged in we should read data from paymentFormResponse, otherwise from paymentFormCheckoutResponse
  const checkoutData = paymentFormCheckoutResponse?.data
    ? paymentFormCheckoutResponse?.data
    : paymentFormResponse?.data?.uiCheckoutForm;
 
  return {
    data: {
      ...paymentFormResponse.data,
      variants: paymentFormVariantsResponse.data?.data
        ? ([...(paymentFormVariantsResponse.data?.data as any)] as any)
        : ([] as any),
      checkout: checkoutData ? checkoutData : {},
    },
    isFetched:
      paymentFormResponse?.isFetched &&
      paymentFormVariantsResponse?.isFetched &&
      (merchantId ? paymentFormCheckoutResponse?.isFetched : true),
    isLoading:
      paymentFormResponse?.isLoading ||
      paymentFormResponse?.isLoading ||
      paymentFormCheckoutResponse?.isLoading ||
      paymentFormResponse.isRefetching ||
      paymentFormCheckoutResponse.isRefetching,
  };
};
 
export default useListPaymentForms;