All files / src/shared/GiveExportModal/hooks/merchantTable merchantTableSubmit.ts

92.22% Statements 83/90
69.91% Branches 86/123
94.44% Functions 17/18
92.94% Lines 79/85

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                                26x                       26x                   26x                                   6x 84x 24x     6x             3x                           5x 1x       4x 3x     1x                   2x                     2x 2x             2x                               2x     2x                                   4x 4x 4x 4x                 6x 6x                     3x 5x 5x 5x 5x         3x 1x             3x 3x   3x       3x                             13x 13x 13x 13x 13x   13x         17x 17x 17x 12x 5x 5x   17x       13x 13x     13x 13x 12x         13x   13x   1x                     1x             3x 3x 4x   4x         4x         3x       3x 3x         3x                         5x 5x 9x   9x         9x         5x       5x 5x                 5x                                                                         1x                         1x     1x              
import { getTimeZoneUtcOffSet, PLATFORM_TIMEZONE } from "@utils/timezones";
import { endOfDay, startOfDay } from "date-fns";
import { zonedTimeToUtc } from "date-fns-tz";
import {
  salesInfo,
  ofacInfo,
  fileNamePrefixNewMerchantApprovalReport,
  filterPersonsTypeColumn,
} from "@shared/GiveExportModal/const";
import type { FormValues } from "@shared/GiveExportModal/giveExportTypes";
import { buildReserveMonthlyFileNamePrefix } from "./merchantTableReserveDate";
 
/**
 * Section filter prefixes for rebranded merchant tabs (must match legacy ExportView).
 * Used so CSV export uses the same filter as the table (e.g. underwriting tab → underwriting section).
 */
export const SECTION_PREFIX_MAP: Record<string, string> = {
  "-underwriting": '(stateName:!"declined")%3B(sectionName:"underwriting")',
  "-sponsor": '(stateName:!"declined")%3B(sectionName:"sponsor")',
  "-approved":
    '(sectionName:"compliance")%3B((stateName:"approved")%2C(stateName:"suspended"))',
  "-kyb": '(stateName:!"declined")%3B(sectionName:"kyb")',
  "-signup": '(stateName:"onboarding")%3B(sectionName:"signup")',
  "-compliance":
    '(riskLevelLabelDisplayName:!"low")%3B(sectionName:"compliance")%3B(stateName:"approved")',
};
 
/** Tab-specific default sort when Redux sort is empty (aligns with table defaults). */
const TAB_DEFAULT_SORT: Record<string, string> = {
  "-underwriting": "-kybApprovalAt,-accID",
  "-sponsor": "-approvalAt,-accID",
  "-approved": "-accID",
  "-kyb": "-kybApprovalAt,-accID",
  "-signup": "-createdAt,-accID",
  "-compliance": "-accID",
};
 
// Sponsor tab sort field name normalization (legacy API compatibility).
const SORT_FIELD_REPLACEMENTS: Array<[RegExp, string]> = [
  [/approvalAt/g, "sponsorStateLastUpdatedAt"],
];
 
export function merchantIncludesRestrictedColumns({
  columnsIncluded,
  selectedColumns,
}: {
  columnsIncluded?: string;
  selectedColumns: string[];
}) {
  /**
   * Restricted columns (Sales/OFAC) require a different endpoint
   * (`submerchants-monthly-processing.csv`) because permissions are enforced there.
   *
   * We treat report presets as restricted even if the UI doesn't include the full list yet,
   * because the legacy backend behavior expects them on the restricted endpoint.
   */
  const restrictedColumnValues = new Set([
    ...salesInfo.map((o) => o.value),
    ...ofacInfo.map((o) => o.value),
  ]);
 
  return (
    [
      "processing_monthly",
      "reserve_monthly",
      "ofac_business",
      "ofac_persons",
    ].includes(columnsIncluded || "") ||
    selectedColumns.some((c) => restrictedColumnValues.has(c))
  );
}
 
export function getMerchantBaseURL({
  columnsIncluded,
  includesRestrictedColumns,
  isAcquirerPortal,
}: {
  columnsIncluded?: string;
  includesRestrictedColumns: boolean;
  isAcquirerPortal: boolean;
}) {
  // The New Merchant Approval export uses a dedicated endpoint.
  if (columnsIncluded === "new_merchant_approval") {
    return "submerchants-approval-report.csv";
  }
 
  // Restricted columns are only protected via the restricted endpoint (acquirer portal only).
  if (isAcquirerPortal && includesRestrictedColumns) {
    return "submerchants-monthly-processing.csv";
  }
 
  return "submerchants.csv";
}
 
export function getMerchantExportFilterPrefix({
  selectedTab,
  isMerchantStatusRefactorEnabled,
}: {
  selectedTab: string;
  isMerchantStatusRefactorEnabled: boolean;
}): string {
  Eif (!isMerchantStatusRefactorEnabled) return "";
  return SECTION_PREFIX_MAP[selectedTab] ?? "";
}
 
export function getMerchantExportSort({
  sort,
  selectedTab,
}: {
  sort: string;
  selectedTab: string;
}): string {
  Iif (sort?.trim()) return sort;
  return TAB_DEFAULT_SORT[selectedTab] ?? "-accID";
}
 
export function normalizeSortForMerchantExport(
  sort: string,
  selectedTab: string,
): string {
  Eif (!sort || selectedTab !== "-sponsor") return sort || "-accID";
  return SORT_FIELD_REPLACEMENTS.reduce(
    (acc, [pattern, replacement]) => acc.replace(pattern, replacement),
    sort,
  );
}
 
export function buildMerchantFilterWithPrefixAndParent({
  baseFilter,
  sectionPrefix,
  parentAccFilter,
}: {
  baseFilter: string;
  sectionPrefix: string;
  parentAccFilter: string;
}): string {
  const filterWithSection = sectionPrefix
    ? sectionPrefix + baseFilter
    : baseFilter;
  Eif (!parentAccFilter) return filterWithSection;
  return filterWithSection
    ? `${filterWithSection}%3B${parentAccFilter}`
    : parentAccFilter;
}
 
export function buildMerchantTableUrlFilters({
  customQueryString,
  sort,
  searchQuery,
  watchlist,
}: {
  customQueryString: string;
  sort: string;
  searchQuery?: string;
  watchlist?: boolean;
}) {
  // Merchant export uses URL query params: `?filter=...&sort=...&q="..."`.
  const filter = customQueryString || "";
  const q = searchQuery ? `&q="${searchQuery}"` : "";
  const watchlistParam = watchlist ? "&watchlist=true" : "";
  return `?filter=${filter}&sort=${sort}${q}${watchlistParam}`;
}
 
/**
 * Builds query-string URL params for the reconciliation report GET endpoint.
 * Returns "" when All Time is requested (no date filter).
 * Dates are anchored to Eastern Time boundaries.
 */
export function buildReconciliationUrlFilters(data: FormValues): string {
  const dateRange = data?.dateRange;
  if (!dateRange?.startDate || !dateRange?.endDate) return "";
 
  // BE expects plain calendar dates (YYYY-MM-DD).
  //
  // The picker yields a Date at the browser's local midnight of the day the user
  // chose, so read that day back off the LOCAL components. Projecting the instant
  // into ET instead (Intl with timeZone) moves it a day earlier for any browser
  // east of New York — picking 1 Jul in UTC+1 gave "2026-06-30", pulling an extra
  // day of activity into the report and reading the wrong opening snapshot. The
  // processing-monthly payload treats the picked day the same way: it takes the
  // local wall-clock day and reinterprets it in ET (see etToUnix below).
  const toPickedDateString = (date: Date): string => {
    const d = new Date(date);
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${d.getFullYear()}-${month}-${day}`;
  };
 
  // "Current month" ends today — that is a real instant, not a picked day, so it
  // resolves on the platform's calendar rather than the browser's.
  const toPlatformTodayString = (): string =>
    new Intl.DateTimeFormat("en-CA", {
      timeZone: PLATFORM_TIMEZONE,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    }).format(new Date()); // en-CA produces "YYYY-MM-DD" natively
 
  const dateValue = dateRange?.value as string | undefined;
  const startDate = toPickedDateString(dateRange.startDate as Date);
  const endDate =
    dateValue === "current_month"
      ? toPlatformTodayString()
      : toPickedDateString(dateRange.endDate as Date);
 
  return `?start_date=${startDate}&end_date=${endDate}`;
}
 
export function buildMerchantTablePayload(data: FormValues) {
  /**
   * This adapts the legacy ExportView `buildPayload` switch to the rebranded form model.
   *
   * Key invariants:
   * - `columnsIncluded` drives `reportType` and whether we send `columns`.
   * - Date ranges are sent as unix seconds, computed in the selected timezone.
   * - For `current_month`, end date is "now" (not end-of-day).
   * - OFAC persons report intentionally omits `columns` for BE compatibility.
   * - Reserve monthly report omits `columns` and sends `includeAllColumns` so the BE
   *   owns its fixed column set.
   */
  const columnsIncluded = (data as any).columnsIncluded as string | undefined;
  const dateRange = data?.dateRange;
  const tz = dateRange?.timeZone || PLATFORM_TIMEZONE;
  const utcOffSet = getTimeZoneUtcOffSet(tz);
  const dateValue = dateRange?.value as string | undefined;
 
  const toUnixInTimezone = (
    date: Date,
    boundary: "start" | "end" | "exact",
  ) => {
    // Convert a local date (in selected timezone) to a UTC unix timestamp (seconds).
    const d = new Date(date);
    let adjusted = d;
    if (boundary === "start") {
      adjusted = startOfDay(d);
    } else Eif (boundary === "end") {
      adjusted = endOfDay(d);
    }
    return Math.floor(zonedTimeToUtc(adjusted, tz).getTime() / 1000);
  };
 
  const hasSelectedDates =
    dateRange?.startDate instanceof Date && dateRange?.endDate instanceof Date;
  const startDateUnix = hasSelectedDates
    ? toUnixInTimezone(dateRange.startDate as Date, "start")
    : undefined;
  let endDateUnix: number | undefined = undefined;
  if (hasSelectedDates) {
    endDateUnix =
      dateValue === "current_month"
        ? Math.floor(Date.now() / 1000)
        : toUnixInTimezone(dateRange.endDate as Date, "end");
  }
  const hasSelectedDate = Boolean(startDateUnix && endDateUnix);
 
  switch (columnsIncluded) {
    case "custom":
      return {
        includeAllColumns: false,
        columns: filterPersonsTypeColumn({
          columnType: "merchant",
          columnsArr: data.columns || [],
          columnsIncluded: columnsIncluded,
        }),
        fileNamePrefix: "GIVE_MERCHANTS_",
        reportType: "merchant_report",
      };
    case "visible":
      return {
        includeAllColumns: false,
        columns: data.columns || [],
        fileNamePrefix: "GIVE_MERCHANTS_",
        reportType: "only_in_view",
      };
    case "processing_monthly": {
      const etUtcOffSet = getTimeZoneUtcOffSet(PLATFORM_TIMEZONE);
      const etToUnix = (date: Date, boundary: "start" | "end" | "exact") => {
        const d = new Date(date);
        const adjusted =
          boundary === "start"
            ? startOfDay(d)
            : boundary === "end"
            ? endOfDay(d)
            : d;
        return Math.floor(
          zonedTimeToUtc(adjusted, PLATFORM_TIMEZONE).getTime() / 1000,
        );
      };
      const etStartUnix =
        dateRange?.startDate instanceof Date
          ? etToUnix(dateRange.startDate, "start")
          : undefined;
      let etEndUnix: number | undefined;
      Eif (dateRange?.endDate instanceof Date) {
        etEndUnix =
          dateValue === "current_month"
            ? Math.floor(Date.now() / 1000)
            : etToUnix(dateRange.endDate, "end");
      }
      return {
        includeAllColumns: false,
        columns: data.columns || [],
        fileNamePrefix: "GIVE_MONTHLY_MERCHANT_PROCESSING_",
        ...(etStartUnix &&
          etEndUnix && {
            dateRange: { startDate: etStartUnix, endDate: etEndUnix },
          }),
        ...(etUtcOffSet && { utcOffSet: etUtcOffSet }),
        reportType: "processing_monthly_report",
      };
    }
    case "reserve_monthly": {
      const etUtcOffSet = getTimeZoneUtcOffSet(PLATFORM_TIMEZONE);
      const etToUnix = (date: Date, boundary: "start" | "end" | "exact") => {
        const d = new Date(date);
        const adjusted =
          boundary === "start"
            ? startOfDay(d)
            : boundary === "end"
            ? endOfDay(d)
            : d;
        return Math.floor(
          zonedTimeToUtc(adjusted, PLATFORM_TIMEZONE).getTime() / 1000,
        );
      };
      const etStartUnix =
        dateRange?.startDate instanceof Date
          ? etToUnix(dateRange.startDate, "start")
          : undefined;
      let etEndUnix: number | undefined;
      Eif (dateRange?.endDate instanceof Date) {
        etEndUnix =
          dateValue === "current_month"
            ? Math.floor(Date.now() / 1000)
            : etToUnix(dateRange.endDate, "end");
      }
      // The Reserve Monthly Report has a fixed, backend-owned column set. Sending an
      // explicit `columns` list makes the backend reject the export outright when the
      // two drift apart (columns must be a subset of the backend header), so request
      // all columns and let the backend define the CSV header.
      return {
        includeAllColumns: true,
        fileNamePrefix: buildReserveMonthlyFileNamePrefix({
          startDate: dateRange?.startDate,
          endDate: dateRange?.endDate,
        }),
        ...(etStartUnix &&
          etEndUnix && {
            dateRange: { startDate: etStartUnix, endDate: etEndUnix },
          }),
        ...(dateValue === "current_month" && { useCurrentBalances: true }),
        ...(etUtcOffSet && { utcOffSet: etUtcOffSet }),
        reportType: "reserve_monthly_report",
      };
    }
    case "new_merchant_approval":
      return {
        includeAllColumns: false,
        columns: data.columns || [],
        fileNamePrefix: fileNamePrefixNewMerchantApprovalReport,
        ...(hasSelectedDate && {
          dateRange: { startDate: startDateUnix, endDate: endDateUnix },
        }),
        ...(utcOffSet && { utcOffSet }),
      };
    case "ofac_business":
      return {
        includeAllColumns: false,
        columns: data.columns || [],
        fileNamePrefix: "GIVE_OFAC_BUSINESS_",
        ...(hasSelectedDate && {
          dateRange: { startDate: startDateUnix, endDate: endDateUnix },
        }),
        ...(utcOffSet && { utcOffSet }),
        reportType: "ofac_legal_entity_report",
      };
    case "ofac_persons":
      return {
        includeAllColumns: false,
        fileNamePrefix: "GIVE_OFAC_PERSONS_",
        ...(hasSelectedDate && {
          dateRange: { startDate: startDateUnix, endDate: endDateUnix },
        }),
        ...(utcOffSet && { utcOffSet }),
        reportType: "ofac_persons_report",
      };
    case "reconciliation_monthly":
    case "bank_reconciliation_monthly":
      // Async GET endpoints — no payload columns needed. Early-return in
      // buildExportRequest sets payload: undefined; guard here for safety.
      return undefined as any;
    case "all":
    default:
      return {
        includeAllColumns: true,
        fileNamePrefix: "GIVE_MERCHANTS_",
        reportType: "merchant_report",
      };
  }
}