All files / src/shared/GiveExportModal/hooks useGenerateFieldData.ts

88.04% Statements 81/92
74.35% Branches 58/78
78.26% Functions 18/23
87.77% Lines 79/90

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 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686                                                                                                                                                          86x 86x 86x 86x         86x     86x 86x   86x           86x                                       86x                         86x   86x                   307x                   307x                   307x     86x             86x               86x       86x 86x   37x   14x     35x               86x 86x   86x 691x 642x 86x           642x 72x           4x     46x         4x     46x                       4x     46x         642x 111x 111x                                                   84x         86x       86x 86x           86x 35x 35x                           51x           86x                                                                                                                                                                                                                                                                                                                                                                                                                       86x   86x                     86x 86x 86x   86x                             86x     691x                                           691x                         691x     691x   391x           23x     368x   86x 86x   86x   86x 5x     86x                       25x     25x 25x 25x 25x     25x   25x                                         25x                 25x 172x                                
import { useForm, UseFormReturn } from "react-hook-form";
import {
  businessOwner,
  businessProfile,
  cardTypes,
  customerOptions,
  exportColumnOptions,
  exportType,
  getMerchantInfoOptions,
  ofacInfo,
  primaryAccountHolder,
  riskMonitor,
  riskOptions,
  salesInfo,
  selectOptions,
  TableType,
  transactionInfoOptions,
} from "../const";
import {
  ExportField,
  FormValues,
  SelectOption,
  TTab,
} from "../giveExportTypes";
import { subDays, subMonths } from "date-fns";
import useManageExportApi from "./useManageExportApi";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { flattenErrors, dateFormat } from "../utils";
import { useGetCurrentMerchantId } from "@hooks/common";
 
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { format, formatInTimeZone } from "date-fns-tz";
import { getDefaultValues } from "./fn";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { VALIDATION_MESSAGES } from "@validation/messages";
import { useState } from "react";
import React from "react";
import { CircularProgress } from "@mui/material";
import { useSubmitExport } from "./useSubmitExport";
import { checkPortals } from "@utils/routing";
import {
  getMerchantColumnsIncludedOptions,
  getMerchantTableAllColumnValues,
  getMerchantTableColumnsContext,
  isReconciliationLikeReport,
  merchantDateRangeOptions,
  shouldHideMerchantTableDateRange,
} from "./merchantTable/merchantTableConfig";
import useExportSideEffects from "./useExportSideEffects";
import { useAccessControl } from "@features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
 
export default function useGenerateFieldData({
  fieldTypes = exportType.ACQUIRE_DISPUTE,
  merchantID,
  counts,
  tab,
  onClose,
  hasFilters,
}: {
  fieldTypes?: TableType;
  merchantID?: number;
  counts?: { total: number; filtered: number };
  tab?: TTab;
  onClose?: () => void;
  hasFilters?: boolean;
}) {
  /**
   * This hook builds the form model + dynamic field list for the rebranded export panel.
   *
   * Design notes:
   * - We keep most "per exportType" behavior isolated (e.g. Merchant Table in `hooks/merchantTable/*`).
   * - Some fields are dynamically hidden based on form state (e.g. Merchant Table date range).
   *   Because of that, we build the validation schema from ALL fields for that export type,
   *   and only filter what is rendered in `fieldRawData`.
   */
  const { isMerchantProcessorEnabled } = useGetFeatureFlagValues();
  const [isOpenAdvancedSettings, setIsOpenAdvancedSettings] = useState(false);
  const { isEnterprisePortal, isAcquirerPortal } = checkPortals();
  const isExportAllowed: boolean = useAccessControl({
    resource: RESOURCE_BASE.MERCHANT,
    operation: OPERATIONS.EXPORT,
  });
 
  const { merchants, reasons, processorOptions } = useManageExportApi({
    fieldTypes,
  });
  const { name, isSponsor } = useGetCurrentMerchantId();
  const isPendingTab = tab === "pending";
  const merchantProcessorEnabled =
    isMerchantProcessorEnabled && !isEnterprisePortal;
 
  const {
    visibleColumns: merchantVisibleColumns,
    reportColumns: merchantReportColumns,
  } =
    fieldTypes === exportType.MERCHANT_TABLE
      ? getMerchantTableColumnsContext({
          tab,
          isEnterprisePortal,
          isPendingTab,
          isMerchantProcessorEnabled: merchantProcessorEnabled,
        })
      : {
          visibleColumns: [],
          reportColumns: {
            monthly: [],
            reserveMonthly: [],
            reconciliationMonthly: [],
            newMerchantApproval: [],
            ofacBusiness: [],
            ofacPersons: [],
          },
        };
 
  const merchantAllColumnValues =
    fieldTypes === exportType.MERCHANT_TABLE
      ? getMerchantTableAllColumnValues({
          isEnterprisePortal,
          isPendingTab,
          isMerchantProcessorEnabled: merchantProcessorEnabled,
        })
      : [];
 
  const {
    onSubmit,
    isLoading: isLoadingSubmission,
    isReconciliationExporting,
    isBankReconciliationExporting,
  } = useSubmitExport(fieldTypes, merchantID, onClose);
 
  const merchantColumnsIncludedOptions = (
    fieldTypes === exportType.MERCHANT_TABLE
      ? getMerchantColumnsIncludedOptions({
          tab,
          isPendingTab,
          isExportAllowed,
          isAcquirerPortal,
        })
      : []
  ).map((option) => {
    Iif (
      option.value === "reconciliation_monthly" &&
      isReconciliationExporting
    ) {
      return {
        ...option,
        disabled: true,
        IconRight: SpinnerIcon,
      };
    }
    Iif (
      option.value === "bank_reconciliation_monthly" &&
      isBankReconciliationExporting
    ) {
      return {
        ...option,
        disabled: true,
        IconRight: SpinnerIcon,
      };
    }
    return option;
  });
 
  const dateString = `until-${formatInTimeZone(
    new Date(),
    PLATFORM_TIMEZONE,
    dateFormat,
  )}`;
 
  // Format: GIVE_TRANSACTIONS_YYYYMMDD_HHMMSS
  const timestamp = formatInTimeZone(
    new Date(),
    PLATFORM_TIMEZONE,
    "yyyyMMdd_HHmmss",
  );
 
  // Template kept with the literal <DateRange> placeholder: ExportRadioComponent
  // swaps it for the selected range so the file name tracks the Date Range radios.
  const disputeFileNameTemplate = `Disputes_Export_${
    name || "<MerchantName>"
  }_<DateRange>`;
 
  const fileName = (() => {
    switch (fieldTypes) {
      case exportType.ACQUIRE_DISPUTE:
        return disputeFileNameTemplate.replace("<DateRange>", dateString);
      case exportType.RISK_TRANSACTIONS: {
        return `GIVE_TRANSACTIONS_${timestamp}`;
      }
      case exportType.MERCHANT_TABLE: {
        return `GIVE_MERCHANTS_${timestamp}`;
      }
      default:
        return "";
    }
  })();
 
  /** ---- build yup schema dynamically per filedTypes ---- */
  const buildSchema = (fields: ExportField[]) => {
    const shape: Record<string, any> = {};
 
    fields.forEach((field) => {
      if (field.fieldType === "button") return;
      if (field.fieldName === "fileName") {
        shape[field.fieldName] = yup
          .string()
          .trim()
          .required("File name is required");
      }
 
      if (field.fieldName === "dateRange") {
        shape[field.fieldName] = yup.object({
          value: yup.string().required(),
          label: yup.string().required(),
          startDate: yup.date().when("value", {
            is: "custom",
            then: (s) =>
              s
                .typeError("Start date must be a valid date")
                .required("Start date is required"),
            otherwise: (s) => s.nullable(),
          }),
          endDate: yup.date().when("value", {
            is: "custom",
            then: (s) =>
              s
                .typeError("End date must be a valid date")
                .required("End date is required"),
            otherwise: (s) => s.nullable(),
          }),
          timeZone: yup
            .string()
            .nullable()
            .when("value", {
              is: "custom",
              // MERCHANT_TABLE: timezone is handled programmatically in merchantTableSubmit.ts
              // (hardcoded ET for monthly reports; session timezone for others). The inner
              // GiveTimezoneDatePicker enforces required when the picker is visible, so we
              // skip the outer required check to avoid blocking monthly-report exports.
              then: (s) =>
                fieldTypes === exportType.MERCHANT_TABLE
                  ? s.nullable()
                  : s.required(VALIDATION_MESSAGES.TIMEZONE_REQUIRED),
              otherwise: (s) => s.nullable(),
            }),
        });
      }
 
      if (field.fieldType === "select" && field.customListValuesName) {
        shape[field.fieldName] = yup.string().required();
        shape[field.customListValuesName] = yup
          .array()
          .of(
            yup.object({
              label: yup.string().required(),
              value: yup.mixed().required(),
              ImageURL: yup.string().url().nullable(),
              checkedIcon: yup.string().nullable(),
              hideImage: yup.boolean().nullable(),
            }),
          )
          .default([])
          .when(field.fieldName, {
            is: "custom",
            then: (s: any) => {
              type MessageKeys = "merchants" | "reasons" | "cardTypes";
              const message: Record<MessageKeys, string> = {
                merchants: "Please select at least one custom merchant",
                reasons: "Please select at least one custom reason",
                cardTypes: "Please select at least one custom card type",
              };
 
              return s
                .min(1, message[field.fieldName as MessageKeys])
                .required();
            },
            otherwise: (s: any) => s.strip(),
          });
      }
    });
 
    return yup.object().shape(shape);
  };
 
  /** ---- defaultValues ---- */
  const defaultValues: Partial<FormValues> = (() => {
    const baseDefaults = getDefaultValues(
      fieldTypes,
      PLATFORM_TIMEZONE,
      hasFilters,
    );
 
    if (fieldTypes === exportType.MERCHANT_TABLE) {
      const isSponsorTab = tab === "sponsor";
      return {
        fileName: fileName,
        ...baseDefaults,
        // Sponsor tab: default to "New Merchant Approval Report" preset.
        // Otherwise: "Columns in the view only" (visible columns depend on portal + tab).
        ...(isSponsorTab
          ? {
              columnsIncluded: "new_merchant_approval" as const,
              columns: merchantReportColumns.newMerchantApproval,
            }
          : { columns: merchantVisibleColumns }),
      };
    }
 
    return {
      fileName: fileName,
      ...baseDefaults,
    };
  })();
 
  const exportFieldsData: Record<TableType, ExportField[]> = {
    [exportType.ACQUIRE_DISPUTE]: [
      {
        label: "File Name",
        value: fileName,
        fieldType: "input",
        fieldName: "fileName",
      },
      {
        label: "Date Range",
        fieldName: "dateRange",
        options: dateRangeOptions,
        fieldType: "radio",
        changeInputValue: disputeFileNameTemplate,
        changeInputName: "fileName",
        stringKeyToUpdate: "<DateRange>",
      },
 
      {
        fieldName: "processorName",
        label: "Processor",
        options: processorOptions,
        fieldType: "select",
        customListValuesName: "",
        hidden: !isMerchantProcessorEnabled || isSponsor,
      },
 
      {
        fieldName: "merchants",
        label: "Merchants",
        options: selectOptions,
        customListValuesName: "merchantAccIDs",
        fieldType: "select",
        contextMenuProps: merchants,
        thumbType: "merchant",
      },
      {
        fieldName: "reason",
        label: "Reasons",
        options: selectOptions,
        customListValuesName: "reasons",
        fieldType: "select",
        contextMenuProps: reasons,
      },
      {
        fieldName: "cardTypes",
        label: "Card Types",
        options: selectOptions,
        customListValuesName: "cardBrands",
        fieldType: "select",
        contextMenuProps: {
          optionsList: cardTypes,
        },
      },
    ],
    [exportType.RISK_TRANSACTIONS]: [
      {
        label: "File Name",
        value: fileName,
        fieldType: "input",
        fieldName: "fileName",
        secondaryField: {
          label: "Choose Type of Export",
          fieldType: "select",
          customListValuesName: "",
          options: exportColumnOptions,
          fieldName: "reportType",
        },
      },
      {
        label: "Export Type",
        fieldName: "type",
        options: getExportTypeOptions(
          counts?.total,
          counts?.filtered,
          hasFilters,
        ),
        fieldType: "radio",
      },
      {
        label: "Show Advanced Settings",
        fieldType: "button",
        onClick: () => setIsOpenAdvancedSettings(true),
        hidden: isOpenAdvancedSettings,
      },
      {
        label: "Transaction Info",
        fieldName: "columns",
        options: transactionInfoOptions,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "Risk",
        fieldName: "columns",
        options: riskOptions,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "Customer",
        fieldName: "columns",
        options: customerOptions,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
    ],
    [exportType.MERCHANT_TABLE]: [
      {
        label: "File Information",
        controlLabel: "File Name",
        value: fileName,
        fieldType: "input",
        fieldName: "fileName",
        secondaryField: {
          label: "Data Selection",
          fieldType: "select",
          customListValuesName: "",
          options: merchantColumnsIncludedOptions,
          fieldName: "columnsIncluded",
        },
      },
      {
        label: "Export Type",
        fieldName: "type",
        options: getExportTypeOptions(
          counts?.total,
          counts?.filtered,
          hasFilters,
        ),
        fieldType: "radio",
      },
      {
        label: "Date Range",
        fieldName: "dateRange",
        options: merchantDateRangeOptions,
        fieldType: "radio",
        changeInputValue: fileName,
        changeInputName: "fileName",
        stringKeyToUpdate: "<DateRange>",
      },
      {
        label: "Show Advanced Settings",
        fieldType: "button",
        onClick: () => setIsOpenAdvancedSettings(true),
        hidden: isOpenAdvancedSettings,
      },
      {
        label: "Merchant Info",
        fieldName: "columns",
        options: getMerchantInfoOptions(
          isMerchantProcessorEnabled,
          isEnterprisePortal,
        ),
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "Sales Info",
        fieldName: "columns",
        options: salesInfo,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings || isEnterprisePortal,
      },
      {
        label: "Risk Monitor",
        fieldName: "columns",
        options: riskMonitor,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "Primary Account Holder",
        fieldName: "columns",
        options: primaryAccountHolder,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "Business Owner",
        fieldName: "columns",
        options: businessOwner,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "Business Profile",
        fieldName: "columns",
        options: businessProfile,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings,
      },
      {
        label: "OFAC Info",
        fieldName: "columns",
        options: ofacInfo,
        fieldType: "radio-multiselect",
        hidden: !isOpenAdvancedSettings || isPendingTab,
      },
    ],
  };
 
  // Build schema from all fields for the given export type.
  // (Visibility can change dynamically based on form state.)
  const schema = buildSchema(exportFieldsData[fieldTypes]);
 
  const methods: UseFormReturn<FormValues> = useForm<FormValues>({
    defaultValues,
    resolver: yupResolver(schema),
    mode: "onChange",
    reValidateMode: "onChange",
    criteriaMode: "all",
    // MERCHANT_TABLE uses MUI Select with contextual menu; focusing invalid fields can be flaky in jsdom/tests
    // and isn't critical to UX for this panel.
    shouldFocusError: fieldTypes !== exportType.MERCHANT_TABLE,
  });
 
  const columns = methods.watch("columns");
  const reportType = methods.watch("reportType");
  const columnsIncluded = methods.watch("columnsIncluded");
 
  useExportSideEffects({
    fieldTypes,
    columns,
    reportType,
    columnsIncluded,
    methods,
    defaultValues,
    merchantAllColumnValues,
    merchantVisibleColumns,
    merchantReportColumns,
    timestamp,
    currentTimezone: PLATFORM_TIMEZONE,
    setIsOpenAdvancedSettings,
  });
 
  const fieldRawData = exportFieldsData[fieldTypes]
    .map((item) => {
      // Disable "Only filtered data" for reconciliation (GET endpoint, no filter support).
      Iif (
        fieldTypes === exportType.MERCHANT_TABLE &&
        isReconciliationLikeReport(columnsIncluded) &&
        "fieldName" in item &&
        item.fieldName === "type" &&
        "options" in item &&
        Array.isArray(item.options)
      ) {
        return {
          ...item,
          options: item.options.map((opt: SelectOption) =>
            opt.value === "filtered"
              ? {
                  ...opt,
                  description:
                    "Filtered data is not available for this report type",
                  disabled: true,
                }
              : opt,
          ),
        };
      }
      Iif (
        fieldTypes === exportType.MERCHANT_TABLE &&
        isReconciliationLikeReport(columnsIncluded) &&
        "fieldName" in item &&
        item.fieldName === "dateRange" &&
        "options" in item &&
        Array.isArray(item.options)
      ) {
        return {
          ...item,
          options: [{ value: "all_time", label: "All Time" }, ...item.options],
        };
      }
      return item;
    })
    .filter((item) => {
      if (item.hidden) return false;
      // Merchant table: date range only applies to report-style exports.
      if (
        fieldTypes === exportType.MERCHANT_TABLE &&
        "fieldName" in item &&
        item.fieldName === "dateRange" &&
        shouldHideMerchantTableDateRange(String(columnsIncluded))
      ) {
        return false;
      }
 
      return true;
    });
  const flatErrors = flattenErrors(methods.formState.errors);
  const firstError = flatErrors[0];
 
  const message = firstError?.message;
 
  const handleSubmit = async (data: FormValues) => {
    onSubmit(data, exportFieldsData);
  };
 
  return {
    methods,
    fieldRawData,
    handleSubmit,
    isFormValid: methods.formState.isValid,
    message,
    isLoading: false,
    isLoadingSubmission,
  };
}
 
/** ---- helpers ---- */
const today = new Date();
 
function formatShortRangeLastMonth() {
  const lastMonth = subMonths(today, 1);
  const start = new Date(lastMonth.getFullYear(), lastMonth.getMonth(), 1);
  const end = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0);
  return `${format(start, "d")}–${format(end, "d MMM")}`;
}
 
const sevenDaysAgo = subDays(today, 7);
 
const dateRangeOptions = [
  { value: "All", label: "All Time" },
  {
    value: "7",
    label: "Last 7 Days",
    description: `Until ${format(sevenDaysAgo, "d MMM")}`,
  },
  {
    value: "month",
    label: "Last Month",
    description: formatShortRangeLastMonth(),
  },
  {
    value: "custom",
    label: "Custom",
  },
];
 
// Reusable loading spinner for export dropdown options while an async export is in progress.
// Declared as a standalone component (via React.createElement to avoid JSX in a .ts file)
// so it can be assigned to the IconRight prop of any GiveSelectOption.
const SpinnerIcon: React.FC<{ size?: number | string; color?: string }> = ({
  size,
  color,
}) =>
  React.createElement(CircularProgress, {
    size: typeof size === "number" ? size : 16,
    sx: { color },
  });
 
const getExportTypeOptions = (total = 0, filtered = 0, hasFilters = false) => {
  return [
    {
      value: "all",
      label: "All Data",
      description: `${total} rows of data will be exported`,
    },
    {
      value: "filtered",
      label: "Only filtered data",
      description: hasFilters
        ? `${filtered} data will be exported`
        : "Please apply a filter first to use this feature",
      disabled: !hasFilters,
    },
  ];
};