All files / src/features/GiveOnboarding/pages/Bank GiveUploadModal.tsx

71.42% Statements 25/35
53.33% Branches 8/15
75% Functions 6/8
75.86% Lines 22/29

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                                                                  1x   21x 21x     21x 21x 21x   21x           21x   21x   21x 1x 1x     21x 1x       1x     21x         21x 1x     1x   1x                                 21x                   21x                                                                                                                                  
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { CircularProgress, Stack } from "@mui/material";
import { useAppTheme } from "@theme/v2/Provider";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveButton from "@shared/Button/GiveButton";
import BankFilesUploader from "./BankFilesUploader";
import { FormProvider, useForm } from "react-hook-form";
import moment from "moment";
import { useAppSelector } from "@redux/hooks";
import { selectUser } from "@redux/slices/auth/auth";
import {
  AcceptAllowedImagesTypes,
  FileAttachmentType,
  useUploadFiles,
} from "@hooks/upload-api/uploadHooks";
import { useState } from "react";
import GiveText from "@shared/Text/GiveText";
import { showMessage } from "@common/Toast";
 
interface ModalProps {
  merchantId: number;
  resourceID?: number;
  tag: FileAttachmentType.BankAccountConfirm; //we can add more options if we reuse the modal
  onSuccess?: () => void;
}
 
type FormInputs = {
  files: {
    file: File;
    createdAt: number;
  }[];
};
 
export const GiveUploadModal = NiceModal.create(
  ({ resourceID, merchantId, tag, onSuccess }: ModalProps) => {
    const modal = useModal();
    const theme = useAppTheme();
    const {
      globalName: { firstName, lastName },
    } = useAppSelector(selectUser);
    const { handleUpload, isLoading } = useUploadFiles();
    const [isFormError, setIsFormError] = useState(false);
 
    const methods = useForm<FormInputs>({
      defaultValues: {
        files: undefined,
      },
    });
 
    const { reset, watch, setValue } = methods;
 
    const { files } = watch();
 
    const handleCancel = () => {
      reset();
      modal.remove();
    };
 
    const onLocalUpload = (file: File | File[]) => {
      const usedFile = {
        file: file as File,
        createdAt: moment().unix(),
      };
      setValue("files", [usedFile]);
    };
 
    const onLocalDelete = (id: string | number, name: string) => {
      const filteredFiles = files?.filter((item) => item.file.name !== name);
      setValue("files", filteredFiles);
    };
 
    const onSubmit = async () => {
      const filesToUpload = files?.map((file) => ({
        file: file.file as File,
      }));
      Iif (!filesToUpload || filesToUpload.length < 1)
        return setIsFormError(true);
      Eif (!resourceID) return showMessage("Error", "No bank account found.");
 
      const result = await handleUpload({
        list: filesToUpload,
        merchantId,
        resourceID: resourceID,
        attachmentType: tag,
        label: tag,
        tag: FileAttachmentType.BankAccountConfirm,
      });
 
      if (result === "upload_failed") return;
      if (onSuccess) onSuccess();
      handleCancel();
    };
 
    //to use them as local files before submission
    const parsedLocalFiles = files?.map((file, index) => ({
      ...file.file,
      id: index,
      createdAt: file.createdAt,
      userFullName: `${firstName} ${lastName}`,
      fileName: file.file.name,
      fileType: file.file.type,
      fileURL: URL.createObjectURL(file.file),
    })) as any[];
 
    return (
      <GiveBaseModal
        title={
          (
            <GiveText variant="bodyS">Business Bank Account Statement</GiveText>
          ) as any
        }
        height="fit-content"
        open={modal.visible}
        onClose={handleCancel}
        buttons={
          <>
            <GiveButton
              label="Cancel"
              size="large"
              onClick={handleCancel}
              disabled={isLoading}
              variant="ghost"
            />
            <GiveButton
              label="Upload"
              size="large"
              onClick={onSubmit}
              disabled={isLoading || !files || files.length < 1}
              endIcon={
                isLoading ? (
                  <CircularProgress
                    size={14}
                    style={{
                      color: theme?.palette.primitive?.neutral?.[0],
                    }}
                  />
                ) : undefined
              }
            />
          </>
        }
        sx={{
          "& .MuiPaper-root": {
            width: "640px !important",
            maxWidth: "640px !important",
          },
        }}
      >
        <FormProvider {...methods}>
          <Stack component="form" gap="24px">
            <BankFilesUploader
              title="Upload File"
              tag={tag}
              isFormError={isFormError}
              merchantId={merchantId}
              resourceID={resourceID}
              bankFiles={parsedLocalFiles}
              max={1}
              onLocalUpload={onLocalUpload}
              onLocalDelete={onLocalDelete}
              isLoading={isLoading}
              accept={AcceptAllowedImagesTypes}
            />
          </Stack>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);