All files / src/routes PrivateRoutes.tsx

48% Statements 24/50
27.94% Branches 19/68
75% Functions 3/4
48% Lines 24/50

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                              1x 6x 6x 6x                 6x 6x     6x   6x     6x 1x                                                                                               6x 6x   6x 6x                 6x 6x                       1x 6x 6x   6x                   6x   6x           6x             6x          
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import { selectMasqueradeMode } from "@redux/slices/app";
import Cookies from "js-cookie";
import { safeParse } from "@utils/index";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";
import { getGivecashToWebData } from "@utils/queryString";
import { useEffect, useRef } from "react";
import { useAutoSwitchAccount } from "@pages/Login/modals/hooks/useAccountSelectionModal";
import { Box } from "@mui/material";
import { useGetAccounts } from "../services/api/onboarding/user";
import LoadingSpinner from "@components/Snipper/LoadingSpinner";
import { logoutAction } from "@redux/slices/auth/auth";
import { ENTERPRISE_PATHS } from "./paths";
import { QUERY_PARAM_KEYS } from "@constants/queryParamKeys";
 
const PrivateRoutes = () => {
  const user = Cookies.get("user");
  const parsedUser = user ? safeParse(user) : null;
  const dispatch = useAppDispatch();
 
  const {
    toPath,
    fromMobile,
    redirectRoute,
    merchantId,
    enterpriseId,
    acquirerId,
  } = getGivecashToWebData();
  const toDoRedirectionRef = useRef<boolean>(
    Boolean(merchantId && enterpriseId && acquirerId),
  );
  const newAccToSetRef = useRef<any>(null);
 
  const { data: userAccounts, isLoading: accountsLoading } = useGetAccounts({
    enabled: toDoRedirectionRef.current,
  });
  useEffect(() => {
    Iif (parsedUser && fromMobile && userAccounts && !accountsLoading) {
      let acquirer, enterprise, merchant;
      for (const acc of userAccounts?.data || []) {
        if (acc.id === acquirerId) {
          acquirer = acc;
        }
        if (acc.id === enterpriseId) {
          enterprise = acc;
        }
        if (acc.id === merchantId) {
          merchant = acc;
        }
      }
      newAccToSetRef.current = acquirer || enterprise || merchant;
 
      if (toDoRedirectionRef.current) {
        // if selected account has access to givecash merchant
        if (newAccToSetRef.current?.id === parsedUser?.id) {
          toDoRedirectionRef.current = false;
        }
 
        /**
         * if selected account doesnt have access to givecash merchant
         * but if there is account in the list that has access to givecash mercht
         * then switch to that new account
         */
        if (
          newAccToSetRef.current &&
          newAccToSetRef.current?.id != parsedUser?.id
        ) {
          switchAccount({
            userParam: newAccToSetRef.current,
            onSuccess: () => {
              toDoRedirectionRef.current = false;
            },
          });
        }
 
        // if no account in list has access to merchant from givecash, logout
        if (!newAccToSetRef.current) {
          toDoRedirectionRef.current = false;
          dispatch(logoutAction());
          navigate(`/login?next=${redirectRoute}`);
        }
      }
    }
  }, [userAccounts, accountsLoading]);
 
  const navigate = useNavigate();
  const { switchAccount, isSwitching } = useAutoSwitchAccount();
 
  if (user) {
    Iif (fromMobile) {
      if (toDoRedirectionRef.current || isSwitching || accountsLoading)
        return (
          <Box>
            <LoadingSpinner />
          </Box>
        );
      return <Navigate to={toPath} replace />;
    } else {
      toDoRedirectionRef.current = false;
      return <RoleAuth role={parsedUser?.role} />;
    }
  } else E{
    return (
      <Navigate
        to={`/login${fromMobile ? `?next=${redirectRoute}` : ""}`}
        replace
      />
    );
  }
};
 
const RoleAuth = ({ role }: { role: string }) => {
  const { pathname, search } = useLocation();
  const { name: isMasquerade, origin } = useAppSelector(selectMasqueradeMode);
 
  Iif (
    (pathname.includes("merchant/welcome") &&
      search.includes(QUERY_PARAM_KEYS.merchantID)) ||
    ((pathname.includes(ENTERPRISE_PATHS.TRANSFERS) ||
      pathname.includes(ENTERPRISE_PATHS.MANAGE_MONEY)) &&
      search.includes(QUERY_PARAM_KEYS.accountID))
  ) {
    return <Navigate to={`${origin}${search}`} replace />;
  }
 
  Iif (pathname.startsWith("/acquirer") && role !== "acquirer") {
    return <Navigate to={`${role}${search}`} replace />;
  } else Iif (
    pathname.startsWith("/provider") &&
    !["provider", "enterprise"].includes(role) &&
    !isMasquerade
  ) {
    return <Navigate to={`${origin || role}${search}`} replace />;
  } else Iif (
    pathname.startsWith("/merchant") &&
    role !== "merchant" &&
    !isMasquerade
  ) {
    return <Navigate to={`${origin || role}${search}`} replace />;
  } else {
    return <Outlet />;
  }
};
 
export default PrivateRoutes;