All files / src/components/UploadFile/Rebranded UploadFileDocumentPreviewItem.tsx

63.63% Statements 28/44
34.61% Branches 9/26
43.75% Functions 7/16
64.86% Lines 24/37

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                                                                          4x               86x 86x 86x 86x 86x 86x 86x         86x             86x               86x       86x 16x 16x       86x                           86x                                                           86x 12x                                                         258x 258x   258x                               86x                                               86x                     258x              
import { useMemo, useState } from "react";
import { TrashBin } from "@assets/icons/RebrandedIcons";
import { DownloadIcon } from "@assets/icons";
import { ClickAwayListener, Stack } from "@mui/material";
import { styled } from "@mui/material";
import { palette } from "@palette";
import { Text, TruncateText } from "@common/Text";
import { StyledIconButton } from "@common/IconButton";
import { EyeIcon } from "@phosphor-icons/react";
import { useDocumentHandlers } from "@hooks/common/documents";
import { checkPortals } from "@utils/routing";
import { TMerchantDocument } from "@components/Merchants/MerchantPreview/data.types";
import { useQueryClient } from "react-query";
import { DELETE_DENY_MESSAGE } from "@constants/permissions";
import { CustomToolTip } from "@common/BusinessOwners/CustomToolTip";
import useDocumentPreviewV2 from "@shared/FilePreview/hooks/useDocumentPreviewV2";
import { getFileExtension } from "@hooks/upload-api/useIsValidFile";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
 
type Props = {
  deleteDocument: (
    id: string | number,
    fileId?: number,
    fileName?: string,
  ) => void;
  fileName: string;
  id: string | number;
  fileURL: string;
  merchantId?: number;
  list?: any;
  isUploaded?: boolean;
  fileType?: string;
  attTypeName?: string;
  hideDeleteIcon?: boolean;
  keepPreviewOpen?: boolean;
};
 
export const UploadFileDocumentPreviewItem = ({
  deleteDocument,
  id,
  list,
  hideDeleteIcon,
  keepPreviewOpen,
  ...props
}: Props) => {
  const { fileName, merchantId, isUploaded, fileURL } = props;
  const fileObject = list?.find((file: any) => file.fileName === fileName);
  const ignoreDeletePermission = isUploaded === false;
  const queryClient = useQueryClient();
  const { isEnterprisePortal } = checkPortals();
  const [isFocused, setIsFocused] = useState<boolean>(false);
  const refetcher = () => {
    queryClient.invalidateQueries(
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_BANK_FILES,
    );
  };
  const { previewHandler, isDeleteAllowed } = useDocumentHandlers(
    merchantId || 0,
    list as TMerchantDocument[],
    isEnterprisePortal,
    refetcher,
  );
 
  const download = async (file: any) => {
    const link = document.createElement("a");
    link.href = file.fileURL;
    link.download = file.fileName;
    link.target = "_blank";
    link.click();
  };
 
  const remove = (id: string | number, fileId?: number, fileName?: string) => {
    deleteDocument(id, fileId, fileName);
  };
 
  const docList = useMemo(() => {
    Iif (list?.length > 0) return list;
    Eif (!fileURL) return [];
    return [{ fileURL, fileName, fileType: getFileExtension(fileName) }];
  }, [list, fileURL]);
 
  const { handlePreview } = useDocumentPreviewV2({
    entityId: merchantId,
    documentList:
      docList?.map((item: any) => ({
        ...item,
        name: item?.fileName,
        type: item?.fileType,
        URL: item.fileURL,
      })) || [],
    isDeleteHidden: !isDeleteAllowed,
    handleLocalDelete: (fileId?: number, fileName?: string) =>
      remove(id, fileId, fileName),
    keepOpen: keepPreviewOpen,
  });
  const actions = [
    {
      label: "view",
      children: <EyeIcon width={18} height={18} color="#8F8F8F" />,
      onClick: () =>
        handlePreview({
          ...props,
          id: isNaN(Number(id || 0)) ? (id as any) : Number(id || 0),
          fileType: props?.fileType || "",
          attTypeName: props?.attTypeName || "",
        }),
    },
    {
      label: "download",
      children: <DownloadIcon width={18} height={18} stroke="#8F8F8F" />,
      onClick: () => download(props),
    },
    {
      label: "delete",
      children: <TrashBin />,
      disabled: !isDeleteAllowed && !ignoreDeletePermission,
      onClick: () => remove(id, id as number, fileName),
      hide: hideDeleteIcon,
      tooltipProps: {
        show: !isDeleteAllowed && !ignoreDeletePermission,
        message: DELETE_DENY_MESSAGE,
      },
    },
  ];
 
  return (
    <ClickAwayListener onClickAway={() => setIsFocused(false)}>
      <ItemContainer
        sx={{
          ...(isFocused && {
            backgroundColor: palette.neutral.white,
            "& .document-item-actions": {
              display: "flex",
            },
          }),
        }}
        data-testid="actions-item-container"
      >
        <Stack direction="row">
          <TruncateText
            lineClamp={1}
            color={palette.black[100]}
            sx={{ wordBreak: "break-all" }}
            variant="body"
            fontWeight="book"
            data-testid={fileName}
          >
            {fileName?.substring(0, fileName?.lastIndexOf("."))}
          </TruncateText>
          <Text color={palette.black[100]} fontWeight="book">
            .{fileName?.substring(fileName?.lastIndexOf(".") + 1)}
          </Text>
        </Stack>
        <ActionsContainer className="document-item-actions">
          {actions.map((action) => {
            const { label, hide, tooltipProps, ...rest } = action;
            Iif (hide) return;
 
            return (
              <CustomToolTip
                key={label}
                showToolTip={!!tooltipProps?.show}
                message={tooltipProps?.message}
              >
                <ActionButton key={label} {...rest} />
              </CustomToolTip>
            );
          })}
        </ActionsContainer>
      </ItemContainer>
    </ClickAwayListener>
  );
};
 
const ItemContainer = styled(Stack)(({ theme }) => ({
  padding: "12px 16px",
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  gap: "8px",
  borderRadius: "8px",
  position: "relative",
  cursor: "pointer",
  minHeight: "50px",
 
  ":hover": {
    backgroundColor: palette.neutral.white,
    "& .document-item-actions": {
      display: "flex",
    },
  },
  [theme.breakpoints.down("sm")]: {
    flexDirection: "column",
    alignItems: "flex-start",
    justifyContent: "flex-start",
  },
}));
 
const ActionsContainer = styled(Stack)(() => ({
  display: "none",
  flexDirection: "row",
  alignItems: "center",
  padding: "4px 8px",
  gap: "12px",
  borderRadius: "4px",
  backgroundColor: palette.neutral.white,
  boxShadow: "0px 4px 8px 0px rgba(0, 0, 0, 0.08)",
}));
 
const ActionButton = styled(StyledIconButton)(() => ({
  maxWidth: "18px",
  maxHeight: "18px",
  backgroundColor: "inherit",
  borderRadius: "4px",
  padding: "0 !important",
}));