All files / src/components/Merchants/Masquerade MasqueradeSnackbar.tsx

51.35% Statements 19/37
24.32% Branches 9/37
40% Functions 2/5
52.77% Lines 19/36

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                                                        11x 107x 107x 107x 107x 107x 107x   107x 107x         107x 107x   107x   107x                                                                                         107x   107x           107x                                                                                                                     11x   11x                                                               11x                  
// import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
// mui
import { Box, Stack } from "@mui/material";
// components
import GiveText from "@shared/Text/GiveText";
import { showMessage } from "@common/Toast/ShowToast";
// redux
import { useAppDispatch } from "@redux/hooks";
import { setMasqueradeMode } from "@redux/slices/app";
// hooks
import { useMasquerade } from "@hooks/enterprise-api/merchants";
 
import useMasqueradeReducer from "@hooks/Reducers/useMasqueradeReducer";
import { checkPortals } from "@utils/routing";
import GiveButton from "@shared/Button/GiveButton";
import { useQueryClient } from "react-query";
import { useUser } from "@hooks/common/useUser";
import { formTypeToUrlMap } from "sections/PayBuilder/utils";
import { FormType } from "@sections/PayBuilder/utils";
import { styled } from "@theme/v2/Provider";
import { SignOutIcon, StorefrontIcon } from "@phosphor-icons/react";
import { useCart } from "@sections/PayBuilder/provider/CartContext";
import GiveTruncateText from "@shared/Text/GiveTruncateText";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { MASQUERADE_SNACKBAR_HEIGHT } from "./constants";
import { useIsStickyMasqueradeBar } from "@hooks/common/useBannerPush";
 
const MasqueradeSnackbar = ({ show = false, formId = "", formType = "" }) => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const { state } = useLocation();
  const { isMerchant } = useUser();
  const { isMaintenanceStatsBannerEnabled } = useGetFeatureFlagValues();
 
  const { deleteMasqueradeMutation } = useMasquerade();
  const { clearCart } = useCart();
  const {
    isMasqueradeMode,
    origin,
    name: merchantName,
  } = useMasqueradeReducer();
  const { isMerchantPortal, isEnterprisePortal } = checkPortals();
 
  const isSticky = useIsStickyMasqueradeBar();
 
  const exitHandler = async () => {
    try {
      const historyControlMode: any[] | undefined =
        await deleteMasqueradeMutation.mutateAsync({});
 
      if (!historyControlMode?.[0]) return;
      const origin = historyControlMode[0].origin;
      dispatch(
        setMasqueradeMode({
          id: "",
          name: "",
          origin,
          imgSrc: "",
          masqueradeUserRole: historyControlMode[0].role,
          historyControlMode: [],
        }),
      );
      queryClient.removeQueries("public-form-id");
      queryClient.clear();
      navigate(origin);
    } catch (error: any) {
      const message = error.response?.data?.message;
      const errorCode = error.response?.data?.code;
 
      showMessage("Error", `${message}`);
      if (
        (errorCode === "resource_not_found" &&
          message === "Masquerade not in session.") ||
        (errorCode === "not_authorized" && message === "access not allowed")
      ) {
        dispatch(
          setMasqueradeMode({
            id: "",
            name: "",
            origin,
            imgSrc: "",
            masqueradeUserRole: "",
            historyControlMode: [],
          }),
        );
      }
    }
  };
 
  const conditionToShowBackButton =
    show && formId !== "" && (isMasqueradeMode || isMerchant);
 
  const handleClick = () => {
    clearCart();
    navigate(`/merchant/${formTypeToUrlMap[formType as FormType]}`);
    queryClient.removeQueries("public-form-id");
  };
 
  return (
    <>
      {((isMasqueradeMode && !state?.preview) || conditionToShowBackButton) &&
        (isMerchantPortal || isEnterprisePortal || state?.preview || show) && (
          <Container
            sticky={isSticky}
            hasMaintenanceBanner={isMaintenanceStatsBannerEnabled}
          >
            {conditionToShowBackButton && (
              <StyledGiveButton
                size="small"
                startIcon={<StorefrontIcon />}
                onClick={handleClick}
                variant="filled"
                label="Back to portal"
              />
            )}
            {isMasqueradeMode ? (
              <Stack
                direction="row"
                gap={{ xs: 1, sm: 1 }}
                alignItems="center"
                width="100%"
                sx={{
                  margin: "0 auto",
                  paddingX: { xs: 0, sm: 0 },
                  paddingLeft: { xs: !conditionToShowBackButton ? 2.5 : 0 },
                  justifyContent: { xs: "space-between", sm: "center" },
                }}
              >
                <GiveTruncateText
                  variant="bodyS"
                  color="secondary"
                  lineClamp={2}
                >
                  You are in control mode of{" "}
                  <GiveText variant="bodyS" color="primary" component="span">
                    {merchantName}
                  </GiveText>
                </GiveTruncateText>
 
                <GiveButton
                  size="small"
                  variant="ghost"
                  label="Exit"
                  onClick={exitHandler}
                  endIcon={<SignOutIcon />}
                  disabled={deleteMasqueradeMutation.isLoading}
                />
              </Stack>
            ) : (
              <Stack width="100%" />
            )}
          </Container>
        )}
    </>
  );
};
 
const Container = styled(Box, {
  shouldForwardProp: (prop) =>
    prop !== "sticky" && prop !== "hasMaintenanceBanner",
})<{ sticky?: boolean; hasMaintenanceBanner?: boolean }>(
  ({ sticky, hasMaintenanceBanner, theme }) => ({
    position: "fixed",
    left: "50%",
    height: `${MASQUERADE_SNACKBAR_HEIGHT}px`,
    transform: "translate(-50%, 0)",
    backgroundColor: theme.palette.surface?.["primary-transparent"],
    borderBottom: `1px solid ${theme.palette.border?.primary}`,
    top: hasMaintenanceBanner ? `${MASQUERADE_SNACKBAR_HEIGHT}px` : 0,
    zIndex: sticky ? 99999 : 10,
    display: "flex",
    alignItems: "center",
    width: "100%",
    gap: "20px",
    "&::after": {
      content: '""',
      flex: 1,
    },
    ...(sticky && {
      position: "sticky",
      left: 0,
      transform: "none",
    }),
    [theme.breakpoints.up("v2_sm")]: {
      backdropFilter: "blur(15px)",
    },
  }),
);
 
export default MasqueradeSnackbar;
 
const StyledGiveButton = styled(GiveButton)({
  gap: "4px",
  marginLeft: "20px",
  minWidth: "fit-content",
  "& .MuiButton-startIcon": {
    marginRight: "0px",
    marginLeft: "0px",
  },
});