All files / src/features/MerchantPortal/ManageMoney ManageMoneyActions.tsx

84.61% Statements 55/65
83.09% Branches 59/71
53.33% Functions 8/15
87.09% Lines 54/62

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                                                                                                                                        7x                                       304x   304x 304x 304x 304x   304x         304x         304x   304x 304x 63x     241x 132x         109x 30x     79x             304x               304x   304x   304x 304x 304x   304x   304x 110x   110x   110x 42x   68x               304x 28x     304x           304x 1x     304x   304x   2x       2x 2x 2x     2x           2x         2x 2x       304x   304x                                                                                                       1216x                   304x   304x 20x                             140x                 20x                                     284x                                                              
import { useDownloadReport } from "@components/ManageMoney/TransactionTable/hooks";
import { NEW_ACTION_DENY_MESSAGE } from "@constants/permissions";
import NiceModal from "@ebay/nice-modal-react";
import { DotsThreeVerticalIcon, Icon, XIcon } from "@phosphor-icons/react";
import { Stack } from "@mui/material";
import GiveExpandingSearch from "@shared/SearchBar/GiveExpandingSearch";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import GiveMerchantTableActions from "@shared/MerchantsProviders/GiveMerchantTableActions";
import { BANK_ACCOUNTS_MODAL_V2 } from "modals/modal_names";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { checkPortals } from "@utils/routing";
import { useFormatManageMoneyFilter } from "./hooks/useFormatManageMoneyFilters";
import { useFilterButton } from "@shared/GiveFilter/hooks/useFilterButton";
import { FilterPagesEnum, urlFilterFormat } from "@shared/GiveFilter/constants";
import ContextualMenu from "@shared/ContextualMenu/ContextualMenu";
import { useCallback, useMemo, useRef, useState } from "react";
import { useStateEffect } from "@hooks/customReactCore";
import { useFiltersState } from "@components/VirtualList/hooks";
import {
  QKEY_ACQUIRER_MANAGE_MONEY_TRANSACTIONS_LIST,
  QKEY_GET_TRANSACTION_STATS,
  QKEY_MANAGE_MONEY_TRANSACTIONS_LIST,
  QKEY_PROCESSING_LIST,
  QKEY_PROVIDER_PROCESSING,
} from "@constants/queryKeys";
import { useQueryClient } from "react-query";
import { useGetCurrentMerchantId } from "@hooks/common";
import {
  Container,
  MOBILE_ACTIONS_ICONS,
  ACTIONS,
} from "./ManageMoneyActions.atoms";
import GiveCircularProgress from "@shared/GiveCircularProgress";
 
type CompactMainAction = {
  label: string;
  icon: Icon;
  action: () => void;
  disabled?: boolean;
  hidden?: boolean;
};
 
type CompactFilter = {
  label: string;
  value: string | number;
  disabled?: boolean;
  hidden?: boolean;
  onClickItem?: (index: number) => void;
};
 
type Props = {
  noTransactions: boolean;
  search: string;
  handleSearchChange: (value: string) => void;
  sortReduxKey?: string;
  selectedTabFilter?: string | number;
  isAcquirerProviderManageMoney?: boolean;
  setLocalIsLoading?: React.Dispatch<React.SetStateAction<boolean>>;
  localIsLoading?: boolean;
  /**
   * Compact-on-scroll banner variant (AC004): collapses search + all actions
   * (main action, table actions, tab filters) into a search icon + kebab menu.
   */
  compact?: boolean;
  mainAction?: CompactMainAction;
  filters?: CompactFilter[];
};
 
const ManageMoneyActions = ({
  noTransactions,
  handleSearchChange,
  search,
  sortReduxKey,
  selectedTabFilter,
  isAcquirerProviderManageMoney,
  setLocalIsLoading,
  localIsLoading,
  compact = false,
  mainAction,
  filters,
}: Props) => {
  const {
    isAcquirerPortal,
    isEnterprisePortal,
    isProcessing,
    isTransactions,
    isAcquirerOrProviderManageMoney,
    isAnyTransfersPage,
  } = checkPortals();
 
  const { merchantId, selectedUser } = useGetCurrentMerchantId();
  const hasBAAccess = ["admin", "owner"].includes(selectedUser?.userRole || "");
  const { isNarrowView } = useCustomThemeV2();
  const queryClient = useQueryClient();
  //TODO clean up with FF
  const queryKey = isProcessing
    ? isEnterprisePortal
      ? QKEY_PROVIDER_PROCESSING
      : QKEY_PROCESSING_LIST
    : QKEY_MANAGE_MONEY_TRANSACTIONS_LIST;
  const usedQueryKey = isAcquirerOrProviderManageMoney
    ? QKEY_ACQUIRER_MANAGE_MONEY_TRANSACTIONS_LIST
    : queryKey;
 
  const { filterObject, filterConst } =
    useFormatManageMoneyFilter(usedQueryKey);
 
  const getFilterPage = () => {
    if (isAcquirerOrProviderManageMoney) {
      return FilterPagesEnum.ACQUIRER_MANAGE_MONEY;
    }
 
    if (isProcessing) {
      return isAcquirerPortal
        ? FilterPagesEnum.ACQUIRER_PROCESSING
        : FilterPagesEnum.PROVIDER_PROCESSING;
    }
 
    if (isAnyTransfersPage) {
      return FilterPagesEnum.TRANSFERS;
    }
 
    return FilterPagesEnum.MANAGE_MONEY;
  };
 
  const {
    handleOpenFilterModal,
    handleResetFilters,
    filtersAmount: buttonFiltersAmount,
  } = useFilterButton({
    filterPage: getFilterPage(),
  });
 
  // useFiltersState (NOT useFiltersRepository): this component is remounted by
  // the compact-on-scroll banner, and useFiltersRepository's unmount cleanup
  // would clear the selected tab's status filter while the tab stays
  // highlighted. The page-level list hook owns the filter reset.
  const { formattedFilter, queryString } = useFiltersState(sortReduxKey);
  const filtersAmount =
    isProcessing || isAnyTransfersPage ? buttonFiltersAmount : filterConst;
 
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const filterKey = urlFilterFormat as keyof typeof filterObject;
  const filter = (filterObject?.[filterKey] as string) || "";
 
  const tabFilter = formattedFilter ? formattedFilter : queryString;
 
  const usedFilter = useMemo(() => {
    Iif (filter && queryString) return `${queryString}%3B${filter}`;
 
    Iif (filter) return filter;
 
    if (queryString && tabFilter === formattedFilter)
      return `${queryString}%3B${tabFilter}`;
 
    return tabFilter;
  }, [filter, queryString, tabFilter, formattedFilter]);
 
  // Reset panel filters only when tabFilter actually changes, never on mount
  // (useStateEffect skips the first run): the compact-on-scroll banner mounts
  // a second instance of this component mid-scroll, and a mount-time reset
  // would wipe the user's applied filters (dynamicFilterSlice) on the same
  // gesture that loads the next page.
  useStateEffect(() => {
    handleResetFilters();
  }, [tabFilter]);
 
  const { disableDownload, downloadReport, denyDownload } = useDownloadReport({
    filterParams: usedFilter,
    sortReduxKey: sortReduxKey,
    exportType: "transactions",
  });
 
  const handleOpenBankAccounts = () => {
    NiceModal.show(BANK_ACCOUNTS_MODAL_V2);
  };
 
  const isRefreshingRef = useRef(false);
 
  const handleReloadData = useCallback(async () => {
    // prevent multiple clicks on the button
    Iif (isRefreshingRef.current) {
      return;
    }
 
    try {
      isRefreshingRef.current = true;
      setLocalIsLoading?.(true);
 
      // invalidate queries to mark them as stale
      await Promise.all([
        queryClient.invalidateQueries([QKEY_GET_TRANSACTION_STATS, merchantId]),
        queryClient.invalidateQueries(sortReduxKey),
      ]);
 
      // explicitly refetch queries and wait for them to complete
      await Promise.all([
        queryClient.refetchQueries([QKEY_GET_TRANSACTION_STATS, merchantId]),
        queryClient.refetchQueries(sortReduxKey),
      ]);
    } finally {
      isRefreshingRef.current = false;
      setLocalIsLoading?.(false);
    }
  }, [queryClient, merchantId, sortReduxKey, setLocalIsLoading]);
 
  const filterLabel = filtersAmount ? `Filters (${filtersAmount})` : "Filter";
 
  const actions = [
    {
      ...ACTIONS.refresh,
      handleAction: handleReloadData,
      disabled: localIsLoading,
      hidden: isAnyTransfersPage,
      ...(localIsLoading && {
        endIcon: (
          <GiveCircularProgress size={14} thickness={4} color={"inherit"} />
        ),
      }),
    },
    {
      ...ACTIONS.bank,
      handleAction: handleOpenBankAccounts,
      disabled: false,
      hidden:
        (isAcquirerPortal && !hasBAAccess) ||
        isTransactions ||
        isAnyTransfersPage,
    },
    {
      ...ACTIONS.filter,
      label: filterLabel,
      handleAction: handleOpenFilterModal,
      disabled: noTransactions,
      ...((filtersAmount || 0) > 0 && {
        endIcon: (
          <GiveIconButton
            Icon={XIcon}
            size="extraSmall"
            onClick={handleResetFilters}
          />
        ),
      }),
      hidden: false,
    },
    {
      ...ACTIONS.export,
      handleAction: downloadReport,
      disabled: disableDownload || noTransactions,
      tooltipProps: {
        title: NEW_ACTION_DENY_MESSAGE,
        disableHoverListener: !denyDownload,
      },
      hidden: isAcquirerProviderManageMoney || isAnyTransfersPage,
      endIcon: disableDownload ? (
        <GiveCircularProgress size={14} thickness={4} color={"inherit"} />
      ) : undefined,
    },
  ];
 
  const mobileActions = actions.map((action) => ({
    text: action.label,
    IconRight: MOBILE_ACTIONS_ICONS[action.id],
    onClick: () => {
      action.handleAction();
    },
    hidden: !!action.hidden,
    disabled: !!action.disabled,
  }));
 
  const showMobileActions = isNarrowView && !isAnyTransfersPage;
 
  if (compact) {
    const compactMenuOptions = [
      ...(mainAction && !mainAction.hidden
        ? [
            {
              text: mainAction.label,
              IconRight: mainAction.icon,
              disabled: mainAction.disabled,
              onClick: () => mainAction.action(),
            },
          ]
        : []),
      ...mobileActions,
      ...((filters?.length ?? 0) > 0
        ? [{ type: "divider" as const, text: "" }]
        : []),
      ...(filters ?? []).map((filter, index) => ({
        text: filter.label,
        isSelected: Number(selectedTabFilter) === index,
        disabled: filter.disabled,
        hidden: filter.hidden,
        onClick: () => filter.onClickItem?.(index),
      })),
    ];
 
    return (
      <Stack direction="row" alignItems="center" gap="8px">
        <GiveExpandingSearch value={search} onChange={handleSearchChange} />
        <GiveIconButton
          Icon={DotsThreeVerticalIcon}
          variant="ghost"
          onClick={(e) => setAnchorEl(e.currentTarget)}
        />
        <ContextualMenu
          anchorEl={anchorEl}
          options={compactMenuOptions}
          handleClose={() => setAnchorEl(null)}
          color="primary"
          texture="solid"
        />
      </Stack>
    );
  }
 
  return (
    <Container isMobileView={showMobileActions}>
      <GiveMerchantTableActions
        actions={actions}
        isAllActionsHidden={showMobileActions}
        search={search}
        onSearchChange={handleSearchChange}
        searchOnEnter
      />
 
      {showMobileActions && (
        <>
          <GiveIconButton
            Icon={DotsThreeVerticalIcon}
            variant="ghost"
            onClick={(e) => setAnchorEl(e.currentTarget)}
          />
          <ContextualMenu
            anchorEl={anchorEl}
            options={mobileActions}
            handleClose={() => setAnchorEl(null)}
            color="primary"
            texture="solid"
          />
        </>
      )}
    </Container>
  );
};
 
export default ManageMoneyActions;