All files / src/shared/FileUpload GiveUploadItem.tsx

72.15% Statements 57/79
66.93% Branches 83/124
53.84% Functions 14/26
73.68% Lines 56/76

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 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597                                                                  52x                                                         691x 691x 691x 691x 691x 691x   691x 691x   691x 178x 178x 178x 23x 23x 22x 22x     178x       691x       691x 1x 1x                   691x   691x 14x 14x 13x     691x               691x                             691x             8x                                                                                                                                                                                                                                                                                                                               52x                           672x   672x       672x       1x 1x   672x                                                                                                                       1x                 52x                   654x   654x 3x                       654x                                                                   654x               4x 4x                         52x                                                     688x 688x                         688x     688x 649x                                                         39x                                                         3x 3x                              
import { Box, CircularProgress, Stack } from "@mui/material";
import {
  DotsThreeIcon,
  DownloadSimpleIcon,
  EyeIcon,
  TrashIcon,
  WarningCircleIcon,
  XIcon,
  Icon,
  FileTextIcon,
  NoteIcon,
} from "@phosphor-icons/react";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import { GiveTagInput } from "@shared/Inputs/GiveEditableTag";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import React, { useEffect, useState } from "react";
import { downloadDocument } from "@hooks/common/documents/utils";
import { useFilePermissions } from "@hooks/common/documents";
import useTagHandler from "features/Merchants/MerchantSidePanel/GiveMerchantFile/hooks/useTagHandler";
import { showMessage } from "@common/Toast";
import { checkPortals } from "@utils/routing";
import { DELETE_DENY_MESSAGE } from "@constants/permissions";
import ContextualMenu from "@shared/ContextualMenu/ContextualMenu";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import GiveTruncateText from "@shared/Text/GiveTruncateText";
import { GiveUploadItemProps, Size, State } from "./types";
import { useEnterprisePermissions } from "@components/AcquirerEnterprises/CreateEnterprise/hooks/useEnterprisePermissions";
import GiveAvatar from "@shared/Avatar/GiveAvatar";
import { convertPdfToImage } from "./utils";
import NiceModal from "@ebay/nice-modal-react";
import { GIVE_ADD_NOTE_MODAL } from "modals/modal_names";
 
const GiveUploadItem = ({
  merchantId,
  errorMessage,
  byMessage,
  dateMessage,
  state,
  size = Size.DEFAULT,
  isMobile,
  isNotice = false,
  noticeContent,
  value,
  setValue,
  setNote,
  fileData,
  isHideDelete = false,
  onDelete = () => null,
  tagType,
  setTagWithApi = false,
  handlePreview,
  isBusinessOwnerID,
  hideAllButtons = false,
  hideEditButtons = false,
  isLast = false,
  sizeMessage,
  useNotes,
  hideDownload = false,
  showAddNote = false,
  showIconTooltip = false,
}: GiveUploadItemProps) => {
  const { palette } = useAppTheme();
  const { isEnterprisePortal } = checkPortals();
  const [hovered, setHovered] = useState(false);
  const [url, setUrl] = useState(fileData?.fileURL);
  const [isLoadingURL, setIsLoadingURL] = useState(false);
  const [tagValue, setTagValue] = useState(value);
  const { isUpdateAllowed, isDeleteAllowed: isAllowedDeleted } =
    useFilePermissions(isEnterprisePortal);
  const { merchant_underwriting } = useEnterprisePermissions();
 
  useEffect(() => {
    setUrl(fileData?.fileURL);
    const getURL = async () => {
      if (fileData?.fileType?.includes("pdf")) {
        setIsLoadingURL(true);
        const newUrl = await convertPdfToImage(fileData?.fileURL);
        setUrl(newUrl);
        setIsLoadingURL(false);
      }
    };
    getURL();
  }, [fileData]);
 
  const isDeleteAllowed =
    !fileData?.isUploaded ||
    (merchant_underwriting && isEnterprisePortal) ||
    isAllowedDeleted;
 
  const handleDownloadClick = () => {
    Eif (fileData)
      downloadDocument(
        {
          fileName: fileData.fileName,
          fileURL: fileData.fileURL,
        },
        false,
        true,
      );
  };
 
  const { editTagHandler } = useTagHandler();
 
  const handlePreviewClick = (event: React.MouseEvent<HTMLElement>) => {
    event.stopPropagation();
    if (!fileData?.fileURL) return;
    handlePreview?.(fileData, isBusinessOwnerID);
  };
 
  const handleNoteClick = () => {
    NiceModal.show(GIVE_ADD_NOTE_MODAL, {
      defaultNote: fileData?.notes,
      onSave: (value: string) => setNote?.(value),
    });
  };
 
  //if we want to set the tag of an already uploaded file we pass setTagWithApi
  const onSaveTag = (tag: string) => {
    if (!merchantId) return;
    if (!tag?.trim()) {
      showMessage("Error", "The uploaded file name can't be empty");
      setTagValue(value ?? "");
    } else {
      if (!setTagWithApi) return setValue(tag);
      editTagHandler({
        merchantID: merchantId,
        documentID: fileData?.id,
        data: { tag: tagValue },
      });
    }
  };
 
  return (
    <Stack
      data-testid="uploaded-document-item"
      padding="12px"
      width="100%"
      gap="12px"
      borderBottom={!isLast ? `1px solid ${palette.border?.primary}` : "none"}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={handlePreviewClick}
      sx={{
        "&:hover": {
          cursor: "pointer",
        },
      }}
    >
      <Stack
        direction="row"
        gap="12px"
        alignItems={isMobile ? "flex-start" : "center"}
        justifyContent="center"
      >
        {url && !isLoadingURL ? (
          <GiveAvatar
            size="48px"
            shape="square"
            imageUrl={url}
            sx={{ marginTop: isMobile ? "12px" : 0 }}
          />
        ) : (
          <Box
            border={`1px solid ${palette.border?.secondary}`}
            borderRadius="8px"
            width="44px"
            height="44px"
            alignItems="center"
            justifyContent="center"
            display="flex"
          >
            <FileTextIcon
              size="24px"
              color={palette.icon?.["icon-secondary"]}
            />
          </Box>
        )}
        <Stack
          flex={1}
          direction="row"
          justifyContent="space-between"
          gap="12px"
          alignItems={
            isMobile && size === Size.DEFAULT ? "flex-start" : "center"
          }
        >
          <Stack direction="column" gap={isMobile ? "2px" : "8px"} width="100%">
            <Stack
              direction="row"
              gap="12px"
              alignItems="center"
              justifyContent={isMobile ? "space-between" : "flex-start"}
              onClick={(e) => e.stopPropagation()}
            >
              {state === State.LOADING && (
                <CircularProgress
                  size={14}
                  sx={{ color: palette.text.primary }}
                />
              )}
              <GiveTruncateText
                lineClamp={1}
                variant={size === Size.DEFAULT ? "bodyS" : "bodyXS"}
                color="primary"
                sx={{ wordBreak: "break-all" }}
                onClick={handlePreviewClick}
              >
                {fileData?.fileName}
              </GiveTruncateText>
              {Size.DEFAULT === size &&
                state === State.UPLOADED &&
                !isMobile &&
                !hideAllButtons &&
                !hideEditButtons && (
                  <GiveTagInput
                    value={tagValue}
                    setValue={setTagValue}
                    isMobile={isMobile}
                    isUpdateAllowed={isUpdateAllowed}
                    type={tagType}
                    onSaveTag={onSaveTag}
                  />
                )}
              {isMobile && (
                <RightMobileView
                  handlePreviewClick={handlePreviewClick}
                  handleDownloadClick={handleDownloadClick}
                  handleDeleteClick={onDelete}
                  isHideDelete={isHideDelete}
                  isDeleteAllowed={isDeleteAllowed}
                  hideDownload={hideDownload}
                  showAddNote={showAddNote}
                  handleNoteClick={handleNoteClick}
                />
              )}
            </Stack>
            <Description
              state={state}
              errorMessage={errorMessage}
              byMessage={byMessage}
              dateMessage={dateMessage}
              size={size}
              isMobile={isMobile}
              value={tagValue}
              setValue={setTagValue}
              isUpdateAllowed={isUpdateAllowed}
              tagType={tagType}
              onSaveTag={onSaveTag}
              sizeMessage={sizeMessage}
            />
          </Stack>
          {!hideAllButtons && (
            <Right
              state={state}
              hovered={hovered}
              isMobile={isMobile}
              handlePreviewClick={handlePreviewClick}
              handleDownloadClick={handleDownloadClick}
              handleNoteClick={handleNoteClick}
              handleDeleteClick={onDelete}
              isHideDelete={isHideDelete}
              isDeleteAllowed={isDeleteAllowed}
              hideDownload={hideDownload}
              showAddNote={showAddNote}
              showIconTooltip={showIconTooltip}
            />
          )}
        </Stack>
 
        {state === State.UPLOADED && isNotice && (
          <NoticeContent text={noticeContent || ""} />
        )}
      </Stack>
      {useNotes && !!fileData?.notes && (
        <NoticeContent text={fileData.notes} isLarge />
      )}
    </Stack>
  );
};
 
export default GiveUploadItem;
 
type TRightContent = {
  state?: (typeof State)[keyof typeof State];
  hovered?: boolean;
  isMobile?: boolean;
  handlePreviewClick: (
    event: React.MouseEvent<HTMLElement, MouseEvent>,
  ) => void;
  handleDownloadClick: () => void;
  handleDeleteClick: () => void;
  isHideDelete?: boolean;
  isDeleteAllowed?: boolean;
  hideDownload?: boolean;
  showAddNote?: boolean;
  handleNoteClick: () => void;
  showIconTooltip?: boolean;
};
 
const Right = ({
  hovered,
  state,
  isMobile,
  handlePreviewClick,
  handleDownloadClick,
  handleDeleteClick,
  handleNoteClick,
  isHideDelete = false,
  isDeleteAllowed,
  hideDownload = false,
  showAddNote = false,
  showIconTooltip = false,
}: TRightContent) => {
  const { palette } = useAppTheme();
 
  Iif (state === State.LOADING || state === State.FAILED) {
    return <GiveIconButton Icon={XIcon} size="small" />;
  }
 
  const handleButtonClick = (
    e: React.MouseEvent<HTMLButtonElement>,
    actionCb: () => void,
  ) => {
    e.stopPropagation();
    actionCb();
  };
  return hovered && !isMobile ? (
    <Stack direction="row" gap="4px" onClick={(e) => e.stopPropagation()}>
      <GiveTooltip
        title="Preview File"
        placement="top"
        disableHoverListener={!showIconTooltip}
        disableTouchListener={!showIconTooltip}
      >
        <GiveIconButton
          Icon={EyeIcon}
          size="small"
          onClick={handlePreviewClick}
          sx={{ bgcolor: "transparent" }}
        />
      </GiveTooltip>
      {!hideDownload && (
        <GiveTooltip
          title="Download"
          placement="top"
          disableHoverListener={!showIconTooltip}
          disableTouchListener={!showIconTooltip}
        >
          <GiveIconButton
            Icon={DownloadSimpleIcon}
            size="small"
            onClick={(e) => handleButtonClick(e, handleDownloadClick)}
            sx={{ bgcolor: "transparent" }}
          />
        </GiveTooltip>
      )}
      {showAddNote && (
        <GiveTooltip
          title="Add Note"
          placement="top"
          disableHoverListener={!showIconTooltip}
          disableTouchListener={!showIconTooltip}
        >
          <GiveIconButton
            Icon={NoteIcon}
            size="small"
            onClick={(e) => handleButtonClick(e, handleNoteClick)}
            sx={{ bgcolor: "transparent" }}
          />
        </GiveTooltip>
      )}
      {!isHideDelete && (
        <GiveTooltip
          width="compact"
          placement={showIconTooltip ? "top" : "bottom"}
          alignment="left"
          title={showIconTooltip ? "Delete" : DELETE_DENY_MESSAGE}
          color="default"
          disableHoverListener={!(showIconTooltip || !isDeleteAllowed)}
        >
          <GiveIconButton
            data-testid="delete-button"
            Icon={TrashIcon}
            size="small"
            disabled={!isDeleteAllowed}
            color={palette.primitive?.error[50]}
            onClick={(e) => handleButtonClick(e, handleDeleteClick)}
            sx={{ bgcolor: "transparent" }}
          />
        </GiveTooltip>
      )}
    </Stack>
  ) : null;
};
 
const RightMobileView = ({
  handlePreviewClick,
  handleDownloadClick,
  handleDeleteClick,
  handleNoteClick,
  isHideDelete = false,
  isDeleteAllowed,
  hideDownload = false,
  showAddNote = false,
}: Omit<TRightContent, "hovered" | "state" | "isMobile">) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
 
  const onCloseMenu = () => {
    setAnchorEl(null);
  };
 
  const options: {
    text: string;
    hidden: boolean;
    onClick: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
    disabled?: boolean;
    tooltipTitle?: string;
    disableTooltip?: boolean;
    type?: "default" | "destructive" | "label" | "divider";
    IconRight?: Icon;
  }[] = [
    {
      text: "Preview",
      hidden: false,
      disabled: false,
      onClick: handlePreviewClick,
      IconRight: EyeIcon,
    },
    {
      text: "Download",
      hidden: hideDownload,
      disabled: false,
      onClick: handleDownloadClick,
      IconRight: DownloadSimpleIcon,
    },
    {
      text: "Add Note",
      hidden: !showAddNote,
      disabled: false,
      onClick: handleNoteClick,
      IconRight: NoteIcon,
    },
    {
      text: "Delete",
      hidden: isHideDelete,
      disabled: !isDeleteAllowed,
      onClick: handleDeleteClick,
      tooltipTitle: DELETE_DENY_MESSAGE,
      disableTooltip: isDeleteAllowed,
      type: "destructive",
      IconRight: TrashIcon,
    },
  ];
 
  return (
    <>
      <GiveIconButton
        Icon={DotsThreeIcon}
        size="small"
        variant="ghost"
        data-testid="more-actions-button"
        onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
          e.stopPropagation();
          setAnchorEl(e.currentTarget);
        }}
      />
      <ContextualMenu
        handleClose={onCloseMenu}
        anchorEl={anchorEl}
        options={options}
        color={"primary"}
        texture={"solid"}
      />
    </>
  );
};
const Description = ({
  errorMessage,
  byMessage,
  dateMessage,
  state,
  size,
  isMobile,
  value,
  setValue,
  isUpdateAllowed,
  tagType,
  onSaveTag,
  sizeMessage,
}: {
  errorMessage?: string;
  byMessage?: string;
  dateMessage?: string;
  state: (typeof State)[keyof typeof State];
  size: (typeof Size)[keyof typeof Size];
  isMobile?: boolean;
  value: string;
  setValue: (value: string) => void;
  isUpdateAllowed: boolean;
  tagType?: "editable" | "form-field";
  onSaveTag?: (value: string) => void;
  sizeMessage?: string;
}) => {
  const { palette } = useAppTheme();
  Iif (state === State.FAILED) {
    return (
      <Stack direction="row" gap="8px" alignItems="center">
        <WarningCircleIcon size={16} color={palette.primitive?.error[50]} />
        <GiveText
          variant={size === Size.DEFAULT ? "bodyXS" : "bodyXXS"}
          color="error"
        >
          {errorMessage}
        </GiveText>
      </Stack>
    );
  }
  Iif (state === State.LOADING) {
    return null;
  }
  if (isMobile && size === Size.DEFAULT) {
    return (
      <Stack
        gap="8px"
        alignItems="flex-start"
        onClick={(e) => e.stopPropagation()}
        sx={{
          cursor: "auto",
        }}
      >
        <GiveTagInput
          value={value}
          setValue={setValue}
          isMobile={isMobile}
          isUpdateAllowed={isUpdateAllowed}
          type={tagType}
          onSaveTag={onSaveTag}
          isTruncated={false}
        />
 
        <GiveText
          variant={size === Size.DEFAULT ? "bodyXS" : "bodyXXS"}
          color="secondary"
        >
          {dateMessage}
        </GiveText>
      </Stack>
    );
  }
 
  return (
    <Stack direction="row" gap="8px">
      {Boolean(byMessage || sizeMessage) && (
        <GiveText
          variant={size === Size.DEFAULT ? "bodyXS" : "bodyXXS"}
          color="primary"
          onClick={(e) => e.stopPropagation()}
          sx={{
            cursor: "auto",
          }}
        >
          {sizeMessage || byMessage}
        </GiveText>
      )}
      <GiveText
        variant={size === Size.DEFAULT ? "bodyXS" : "bodyXXS"}
        color="secondary"
        onClick={(e) => e.stopPropagation()}
        sx={{
          cursor: "auto",
        }}
      >
        {dateMessage}
      </GiveText>
    </Stack>
  );
};
 
function NoticeContent({ text, isLarge }: { text: string; isLarge?: boolean }) {
  const { palette } = useAppTheme();
  return (
    <Box
      sx={{
        background: palette.surface?.secondary,
        padding: `${isLarge ? 12 : 8}px`,
        borderRadius: `${isLarge ? 8 : 4}px`,
        textAlign: `${isLarge ? "left" : "center"}`,
      }}
    >
      <GiveText variant="bodyXS" color="secondary">
        {text}
      </GiveText>
    </Box>
  );
}