All files / src/features/Merchants/MerchantsTable MerchantsTable.tsx

68.49% Statements 50/73
74.07% Branches 40/54
63.63% Functions 7/11
68.05% Lines 49/72

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                                                                                                                                      4x                                   259x 259x 259x   259x                       259x   259x                         259x   259x 259x   259x   259x 259x 27x             259x                     259x       259x 259x 259x   259x 259x 178x 178x         178x 178x                                                                               259x 27x                 27x                                                             259x 230x 230x     259x             259x         259x     259x               259x                       259x       259x               259x     259x               259x   259x         259x           259x   259x   259x                                                                       259x   259x                                                                           259x                                                                                          
import Table from "componentsV2/Table/Table";
import { useGetMerchantsTableColumns } from "./hooks/useGetMerchantsTableColumns";
import { MERCHANT_PREVIEW_PANEL_MODAL } from "modals/modal_names";
import { TableProps } from "componentsV2/Table/Table.types";
import { useCreateMerchantActions } from "@components/AcquirerMerchants/hooks/useCreateMerchantActions";
import RESOURCE_BASE, {
  CREATE_DENY_MESSAGE,
  CREATE_MERCHANT_DENY_MESSAGE_UNAPPROVED_PROVIDER,
  OPERATIONS,
} from "@constants/permissions";
import GiveMerchantBanner from "@shared/Banner/GiveMerchantBanner";
import { useTabs } from "./hooks/useTabs";
import GiveMotionWrapper from "@shared/Motion/GiveMotionWrapper";
import { useEffect, useMemo } from "react";
import { useTable } from "componentsV2/Table/hooks/useTable";
import useTableSearch from "componentsV2/Table/hooks/useTableSearch";
import BackgroundAnimation from "@shared/Banner/BackgroundAnimation";
import { useHandleScroll } from "componentsV2/Table/hooks/useHandleScroll";
import { MerchantStatsType } from "@hooks/enterprise-api/account/MerchantStatsType";
import { setFilters, useTableFilters } from "@redux/slices/tableFilters";
import useEnterpriseFilter from "componentsV2/Table/hooks/useEnterpriseFilter";
import { useFilterButton } from "@shared/GiveFilter/hooks/useFilterButton";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { getSelectedFilterPage } from "componentsV2/Table/MerchantActionsHandler";
import { FilterPageValuesTYpes } from "@shared/GiveFilter/constants";
import { useAppSelector } from "@redux/hooks";
import {
  selectMerchantTab,
  setMerchantTab,
} from "@redux/slices/enterprise/merchants";
import { TabNames } from "./hooks/useTabs";
import {
  composePermission,
  useAccessControl,
} from "@features/Permissions/AccessControl";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { useGetCurrentMerchantId } from "@hooks/common";
import {
  setFilterByKey,
  selectFiltersObject,
} from "@redux/slices/dynamicFilterSlice";
import { QKEY_LIST_ACQUIRER_MERCHANTS } from "@constants/queryKeys";
import {
  customAmountArrayKey,
  urlFilterFormat,
} from "@shared/GiveFilter/constants";
import { store } from "@redux/store";
import { capitalizeFirstLetter } from "@utils/index";
import { formatQueryParamsList } from "@common/TableFilters/utils";
import { STORED_MERCHANTS_ROWS_PER_PAGE } from "@constants/stringConstants";
import { MerchantCounterType } from "@hooks/acquirer-api/merchants/stats/useGetMerchantCounters";
import { MerchantStats } from "@customTypes/merchant.stats.types";
import { useComponentHeight } from "@hooks/common/useComponentHeight";
 
type MerchantsTableProps = Omit<TableProps, "columns" | "openModal"> & {
  stats: MerchantStatsType;
  statsRaw?: {
    stats: MerchantStats;
    counters: MerchantCounterType;
  };
  totalExportRecords?: number;
  allRows?: any;
  totalRows?: number;
  isLoadingStats?: boolean;
};
 
const MerchantsTable = ({
  stats,
  isLoadingStats,
  ...props
}: MerchantsTableProps) => {
  const {
    columns,
    defaultSort,
    defaultDescending,
    selectedTabStatus: {
      isAllTabSelected,
      isSponsorTabSelected,
      isKYBSelected,
      isUnderwritingTabSelected,
      isApprovedTabSelected,
      isPendingTabSelected,
      isRiskTabSelected,
    },
  } = useGetMerchantsTableColumns();
  const tab = useAppSelector(selectMerchantTab);
  const { ref, height } = useComponentHeight();
 
  const dataIsNotReady = props.statsRaw === undefined || isLoadingStats;
 
  const {
    totalExportRecords,
    allRows,
    totalRows,
    type,
    queryKey,
    page,
    setPageDispatcher,
    setPage,
    isSponsor,
  } = props;
 
  const { tabs, hasEntities, countsMap, defaultTab } = useTabs({
    stats,
    isLoading: dataIsNotReady,
    isSponsor,
  });
 
  const {
    handleClickCreateMerchant,
    isLoading,
    isFetching,
    isAcquirer,
    isProviderDisabled,
    isCreateMerchantAllowed,
  } = useCreateMerchantActions();
 
  const { merchantId } = useGetCurrentMerchantId();
  const navigate = useNavigate();
 
  const { onScroll } = useHandleScroll();
  const disableCreateMerchant =
    ((isLoading || isFetching) && isAcquirer) || !isCreateMerchantAllowed;
  const emptyStateAction = useMemo(
    () => ({
      handleAction: handleClickCreateMerchant,
      disabled: !isCreateMerchantAllowed,
    }),
    [],
  );
  const { setSelectedRowIdx, loadMore, numberOfPages, selectedRowIdx } =
    useTable({
      allRows,
      isLoading,
      totalRows,
      page,
      setPageDispatcher,
      setPage,
      openModal: MERCHANT_PREVIEW_PANEL_MODAL,
      storageKey: STORED_MERCHANTS_ROWS_PER_PAGE,
    });
 
  const { search, searchQuery, handleSearchChange } = useTableSearch({
    queryKey: queryKey || "",
  });
 
  const dispatch = useDispatch();
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
 
  useEffect(() => {
    if (isLoading || !merchantId) return;
    const tabQuery = queryParams.get("tab");
    Iif (tabQuery) {
      dispatch(setMerchantTab(`-${tabQuery}`));
      queryParams.delete("tab");
      navigate({ search: queryParams.toString() }, { replace: true });
    }
    const stateName = queryParams.get("stateName");
    Iif (stateName) {
      const stateNameLabel = capitalizeFirstLetter(stateName);
      const indexStateName = ["declined", "suspended"].findIndex(
        (tab) => tab === stateName,
      );
 
      const values = {
        ownerMembershipStatus: [{ value: "!=invited" }, { value: "null" }],
        stateName: [
          {
            label: `${stateNameLabel}`,
            value: `${stateName}`,
            id: `${stateNameLabel} - ${indexStateName}`,
            hidden: false,
          },
        ],
      };
 
      const queries = {
        queryString: formatQueryParamsList(values),
        queryParams: values,
      };
 
      const queryStrQuickF = formatQueryParamsList(queries.queryParams);
 
      dispatch(
        setFilters({
          queryString: queries.queryString,
          queryParams: queries.queryParams,
        }),
      );
 
      setQueryStringWithQuickFilter(queryStrQuickF);
 
      queryParams.delete("stateName");
      navigate({ search: queryParams.toString() }, { replace: true });
    }
  }, [queryParams, dispatch]);
 
  // handle navigation from provider "View Merchant List" - logic
  useEffect(() => {
    const navState = location.state as {
      fromProvider?: boolean;
      shouldSetApprovedTab?: boolean;
      providerFilter?: {
        parentNameFilter: any[];
        formattedFilterString: string;
      };
    } | null;
 
    Iif (navState?.fromProvider) {
      // if sponsor, set approved tab after
      if (navState?.shouldSetApprovedTab) {
        dispatch(setMerchantTab(TabNames.approved));
      }
 
      // Set filter after tab is set using microtask to ensure it runs after cleanup effects
      if (navState?.providerFilter) {
        queueMicrotask(() => {
          const { parentNameFilter, formattedFilterString } =
            navState.providerFilter!;
 
          const filterParams = {
            parentName: parentNameFilter,
            [urlFilterFormat]: encodeURIComponent(formattedFilterString),
          };
 
          dispatch(
            setFilterByKey({
              filterKey: QKEY_LIST_ACQUIRER_MERCHANTS,
              params: filterParams,
            }),
          );
        });
      }
 
      // clear navigation state to prevent re-applying on re-renders
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location.state, dispatch, navigate, location.pathname]);
 
  const actualTotalRows = useMemo(() => {
    const tabCount = tab ? countsMap[tab] : stats?.countTotalAquirer;
    return totalExportRecords ? totalExportRecords : tabCount || 0;
  }, [totalExportRecords, tab, stats]);
 
  const isCurrentTabEmpty = !isAllTabSelected && hasEntities && totalRows === 0;
 
  const {
    resetTableFilters: handleResetMerchantsFilter,
    filtersAmount: merchantFilterAmount,
    hasQuickFilter: hasMerchantQuickFilter,
    setQueryStringWithQuickFilter,
  } = useTableFilters();
 
  //TODO cleanup on filter rebrand cleanup
  //This is the FF what we are using for the new story where we integrating the new filter modal, isMerchantProcessorEnabled- with this we completr all tabs filter rebrand
  const { isNewApprovalFlowEnabled, isMerchantProcessorEnabled } =
    useGetFeatureFlagValues();
 
  const isRebrandedFilterEnabled =
    (isNewApprovalFlowEnabled &&
      (isSponsorTabSelected ||
        isKYBSelected ||
        isUnderwritingTabSelected ||
        isApprovedTabSelected ||
        isPendingTabSelected)) ||
    isMerchantProcessorEnabled;
 
  const selectedFilterPage = getSelectedFilterPage({
    isKYBSelected,
    isSponsorTabSelected,
    isApprovedTabSelected,
    isPendingTabSelected,
    isRiskTabSelected,
    isAllTabSelected,
  });
 
  const {
    handleResetFilters: resetFiltersV2,
    filtersAmount: buttonFiltersAmount,
  } = useFilterButton({
    filterPage: selectedFilterPage as FilterPageValuesTYpes,
  });
  //TODO CLEAN UP
  const usedMerchantFilterAmount = isRebrandedFilterEnabled
    ? buttonFiltersAmount
    : merchantFilterAmount;
  //////
 
  const {
    handleResetFilters: handleResetEnterprisesFilter,
    filtersAmount: ProviderFilterAmount,
  } = useEnterpriseFilter();
 
  const handleResetFilters =
    type === "merchant"
      ? () => {
          isRebrandedFilterEnabled
            ? resetFiltersV2()
            : handleResetMerchantsFilter(true);
        }
      : () => handleResetEnterprisesFilter();
 
  const hasFilters = usedMerchantFilterAmount > 0 || ProviderFilterAmount > 0;
 
  const hasListMerchantPermission = useAccessControl({
    resource: RESOURCE_BASE.MERCHANT,
    operation: OPERATIONS.LIST,
  });
 
  const sponsorHasListMerchantPermission = useAccessControl({
    resource: composePermission(RESOURCE_BASE.MERCHANT, RESOURCE_BASE.SPONSOR),
    operation: OPERATIONS.LIST,
  });
 
  const listMerchantPermission =
    sponsorHasListMerchantPermission || hasListMerchantPermission;
 
  const Head = useMemo(
    () => (
      <GiveMerchantBanner
        title="Merchants"
        action="Add Merchant"
        filters={tabs}
        handleCreate={handleClickCreateMerchant}
        disableCreate={disableCreateMerchant}
        tooltipProps={{
          title: isProviderDisabled
            ? CREATE_MERCHANT_DENY_MESSAGE_UNAPPROVED_PROVIDER
            : CREATE_DENY_MESSAGE,
          disableHoverListener: isCreateMerchantAllowed,
        }}
        actualTotalRows={actualTotalRows}
        totalRows={totalRows}
        type={type as "provider" | "merchant"}
        handleSearchChange={handleSearchChange}
        search={search}
        defaultTab={defaultTab}
      />
    ),
    [
      tabs,
      handleClickCreateMerchant,
      disableCreateMerchant,
      isCreateMerchantAllowed,
      actualTotalRows,
      totalRows,
      type,
      handleSearchChange,
      search,
      defaultTab,
    ],
  );
 
  // TRA013 AC004: compact-on-scroll banner — same tab counts, collapsed
  // search + actions + tab filters (mirrors the full Head above).
  const CompactHead = useMemo(
    () => (
      <GiveMerchantBanner
        compact
        countsMap={countsMap}
        title="Merchants"
        action="Add Merchant"
        filters={tabs}
        handleCreate={handleClickCreateMerchant}
        disableCreate={disableCreateMerchant}
        tooltipProps={{
          title: isProviderDisabled
            ? CREATE_MERCHANT_DENY_MESSAGE_UNAPPROVED_PROVIDER
            : CREATE_DENY_MESSAGE,
          disableHoverListener: isCreateMerchantAllowed,
        }}
        actualTotalRows={actualTotalRows}
        totalRows={totalRows}
        type={type as "provider" | "merchant"}
        handleSearchChange={handleSearchChange}
        search={search}
        defaultTab={defaultTab}
      />
    ),
    [
      countsMap,
      tabs,
      handleClickCreateMerchant,
      disableCreateMerchant,
      isCreateMerchantAllowed,
      isProviderDisabled,
      actualTotalRows,
      totalRows,
      type,
      handleSearchChange,
      search,
      defaultTab,
    ],
  );
 
  return (
    <>
      <BackgroundAnimation page="merchants" />
      <GiveMotionWrapper
        delay={30}
        containerProps={{ sx: { height: "100%", zIndex: 2 } }}
        customStyle={{
          height: "100%",
          display: "flex",
          justifyContent: "center",
        }}
      >
        <Table
          {...props}
          top={height}
          totalExportRecords={totalExportRecords}
          openModal={MERCHANT_PREVIEW_PANEL_MODAL}
          columns={columns}
          emptyStateAction={emptyStateAction}
          queryKey={queryKey}
          onScroll={onScroll}
          searchQuery={searchQuery}
          handleSearchChange={handleSearchChange}
          setSelectedRowIdx={setSelectedRowIdx}
          selectedRowIdx={selectedRowIdx}
          loadMore={loadMore}
          numberOfPages={numberOfPages}
          Head={Head}
          CompactHead={CompactHead}
          compactAnimationPage="merchants"
          isSponsorTabSelected={isSponsorTabSelected}
          isCurrentTabEmpty={isCurrentTabEmpty}
          hasFilters={hasFilters || hasMerchantQuickFilter}
          handleResetFilters={handleResetFilters}
          defaultSortKey={defaultSort}
          isDescending={defaultDescending}
          isListPermissionAllowed={listMerchantPermission}
          sectionName="merchant"
        />
      </GiveMotionWrapper>
    </>
  );
};
 
export default MerchantsTable;