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 | 29x 1094x 1094x 1094x 1094x 1094x 1094x 1241x 1094x 1094x 1094x 1094x 1094x 1094x 1094x 1094x 17x 17x 82x 17x 17x 17x 17x 17x 17x 85x 17x 17x 17x 17x 17x 1094x 3x 3x 3x 1094x 244x 1094x 1094x 2x 2x 2x 1094x 113x 1094x 2188x 17624x 1094x 1094x 1094x 1094x 36x 36x 36x 36x 16x 36x 36x 1094x 29x 1094x 7573x 7573x 7573x 16x 32x 32x 7573x 34x 68x 68x 7573x 1094x 29x 6564x 463x 1998x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 29x 2664x 2664x 2664x 2660x 4x 29x 29x 29x 1094x | import { useForm, UseFormReturn } from "react-hook-form";
import * as yup from "yup";
import {
FilterPagesEnum,
FilterPageValuesTYpes,
endpointNames,
customAmountArrayKey,
reduxFilterKeys,
urlFilterFormat,
TRANSACTION_TRANSFER,
inflowOutFlowApiKey,
ticketApiKeys,
expandEventTxnStatuses,
} from "../constants";
import {
CardPropsTypes,
FilterValue,
} from "@pages/ManageMoney/Modal/filter.types";
import { yupResolver } from "@hookform/resolvers/yup";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import {
resetFilterByKey,
selectFiltersObject,
setFilterByKey,
} from "@redux/slices/dynamicFilterSlice";
import NiceModal from "@ebay/nice-modal-react";
import { GIVE_FILTER_MODAL } from "modals/modal_names";
import { isEqual } from "lodash";
import { useEffect, useMemo } from "react";
import {
checkBoolean,
formatArrayFilter,
formatAssigneeFilter,
formatDateFilter,
formatInflowOutFlowFilter,
formatObjectArrayFilter,
formatObjectToTupleString,
formatAccountTypeFilter,
handleDisplayStatusFilter,
joinWithSemicolon,
joinWithColon,
} from "../utils";
import { checkPortals } from "@utils/routing";
import {
addBlockedAndQuarantinedFilter,
addStatusFilter,
clearFilters,
setProcessingTab,
} from "@redux/slices/transactions";
import useGetFilterSectionPerPage from "./useGetFilterSectionPerPage";
import { selectMerchantTab } from "@redux/slices/enterprise/merchants";
import { useFormatDateInTimezone } from "@utils/date.helpers";
import moment from "moment";
import { tabNames } from "@features/Processing/hooks/useTransactionsFilters";
import { useFormatDisputeFilters } from "./useFormatDisputeFilters";
import { getFormattedMerchantStateName } from "./useFormattedFilters";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
// All date filters use ET — pass PLATFORM_TIMEZONE so API queries are
// anchored to Eastern Time midnight on every filter page.
const USE_TIMEZONE = true;
export default function useGeneralFilters({
filterPage = FilterPagesEnum.MANAGE_MONEY,
open,
handleClose,
productId,
}: {
filterPage: FilterPageValuesTYpes;
open?: boolean;
handleClose?: () => void;
/** Scopes an entity-specific filter page — see useGetFilterSectionPerPage. */
productId?: string;
}) {
const filterSections = useGetFilterSectionPerPage({ filterPage, productId });
const { currentTimezone } = useFormatDateInTimezone();
const merchantTabName = useAppSelector(selectMerchantTab);
const {
isProcessing,
isManageMoney,
isMerchantPortal,
isDisputes,
isEnterprisePortal,
} = checkPortals();
const dispatch = useAppDispatch();
const filterObject = useAppSelector((state) =>
selectFiltersObject(state, reduxFilterKeys?.[filterPage]),
) as any;
const reduxKey = reduxFilterKeys[filterPage];
const defaultValues = getDefaultValues(filterSections);
type FormValues = typeof defaultValues;
// use ID-based filtering for transactions and transactions-basic to avoid matching multiple merchants with the same name
const isAcquirerOrProviderManageMoney = [
FilterPagesEnum.ACQUIRER_MANAGE_MONEY,
FilterPagesEnum.ACQUIRER_PROCESSING,
FilterPagesEnum.PROVIDER_PROCESSING,
].includes(filterPage);
const isMerchantRiskPanel =
filterPage === FilterPagesEnum.MERCHANT_RISK_PANEL;
const methods: UseFormReturn<FormValues> = useForm<FormValues>({
defaultValues,
// Validation timezone matches the filter window timezone (America/New_York)
// so users can't pick a date that's still "in the future" in ET.
resolver: yupResolver(
getSchema(USE_TIMEZONE ? PLATFORM_TIMEZONE : undefined),
),
mode: "onChange",
reValidateMode: "onChange",
criteriaMode: "all",
});
const values = methods.watch();
const { formatDisputeStatusFilter, formatDisputeCaseTypeFilter } =
useFormatDisputeFilters();
const handleSubmit = () => {
const data = methods.watch();
const originalTransfer = filterSections?.find(
(item: any) => item.apiKeyName === endpointNames.transferStatus,
)?.chips;
const status = handleDisplayStatusFilter({
originalTransfer,
[TRANSACTION_TRANSFER.TRANSACTION]:
data?.[endpointNames.transactionStatus] || ([] as any),
[TRANSACTION_TRANSFER.TRANSFER]:
data?.[endpointNames.transferStatus] || ([] as any),
filterPage,
});
const isTransfersPage = FilterPagesEnum.TRANSFERS === filterPage;
const merchantNameEndpointName = isDisputes
? endpointNames.disputeMerchantAccID
: isTransfersPage
? endpointNames.merchantNameTransfer
: endpointNames.merchantName;
const providerNameEndpointName = isTransfersPage
? endpointNames.providerNameTransfer
: endpointNames.providerName;
const merchantProviderFilter = joinWithColon(
...(isAcquirerOrProviderManageMoney //for transaction-base insted of merrchantName we need to filter by dstAccMerchantName and srcAccMerchantName
? [
formatObjectArrayFilter({
array: data?.[endpointNames.merchantName] || ([] as any),
key: endpointNames.srcAccountId,
}),
formatObjectArrayFilter({
array: data?.[endpointNames.merchantName] || ([] as any),
key: endpointNames.dstAccountId,
}),
formatObjectArrayFilter({
array: data?.[endpointNames.providerName] || ([] as any),
key: endpointNames.srcParentAccID,
}),
formatObjectArrayFilter({
array: data?.[endpointNames.providerName] || ([] as any),
key: endpointNames.dstParentAccID,
}),
]
: [
formatObjectArrayFilter({
array: data?.[endpointNames.merchantName] || ([] as any),
key: merchantNameEndpointName,
}),
//for transfer page when a provider is selected we need to add the merchantNameEndpointName
//with the provider name as well to get the provider initiated transfers
...(isTransfersPage
? [
formatObjectArrayFilter({
array: data?.[endpointNames.providerName] || ([] as any),
key: merchantNameEndpointName,
}),
formatObjectArrayFilter({
array: data?.[endpointNames.providerName] || ([] as any),
key: providerNameEndpointName,
}),
]
: [
formatObjectArrayFilter({
array: data?.[endpointNames.providerName] || ([] as any),
key: providerNameEndpointName,
}),
]),
]),
);
const url = joinWithSemicolon(
formatDateFilter({
dateRange: data?.[endpointNames?.date] as string,
endpointName: endpointNames?.date,
// Aligns the createdAt filter window with the Monthly Processing Report,
// which is anchored to America/New_York. Without this, users in non-ET
// timezones get a different UTC window and the two exports disagree.
timezone: USE_TIMEZONE ? PLATFORM_TIMEZONE : "",
}),
// Independent settlement-date window; ANDs with the createdAt window above.
formatDateFilter({
dateRange: data?.[endpointNames?.settledAt] as string,
endpointName: endpointNames?.settledAt,
timezone: USE_TIMEZONE ? PLATFORM_TIMEZONE : "",
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames.inFlow] as string,
endpointName: isMerchantRiskPanel
? endpointNames.inFlow
: inflowOutFlowApiKey,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames.outFlow] as string,
endpointName: isMerchantRiskPanel
? endpointNames.inFlow
: inflowOutFlowApiKey,
isNegative: !isMerchantRiskPanel,
}),
merchantProviderFilter,
checkBoolean({
value: data?.[endpointNames?.paymentMethod] as string,
endpointName: endpointNames?.paymentMethod,
validatorStr: "Debit",
}),
status,
formatAssigneeFilter({
assignees: data?.[endpointNames.assignee] || ([] as any),
tab: isDisputes ? "disputes" : merchantTabName,
}),
formatObjectArrayFilter({
array: data?.[endpointNames.categoryCode] || ([] as any),
key: endpointNames.categoryCode,
}),
formatDisputeCaseTypeFilter(
data?.[endpointNames.disputeCaseType] as FilterValue[],
),
formatDateFilter({
dateRange: data?.[endpointNames?.approvedDate] as string,
endpointName: endpointNames?.approvedDate,
timezone: PLATFORM_TIMEZONE,
}),
formatDateFilter({
dateRange: data?.[endpointNames?.approvalAt] as string,
endpointName: endpointNames?.approvalAt,
timezone: PLATFORM_TIMEZONE,
}),
formatDateFilter({
dateRange: data?.[endpointNames?.lastEscalationAt] as string,
endpointName: endpointNames?.lastEscalationAt,
timezone: PLATFORM_TIMEZONE,
}),
formatDateFilter({
dateRange: data?.[endpointNames?.lastRiskActivityAt] as string,
endpointName: endpointNames?.lastRiskActivityAt,
timezone: PLATFORM_TIMEZONE,
}),
formatArrayFilter({
array: data?.[endpointNames?.riskLevelLabelDisplayName] as any,
key: endpointNames?.riskLevelLabelDisplayName,
}),
formatArrayFilter({
array: data?.[endpointNames?.riskStatusDisplayName] as any,
key: endpointNames?.riskStatusDisplayName,
}),
formatArrayFilter({
array: data?.[endpointNames?.processor] as any,
key: endpointNames?.processor,
value: data?.[endpointNames?.processor] as string,
}),
formatDisputeStatusFilter(data?.status as FilterValue[]),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.disputeAmount] as string,
endpointName: endpointNames?.disputeAmount,
}),
getFormattedMerchantStateName(
data?.[endpointNames?.stateName] as string[],
{ excludeClosed: isEnterprisePortal },
),
formatArrayFilter({
array: data?.[endpointNames?.className] as any,
key: endpointNames?.className,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.transactionsCount] as string,
endpointName: endpointNames?.transactionsCount,
multiplyBy: 1,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.approvedSubmerchants] as string,
endpointName: endpointNames.approvedSubmerchants,
multiplyBy: 1,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.processedVolume] as string,
endpointName: endpointNames?.processedVolume,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.charged] as string,
endpointName: endpointNames?.charged,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.cost] as string,
endpointName: endpointNames?.cost,
}),
formatInflowOutFlowFilter({
flowRange: data?.[endpointNames?.fees] as string,
endpointName: endpointNames?.fees,
}),
formatObjectToTupleString({
canProcessMoney: data?.canProcessMoney,
canTransferMoney: data?.canTransferMoney,
}),
formatAccountTypeFilter({
isProviderTransfers: !!data?.isProviderTransfers,
isMerchantTransfers: !!data?.isMerchantTransfers,
}),
formatObjectToTupleString({
isBlocked: data?.isBlocked,
isFalsePositive: data?.isFalsePositive,
}),
formatArrayFilter({
array: data?.[endpointNames?.emailStatus] as any,
key: endpointNames?.emailStatus,
}),
formatArrayFilter({
array: data?.[endpointNames?.cardInfoType] as any,
key: endpointNames?.cardInfoType,
}),
formatArrayFilter({
array: data?.[endpointNames?.riskLevel] as any,
key: endpointNames?.riskLevel,
}),
formatArrayFilter({
array: data?.[endpointNames?.txnDisplayStatus] as any,
key: endpointNames?.txnDisplayStatus,
}),
// Event Tickets tab (frame 7397-90376). Form keys are prefixed to stay
// clear of the disputes panel's `status`, so each maps to its
// event_ticket_holders_view field here. Purchase Date needs no line — it
// reuses the createdAt window at the top of this chain.
...Object.entries(ticketApiKeys).map(([formKey, apiKey]) =>
formatArrayFilter({
array: data?.[formKey] as any,
key: apiKey,
}),
),
// Event Transactions tab (frame 7397-80180). Its own line rather than a
// ticketApiKeys entry because "Processing" is a portal-only label that has
// to expand into the display statuses it stands for.
formatArrayFilter({
array: expandEventTxnStatuses(
data?.[endpointNames.eventTxnStatus] as any,
),
key: "transactionDisplayStatus",
}),
);
Iif (isProcessing || isManageMoney) {
dispatch(clearFilters());
dispatch(setProcessingTab(tabNames.all));
if (!!isMerchantPortal) {
dispatch(addStatusFilter("!declined"));
dispatch(addBlockedAndQuarantinedFilter());
}
}
dispatch(
setFilterByKey({
filterKey: reduxKey,
params: {
...data,
[urlFilterFormat]: encodeURIComponent(url),
},
}),
);
methods?.reset();
handleClose?.();
NiceModal.hide(GIVE_FILTER_MODAL);
};
const resetModal = () => {
methods?.reset(defaultValues);
handleClose?.();
NiceModal.hide(GIVE_FILTER_MODAL);
};
useEffect(() => {
if (open) methods?.reset({ ...defaultValues, ...filterObject });
}, [filterObject, open]);
const { isValid } = methods.formState;
const handleClearFilters = () => {
dispatch(
resetFilterByKey({
filterKey: reduxKey,
}),
);
methods?.reset(defaultValues);
Iif (
//currently we only have special callback for this case, but if other filters will need it in future we can refactor this logic and customize more
[
FilterPagesEnum.MANAGE_MONEY,
FilterPagesEnum.PROVIDER_PROCESSING,
].includes(filterPage) &&
!!isMerchantPortal
) {
dispatch(addBlockedAndQuarantinedFilter());
}
};
//reset filters if there's a date filter applyed and the user chnages the timezone
useEffect(() => {
Iif (
(values?.[endpointNames.date] || values?.[endpointNames.settledAt]) &&
USE_TIMEZONE
)
handleClearFilters();
}, [currentTimezone]);
const removeUndefinedKeys = (obj: Record<string, any>) => {
return Object.fromEntries(
Object.entries(obj).filter(([_, value]) => value !== undefined),
);
};
const areObjectsSame = isEqual(
removeUndefinedKeys(methods.watch()),
removeUndefinedKeys(defaultValues),
);
const errorsForCustomChip = useMemo(() => {
const selectedCustoms = (values?.[customAmountArrayKey] as []) ?? [];
return selectedCustoms
?.map((valKey: string) => {
const inputValue = values?.[valKey];
Iif (inputValue) return null;
let valueErrorText = valKey;
if (valKey === endpointNames.date) {
valueErrorText = "custom transaction date";
}
Iif (valKey === endpointNames.settledAt) {
valueErrorText = "custom settlement date";
}
return `Enter a custom ${valueErrorText} to apply the filters`;
})
.filter(Boolean);
}, [values]);
return {
filterSections,
methods,
handleSubmit,
isValid,
handleClearFilters,
areObjectsSame,
resetModal,
errorsForCustomChip,
};
}
const getDefaultValues = (filterSections: CardPropsTypes[]) => {
const baseDefaults = filterSections?.reduce(
(acc, section) => {
Iif (Array.isArray(section.apiKeyName)) {
return acc;
}
acc[section.apiKeyName] = section.selected ?? "";
// Add default values for additional toggles
if (section.additionalToggles?.length) {
section.additionalToggles.forEach((toggle) => {
Iif (typeof toggle.apiKeyName !== "string") {
return;
}
acc[toggle.apiKeyName] = null as any;
});
}
// Add default values for switches (like canProcessMoney, canTransferMoney)
if (section.switches?.length) {
section.switches.forEach((switchItem: any) => {
Eif (typeof switchItem.name === "string") {
acc[switchItem.name] = undefined;
}
});
}
return acc;
},
{
[customAmountArrayKey]: [],
} as Record<string, CardPropsTypes["selected"] | undefined>,
);
return baseDefaults;
};
const getDateValidation = (timezone?: string) => {
return yup
.string()
.nullable()
.notRequired()
.default("")
.transform((value) => (value === null ? "" : value)) // Convert null to empty string
.test(
"is-empty-or-valid",
"The date format is not valid",
function (value) {
if (!value || value.trim() === "") return true; // Allow empty if not required
const dateRangeRegex =
/^(\d{2})\/(\d{2})\/(\d{4})(?:\s?-\s?(\d{2})\/(\d{2})\/(\d{4}))?$/;
const match = value.match(dateRangeRegex);
Iif (!match) return false; // ❌ Reject invalid formats
const [, MM1, DD1, YYYY1, MM2, DD2, YYYY2] = match.map(Number);
const isValidDate = (MM: number, DD: number, YYYY: number) => {
Iif (MM < 1 || MM > 12) return false;
const daysInMonth = new Date(YYYY, MM, 0).getDate();
Iif (new Date(`${MM}/${DD}/${YYYY}`) > new Date() && !timezone)
return false;
Eif (timezone) {
const dateToValidate = moment.tz(
`${MM}/${DD}/${YYYY}`,
"MM/DD/YYYY",
timezone,
);
const nowInTimezone = moment().tz(timezone);
Iif (!dateToValidate.isSameOrBefore(nowInTimezone, "day"))
return false;
}
return DD >= 1 && DD <= daysInMonth;
};
Iif (!isValidDate(MM1, DD1, YYYY1)) return false;
Iif (MM2 && DD2 && YYYY2 && !isValidDate(MM2, DD2, YYYY2)) return false;
// Compare start and end date
Iif (MM2 && DD2 && YYYY2) {
const startDate = new Date(YYYY1, MM1 - 1, DD1);
const endDate = new Date(YYYY2, MM2 - 1, DD2);
if (endDate < startDate) return false; // ❌ Reject if end date is earlier
}
return true;
},
);
};
const rangeValidation = yup
.string()
.nullable()
.notRequired()
.test("is-valid-range", "The range is invalid", function (value) {
const { parent, path } = this; // `path` is the key being validated
const keysRequiringRange = parent[customAmountArrayKey] || [];
// Only validate if the field is in keysRequiringRange and has a value
if (!keysRequiringRange.includes(path)) {
return true; // Skip validation if the field doesn't require a range
}
// Ensure a value exists before testing format
Eif (!value) return true;
// Allow "X" or "X-Y" where X and Y can be integers or decimals
const match = value.match(/^(\d+(?:\.\d+)?)(?:-(\d+(?:\.\d+)?))?$/);
if (!match) return false;
const start = Number(match[1]);
const end = match[2] ? Number(match[2]) : start;
return start <= end; // Ensure first number is not greater than the second
})
.default("");
const arrayValidation = yup
.array()
.of(yup.string())
.nullable()
.notRequired()
.default([]);
const arrayOfObjectValidation = yup
.array()
.of(yup.object())
.nullable()
.notRequired()
.default([]);
const getSchema = (timezone?: string) => {
return yup.object().shape({
[endpointNames.date]: getDateValidation(timezone),
[endpointNames.settledAt]: getDateValidation(timezone),
[endpointNames.approvedDate]: getDateValidation(timezone),
[endpointNames.approvalAt]: getDateValidation(timezone),
[endpointNames.lastEscalationAt]: getDateValidation(timezone),
[endpointNames.lastRiskActivityAt]: getDateValidation(timezone),
[customAmountArrayKey]: arrayValidation,
[endpointNames.merchantName]: arrayOfObjectValidation,
[endpointNames.transactionStatus]: arrayValidation,
[endpointNames.transferStatus]: arrayValidation,
[endpointNames.inFlow]: rangeValidation,
[endpointNames.outFlow]: rangeValidation,
[endpointNames.paymentMethod]: arrayValidation,
[endpointNames.providerName]: arrayOfObjectValidation,
[endpointNames.assignee]: arrayOfObjectValidation,
[endpointNames.watchlist]: arrayValidation,
[endpointNames.processedVolume]: rangeValidation,
[endpointNames.transactionsCount]: rangeValidation,
[endpointNames.approvedSubmerchants]: rangeValidation,
[endpointNames.disputeAmount]: rangeValidation,
[endpointNames.charged]: rangeValidation,
[endpointNames.cost]: rangeValidation,
isProviderTransfers: yup.mixed().oneOf([true, false, null]).default(null),
isMerchantTransfers: yup.mixed().oneOf([true, false, null]).default(null),
[endpointNames.isBlocked]: yup
.mixed()
.oneOf([true, false, null])
.default(null),
[endpointNames.isFalsePositive]: yup
.mixed()
.oneOf([true, false, null])
.default(null),
[endpointNames.cardInfoType]: arrayValidation,
[endpointNames.riskLevel]: arrayValidation,
});
};
|