All files / src/hooks/exports useAsyncReconciliationExport.ts

43.9% Statements 36/82
34.54% Branches 19/55
57.14% Functions 8/14
43.75% Lines 35/80

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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265                                        29x           29x         559x   559x                                                               29x       559x 559x   559x                                     559x 52x                                                                                                       559x             29x                             559x 559x 559x   559x 52x 52x 52x           559x     559x 559x   559x 52x               52x     559x 52x     52x       559x   559x   559x 52x                   559x                                             559x         559x                                
import { useMutation, useQuery, useQueryClient } from "react-query";
import {
  initiateReconciliationExport,
  getBackgroundTaskStatus,
} from "@services/api/transactions";
import type {
  ReconciliationExportTask,
  BackgroundTaskStatus,
} from "@customTypes/backgroundTasks";
import { useGetCurrentMerchantId } from "@hooks/common";
import { showMessage } from "@common/Toast";
import { useEffect, useRef, useState } from "react";
import {
  activeExports,
  cleanupAllAsyncExports,
  handleExportDownload,
  startGlobalPolling,
} from "@hooks/exports/asyncExportCore";
import { getTaskErrorMessage } from "@hooks/exports/asyncExport.helpers";
 
const QUERY_KEY_PREFIX = "reconciliation-export-task";
 
/**
 * Hook to initiate an async reconciliation export.
 * The endpoint is always async — returns 202 immediately.
 */
const useInitiateReconciliationExport = (
  initiateFn: (
    urlFilters: string,
  ) => Promise<ReconciliationExportTask> = initiateReconciliationExport,
) => {
  const queryClient = useQueryClient();
 
  return useMutation(
    async ({ urlFilters }: { urlFilters: string }) => {
      return await initiateFn(urlFilters);
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries([QUERY_KEY_PREFIX]);
 
        showMessage(
          "Info",
          "Your export is being prepared. This may take a few minutes.",
          true,
          "Export Started",
          3000,
        );
      },
      onError: (error: Error) => {
        showMessage(
          "Error",
          error?.message || "Failed to initiate export. Please try again.",
          true,
          "Export Failed",
        );
      },
    },
  );
};
 
/**
 * Hook to poll the status of a reconciliation export task.
 * Uses the shared global polling that continues regardless of component lifecycle.
 */
const useReconciliationExportTaskStatus = (
  taskId: number | null,
  exportType = "default",
) => {
  const { merchantId } = useGetCurrentMerchantId();
  const queryClient = useQueryClient();
 
  const query = useQuery<ReconciliationExportTask>(
    [QUERY_KEY_PREFIX, merchantId, taskId],
    async (): Promise<ReconciliationExportTask> => {
      if (!merchantId || !taskId) {
        throw new Error("Merchant ID and Task ID are required");
      }
      return (await getBackgroundTaskStatus(
        merchantId,
        taskId,
      )) as ReconciliationExportTask;
    },
    {
      enabled: Boolean(merchantId && taskId),
      refetchOnWindowFocus: true,
      staleTime: 0,
      cacheTime: Infinity,
    },
  );
 
  useEffect(() => {
    Eif (!merchantId || !taskId || !query.data) return;
 
    const storageKey = `reconciliation-export-task-${merchantId}-${exportType}`;
    const taskData = query.data;
 
    if (taskData.status === "running") {
      startGlobalPolling(
        merchantId,
        taskId,
        queryClient,
        storageKey,
        QUERY_KEY_PREFIX,
      );
    }
 
    if (taskData.status === "completed") {
      const key = `${merchantId}-${taskId}`;
      const existingExport = activeExports.get(key);
      // After a page refresh activeExports is empty; sessionStorage still holds the
      // task ID until download completes, so use its presence as the fallback guard.
      const shouldDownload = existingExport
        ? !existingExport.downloadAttempted
        : Boolean(sessionStorage.getItem(storageKey));
 
      if (shouldDownload) {
        if (existingExport) existingExport.downloadAttempted = true;
        handleExportDownload(taskData, merchantId);
        activeExports.delete(key);
        sessionStorage.removeItem(storageKey);
      }
    }
 
    if (taskData.status === "failed") {
      const key = `${merchantId}-${taskId}`;
      const existingExport = activeExports.get(key);
      const shouldNotify = existingExport
        ? !existingExport.downloadAttempted
        : Boolean(sessionStorage.getItem(storageKey));
 
      if (shouldNotify) {
        showMessage(
          "Error",
          getTaskErrorMessage(taskData.error),
          true,
          "Export Failed",
        );
        activeExports.delete(key);
        sessionStorage.removeItem(storageKey);
      }
    }
  }, [merchantId, taskId, query.data, queryClient]);
 
  return query;
};
 
/**
 * Hook to manage the full async reconciliation export workflow.
 * Call startExport(urlFilters) to initiate; polling and download happen automatically.
 */
export const useAsyncReconciliationExport = (
  exportType = "default",
  initiateFn: (
    urlFilters: string,
  ) => Promise<ReconciliationExportTask> = initiateReconciliationExport,
): {
  startExport: (urlFilters: string) => Promise<ReconciliationExportTask>;
  cancelExport: () => void;
  isExporting: boolean;
  isInitiating: boolean;
  isPolling: boolean;
  taskData: ReconciliationExportTask | undefined;
  activeTaskId: number | null;
  progress: BackgroundTaskStatus | "processing" | undefined;
} => {
  const { merchantId } = useGetCurrentMerchantId();
  const queryClient = useQueryClient();
  const storageKey = `reconciliation-export-task-${merchantId}-${exportType}`;
 
  const getStoredTaskId = () => {
    try {
      const stored = sessionStorage.getItem(storageKey);
      return stored ? Number(stored) : null;
    } catch {
      return null;
    }
  };
 
  const [activeTaskId, setActiveTaskId] = useState<number | null>(
    getStoredTaskId,
  );
  const downloadAttemptedRef = useRef(false);
  const previousMerchantIdRef = useRef<number | undefined>(merchantId);
 
  useEffect(() => {
    Iif (
      previousMerchantIdRef.current !== undefined &&
      previousMerchantIdRef.current !== merchantId
    ) {
      cleanupAllAsyncExports();
      setActiveTaskId(null);
      downloadAttemptedRef.current = false;
    }
    previousMerchantIdRef.current = merchantId;
  }, [merchantId, activeTaskId]);
 
  useEffect(() => {
    Iif (activeTaskId) {
      sessionStorage.setItem(storageKey, String(activeTaskId));
    } else {
      sessionStorage.removeItem(storageKey);
    }
  }, [activeTaskId, storageKey]);
 
  const initiateMutation = useInitiateReconciliationExport(initiateFn);
  const { data: taskData, isLoading: isPolling } =
    useReconciliationExportTaskStatus(activeTaskId, exportType);
 
  useEffect(() => {
    Iif (
      taskData?.status === "completed" ||
      taskData?.status === "failed" ||
      taskData?.status === "cancelled"
    ) {
      setActiveTaskId(null);
      downloadAttemptedRef.current = false;
    }
  }, [taskData]);
 
  const startExport = async (urlFilters: string) => {
    downloadAttemptedRef.current = false;
    const result = await initiateMutation.mutateAsync({ urlFilters });
    // Persist and start polling synchronously before returning so both survive
    // a modal unmount that may occur immediately after this await resolves.
    try {
      sessionStorage.setItem(storageKey, String(result.id));
    } catch {
      // sessionStorage unavailable (private browsing restrictions etc.)
    }
    if (merchantId) {
      startGlobalPolling(
        merchantId,
        result.id,
        queryClient,
        storageKey,
        QUERY_KEY_PREFIX,
      );
    }
    setActiveTaskId(result.id);
    return result;
  };
 
  const cancelExport = () => {
    setActiveTaskId(null);
    downloadAttemptedRef.current = false;
  };
 
  return {
    startExport,
    cancelExport,
    isExporting:
      initiateMutation.isLoading ||
      (Boolean(activeTaskId) &&
        taskData?.status !== "completed" &&
        taskData?.status !== "failed" &&
        taskData?.status !== "cancelled"),
    isInitiating: initiateMutation.isLoading,
    isPolling,
    taskData,
    activeTaskId,
    progress: taskData?.status === "running" ? "processing" : taskData?.status,
  };
};