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

55.55% Statements 25/45
59.25% Branches 16/27
40% Functions 6/15
58.97% Lines 23/39

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                                                                                                  32x                 30x 30x   30x 30x 30x 30x 30x 30x   7x               7x 1x   1x                   7x     30x   30x                                                                 30x 1x   1x 1x 1x                                     30x                         30x                                                                                                                                                                
import * as React from "react";
import "react-dropzone-uploader/dist/styles.css";
import {
  AcceptAllowedGeneralDocumentsTypes,
  MAX_UPLOAD_SIZE,
  useUploadFiles,
} from "@hooks/upload-api/uploadHooks";
import { Box, Stack } from "@mui/material";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
import TaskCard from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/TaskCard";
import GiveUploadArea from "@shared/FileUpload/GiveUploadArea";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import { AttachmentsUpload } from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/Sections.atoms";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import { UploadSimpleIcon } from "@phosphor-icons/react";
import { checkPortals } from "@utils/routing";
import { useQueryClient } from "react-query";
import {
  QKEY_GET_MERCHANT_BY_ID,
  QKEY_IDENTIFICATION_FILES,
} from "@constants/queryKeys";
import { useGetIdentificationFiles } from "@sections/VerifyAccountHolder_v2/hooks/useCamera";
import { TMerchantDocument } from "@components/Merchants/MerchantPreview/data.types";
import moment from "moment";
import GiveUploadStack from "@shared/FileUpload/GiveUploadStack";
import { useParseDocumentsList } from "@features/Merchants/MerchantSidePanel/GiveMerchantFile/components/DocumentsSection";
import useDeleteDocument from "@features/Merchants/MerchantSidePanel/GiveMerchantFile/hooks/useDeleteDocument";
 
type UploadFileProps = {
  disabled?: boolean;
  documentType?: UploadDocumentTypes;
  merchantId: number;
  bankAccountId?: number;
  localFiles?: {
    id: string;
    createdAt: Date;
    createdBy: string;
    file: File | File[];
  }[];
  removedExistingFiles?: { id: string | number; name: string }[];
  uploadLocalFile?: (file: File | File[]) => void;
  deleteLocalFile?: (
    id: string | number,
    name: string,
    isExist: boolean,
  ) => void;
};
 
export const GiveUploadFileNew = React.memo(function UploadFile({
  disabled = false,
  merchantId,
  bankAccountId,
  localFiles = [],
  removedExistingFiles = [],
  uploadLocalFile,
  deleteLocalFile,
}: UploadFileProps) {
  const theme = useAppTheme();
  const { isEnterprisePortal } = checkPortals();
 
  const { handleUpload } = useUploadFiles();
  const queryClient = useQueryClient();
  const { parseDocumentsList } = useParseDocumentsList();
  const { deleteDocument } = useDeleteDocument();
  const { data: files } = useGetIdentificationFiles({ ID: merchantId });
  const bankFiles = React.useMemo(() => {
    const initFiles =
      files?.data
        ?.filter((doc: any) => doc?.attTypeName === "bank_account")
        ?.filter((doc: any) => doc?.bankAccountID === bankAccountId)
        ?.filter(
          (doc: any) =>
            !removedExistingFiles.some((file) => +file.id === +doc.id),
        ) || [];
 
    const parsedLocalFiles = localFiles.flatMap((item) => {
      const fileList = Array.isArray(item.file) ? item.file : [item.file];
 
      return fileList.map((f) => ({
        id: item.id,
        createdAt: moment(item.createdAt).unix(),
        userFullName: item.createdBy,
        fileName: f.name,
        fileType: f.type,
        fileURL: URL.createObjectURL(f),
      }));
    });
 
    return [...initFiles, ...parsedLocalFiles];
  }, [files, localFiles, removedExistingFiles]) as TMerchantDocument[];
 
  const isNoBankFile = bankFiles.length === 0;
 
  const parsedData = !isNoBankFile
    ? parseDocumentsList({
        documents: bankFiles,
        id: merchantId,
        handleDeleteDocument: (data, fileId) => {
          const filetoDelete = bankFiles?.find((item) => item?.id === fileId);
          const isLocalFile = filetoDelete?.fileURL?.startsWith("blob");
 
          if (!filetoDelete) return;
 
          if (isLocalFile) {
            return deleteLocalFile?.(fileId, filetoDelete?.fileName, false);
          }
          deleteDocument(
            merchantId,
            { fileName: filetoDelete?.fileName, id: filetoDelete?.id },
            () => {
              queryClient.invalidateQueries([
                QKEY_IDENTIFICATION_FILES,
                merchantId,
              ]);
              () => {
                queryClient.invalidateQueries([
                  QKEY_IDENTIFICATION_FILES,
                  merchantId,
                ]);
              };
            },
          );
        },
      })
    : [];
 
  const uploadFunction = async (file: File | File[]) => {
    const fileArray = Array.isArray(file) ? file : [file];
 
    Eif (uploadLocalFile) {
      fileArray.forEach((f) => uploadLocalFile(f));
      return;
    }
 
    const filesToUpload = fileArray.map((f) => ({ file: f as File }));
 
    await handleUpload({
      list: filesToUpload,
      merchantId,
      resourceID: bankAccountId as number,
      attachmentType: "bank_account",
      label: "",
      tag: "Acquirer document",
    });
 
    queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]);
    queryClient.invalidateQueries([QKEY_IDENTIFICATION_FILES, merchantId]);
  };
 
  const uploadMessage = (
    <Stack justifyContent="center" gap="8px">
      <GiveText textAlign="center" color="secondary" variant="bodyXS">
        Drag and drop your files here or{" "}
        <Box component="span" color={theme.palette.primitive?.blue[100]}>
          click to browse
        </Box>
      </GiveText>
      <GiveText color="secondary" variant="bodyXS">
        {`Up to ${MAX_UPLOAD_SIZE.label} each (.pdf, .png, .jpg, .jpeg, .webp, .heic)`}
      </GiveText>
    </Stack>
  );
 
  return (
    <TaskCard
      title="Attachment"
      containerSx={{ width: "100%" }}
      actions={
        isNoBankFile
          ? []
          : [
              {
                element: (
                  <AttachmentsUpload
                    merchantID={merchantId}
                    isEnterprise={isEnterprisePortal}
                    handleCustomUpload={uploadLocalFile}
                    disabled={disabled}
                    customElement={
                      <GiveIconButton
                        variant="ghost"
                        size="small"
                        Icon={UploadSimpleIcon}
                        disabled={disabled}
                      />
                    }
                    resourceID={bankAccountId}
                    attachmentType="bank_account"
                    sx={{
                      backgroundColor: "transparent",
                      padding: 0,
                      height: "auto",
                      width: "auto",
                    }}
                  />
                ),
              },
            ]
      }
      sx={{
        ...(!isNoBankFile && { padding: 0 }),
      }}
    >
      <>
        <GiveUploadArea
          height="113px"
          message={uploadMessage}
          disabled={disabled}
          uploadFunction={uploadFunction}
          accept={AcceptAllowedGeneralDocumentsTypes}
          multiple
          maxSizeInBytes={MAX_UPLOAD_SIZE.value}
          backgroundColor="transparent"
          title="Upload file"
          showSelectFileButton={false}
          sx={{
            ...(!isNoBankFile && {
              padding: 0,
              height: "auto",
              margin: 0,
            }),
          }}
          iconBg={theme.palette.primitive?.transparent["darken-5"]}
          customElement={
            !isNoBankFile && (
              <GiveUploadStack
                items={parsedData ?? []}
                hideEditButtons
                customStyles={{
                  border: "none",
                  width: "100%",
                  borderBottomLeftRadius: "20px",
                  borderBottomRightRadius: "20px",
                  padding: 0,
                }}
              />
            )
          }
        />
      </>
    </TaskCard>
  );
});