All files / src/shared/AssignButton GiveAssignButton.tsx

64.7% Statements 33/51
64.17% Branches 43/67
62.5% Functions 5/8
64.58% Lines 31/48

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                                                      50x                                   416x               416x 416x     416x 416x   416x 416x 416x 416x 416x   416x     416x 416x     416x           416x       416x   1x 1x 1x 1x 1x         416x             416x                                                                 416x                       416x                                                                                                                                                                                       396x                                           50x 396x                       50x                                           50x        
import { useEnterprisePermissions } from "@components/AcquirerEnterprises/CreateEnterprise/hooks/useEnterprisePermissions";
import { NEW_ACTION_DENY_MESSAGE } from "@constants/permissions";
import {
  QKEY_LIST_ACQUIRER_MERCHANTS,
  QKEY_LIST_ENTERPRISE_STATS,
  QKEY_LIST_MERCHANTS,
} from "@constants/queryKeys";
import { Box, ButtonBase, Stack } from "@mui/material";
import { CaretDownIcon, PlusIcon } from "@phosphor-icons/react";
import GiveAvatar from "@shared/Avatar/GiveAvatar";
import GiveButton from "@shared/Button/GiveButton";
import GiveTruncateText from "@shared/Text/GiveTruncateText";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { CustomTheme } from "@theme/v2/palette.interface";
import { styled, useAppTheme } from "@theme/v2/Provider";
import { checkPortals } from "@utils/routing";
import placeholder from "assets/images/profile-placeholder.png";
import AssignmentSelect from "componentsV2/Table/components/AssignmentSelect";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "features/Merchants/MerchantSidePanel/constants";
import { useUnderwriterPermissions } from "features/Permissions/AccessControl/hooks";
import { memo, useCallback, useState } from "react";
import { useQueryClient } from "react-query";
import { AssignButtonProps } from "./GiveAssignButton.types";
import { useUpdateAssigneeV2 } from "@features/Merchants/MerchantSidePanel/hooks/useUpdateAssignee";
import { useUpdateAssignee } from "@components/Merchants/MerchantPreview/hooks/useGetTeamMembers";
import useAssigneeManagedByAcquirer from "@hooks/useAssigneeManagedByAcquirer";
 
const GiveAssignButton = ({
  title = "Assign",
  disabled = false,
  isDenied = false,
  handleClick,
  data,
  onOpening,
  isOnlyName,
  anchorOrigin,
  transformOrigin,
  showCaretIcon = true,
  type,
  customContextualMenuPaperStyle,
  query,
  onChange,
  avatarOnly,
  displayNameOnly,
}: AssignButtonProps) => {
  const theme = useAppTheme();
  const {
    accID: merchantID,
    underwriterID,
    underwriterName,
    underwriterImageURL,
    underwriterEmail,
    underwriterSetByAcquirer = false,
  } = data || {};
  const displayName = isOnlyName
    ? underwriterName
    : underwriterName?.trim() || underwriterEmail;
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const queryClient = useQueryClient();
  const { handleChangeAssignee: handleChangeSalesAssignee } =
    useUpdateAssigneeV2(merchantID);
  const { handleChangeAssignee } = useUpdateAssignee(merchantID);
  const { isUpdateUnderwriterAllowed } = useUnderwriterPermissions();
  const { merchant_underwriting } = useEnterprisePermissions();
  const { isEnterprisePortal, isEnterpriseTable } = checkPortals();
 
  const { isManagedByAcquirer } = useAssigneeManagedByAcquirer({
    underwriterSetByAcquirer,
  });
  const isSales = type === "sales";
  const assignee = data?.underwriterName || data?.underwriterEmail;
 
  const hasUpdatePermission =
    ((isEnterprisePortal
      ? merchant_underwriting && isUpdateUnderwriterAllowed
      : isUpdateUnderwriterAllowed) ||
      isSales) &&
    !isDenied;
 
  const cannotChangeAssignee = Boolean(
    isEnterprisePortal && underwriterID && isManagedByAcquirer,
  );
 
  const handleOpenMenu = useCallback(
    (event: React.MouseEvent<HTMLButtonElement>) => {
      event?.stopPropagation();
      event?.preventDefault();
      Iif (cannotChangeAssignee) return;
      setAnchorEl(event.currentTarget);
      onOpening && onOpening("toggle_tooltip", true);
    },
    [],
  );
 
  const closeMenu = (event?: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(null);
    onOpening && onOpening("toggle_tooltip", false);
 
    event?.stopPropagation();
  };
 
  const handleChange = (value: any) => {
    const newAssignee = value === "unassigned" ? null : value;
    const onSuccess = () => {
      // This is unnecessary. Called in `useGetEnterprisesTableColumns`.
      // Why the same refetch when it is on line below?
      // if (handleClick) handleClick(newAssignee);
 
      if (isEnterpriseTable)
        queryClient.invalidateQueries(QKEY_LIST_ENTERPRISE_STATS);
 
      // Why the same refetch twice? This is duplicated and also should be done when
      // on the merchant table.
      if (!isEnterpriseTable) {
        queryClient.invalidateQueries(QKEY_LIST_MERCHANTS);
        queryClient.invalidateQueries(QKEY_LIST_ACQUIRER_MERCHANTS);
      }
      //this is needed for merchant and provider as well
      queryClient.invalidateQueries([
        MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_ASSIGNEES,
        merchantID,
      ]);
    };
 
    if (onChange)
      return onChange(underwriterID, newAssignee, type as any, onSuccess);
 
    if (isSales) {
      handleChangeSalesAssignee(underwriterID, newAssignee, onSuccess);
    } else {
      handleChangeAssignee(underwriterID, newAssignee, onSuccess);
    }
  };
 
  Iif (isManagedByAcquirer) {
    return (
      <StyledManagedByAcquirerText
        variant="bodyS"
        color="secondary"
        lineClamp={2}
      >
        Managed by the Acquirer
      </StyledManagedByAcquirerText>
    );
  }
 
  return (
    <>
      <GiveTooltip
        title={hasUpdatePermission ? assignee : NEW_ACTION_DENY_MESSAGE}
        color="default"
        disableHoverListener={
          hasUpdatePermission ? !assignee : hasUpdatePermission
        }
        customTooltipStyles={{ width: "fit-content" }}
      >
        {underwriterName || underwriterEmail ? (
          <StyledContainer
            disabled={
              disabled ||
              (!hasUpdatePermission && !isSales) ||
              cannotChangeAssignee
            }
            onClick={handleOpenMenu}
          >
            <Stack direction="row" alignItems="center">
              {!displayNameOnly && (
                <GiveAvatar
                  size="24px"
                  imageUrl={
                    underwriterImageURL
                      ? `${underwriterImageURL}/thumb`
                      : placeholder
                  }
                />
              )}
              {!avatarOnly && (
                <GiveTruncateText
                  variant="bodyS"
                  lineClamp={1}
                  sx={{
                    wordBreak: "break-all",
                    margin: "0 0 0 8px",
                    lineHeight: 1.5,
                  }}
                >
                  {displayName}
                </GiveTruncateText>
              )}
              {showCaretIcon && !cannotChangeAssignee && (
                <Box
                  minWidth={16}
                  minHeight={16}
                  display="inline-flex"
                  className="caret-down-icon"
                  marginLeft="4px"
                >
                  <CaretDownIcon
                    size={16}
                    fill={theme?.palette?.icon?.["icon-primary"]}
                  />
                </Box>
              )}
            </Stack>
          </StyledContainer>
        ) : (
          <GiveButton
            data-testid="assign-button"
            label={title}
            disabled={disabled || (!isUpdateUnderwriterAllowed && !isSales)}
            onClick={handleOpenMenu}
            startIcon={
              <IconFrame>
                <PlusIcon height={16} width={16} />
              </IconFrame>
            }
            sx={buttonStyles({ theme })}
            fullWidth
          />
        )}
      </GiveTooltip>
      <AssignmentSelect
        anchorEl={anchorEl}
        handleClose={closeMenu}
        handleChange={handleChange}
        merchantId={merchantID}
        underwriterID={data?.underwriterID}
        anchorOrigin={anchorOrigin}
        type={type}
        customContextualMenuPaperStyle={customContextualMenuPaperStyle}
        query={query}
        transformOrigin={transformOrigin}
      />
    </>
  );
};
export default memo(GiveAssignButton);
 
const buttonStyles = ({ theme }: { theme: CustomTheme }) => ({
  padding: 0,
  border: "none",
  color: theme.palette.text.primary,
  backgroundColor: "transparent",
  "&:hover": {
    textDecoration: "underline",
    background: "transparent",
  },
  "&.Mui-disabled": {
    textDecoration: "none",
    color: `${theme.palette.text.disabled} !important`,
  },
  "& .MuiButton-startIcon": {
    marginRight: 0,
    marginLeft: 0,
  },
  "&:hover p, &:hover svg": {
    opacity: 0.5,
  },
});
 
const IconFrame = styled(Box)(({ theme }) => {
  return {
    backgroundColor: theme.palette.surface?.tertiary,
    borderRadius: "50%",
    height: 24,
    width: 24,
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    marginRight: "4px",
  };
});
 
const StyledContainer = styled(ButtonBase)(({ disabled, theme }) => ({
  all: "unset",
  display: "flex",
  gap: "8px",
  cursor: "pointer",
  ...(disabled && {
    cursor: "default",
  }),
  "& .caret-down-icon": {
    visibility: "hidden",
  },
  "&:hover p, &:hover .caret-down-icon": {
    visibility: "visible",
    opacity: 0.5,
  },
  [theme.breakpoints.down("v2_sm")]: {
    "& .caret-down-icon": {
      visibility: "visible",
    },
  },
}));
 
const StyledManagedByAcquirerText = styled(GiveTruncateText)({
  wordBreak: "break-word",
  alignSelf: "center",
});