All files / src/components/common/TableFilters utils.ts

59.05% Statements 75/127
43.44% Branches 63/145
80% Functions 12/15
64.6% Lines 73/113

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                                                                                                                                                                                                                    544x             544x                                                             22x 155x 3x     22x 155x   155x 155x 3x 3x       3x 3x 3x         3x   152x                   155x   22x 22x     22x     544x             22x     22x     3x           3x     3x         3x       22x         544x 152x     152x     544x                                   21x 21x   7x       7x       14x                       14x                                                                       14x 14x         21x     544x                             114x 114x 38x             38x                 38x   38x   38x   38x     76x 76x             114x     544x         56x   56x 56x 56x   56x 56x 56x 56x     544x                 9x                 9x   9x   9x       9x       9x   544x         544x 3x   544x                                            
import { SxProps } from "@mui/material";
import { FilterObjectTypes as RiskLevelType } from "@customTypes/utils.types";
import { Theme } from "@mui/system";
import { replaceValues, withAppendedKey } from "@services/filtering";
import { toUnixDateFormat } from "@utils/date.helpers";
import { sub } from "date-fns";
import { zonedTimeToUtc } from "date-fns-tz";
import { isBoolean, isEmpty } from "lodash";
import moment from "moment";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { FilterDates } from "@redux/slices/tableFilters/types";
import { SelectorOption } from "./SelectorOption";
 
export type CustomSections = {
  portfolio: FilterSectionItemType[];
  underwriting: FilterSectionItemType[];
  risk: FilterSectionItemType[];
};
 
export type FilterSectionItemType = {
  startIcon?: React.ReactElement;
  title: string;
  description?: string;
  endElement?: React.ReactElement;
  children?: React.ReactElement;
  containerStyle?: SxProps<Theme>;
  hidden?: boolean;
  dataTestId?: string;
};
 
export type FormValues = {
  watchlist?: boolean | string;
  parentName?: SelectorOption[];
  merchantName?: SelectorOption[];
  caseType?: SelectorOption[];
  totalProcessed?: string | number;
  statusDisplayName?: Partial<SelectorOption>[];
  stateName?: Partial<SelectorOption>[];
  categoryCode?: SelectorOption[];
  underwriterEmail?: SelectorOption[];
  createdAt?: string | number;
  lastEscalationAt?: string | number;
  lastRiskActivityAt?: string | number;
  approvedAt?: string | number;
  riskLevelLabelDisplayName?: Partial<SelectorOption>[];
  canProcessMoney?: boolean;
  canTransferMoney?: boolean;
  ownerMembershipStatus?: Partial<SelectorOption>[];
  underwritingChallengeScorePercentage?: string;
  filterDates?: FilterDates;
  riskStatusDisplayName?: Partial<SelectorOption>[];
  underwritingScorePercentage?: string;
  merchantRiskStatusDisplayName?: Partial<SelectorOption>[];
  isInOnboardingSection?: boolean;
  approvalStateName?: Partial<SelectorOption>[];
};
 
export type TransactionFilterValues = {
  emailStatus?: Array<RiskLevelType>;
  riskLevel?: Array<RiskLevelType>;
  createdAt?: string;
  outFlow?: string;
  inFlow?: string;
  cardInfoType?: string;
  txnDisplayStatus?: Array<RiskLevelType>;
  isFalsePositive?: boolean;
  isBlocked?: boolean;
  type?: Array<RiskLevelType>;
  processingState?: Array<RiskLevelType>;
  displayStatus?: Array<RiskLevelType>;
  displayName?: Array<RiskLevelType>;
  "class.displayName"?: Array<RiskLevelType>;
  processed?: string;
  transactionsCount?: string;
  approvedMerchants?: string;
  approvalStateName?: any[];
};
 
export type CustomRenderoption = {
  item: SelectorOption;
  selected: boolean;
};
 
export type FormFields =
  | "watchlist"
  | "parentName"
  | "totalProcessed"
  | "statusDisplayName"
  | "categoryCode"
  | "underwriterEmail"
  | "merchantName"
  | "caseType"
  | "createdAt"
  | "approvedAt"
  | "lastRiskActivityAt"
  | "lastEscalationAt"
  | "canProcessMoney"
  | "canTransferMoney"
  | "riskLevelLabelDisplayName"
  | "underwritingScorePercentage"
  | "riskStatusDisplayName"
  | "ownerMembershipStatus"
  | "underwritingChallengeScorePercentage"
  | "merchantRiskStatusDisplayName"
  | "isInOnboardingSection";
 
const excludeKeys = [
  "createdAt",
  "totalProcessed",
  "underwritingChallengeScorePercentage",
  "filterDates",
];
 
export const defaultFormValues: FormValues = {
  watchlist: undefined,
  parentName: [],
  totalProcessed: undefined,
  statusDisplayName: [],
  ownerMembershipStatus: undefined,
  categoryCode: [],
  createdAt: "",
  lastRiskActivityAt: "",
  lastEscalationAt: "",
  approvedAt: "",
  underwriterEmail: [],
  riskStatusDisplayName: [],
  underwritingScorePercentage: undefined,
  underwritingChallengeScorePercentage: undefined,
  canProcessMoney: undefined,
  canTransferMoney: undefined,
  merchantRiskStatusDisplayName: [],
  isInOnboardingSection: undefined,
};
 
interface customizeProps {
  joinKey?: string;
  extraJoinKey?: string; //to be use to handle a relationship specifically with the item BEFORE the 'beforeKey' value
  beforeKey?: string;
}
 
export function formatQueryParamsList(
  formValues: Partial<FormValues | TransactionFilterValues>,
  { joinKey = "%3B", extraJoinKey, beforeKey }: customizeProps = {},
) {
  const queryObjectList = [
    ...Object.entries(formValues).map(([key, value]) => ({
      [key]: Array.isArray(value) ? value.map((val) => val.value) : value,
    })),
  ];
  const formattedParamsList = queryObjectList.map((obj) => {
    const params = [];
 
    for (const [key, value] of Object.entries(obj)) {
      if (Array.isArray(value) && !isEmpty(value)) {
        value.forEach((val) => {
          const keyName = isSuspendedSelectedInRiskLevel(key, val)
            ? "statusDisplayName"
            : key;
          const isNot =
            typeof val === "string" && val[0] === "!" && val[1] === "=";
          const isNull = typeof val === "string" && val === "null";
          const paramString = isNot
            ? `${keyName}:!"${val.substring(2)}"`
            : isNull
            ? `${keyName}:null`
            : `${keyName}:"${val}"`;
          params.push(paramString);
        });
      } else Iif (isValueUseful(key, value)) {
        // Check if the value is a string, if so, include it directly
        params.push(
          excludeKeys.includes(key) || typeof value === "string"
            ? value
            : `${key}:"${value}"`,
        );
      }
    }
 
    return !isEmpty(params) ? `(${params.join(",")})` : "";
  });
  const filteredList = formattedParamsList.filter(Boolean);
  const extraJoinKeyIndex = beforeKey
    ? filteredList.findIndex((i) => i.includes(beforeKey)) - 1
    : undefined;
  return customJoinList(filteredList, joinKey, extraJoinKey, extraJoinKeyIndex);
}
 
export const customJoinList = (
  list: string[],
  joinKey: string,
  extraJoinKey?: string,
  extraJoinKeyIndex?: number,
) => {
  // Initialize the resulting array
  const result = [];
 
  // Iterate through the list and push each item to the results
  for (let i = 0; i < list.length; i++) {
    // Add the current item
    // the item before the extraJoinKey operator should be nested together with the one that has the extraJoinKey
    Iif (
      extraJoinKey &&
      extraJoinKeyIndex !== undefined &&
      i === extraJoinKeyIndex
    )
      result.push("(");
    result.push(list[i]);
 
    // If we are at the specified index, add the join key, otherwise if it's index before the last item add base join key
    Iif (extraJoinKey && extraJoinKeyIndex !== undefined) {
      if (i === extraJoinKeyIndex) result.push(extraJoinKey);
      else if (i === extraJoinKeyIndex + 1) result.push(`)${joinKey}`);
      //nesting should be finished after the extraJoinKey usage
      else if (i < list.length - 1) result.push(joinKey);
    } else Iif (i < list.length - 1) result.push(joinKey);
  }
 
  // Join the result array into a string without any additional keys
  return result.join("");
};
 
// for watchlist only: filter to be applied only when it's true but not for false
// for able to transfer/process: filter to be applied for true,false both but not for null
const isValueUseful = (keyName: any, value: any) => {
  Iif (keyName === "watchlist") {
    return value;
  }
  return !isEmpty(value) || isBoolean(value);
};
 
export const getDateValue = ({
  modifier,
  range,
  days,
  date,
  prefix = "createdAt",
}: {
  modifier:
    | "on"
    | "is on or after"
    | "is on or before"
    | "is between"
    | "in the last";
  range?: { startDate?: Date; endDate?: Date };
  days?: number;
  date?: Date;
  prefix?: string;
}) => {
  let value = "";
  if (modifier === "on" && date) {
    // Anchor start-of-day to ET so filter boundaries match platform timezone.
    const startOfDayET = zonedTimeToUtc(
      new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0),
      PLATFORM_TIMEZONE,
    );
    value = replaceValues(
      withAppendedKey.created["is on or after"].replace("createdAt", prefix),
      toUnixDateFormat(startOfDayET),
    );
  } else Iif (
    date &&
    (modifier === "is on or after" || modifier === "is on or before")
  ) {
    const startOfDayET = zonedTimeToUtc(
      new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0),
      PLATFORM_TIMEZONE,
    );
    value = replaceValues(
      withAppendedKey.created[modifier].replace("createdAt", prefix),
      toUnixDateFormat(new Date(startOfDayET.getTime() + 86400000)),
    );
  } else Iif (modifier === "is between" && range) {
    const startDate = range?.startDate;
    const endDate = range?.endDate;
    const startOfDayET = startDate
      ? zonedTimeToUtc(
          new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), 0, 0, 0, 0),
          PLATFORM_TIMEZONE,
        )
      : undefined;
    const endOfDayET = endDate
      ? zonedTimeToUtc(
          new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), 23, 59, 59, 0),
          PLATFORM_TIMEZONE,
        )
      : undefined;
    const first = startOfDayET
      ? replaceValues(
          withAppendedKey.created["is on or after"].replace(
            "createdAt",
            prefix,
          ),
          toUnixDateFormat(startOfDayET),
        )
      : undefined;
    const second = endOfDayET
      ? replaceValues(
          withAppendedKey.created["is on or before"].replace(
            "createdAt",
            prefix,
          ),
          toUnixDateFormat(endOfDayET),
        )
      : undefined;
    if (first && second) value = `${first}%3B${second}`;
    else if (first && !second) value = `${first}`;
    else if (!first && second) value = `${second}`;
  } else Eif (modifier === "in the last") {
    value = replaceValues(
      withAppendedKey.created[modifier].replace("createdAt", prefix),
      toUnixDateFormat(sub(new Date(), { days: days })),
    );
  }
  return value;
};
 
export const getProcessingAmount = ({
  amount,
  secondAmount,
  modifier,
  prefix = "totalProcessed",
}: {
  amount?: number;
  secondAmount?: number;
  modifier:
    | "is between"
    | "greater than"
    | "is equal to or greater than"
    | "is equal to or less than";
  prefix?: string;
}) => {
  let value = "";
  if (modifier === "is between") {
    const first = replaceValues(
      withAppendedKey.totalProcessed["is equal to or greater than"].replace(
        "totalProcessed",
        prefix,
      ),
      amount,
    );
    const second = replaceValues(
      withAppendedKey.totalProcessed["is equal to or less than"].replace(
        "totalProcessed",
        prefix,
      ),
      secondAmount,
    );
 
    const hasBothAmounts =
      typeof amount === "number" && typeof secondAmount === "number";
    const hasOnlyFirstAmount =
      typeof amount === "number" && typeof secondAmount !== "number";
    const hasOnlySecondAmount =
      typeof amount !== "number" && typeof secondAmount === "number";
 
    if (hasBothAmounts) value = `${first}%3B${second}`;
    else Eif (hasOnlyFirstAmount) value = `${first}`;
    else if (hasOnlySecondAmount) value = `${second}`;
  } else Eif (amount !== undefined)
    value = replaceValues(
      withAppendedKey.totalProcessed[modifier].replace(
        "totalProcessed",
        prefix,
      ),
      amount,
    );
  return value;
};
 
export const getCustomProcessingLabel = (
  from?: number,
  to?: number,
  isMoney?: boolean,
) => {
  const suffix = isMoney ? " USD" : "";
 
  const hasFromAndTo = typeof from === "number" && typeof to === "number";
  const hasOnlyFrom = typeof from === "number" && typeof to !== "number";
  const hasOnlyTo = typeof from !== "number" && typeof to === "number";
 
  Iif (hasFromAndTo) return `Custom: ${from} - ${to} ${suffix}`;
  else Iif (hasOnlyFrom) return `Custom: > ${from} ${suffix}`;
  else Iif (hasOnlyTo) return `Custom: < ${to} ${suffix}`;
  else return "Custom";
};
 
export const generateCustomLabel = ({
  startDate,
  endDate,
  showColon = true,
}: {
  startDate: number | Date | undefined;
  endDate: number | Date | undefined;
  showColon?: boolean;
}) => {
  const formatDate = (date: number | Date) => {
    if (typeof date === "number") {
      return moment.unix(date).tz(PLATFORM_TIMEZONE).format("DD MMM YYYY");
    } else if (date instanceof Date) {
      return moment(date).tz(PLATFORM_TIMEZONE).format("DD MMM YYYY");
    }
    return "";
  };
 
  const starterCharacter = showColon ? ": " : "";
 
  Iif (endDate && startDate && formatDate(startDate) === formatDate(endDate)) {
    return `${starterCharacter}${formatDate(startDate)}`;
  } else Iif (endDate && startDate) {
    return `${starterCharacter}${formatDate(startDate)} - ${formatDate(
      endDate,
    )}`;
  } else Iif (startDate && !endDate) {
    return `${starterCharacter}${formatDate(startDate)}`;
  }
 
  return "";
};
export const UnderwritingScoreValues = {
  belowEighty: "underwritingChallengeScorePercentage:<80",
  overEighty: "underwritingChallengeScorePercentage:>80",
};
 
const isSuspendedSelectedInRiskLevel = (key: string, value: string) =>
  key === "riskLevelLabelDisplayName" && value === "Suspended";
 
export const mapRange = (rangeString: string): string => {
  if (rangeString === "0 USD") {
    return "0";
  }
 
  const match = rangeString.match(/^(\d+)\s+-\s+(\d+) USD$/);
 
  if (match) {
    const min = parseInt(match[1], 10);
    const max = parseInt(match[2], 10);
    return `>${min - 1};<${max + 1}`;
  }
 
  const greaterMatch = rangeString.match(/>(\d+) USD/);
 
  if (greaterMatch) {
    const min = parseInt(greaterMatch[1], 10);
    return `>${min}`;
  }
 
  return "custom";
};