All files / src/components/ManageMoney/TransactionTable/TransactionInfoModal hooks.ts

66.17% Statements 45/68
58.2% Branches 39/67
61.11% Functions 11/18
66.15% Lines 43/65

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                                      52x     367x   52x           367x 367x   367x               367x               367x   36x           32x         367x   367x               367x                                       367x 367x                           367x       367x               367x                                       367x 79x   26x     26x       26x       26x                   367x 79x   26x 26x       26x         367x   367x     367x 53x             367x         367x 185x       367x                                       367x   199x         367x           367x                             52x                           52x                                      
import { TagType } from "@common/Tag/TransactionTableTag";
import { useEffect, useMemo, useState } from "react";
import { showMessage } from "@common/Toast";
import { getStatus, getTransaction } from "./utils";
import { checkPortals } from "@utils/routing";
import {
  composePermission,
  useAccessControl,
} from "features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import { useQuery } from "react-query";
import { QKEY_GET_TRANSACTIONS_HISTORY } from "@constants/queryKeys";
import { TransactionTableRowParsed } from "../transactions.types";
import { parseTransfer } from "../transactions.helpers";
import { TChildTransaction } from "@features/TransactionPanel/types";
 
type TransferTransaction = ReturnType<typeof parseTransfer>;
type TransactionData = TransactionTableRowParsed | TransferTransaction;
 
const isTransactionTableRowParsed = (
  txn: TransactionData | undefined,
): txn is TransactionTableRowParsed =>
  Boolean(txn) && "originalTransactionID" in txn;
 
export const useTransactionHistory = (
  id?: string,
  isHistoryEnabled?: boolean,
  updatedData?: any,
  isModalVisible?: boolean,
) => {
  const [currentTab, setCurrentTab] = useState<number>(0);
  const { isTransfersPage, isEnterprisePortal } = checkPortals();
 
  const isAllowedViewTransaction = useAccessControl({
    resource: composePermission(
      RESOURCE_BASE.MERCHANT,
      RESOURCE_BASE.TRANSACTION,
    ),
    operation: OPERATIONS.READ,
  });
 
  const isEnabled = Boolean(id) && isModalVisible && isAllowedViewTransaction;
 
  // Query 1: Initial transaction
  const {
    data: initialTransaction,
    error: initialError,
    isLoading: isInitialLoading,
    isFetching: isInitialFetching,
  } = useQuery(
    [QKEY_GET_TRANSACTIONS_HISTORY, id, updatedData],
    () => getTransaction(id, isTransfersPage),
    {
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      enabled: isEnabled,
      onSuccess: () => {
        setCurrentTab(0);
      },
    },
  );
  // Query 2: Parent history (only if needed)
  const parentId = initialTransaction?.originalTransactionID;
  const shouldFetchParents =
    parentId &&
    initialTransaction?.transactionType !== "purchase" &&
    !isTransfersPage;
 
  const {
    data: parentTransactions,
    isLoading: isParentsLoading,
    isFetching: isParentsFetching,
  } = useQuery(
    [
      QKEY_GET_TRANSACTIONS_HISTORY,
      id,
      updatedData,
      {
        relation: "parent",
        parentId,
      },
    ],
 
    () => getParentHistory(parentId!),
    {
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      enabled: Boolean(shouldFetchParents),
    },
  );
 
  // Query 3: Child history (only if needed)
  const childTransactionsList = (() => {
    Iif (
      initialTransaction &&
      "childTransactions" in initialTransaction &&
      Array.isArray(initialTransaction.childTransactions)
    ) {
      if (isEnterprisePortal)
        return initialTransaction.childTransactions?.filter(
          (item) =>
            !["reserve_release", "reserve_deposit"].includes(
              item?.typeName || "",
            ),
        );
      else return initialTransaction.childTransactions;
    }
    return undefined;
  })();
 
  const shouldFetchChildren =
    childTransactionsList &&
    childTransactionsList.length > 0 &&
    !isTransfersPage;
 
  const {
    data: childTransactions,
    isLoading: isChildrenLoading,
    isFetching: isChildrenFetching,
  } = useQuery(
    [
      QKEY_GET_TRANSACTIONS_HISTORY,
      id,
      updatedData,
      {
        relation: "children",
        count: childTransactionsList?.length,
      },
    ],
 
    () => getChildHistory(childTransactionsList),
    {
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      enabled: Boolean(shouldFetchChildren),
    },
  );
 
  // Memoize the combined data
  const data = useMemo(() => {
    if (!initialTransaction) return undefined;
 
    const allTransactions = [initialTransaction];
 
    // Add parent transactions if we're in backward flow
    Iif (parentTransactions && shouldFetchParents) {
      return [...allTransactions, ...parentTransactions];
    }
    // Add child transactions if we're in forward flow
    else Iif (childTransactions && shouldFetchChildren) {
      return [...allTransactions, ...childTransactions];
    }
 
    return allTransactions;
  }, [
    initialTransaction,
    parentTransactions,
    childTransactions,
    shouldFetchParents,
    shouldFetchChildren,
  ]);
 
  // Memoize tabs
  const tabs = useMemo(() => {
    if (!data) return [];
 
    return data.map((txn) => {
      const normalizedStatus = getStatus(
        txn.displayStatus,
        txn.processingState,
      );
      return normalizedStatus as TagType;
    });
  }, [data]);
 
  // Loading states
  const isLoadingInitial = isInitialLoading || isInitialFetching;
  const isLoadingMore =
    (shouldFetchParents && (isParentsLoading || isParentsFetching)) ||
    (shouldFetchChildren && (isChildrenLoading || isChildrenFetching));
 
  useEffect(() => {
    Iif (initialError)
      showMessage(
        "Error",
        "Whoops.. an error occurred while fetching the data",
      );
  }, [initialError]);
 
  const currentTabData = data ? data[currentTab] : undefined;
 
  //we cannot use originalTransactionID for this, bc that always points to previous transaction not neccessarily the purchase one
 
  const originalPurchaseTransaction =
    currentTabData?.originalTransactionID && data
      ? data.find((item) => item.transactionType === "purchase") ||
        currentTabData
      : currentTabData;
  const displayedData =
    data && currentTabData
      ? {
          ...currentTabData,
          updatedAt: currentTabData.createdAt,
          sorceAccountFullName: data[data.length - 1]?.customerName,
          originalTransactionReversalState:
            originalPurchaseTransaction?.reversalState, //to get the original transactions reversal state - refactor if BE gives us the value
          originalTransactionItems: originalPurchaseTransaction?.items, //to get the original transactions items - refactor if BE gives us the value
          originalTransactionDestination:
            originalPurchaseTransaction?.merchant?.accID,
          originalTransactionData: {
            charged: originalPurchaseTransaction?.charged, // extend when needed, untill BE provide a value
          },
          originalPurchaseTransactionID: originalPurchaseTransaction?.id,
          isOriginalPurchaseBlocked: originalPurchaseTransaction?.isBlocked,
          isOriginalPurchaseFalsePositive:
            originalPurchaseTransaction?.isFalsePositive,
        }
      : undefined;
 
  const isAlreadyRefunded = tabs.some(
    (tab) =>
      !(["settled", "authorized", "pending", "captured"] as TagType[]).includes(
        tab,
      ),
  );
 
  const isBackwardFlow = !(
    isTransactionTableRowParsed(initialTransaction) &&
    "childTransactions" in initialTransaction &&
    initialTransaction?.childTransactions
  );
 
  return {
    displayedData,
    isLoading: isLoadingInitial,
    isLoadingMore, // separate loading state for related transactions
    tabs,
    currentTab,
    setCurrentTab,
    tabsData: data,
    isAlreadyRefunded,
    isFetched: Boolean(initialTransaction),
    isBackwardFlow,
  };
};
 
// Helper functions (keep these outside the hook)
const getParentHistory = async (previousThxId: string): Promise<any[]> => {
  const thxData = await getTransaction(previousThxId);
  const originalTransactionID = isTransactionTableRowParsed(thxData)
    ? thxData?.originalTransactionID
    : undefined;
  const transactionType = thxData?.transactionType;
 
  if (originalTransactionID && transactionType !== "purchase") {
    const prevHistory = await getParentHistory(originalTransactionID);
    return [thxData, ...prevHistory];
  }
  return [thxData];
};
 
const getChildHistory = async (
  childTransactions: TChildTransaction[] | undefined,
): Promise<any[]> => {
  if (!childTransactions || childTransactions.length === 0) return [];
 
  const childPromises = childTransactions.map((child) =>
    getTransaction(child.id),
  );
 
  const childrenData = await Promise.all(childPromises);
 
  return childrenData.sort(
    (a: any, b: any) =>
      new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
  );
};
export type useTransactionHistoryReturnType = ReturnType<
  typeof useTransactionHistory
>;