All files / src/features/GiveRiskProfile/Overview/components RiskActivityCard.tsx

69.04% Statements 58/84
60% Branches 63/105
47.05% Functions 8/17
69.62% Lines 55/79

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                                                                                                                                                              53x                               14x   14x 14x 14x 14x   14x     14x   14x         14x                               14x   14x   14x 14x 14x         14x 14x     14x 14x   14x       14x                 14x 14x 14x 14x 14x 14x 14x     14x     14x       14x   14x             14x       14x                 14x 14x 14x       14x               14x                                     14x           14x   14x 14x     14x                                                                                                                                                                                                                 14x   14x                                                                                                                                                                                                                                                                                                     53x               53x           53x 81x 14x                     53x 53x                                               53x                       53x                            
import {
  cardIconsMap,
  GiveTransactionStatus,
} from "@features/MerchantPortal/ManageMoney/ManageMoneyTable.atoms";
import { Box, Stack } from "@mui/material";
import GiveText from "@shared/Text/GiveText";
import { styled, useAppTheme } from "@theme/v2/Provider";
import { parseAmount } from "@utils/index";
import { CustomerEmailStatus, EmailStatusType } from "./atoms";
import GiveChip, { TChipColors } from "@shared/Chip/GiveChip";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import ContextualMenu from "@shared/ContextualMenu/ContextualMenu";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { Dispatch, useState } from "react";
import {
  CaretDownIcon,
  CaretUpIcon,
  CheckIcon,
  WarningDiamondIcon,
  ArrowBendUpRightIcon,
  DotsThreeIcon,
  InfoIcon,
  ArrowsLeftRightIcon,
} from "@phosphor-icons/react";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import {
  ENHANCED_REFUND_MODAL,
  MANAGE_MONEY_INFO_MODAL,
  MERCHANT_PORTAL_MARK_AS_FRAUD_V2,
  TRANSACTION_INFO_MODAL,
} from "modals/modal_names";
import { useFalsePositive } from "@features/TransactionPanel/hooks/useFalsePositive";
import {
  getTransactionStatus,
  TransactionStatus,
} from "@features/TransactionPanel/utils";
import { useRefund } from "@features/TransactionPanel/hooks/useRefund";
import {
  composePermission,
  useAccessControl,
} from "@features/Permissions/AccessControl";
import RESOURCE_BASE, {
  NEW_ACTION_DENY_MESSAGE,
  OPERATIONS,
} from "@constants/permissions";
import { checkPortals } from "@utils/routing";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { useTransactionAllow } from "@features/GiveRiskProfile/hooks/useTransactionAllow";
import { CURRENCY } from "@constants/constants";
import { useGetCurrentMerchantId } from "@hooks/common";
import { TTransaction } from "@features/TransactionPanel/types";
 
type Props = {
  date: string;
  name: string;
  card: {
    cardBrand: string;
    last4: string;
    cardHolder: string;
    email: string;
    emailStatus: EmailStatusType;
  };
  reversalState: string;
  charged: number;
  status: TChipColors;
  showCards?: boolean;
  data: any;
  setSelectedRow?: Dispatch<any>;
  isFirst?: boolean;
  isLast?: boolean;
  displayStatus?: string;
  statusObject?: any;
  itemId?: string;
  isEscalation?: boolean;
  openMainPanel?: (transaction: TTransaction) => void;
};
 
type ChipStatus = "blocked" | "false_positive" | "allowed";
 
const RiskActivityCard = ({
  card,
  charged,
  date,
  name,
  itemId = "",
  showCards,
  statusObject,
  data, //this is the full, original item as it comes from BE, without any parsing.
  isFirst,
  isLast,
  reversalState,
  setSelectedRow,
  isEscalation,
  openMainPanel,
}: Props) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const { isEnterprisePortal, isAcquirerManageMoney, isProviderManageMoney } =
    checkPortals();
  const { isMobileView } = useCustomThemeV2();
  const { name: selectedAccountName } = useGetCurrentMerchantId();
  const theme = useAppTheme();
  const usedModalKey =
    isAcquirerManageMoney || isProviderManageMoney
      ? MANAGE_MONEY_INFO_MODAL
      : TRANSACTION_INFO_MODAL;
  const { show } = useModal(usedModalKey);
 
  const handleDotsClick = (e: React.MouseEvent<HTMLElement>) => {
    e.stopPropagation();
    setAnchorEl(e.currentTarget);
  };
 
  const onCloseMenu = (e?: React.MouseEvent<HTMLElement>) => {
    e?.stopPropagation?.();
    setAnchorEl(null);
  };
  const {
    //binInfo: { currencyCode = "USD" } = {}, for now we are using USD only for refunds
    dstAccID,
    srcAccID,
    amount = "",
    isQuarantined,
    parentMerchantName,
    isManuallyCaptured,
    isFalsePositive: isFalsePositiveBool,
    isOriginalTransactionBlocked,
    typeName,
    merchantAccID,
  } = data || {};
 
  const { status, processingStateName, displayStatus } = statusObject;
 
  const transactionStatusName = (() => {
    Iif (isQuarantined) return "Quarantined";
    Iif (
      !isQuarantined &&
      processingStateName === TransactionStatus.AUTHORIZED.toLowerCase()
    )
      return "Authorized";
    Iif (displayStatus === "Pre-Chargeback Refund") return "Chargeback Refund";
    else return displayStatus;
  })();
 
  const isBlocked = status === "blocked";
  const isFalsePositive = status === "false_positive";
  const isAllowed =
    isManuallyCaptured &&
    !isFalsePositive &&
    !isBlocked &&
    processingStateName === "captured";
  const usedStatus = isAllowed ? "allowed" : status;
 
  const {
    isChargeback,
    isCaptured,
    isVoided,
    isRefund,
    isPrechargebackRefund,
    isDeclined,
  } = getTransactionStatus(transactionStatusName);
  const isSettled = status === TransactionStatus.SETTLED.toLowerCase();
  const isAuthorized = status === TransactionStatus.AUTHORIZED.toLowerCase();
  const isVoidable = isAuthorized || isCaptured || isQuarantined;
  const isFullyReversed = reversalState === "fully_reversed";
  const isPurchase = typeName === "purchase";
  const isOriginalBlocked = isOriginalTransactionBlocked && !isPurchase;
 
  //action logic checks
  const isThreeDots = !isFalsePositive && !isAllowed && !isBlocked;
 
  const hideRefund =
    isVoided || isRefund || isChargeback || isPrechargebackRefund || isDeclined;
 
  //permission checks
  const isStatusUpdateDisabled =
    isEnterprisePortal && selectedAccountName !== parentMerchantName;
 
  const isUnblockAllowed = useAccessControl({
    resource: composePermission(
      RESOURCE_BASE.MERCHANT,
      RESOURCE_BASE.TRANSACTION_UNBLOCK,
    ),
    operation: OPERATIONS.UPDATE,
  });
  const isVoidedAllowed = useAccessControl({
    resource: composePermission(RESOURCE_BASE.MERCHANT, RESOURCE_BASE.REFUND),
    operation: OPERATIONS.CREATE,
  });
  const isBlockAllowed = useAccessControl({
    resource: composePermission(
      RESOURCE_BASE.MERCHANT,
      RESOURCE_BASE.TRANSACTION_BLOCK,
    ),
    operation: OPERATIONS.UPDATE,
  });
 
  //action hooks
  const { handleFalsePositive } = useFalsePositive(merchantAccID, itemId);
  const { handleMarkAllow } = useTransactionAllow(merchantAccID, itemId);
  const { handleRefund: handleRefundMutation } = useRefund({
    ids: { transactionIDs: [itemId] },
  });
 
  const refundTooltip = isFullyReversed
    ? "The transaction has already been refunded."
    : "This transaction has already been partially refunded.";
 
  //chip color logic
  const chipIconColors: Record<
    ChipStatus,
    { textColor?: string; bg?: string; text: string }
  > = {
    blocked: {
      textColor: theme.palette.primitive?.error[100],
      bg: theme.palette.primitive?.error[25],
      text: "Suspected",
    },
    false_positive: {
      textColor: theme.palette.primitive?.success?.[100],
      bg: theme.palette.primitive?.success?.[25],
      text: "False Positive",
    },
    allowed: {
      textColor: theme.palette.primitive?.success?.[100],
      bg: theme.palette.primitive?.success?.[25],
      text: "Allowed",
    },
  };
 
  // if status comes from outside, assert or narrow it
  const safeStatus = (
    ["blocked", "false_positive", "allowed"] as const
  ).includes(usedStatus as any)
    ? (usedStatus as ChipStatus)
    : "false_positive";
 
  const { textColor, bg } = chipIconColors[safeStatus];
 
  const isPartiallyRefunded = data?.ReversalState === "partially_reversed";
  const hideSuspect = isBlocked || Boolean(isOriginalBlocked);
 
  //3dot and dropdown actions
  const actions = [
    {
      IconRight: ArrowBendUpRightIcon,
      text: isVoidable ? "Void" : "Refund",
      onClick: () => {
        setAnchorEl(null);
        NiceModal.show(ENHANCED_REFUND_MODAL, {
          customerName: card?.cardHolder,
          customerEmail: card.email,
          cardName: card.cardBrand,
          cardLast4: card.last4,
          isVoidable,
          amount,
          currency: CURRENCY,
          transactionID: itemId,
          isNotSettled: !(isSettled && !isRefund) && !isVoidable,
          actions: {
            handleSuccess: {
              onClick: (refundData?: any) => {
                handleRefundMutation({
                  fullTransaction: refundData.total,
                  refundIDs: refundData.refundIDs,
                  reason: refundData.reason,
                  notifyCustomer: refundData?.notifyCustomer,
                  amount: refundData?.amount,
                });
              },
            },
          },
          isPartiallyRefunded,
        });
      },
      hidden: hideRefund || isFullyReversed,
      tooltipTitle: NEW_ACTION_DENY_MESSAGE,
      disabled: !isVoidedAllowed || isStatusUpdateDisabled,
      disableTooltip: isVoidedAllowed && !isStatusUpdateDisabled,
    },
    {
      IconRight: WarningDiamondIcon,
      text: "Suspect",
      onClick: () => {
        setAnchorEl(null);
        NiceModal.show(MERCHANT_PORTAL_MARK_AS_FRAUD_V2, {
          transactionId: [itemId],
          isFirst,
          isLast,
          setSelectedRow,
        });
      },
      hidden: hideSuspect,
      tooltipTitle: NEW_ACTION_DENY_MESSAGE,
      disabled: !isBlockAllowed || isStatusUpdateDisabled,
      disableTooltip: isBlockAllowed && !isStatusUpdateDisabled,
    },
    {
      IconRight: CheckIcon,
      text: "Mark as False Positive",
      onClick: () => {
        setAnchorEl(null);
        handleFalsePositive();
      },
      hidden: !hideSuspect || isFalsePositiveBool,
      tooltipTitle: NEW_ACTION_DENY_MESSAGE,
      disabled: !isUnblockAllowed || isStatusUpdateDisabled,
      disableTooltip: isUnblockAllowed && !isStatusUpdateDisabled,
    },
    {
      IconRight: CheckIcon,
      text: "Allow",
      onClick: () => {
        setAnchorEl(null);
        handleMarkAllow();
      },
      hidden: !isQuarantined,
      tooltipTitle: NEW_ACTION_DENY_MESSAGE,
      disabled: !isUnblockAllowed || isStatusUpdateDisabled,
      disableTooltip: isUnblockAllowed && !isStatusUpdateDisabled,
    },
    {
      IconRight: ArrowsLeftRightIcon,
      text: "Purchase Info",
      onClick: () => {
        setAnchorEl(null);
        const modalData = {
          ...data,
          objID: data?.id,
          destinationAccount: { id: dstAccID },
          sourceAccount: { id: srcAccID },
        };
 
        if (openMainPanel) {
          openMainPanel(modalData);
          return;
        }
 
        show({
          data: modalData,
          setSelectedRow: undefined, //if its undefined buttons will be hidden
          isFirst: undefined,
          isLast: undefined,
          secondPanelType: null,
        });
      },
    },
  ];
  const showCaret = actions.some((action) => !action.hidden);
 
  return (
    <>
      <CardWrapper>
        <Container isEscalation={isEscalation}>
          <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
          >
            <GiveText variant="bodyXS" color="secondary">
              {date}
            </GiveText>
            <GiveText variant="bodyXS">{name}</GiveText>
          </Box>
 
          <DetailsContainer>
            <Stack spacing={1}>
              <Stack direction="row" spacing={1} alignItems="center">
                {cardIconsMap()[card?.cardBrand as keyof typeof cardIconsMap]}
                <GiveText variant="bodyS">
                  {card?.last4} - {card?.cardHolder}
                </GiveText>
              </Stack>
              <Stack
                direction="row"
                spacing={0.5}
                alignItems="center"
                sx={{
                  maxWidth: "100%",
                  overflow: "hidden",
                }}
              >
                <GiveText
                  variant="bodyXS"
                  color="secondary"
                  sx={{
                    whiteSpace: "nowrap",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    display: "block",
                    maxWidth: isMobileView ? "30%" : "250px",
                  }}
                  title={card?.email}
                >
                  {card?.email}
                </GiveText>
                <CustomerEmailStatus
                  emailStatus={card?.emailStatus as EmailStatusType}
                />
              </Stack>
            </Stack>
 
            <StatusChargedContainer>
              <GiveText variant="bodyS">
                {isVoided ? "0.00" : parseAmount(charged)} USD
              </GiveText>
 
              <Stack
                alignItems="center"
                direction={isMobileView ? "row-reverse" : "row"}
                spacing={1}
              >
                {Boolean(reversalState && !hideRefund) && (
                  <GiveTooltip
                    title={`${refundTooltip} It may appear at the top because the refund occurred at a different time.`}
                  >
                    <GiveIconButton variant="ghost" Icon={InfoIcon} />
                  </GiveTooltip>
                )}
                {isThreeDots ? (
                  <GiveIconButton
                    variant="ghost"
                    Icon={DotsThreeIcon}
                    onClick={handleDotsClick}
                  />
                ) : (
                  <>
                    {labels?.[usedStatus] && (
                      <GiveChip
                        onClick={showCaret ? handleDotsClick : undefined}
                        label={
                          <Stack direction="row" gap={0.5} alignItems="center">
                            <GiveText
                              variant="bodyXS"
                              sx={{ color: textColor, lineHeight: "14px" }}
                            >
                              {labels?.[usedStatus]}
                            </GiveText>
                            {showCaret &&
                              (anchorEl ? (
                                <CaretUpIcon size={16} />
                              ) : (
                                <CaretDownIcon size={16} />
                              ))}
                          </Stack>
                        }
                        variant="light"
                        sx={{
                          boxShadow: "none !important",
                          background: bg,
                        }}
                      />
                    )}
                  </>
                )}
 
                <GiveTransactionStatus
                  status={
                    (transactionStatusName
                      ? transactionStatusName.toLocaleLowerCase()
                      : processingStateName) as TChipColors
                  }
                  label={transactionStatusName}
                  sx={{
                    borderRadius: "8px",
                    padding: "4px 8px",
                    height: "24px",
                    "& span": {
                      fontSize: "12px",
                      lineHeight: "14px !important",
                    },
                  }}
                />
              </Stack>
            </StatusChargedContainer>
          </DetailsContainer>
        </Container>
 
        {showCards && (
          <Stack width="100%" alignItems="center">
            <CardShadow isFirst />
            <CardShadow />
          </Stack>
        )}
      </CardWrapper>
 
      <ContextualMenu
        handleClose={onCloseMenu as any}
        anchorEl={anchorEl}
        color={isMobileView ? "primary" : "tertiary"}
        texture={isMobileView ? "solid" : "blurred"}
        options={actions}
      />
    </>
  );
};
 
const labels: Record<string, string> = {
  blocked: "Suspected",
  false_positive: "False Positive",
  allowed: "Allowed",
  //approved: "Settled",
  //failed: "Error",
};
 
const CardWrapper = styled("div")({
  position: "relative",
  display: "inline-block",
  width: "100%",
});
 
const Container = styled(Box, {
  shouldForwardProp: (prop) => prop !== "isEscalation", // prevents passing it to DOM
})<{ isEscalation?: boolean }>(({ theme, isEscalation }) => ({
  padding: "20px",
  display: "flex",
  flexDirection: "column",
  gap: "12px",
  background: theme.palette.surface?.primary,
  borderRadius: isEscalation ? "12px" : "20px",
  position: "relative",
  zIndex: 20,
}));
 
const CardShadow = styled(Box, {
  shouldForwardProp: (prop) => prop !== "isFirst",
})<{
  isFirst?: boolean;
}>(({ theme, isFirst }) => {
  const surfacePrimary = theme.palette.surface?.primary;
  const surfaceInvert = "rgba(0,0,0,0.05)";
  const darken = theme.palette.primitive?.transparent?.["darken-10"];
 
  return {
    height: "8px",
    borderBottomLeftRadius: "20px",
    borderBottomRightRadius: "20px",
    opacity: 0.9,
    zIndex: isFirst ? 1 : 0,
    width: isFirst ? "92%" : "84%",
    background: `
      linear-gradient(0deg, ${surfaceInvert}, transparent 100%),
      linear-gradient(180deg, ${darken}, transparent 130%),
      ${surfacePrimary}
    `,
    boxShadow: "0px 3px 15px 0px rgba(161, 175, 180, 0.10)",
  };
});
 
const DetailsContainer = styled(Box)(({ theme }) => ({
  borderTop: `1px solid ${theme.palette.border?.primary}`,
  paddingTop: "12px",
  display: "flex",
  justifyContent: "space-between",
  alignItems: "center",
  [theme.breakpoints.down("v2_sm")]: {
    flexDirection: "column",
    alignItems: "flex-start",
  },
}));
 
const StatusChargedContainer = styled(Box)(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  gap: "8px",
  alignItems: "flex-end",
  [theme.breakpoints.down("v2_sm")]: {
    width: "100%",
    flexDirection: "row-reverse",
    justifyContent: "space-between",
    marginTop: "12px",
  },
}));
 
export default RiskActivityCard;