All files / src/shared/GiveExportModal/hooks useSubmitExport.tsx

85.81% Statements 127/148
64.13% Branches 59/92
88% Functions 22/25
86.2% Lines 125/145

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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500                                                                                              25x           25x                     25x         86x 86x 86x       86x       86x       86x 86x 86x 86x 86x 98x   98x 86x 86x 86x 86x 86x   86x         86x             86x   86x   86x 12x 12x 1x           86x 86x         86x 86x   37x       49x       86x 2x   1x         2x                                     86x               2x         2x         2x       2x         2x   2x             2x               2x 2x                     2x                 1x 1x                       1x   1x       86x         2x 12x     2x 6x 6x   6x       6x       2x   12x       2x 4x 4x 4x 2x     4x     2x 2x             2x     86x 3x   1x   1x                 1x   2x   2x         86x           5x     5x                               5x 2x     5x   5x                   5x   5x 6x 6x               6x                       5x 5x     5x 2x   3x         5x   5x             5x 2x       5x 2x         2x     2x                     5x                   5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   5x       4x 4x 4x   4x 4x 4x                                                     86x              
import { isEmpty } from "lodash";
import { exportType, TableType } from "../const";
import {
  ExportField,
  FormValues,
  InputField,
  SelectField,
} from "../giveExportTypes";
import { buildExportDateRange, useBuildFilterString } from "./fn";
import { useAppSelector } from "@redux/hooks";
import { selectQueryString } from "@redux/slices/search";
import { DISPUTES_QUERY_KEY } from "@components/Disputes/DisputesList/hooks/useDisputesTable";
import {
  selectDisputeTab,
  selectQueryFilters,
} from "@redux/slices/transactions";
import { useFormattedFilters } from "@shared/GiveFilter/hooks/useFormattedFilters";
import { useDisputesQueryString } from "@components/Disputes/DisputesList/hooks/useDisputesQueryString";
import { prepareBasePath } from "@components/VirtualList/api";
import { dismissToast, showMessage, updateToast } from "@common/Toast";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { useGetCSV } from "./useGetCSV";
import { sortingKey } from "@redux/slices/fundraisers";
import {
  QKEY_LIST_ACQUIRER_MERCHANTS,
  QKEY_RISK_MONITOR_TRANSACTIONS,
} from "@constants/queryKeys";
import { checkPortals } from "@utils/routing";
import {
  buildMerchantFilterWithPrefixAndParent,
  buildMerchantTablePayload,
  buildMerchantTableUrlFilters,
  buildReconciliationUrlFilters,
  getMerchantBaseURL,
  getMerchantExportFilterPrefix,
  getMerchantExportSort,
  merchantIncludesRestrictedColumns,
  normalizeSortForMerchantExport,
} from "./merchantTable/merchantTableSubmit";
import { isReconciliationLikeReport } from "./merchantTable/merchantTableConfig";
import { useEffect, useRef } from "react";
import { useParams } from "react-router-dom";
import { selectMerchantTab } from "@redux/slices/enterprise/merchants";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { useAsyncReconciliationExport } from "@hooks/exports/useAsyncReconciliationExport";
import { initiateBankReconciliationExport } from "@services/api/transactions";
 
const tableQKey = {
  [exportType.ACQUIRE_DISPUTE]: DISPUTES_QUERY_KEY,
  [exportType.RISK_TRANSACTIONS]: QKEY_RISK_MONITOR_TRANSACTIONS,
  [exportType.MERCHANT_TABLE]: QKEY_LIST_ACQUIRER_MERCHANTS,
};
 
const filterExportTypes: TableType[] = [exportType.ACQUIRE_DISPUTE];
 
/**
 * Submits the export request and downloads the resulting CSV.
 *
 * Architecture:
 * - The request URL varies per exportType (and for merchant table it depends on selected columns).
 * - We keep the branching in small per-exportType resolvers (`exportURL`, `buildExportRequest`).
 * - Merchant Table specifics (endpoint selection, url filters, payload shape) are extracted to
 *   `hooks/merchantTable/merchantTableSubmit.ts`.
 */
export const useSubmitExport = (
  fieldTypes: TableType,
  merchantID?: number,
  onClose?: () => void,
) => {
  const { isMobileView } = useCustomThemeV2();
  const { isAcquirerPortal } = checkPortals();
  const { mutateAsync, isLoading } = useGetCSV();
  const {
    startExport: startReconciliationExport,
    isExporting: isReconciliationExporting,
  } = useAsyncReconciliationExport();
  const {
    startExport: startBankReconciliationExport,
    isExporting: isBankReconciliationExporting,
  } = useAsyncReconciliationExport(
    "bank_reconciliation",
    initiateBankReconciliationExport,
  );
  const exportProgressInterval = useRef<NodeJS.Timeout | null>(null);
  const queryKey = tableQKey[fieldTypes];
  const { buildFilterString } = useBuildFilterString();
  const { queryString: disputeQueryString } = useDisputesQueryString();
  const searchQuery = useAppSelector((state) =>
    selectQueryString(state, queryKey),
  );
  const sort = useAppSelector((state) => sortingKey(state, queryKey));
  const queryFilters = useAppSelector(selectQueryFilters);
  const selectedMerchantTab = useAppSelector(selectMerchantTab);
  const { id: enterpriseId } = useParams();
  const { isMerchantStatusRefactorEnabled } = useGetFeatureFlagValues();
  const { isAcquirerEnterprises } = checkPortals();
  // for rebranded filter
  const { formattedFilterString, watchlistFilter } = useFormattedFilters({
    queryKey: queryKey,
  });
 
  //some table may still have old filter logic and new export
  const legacyFilterString = {
    [exportType.ACQUIRE_DISPUTE]: disputeQueryString,
    [exportType.RISK_TRANSACTIONS]: "",
    [exportType.MERCHANT_TABLE]: "",
  };
 
  const usedQueryString =
    formattedFilterString ?? legacyFilterString[fieldTypes];
 
  const exportToastId = "Download";
 
  useEffect(() => {
    return () => {
      if (exportProgressInterval.current) {
        clearInterval(exportProgressInterval.current);
      }
    };
  }, []);
 
  //--dispute additional logic
  const tab = useAppSelector(selectDisputeTab);
  const filterWithoutPrevented = queryFilters.disputeStatus.replace(
    /,status:"prevented"/,
    "",
  );
 
  const usedFilters = (() => {
    switch (fieldTypes) {
      case exportType.ACQUIRE_DISPUTE:
        return tab === "-closed" && usedQueryString.includes("outcome")
          ? filterWithoutPrevented
          : queryFilters.disputeStatus;
      default:
        return "";
    }
  })();
 
  const exportURL: Record<TableType, (args?: any) => string> = {
    [exportType.ACQUIRE_DISPUTE]: () => "disputes.csv",
    [exportType.RISK_TRANSACTIONS]: () =>
      `merchants/${merchantID}/transactions-minimal.csv`,
    [exportType.MERCHANT_TABLE]: (args?: {
      columnsIncluded?: string;
      includesRestrictedColumns: boolean;
    }) =>
      getMerchantBaseURL({
        ...(args ?? {
          columnsIncluded: undefined,
          includesRestrictedColumns: false,
        }),
        isAcquirerPortal,
      }),
  };
 
  const buildExportRequest: Record<
    TableType,
    (args: {
      data: FormValues;
      customQueryString: string;
      urlFilters: string;
      payload?: Record<string, any>;
      sortOverride?: string;
      watchlist?: boolean;
    }) => { url: string; urlFilters: string; payload?: Record<string, any> }
  > = {
    [exportType.MERCHANT_TABLE]: ({
      data,
      customQueryString,
      payload,
      sortOverride,
      watchlist,
    }) => {
      const columnsIncluded = (data as any).columnsIncluded as
        | string
        | undefined;
 
      // Decide which merchant export endpoint to hit based on "restricted" columns.
      const includesRestrictedColumns = merchantIncludesRestrictedColumns({
        columnsIncluded,
        selectedColumns: data.columns || [],
      });
 
      const url = exportURL[exportType.MERCHANT_TABLE]({
        columnsIncluded,
        includesRestrictedColumns,
      });
      const merchantSort = getMerchantExportSort({
        sort: sort || "",
        selectedTab: selectedMerchantTab,
      });
      const effectiveSort =
        sortOverride ??
        normalizeSortForMerchantExport(merchantSort, selectedMerchantTab);
      const urlFilters = buildMerchantTableUrlFilters({
        customQueryString,
        sort: effectiveSort || "-accID",
        searchQuery,
        watchlist,
      });
 
      return { url, urlFilters, payload };
    },
 
    [exportType.ACQUIRE_DISPUTE]: ({
      customQueryString,
      urlFilters,
      payload,
    }) => {
      const url = exportURL[exportType.ACQUIRE_DISPUTE]();
      const allFilters = prepareBasePath(
        {
          queryString: customQueryString,
          searchQuery,
          filter: urlFilters
            ? usedFilters + encodeURIComponent(`${urlFilters}`)
            : usedFilters,
          sorting: sort || "-createdAt",
        },
        false,
      );
      return { url, urlFilters: allFilters, payload };
    },
 
    [exportType.RISK_TRANSACTIONS]: ({
      data,
      customQueryString,
      urlFilters,
      payload,
    }) => {
      const url = exportURL[exportType.RISK_TRANSACTIONS]();
      const allFilters = prepareBasePath(
        {
          queryString: customQueryString,
          searchQuery,
          filter: urlFilters
            ? usedFilters + encodeURIComponent(`${urlFilters}`)
            : usedFilters,
          sorting: sort || "-createdAt",
        },
        false,
      );
 
      const finalUrlFilters = data.type?.value === "all" ? "" : allFilters;
 
      return { url, urlFilters: finalUrlFilters, payload };
    },
  };
 
  const handleFilterExportPreparation = (
    data: FormValues,
    exportFieldsData: Record<TableType, ExportField[]>,
  ) => {
    // dateRange
    const selectArrays = exportFieldsData[exportType.ACQUIRE_DISPUTE].filter(
      (f) => f.fieldType === "select" && f.customListValuesName,
    ) as SelectField[];
 
    const allSelectInputs = selectArrays.reduce((acc, field) => {
      const key = field.customListValuesName; // e.g. "merchantAccIDs"
      const valueFromObject = key ? data[key] : undefined;
 
      Iif (!isEmpty(valueFromObject)) {
        acc[key] = valueFromObject.map((item: any) => item?.value);
      }
 
      return acc;
    }, {} as Record<string, any>);
 
    // inputs
    const allInputsArray = exportFieldsData[exportType.ACQUIRE_DISPUTE].filter(
      (f) =>
        (f.fieldType === "input" && f.fieldName) ||
        (f.fieldType === "select" && !f.customListValuesName),
    ) as InputField[];
 
    const allInputs = allInputsArray.reduce((acc, field) => {
      const key = field.fieldName;
      const valueFromObject = key ? data[key] : undefined;
      if (!isEmpty(valueFromObject) && valueFromObject !== "all") {
        acc[key] = valueFromObject;
      }
 
      return acc;
    }, {} as Record<string, any>);
 
    const dateRange = buildExportDateRange(data.dateRange);
    const payload = {
      ...allSelectInputs,
      ...allInputs,
      dateRange,
      timeZone: data?.dateRange?.timeZone,
    };
 
    return buildFilterString(payload as any);
  };
 
  const handlePayloadExportPreparation = (data: FormValues) => {
    if (fieldTypes === exportType.RISK_TRANSACTIONS) {
      // "All columns" should map to includeAllColumns regardless of "All/Filtered data"
      const includeAllColumns = data.reportType === "all";
 
      const builtPayload = {
        includeAllColumns,
        fileNamePrefix: data.fileName,
        reportType:
          data.reportType === "all" ? "merchant_report" : data.reportType,
        ...(!includeAllColumns && {
          columns: data.columns,
        }),
      };
      return builtPayload;
    }
    Eif (fieldTypes === exportType.MERCHANT_TABLE) {
      // Merchant Table payload is a legacy-compatible switch driven by `columnsIncluded`.
      return buildMerchantTablePayload(data);
    }
    return data;
  };
 
  const onSubmit = async (
    data: FormValues,
    exportFieldsData: Record<TableType, ExportField[]>,
  ) => {
    // Reconciliation: initiate BEFORE closing the modal so the hook stays mounted
    // until the task ID is persisted and global polling is registered.
    const columnsIncludedValue = (data as any).columnsIncluded as
      | string
      | undefined;
    Iif (
      fieldTypes === exportType.MERCHANT_TABLE &&
      isReconciliationLikeReport(columnsIncludedValue)
    ) {
      const allTime = ((data as any).allTime as boolean) ?? true;
      const urlFilters = allTime ? "" : buildReconciliationUrlFilters(data);
      const startExport =
        columnsIncludedValue === "bank_reconciliation_monthly"
          ? startBankReconciliationExport
          : startReconciliationExport;
      await startExport(urlFilters);
      onClose?.();
      return;
    }
 
    // Close the modal immediately for all other merchant table exports.
    if (fieldTypes === exportType.MERCHANT_TABLE) {
      onClose?.();
    }
 
    let currentProgress = 0;
 
    showMessage(
      "Download",
      "",
      !isMobileView,
      "Exporting...",
      false,
      { style: { width: "190px" } },
      { progress: currentProgress },
    );
 
    Iif (exportProgressInterval.current)
      clearInterval(exportProgressInterval.current);
    exportProgressInterval.current = setInterval(() => {
      currentProgress += Math.floor(Math.random() * 10) + 5;
      Iif (currentProgress >= 90) {
        currentProgress = 90;
        if (exportProgressInterval.current) {
          clearInterval(exportProgressInterval.current);
          exportProgressInterval.current = null;
        }
      }
 
      updateToast(
        exportToastId,
        "Download",
        "",
        !isMobileView,
        "Exporting...",
        false,
        { style: { width: "190px" } },
        { progress: currentProgress },
      );
    }, 150);
 
    let urlFilters = "";
    let payload: Record<string, any> | undefined = undefined;
 
    //these exports are useing filtering on GET endpoint instead of POST
    if (filterExportTypes.includes(fieldTypes)) {
      urlFilters = handleFilterExportPreparation(data, exportFieldsData);
    } else {
      payload = handlePayloadExportPreparation(data);
    }
 
    // in export panel, created at and merchant filter takes precedence over the ones selected in filter panel
    // but only if both exist
    let customQueryString = usedQueryString;
 
    Iif (urlFilters.includes("merchant.accID:")) {
      customQueryString = customQueryString.replace(
        /\(?merchant\.name:[^;)]*\)?;?/g,
        "",
      );
    }
 
    if (urlFilters.includes("createdAt:")) {
      customQueryString = customQueryString.replace(/;?createdAt:[^;]*;?/g, "");
    }
 
    // Rebranded merchant export: apply section filter (e.g. underwriting tab) and parentAcc so CSV matches table.
    if (fieldTypes === exportType.MERCHANT_TABLE) {
      const sectionPrefix = getMerchantExportFilterPrefix({
        selectedTab: selectedMerchantTab,
        isMerchantStatusRefactorEnabled,
      });
      const parentAccFilter =
        isAcquirerEnterprises && enterpriseId
          ? "parentAccID:" + enterpriseId
          : "";
      customQueryString = buildMerchantFilterWithPrefixAndParent({
        baseFilter: customQueryString,
        sectionPrefix,
        parentAccFilter,
      });
    }
 
    const {
      url,
      urlFilters: finalUrlFilters,
      payload: finalPayload,
    } = buildExportRequest[fieldTypes]({
      data,
      customQueryString,
      urlFilters,
      payload,
      ...(fieldTypes === exportType.MERCHANT_TABLE && {
        watchlist: watchlistFilter,
      }),
    });
 
    const fn = (response: any) => {
      const blob = new Blob([response], { type: "text/csv" });
      const blobURL = window.URL.createObjectURL(blob);
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.download = data?.fileName;
      tempLink.setAttribute("target", "_blank");
      document.body.appendChild(tempLink);
      tempLink.click();
      Eif (document.body.contains(tempLink)) document.body.removeChild(tempLink);
      window.URL.revokeObjectURL(blobURL);
    };
    await mutateAsync(
      { url, urlFilters: finalUrlFilters, payload: finalPayload },
      {
        onSuccess: (response: any) => {
          Eif (exportProgressInterval.current) {
            clearInterval(exportProgressInterval.current);
            exportProgressInterval.current = null;
          }
          fn(response);
          dismissToast(exportToastId);
          setTimeout(() => {
            showMessage(
              "Success",
              "",
              !isMobileView,
              "Export Successful",
              2000,
              {
                style: { width: "190px" },
              },
            );
          }, 300);
        },
        onError: () => {
          if (exportProgressInterval.current) {
            clearInterval(exportProgressInterval.current);
            exportProgressInterval.current = null;
          }
          dismissToast(exportToastId);
          showMessage("Error", "", !isMobileView, "Export Failed", 5000, {
            style: { width: "190px" },
          });
        },
      },
    );
  };
 
  return {
    onSubmit,
    isLoading,
    isReconciliationExporting,
    isBankReconciliationExporting,
  };
};