All files / src/components/Analytics/SidePanels/CampaignSidePanel/hooks useGetRecurringCustomers.tsx

0% Statements 0/11
0% Branches 0/6
0% Functions 0/4
0% Lines 0/11

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                                                                                                         
import { QKEY_ANALYTICS_RECURRING_CUSTOMERS } from "@constants/queryKeys";
import { GENERAL_STALE_TIME_15 } from "@features/Merchants/MerchantSidePanel/constants";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useAppSelector } from "@redux/hooks";
import { selectFilterQuery } from "@redux/slices/analytics";
import { getCustomersAnalytics } from "@services/api/analytics/customers";
import { getTransactionChart } from "@services/api/analytics/transactions";
import { getSettledPromise } from "@utils/index";
import { useQuery } from "react-query";
 
export const useGetRecurringCustomers = (isModalVisible: boolean) => {
  const { merchantId } = useGetCurrentMerchantId();
 
  const customersFilterQuery = useAppSelector((state) =>
    selectFilterQuery(state, QKEY_ANALYTICS_RECURRING_CUSTOMERS),
  );
 
  const { data, isLoading } = useQuery(
    ["get-recurring-customers-chart", customersFilterQuery, merchantId],
    async () => {
      const customersFilter = customersFilterQuery.dateFilter;
      const [customersChart, customers] = await Promise.allSettled(
        [
          {
            filter: customersFilter,
            chartType: "recurring_customers",
          },
          {
            filter: customersFilter,
          },
        ].map((c, idx) => {
          return idx === 0 ? getTransactionChart(c) : getCustomersAnalytics(c);
        }),
      );
      const recurringsChart = getSettledPromise(customersChart)?.data || [];
 
      return {
        chart: customersFilter
          ? recurringsChart?.slice(0, recurringsChart.length - 1)
          : recurringsChart,
        customers: getSettledPromise(customers),
      };
    },
    {
      refetchOnWindowFocus: false,
      enabled: !!isModalVisible,
      staleTime: GENERAL_STALE_TIME_15,
    },
  );
 
  return { data, isLoading };
};