All files / src/features/TransactionPanel/hooks useTransactionSummary.tsx

84.9% Statements 90/106
72.8% Branches 91/125
78.57% Functions 11/14
88.88% Lines 88/99

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                                                            53x                         169x               169x 169x 169x   169x     169x   169x         169x   169x 169x 169x   169x 169x   169x 169x 169x     169x   169x 169x 169x   169x 169x   169x             169x           169x           169x 169x 169x     169x                             169x         169x   169x 169x         169x   169x 169x             169x       169x           169x                 169x   169x     169x             169x             169x                           169x       169x     169x 59x 59x 59x               141x 60x 81x 4x   141x       59x     169x 59x 59x   59x   141x 60x   141x       59x     169x     169x 59x 59x   59x   141x     141x       59x       169x                     169x 59x 59x 59x 59x   53x   125x 121x   125x       53x     169x               169x 157x                                                                       169x                                                
import { useMemo } from "react";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { checkPortals } from "@utils/routing";
import {
  getTransactionLineItems,
  TransactionSummarySection,
} from "../helpers/getTransactionLineItems";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import {
  MANAGE_MONEY_INFO_MODAL,
  TRANSACTION_INFO_MODAL,
} from "modals/modal_names";
import { useEnterprisePermissions } from "@components/AcquirerEnterprises/CreateEnterprise/hooks/useEnterprisePermissions";
import { shouldBeHidden } from "@constants/constants";
import { useAccessControl } from "@features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import { useFormatDateInTimezone } from "@utils/date.helpers";
import { MERCHANT_PREVIEW_PANEL_MODAL } from "modals/modal_names";
import {
  feesArray,
  moveFundsArray,
} from "@components/ManageMoney/TransactionTable/transactions.types";
import { getDisplayStatusPortal } from "@components/ManageMoney/TransactionTable/transactions.helpers";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { TransactionSidePanelType } from "../types";
import { TransactionStatus } from "@features/TransactionPanel/shared.types";
import { processorMap } from "@features/Merchants/MerchantSidePanel/constants";
import { ProcessorValue } from "@features/Merchants/MerchantSidePanel/types";
import { MerchantAccountType } from "types/merchant.preview.types";
 
export const useTransactionSummary = ({
  data,
  handleSidePanelOpen,
  handleOpenMerchant,
  isRevenueSection,
  isManageMoneyPanel,
}: {
  data: any;
  handleSidePanelOpen?: (type: TransactionSidePanelType) => void;
  isRevenueSection?: boolean;
  isManageMoneyPanel?: boolean;
  handleOpenMerchant?: (modalType: MerchantAccountType, id: string) => void;
}) => {
  const { isMobileView, isMediumView } = useCustomThemeV2();
  const {
    isAcquirerPortal,
    isEnterprisePortal,
    isMerchantPortal,
    isAcquirerManageMoney,
    isProviderManageMoney,
    isDisputes,
  } = checkPortals();
  const { risk_monitoring } = useEnterprisePermissions();
  const { isMerchantProcessorEnabled } = useGetFeatureFlagValues();
  const modalKey =
    isAcquirerManageMoney || isProviderManageMoney
      ? MANAGE_MONEY_INFO_MODAL
      : TRANSACTION_INFO_MODAL;
  const { hide, show, args } = useModal(modalKey);
 
  const portalType = isAcquirerPortal
    ? "acquirer"
    : isEnterprisePortal
    ? "provider"
    : "merchant";
  const transactionType = data?.status as TransactionStatus;
  const isPreChargebackRefund =
    transactionType === TransactionStatus.PRE_CHARGEBACK_REFUND;
  const isRefunded = transactionType === TransactionStatus.REFUNDED;
  const isChargeback = transactionType === TransactionStatus.CHARGEBACK;
  const isChargebackReversal =
    transactionType === TransactionStatus.CHARGEBACK_REVERSAL;
  const isTransferFunds = moveFundsArray.includes(data?.transactionType);
  const isTransfer =
    data?.displayType === TransactionStatus.MONEY_TRANSFER || isTransferFunds;
  const isDeclined = data?.displayStatus === TransactionStatus.DECLINED;
  const isError = data?.displayStatus === TransactionStatus.ERROR;
 
  const isPurchase =
    !isRefunded && !isChargeback && !isChargebackReversal && !isTransfer;
 
  const isMarkedAsFraud = data?.isBlocked;
  const isFalsePositive = data?.isFalsePositive;
  const isFees = feesArray.includes(data?.transactionType || "");
 
  const ipProfileID = data?.ipProfileID;
  const isRiskLevelHidden = Boolean(!isTransfer && !isFees);
  const isRiskHeaderVisible =
    !shouldBeHidden.riskProfile &&
    (shouldBeHidden.enterpriseConfiguration
      ? isAcquirerPortal
      : risk_monitoring && !isMerchantPortal) &&
    !!ipProfileID &&
    isRiskLevelHidden;
 
  const canViewIP = useAccessControl({
    resource: RESOURCE_BASE.IPPROFILE,
    operation: OPERATIONS.LIST,
    withPortal: true,
  });
 
  const canViewTransactionList = useAccessControl({
    resource: RESOURCE_BASE.IPPROFILE_TRANSACTION,
    operation: OPERATIONS.LIST,
    withPortal: true,
  });
 
  const hasBalance = typeof data?.balanceAdjustment === "number";
  const isTransferSent = isTransfer && data?.processingState === "settled";
  const status = getDisplayStatusPortal(data);
 
  const isExcludedStatus =
    [
      TransactionStatus.CAPTURED,
      TransactionStatus.QUARANTINED,
      TransactionStatus.VOIDED,
      TransactionStatus.AUTHORIZED,
      TransactionStatus.DECLINED,
      TransactionStatus.REFUND_PENDING,
      TransactionStatus.REFUND_CANCELED,
      TransactionStatus.REFUND_DECLINED,
      TransactionStatus.REFUND_ERROR,
      TransactionStatus.PENDING,
    ].includes(status as TransactionStatus) ||
    (isAcquirerPortal && isChargebackReversal);
 
  const showEndingBalance =
    !isMobileView &&
    typeof data?.endingBalance === "number" &&
    ((!isTransfer && !isExcludedStatus) || isTransferSent) &&
    !(isTransferFunds && !isMerchantPortal);
 
  const { formatInTimezone } = useFormatDateInTimezone();
  const createdAt =
    data?.createdAt === "number" ? data?.createdAt : data?.createdAtTimestamp;
  const rawFormattedCreatedAt = formatInTimezone(
    createdAt,
    "MMM dd, yyyy, HH:mm",
  );
  const formattedCreatedAt: string | undefined =
    rawFormattedCreatedAt != null ? String(rawFormattedCreatedAt) : undefined;
 
  const isFromProvider = data?.sourceAccount?.user?.type === "enterprise";
  const isTransferFromProvider = isFromProvider && isTransfer;
 
  // The acquirer owning a transfer surfaces differently per endpoint: the
  // transaction read endpoint resolves it into `merchant` (source account first),
  // while the transfers endpoint only maps the owner account type onto
  // `sourceAccount.user.type` (see parseTransfer).
  const isFromAcquirer =
    data?.sourceAccount?.user?.type === "acquirer" ||
    data?.sourceAccount?.merchant?.type === "acquirer" ||
    data?.merchant?.type === "acquirer";
 
  const destinationMerchantType = data?.destinationAccount?.merchant?.type;
  // GB-21366: a transfer landing on a merchant account carries merchant and
  // provider details. GB-21607: an acquirer transfer to its own bank account
  // lands back on the acquirer account, so it has none to show — same for an
  // acquirer-to-provider transfer (NAC018).
  const isAcquirerToMerchant =
    isFromAcquirer &&
    isTransfer &&
    Boolean(destinationMerchantType) &&
    destinationMerchantType !== "acquirer" &&
    destinationMerchantType !== "enterprise";
 
  // Acquirer moving its own funds: hide the merchant/provider block entirely so
  // the transaction details start with the revenue section.
  const isAcquirerTransfer =
    isFromAcquirer && isTransfer && !isAcquirerToMerchant;
 
  const isReconciliation = data?.transactionType === "reconciliation_credit";
 
  const merchant =
    isReconciliation || isAcquirerToMerchant
      ? {
          ...data?.destinationAccount?.merchant,
          accID: data?.destinationAccount?.id,
        }
      : data?.merchant;
 
  const merchantAccount = {
    name: merchant?.name || data?.merchantName,
    id: merchant?.accID || data?.merchAccID,
    modalType: MERCHANT_PREVIEW_PANEL_MODAL,
    deleted: merchant?.deletedAt ? true : false,
  };
 
  const providerAccount = {
    name: isTransferFromProvider
      ? merchant?.name
      : merchant?.parentName || data?.parentName,
    id: isTransferFromProvider
      ? merchant?.accID
      : merchant?.parentAccID || data?.parentAccID,
    modalType: MERCHANT_PREVIEW_PANEL_MODAL,
    deleted: !!(isFromProvider
      ? merchant?.deletedAt
      : merchant?.parentDeletedAt),
  };
 
  const hasNoRevenue =
    data?.processingState === "processing_issue" &&
    ["purchase", "refund"].includes(data?.transactionType);
 
  const hasNoAmount =
    data?.processingState === "processing_issue" &&
    ["refund"].includes(data?.transactionType);
 
  const providerRevenue = useMemo(() => {
    Iif (hasNoRevenue) return 0;
    const feeItems = data?.feeItems || [];
    const { merchantToProviderFees, providerToAcquirerFees } = feeItems.reduce(
      (
        acc: {
          merchantToProviderFees: number;
          providerToAcquirerFees: number;
        },
        curr: any,
      ) => {
        if (curr.destinationAccount?.merchant?.type === "enterprise") {
          acc.merchantToProviderFees += curr.price;
        } else if (curr.sourceAccount?.merchant?.type === "enterprise") {
          acc.providerToAcquirerFees += curr.price;
        }
        return acc;
      },
      { merchantToProviderFees: 0, providerToAcquirerFees: 0 },
    );
    return (merchantToProviderFees - providerToAcquirerFees) / 100;
  }, [data?.feeItems, hasNoRevenue]);
 
  const acquirerRevenue = useMemo(() => {
    Iif (hasNoRevenue) return 0;
    const feeItems = data?.feeItems || [];
 
    const { acquirerFees } = feeItems.reduce(
      (acc: { acquirerFees: number }, curr: any) => {
        if (curr.destinationAccount?.merchant?.type === "acquirer") {
          acc.acquirerFees += curr.price;
        }
        return acc;
      },
      { acquirerFees: 0 },
    );
    return acquirerFees / 100;
  }, [data?.feeItems, hasNoRevenue]);
 
  const interchangeFeesPaid = data?.interchangeFees / 100;
 
  // Update : 12 Jan 2026 : chargeback Fee is calculated based on the feeItems where the type is chargeback_fee
  const chargebackRevenue = useMemo(() => {
    Iif (hasNoRevenue) return 0;
    const feeItems = data?.feeItems || [];
 
    const { chargebackFees } = feeItems.reduce(
      (acc: { chargebackFees: number }, curr: any) => {
        Iif (curr.type === "chargeback_fee") {
          acc.chargebackFees += curr.price;
        }
        return acc;
      },
      { chargebackFees: 0 },
    );
    return chargebackFees / 100;
  }, [data?.feeItems, hasNoRevenue]);
 
  const openModalHandler =
    (modalType: string, id: string, type: MerchantAccountType) => () => {
      hide();
      if (handleOpenMerchant) {
        handleOpenMerchant(type, id);
        return;
      }
      NiceModal.show(modalType, {
        id,
        onCloseCallback: !isDisputes ? () => show(args) : undefined,
      });
    };
  const chargebackReversalCustomerFees = useMemo(() => {
    Iif (hasNoRevenue) return 0;
    const feeItems = data?.feeItems || [];
    const cost = data?.cost;
    if (data?.passFees) return cost;
 
    const { chargebackReversalFees } = feeItems.reduce(
      (acc: { chargebackReversalFees: number }, curr: any) => {
        if (curr.type === "processing_fee") {
          acc.chargebackReversalFees += curr.price;
        }
        return acc;
      },
      { chargebackReversalFees: 0 },
    );
    return cost + chargebackReversalFees / 100;
  }, [data?.feeItems, hasNoRevenue]);
 
  const openRiskModal = () => {
    if (!canViewIP && !canViewTransactionList) return;
    if (handleSidePanelOpen) {
      handleSidePanelOpen("risk");
      return;
    }
  };
 
  const section: TransactionSummarySection = useMemo(() => {
    return getTransactionLineItems(data, {
      isRefunded,
      isPreChargebackRefund,
      isChargeback,
      isChargebackReversal,
      isTransfer,
      portalType,
      isMobileView,
      formattedCreatedAt,
      merchantAccount,
      isTransferFromProvider,
      isAcquirerToMerchant,
      providerAccount,
      providerRevenue: providerRevenue,
      merchantRevenue: hasNoRevenue
        ? 0
        : Number((data?.charged - data?.fees).toFixed(2)),
      acquirerRevenue: acquirerRevenue,
      chargebackRevenue,
      chargebackReversalCustomerFees,
      interchangeFeesPaid,
      openModalHandler,
      isFees,
      hasNoRevenue,
      hasNoAmount,
      isManageMoneyPanel,
      isRevenueSection,
      processor: data?.processorName
        ? processorMap[data.processorName as ProcessorValue]
        : "-",
      showProcessor:
        (isAcquirerPortal && isMerchantProcessorEnabled) ||
        isAcquirerToMerchant,
    });
  }, [data]);
 
  return {
    section,
    isDeclined,
    isError,
    isChargeback,
    isRefunded,
    isPreChargebackRefund,
    isChargebackReversal,
    isTransfer,
    isPurchase,
    isFees,
    isMarkedAsFraud,
    isFalsePositive,
    isRiskHeaderVisible,
    hasBalance,
    showEndingBalance,
    openRiskModal,
    merchantAccount,
    providerAccount,
    formattedCreatedAt,
    isAcquirerToMerchant,
    isAcquirerTransfer,
  };
};