All files / src/hooks/merchant-api/cart useGetProductFeePayment.tsx

81.25% Statements 13/16
60% Branches 6/10
66.66% Functions 2/3
81.25% Lines 13/16

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            17x 1182x 1182x 1182x 1182x                       1182x       1182x                                               1182x 1182x   1182x   1182x             646x 646x    
import { FEE_PAYER_OPTIONS } from "@sections/PayBuilder/Checkout/consts";
import { customInstance } from "@services/api";
import { isFinite, toNumber } from "lodash";
import { useQuery } from "react-query";
import { useLocation, useParams } from "react-router-dom";
 
export const useGetProductFeePayment = () => {
  const { pathname } = useLocation();
  const { id: defaultProductID } = useParams();
  const id = pathname?.substring(pathname.lastIndexOf("/") + 1);
  const productId = defaultProductID || id || "0";
 
  /**
   * CRITICAL FIX: Use the same query key as other product hooks to share cache!
   * This was the 3rd duplicate call we missed!
   *
   * We changed from ["find-product-payment-by-id", productId] to ["public-form-id", productId]
   * to match useGetPublicForm and useCheckFormType.
   */
 
  // Validate ID - must be a valid number, not "true", "0", undefined, etc.
  const isValidId =
    Boolean(Number(productId)) &&
    checkIfNumber(productId) &&
    Number(productId) > 0;
 
  const { data } = useQuery(
    ["public-form-id", productId], // Changed to match other hooks!
    async () => {
      // Safety check: should never execute with invalid ID due to enabled check
      if (!isValidId) {
        throw new Error(`Invalid product ID: ${productId}`);
      }
      return customInstance({
        url: `products/${productId}`,
        method: "GET",
      });
    },
    {
      refetchOnWindowFocus: false,
      // Prevent duplicate API calls - reuse cached data
      staleTime: 1000 * 60 * 2,
      cacheTime: 1000 * 60 * 5,
      // Only fetch if ID is valid (not "0", "true", undefined, etc.)
      enabled: isValidId,
      // Don't retry on invalid IDs
      retry: false,
    },
  );
 
  const isRequiredMerchantPayer = data?.feePayer === FEE_PAYER_OPTIONS.MERCHANT;
  const isRequiredCustomerPayer = data?.feePayer === FEE_PAYER_OPTIONS.CUSTOMER;
  const isCustomerChoicePayer =
    data?.feePayer === FEE_PAYER_OPTIONS.CUSTOMER_CHOICE;
 
  return {
    isCustomerChoicePayer,
    passFees: isRequiredCustomerPayer ? false : isRequiredMerchantPayer,
  };
};
 
function checkIfNumber(value: string | number) {
  const num = toNumber(value); // Convert the value to a number
  return isFinite(num); // Check if it's a finite number
}