All files / src/components/BankAccounts UploadStatement.tsx

80% Statements 24/30
58.33% Branches 7/12
50% Functions 5/10
82.75% Lines 24/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 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                                                                                                      1x   48x 48x 48x 48x   48x   48x               48x   48x         48x 48x   48x       6x 6x 12x                     6x   6x         6x 6x   48x           48x 12x                 48x                                                                                                                       72x                                      
import { palette } from "@palette";
// @mui
import Box from "@mui/material/Box";
// components
import { Text } from "@common/Text";
import { Modal, ModalTitle } from "@common/Modal";
 
// assets
import { ArrowBackIcon } from "@assets/icons";
import { StatusValue } from "react-dropzone-uploader";
import NiceModal, { muiDialogV5, useModal } from "@ebay/nice-modal-react";
import CampaignModalActions from "@common/Modal/CampaignModalActions";
import { SubmitHandler, useForm, FormProvider } from "react-hook-form";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useGetCurrentMerchantId } from "@hooks/common";
import { customInstance } from "@services/api";
import { useQueryClient } from "react-query";
import { buildMerchantEndpoints } from "@services/api/utils.api";
import FadeUpWrapper from "@components/animation/FadeUpWrapper";
import { useFileUploadContext } from "@components/UploadFile/FileUploadContext";
import { UploadFileDocumentPreviewItem } from "@components/UploadFile/Rebranded/UploadFileDocumentPreviewItem";
import { IMerchantBankAccount } from "@components/Merchants/MerchantPreview/data.types";
import {
  AcceptAllowedGeneralDocumentsTypes,
  useUploadFiles,
} from "@hooks/upload-api/uploadHooks";
import { UploadFileNew } from "@components/UploadFile/Rebranded/UploadFileNew";
import { DocumentUploadDisclaimer } from "@components/ProfilePage/BankAccountSetup/OnboardingBankStatement";
import { QKEY_LIST_ALL_BANK_ACCOUNTS } from "@constants/queryKeys";
import { FileAttachmentType } from "@hooks/upload-api/uploadHooks";
 
type UploadStatementProps = {
  data: IMerchantBankAccount;
  merchantId?: number;
};
 
type IFormInputsNew = {
  files: {
    allFiles: {
      file: File;
    }[];
  };
};
type IFormInputs = {
  files: {
    fileWithMeta: any | null;
    status: StatusValue;
    allFiles: any[];
  };
};
const UploadStatement = NiceModal.create(
  ({ data, merchantId }: UploadStatementProps) => {
    const modal = useModal();
    const queryClient = useQueryClient();
    const { merchantId: currentMerchantID } = useGetCurrentMerchantId();
    const { handleUpload, isLoading } = useUploadFiles();
 
    const { isUploadAllowed } = useFileUploadContext();
 
    const defaultValues = {
      files: {
        fileWithMeta: null,
        status: "started" as const,
        allFiles: [],
      },
    };
 
    const schema = Yup.object({});
 
    const methods = useForm<IFormInputsNew | IFormInputs>({
      resolver: yupResolver(schema),
      defaultValues,
    });
 
    const { watch, setValue } = methods;
    const values = watch();
 
    const onSubmit: SubmitHandler<IFormInputsNew | IFormInputs> = async (
      submittedData,
    ) => {
      let uploadRes;
      Eif (submittedData.files?.allFiles?.length > 0) {
        uploadRes = await handleUpload({
          list: submittedData.files?.allFiles.map((item, index) => ({
            file: item.file,
            id: index,
          })),
          merchantId: merchantId || currentMerchantID,
          resourceID: +data.id,
          attachmentType: "bank_account",
          label: "bank account document",
          tag: FileAttachmentType.BankAccountConfirm,
        });
      }
      Iif (uploadRes === "upload_failed") return;
 
      await customInstance({
        url: buildMerchantEndpoints(`bank-accounts/${data.id}`),
        method: "PATCH",
        data: { status: "pending_review" },
      });
      queryClient.invalidateQueries(QKEY_LIST_ALL_BANK_ACCOUNTS);
      modal.hide();
    };
    const deleteFileHandlerNew = (id: string | number) => {
      setValue("files", {
        allFiles: values.files.allFiles.filter((_, i) => i !== id),
      } as any);
    };
 
    const handleSelect = (file: File) => {
      setValue(
        "files",
        {
          allFiles: [...values.files.allFiles, { file }],
        } as any,
        { shouldDirty: true },
      );
    };
 
    return (
      <Modal
        {...muiDialogV5(modal)}
        width="600px"
        sx={{
          "& .MuiDialogContent-root": {
            paddingTop: "0px !important",
            marginTop: "0px !important",
          },
        }}
        backgroundColor={palette.liftedWhite.main}
        headerComponent={
          <ModalTitle
            backgroundColor={palette.liftedWhite.main}
            title="Upload bank statement"
            subTitle={`"${data.name || ""}" ${data.bankName || ""}`}
            onClose={() => modal.hide()}
          />
        }
        onClose={() => modal.hide()}
        actions={
          <CampaignModalActions
            isShowDiscard
            isNotFullWidth
            direction="row"
            form="upload-statement"
            primaryBtnLabel={"Upload"}
            handleDiscard={() => modal.hide()}
            isSecondaryActionDisabled={false}
            isPrimaryActionDisabled={
              values.files.allFiles.length === 0 || isLoading
            }
            discardBtnLabel={
              <Box gap={1.5} display="flex" alignItems="center">
                <ArrowBackIcon />
                <Text color={palette.neutral[600]}>Back to bank accounts</Text>
              </Box>
            }
          />
        }
      >
        <FormProvider {...methods}>
          <Box
            component="form"
            id="upload-statement"
            onSubmit={methods.handleSubmit(onSubmit)}
          >
            {/** -------- Upload Icon -------- */}
            <FadeUpWrapper delay={80}>
              <DocumentUploadDisclaimer isFirstStep />
              <Box mb={1} mt={2.5}>
                <UploadFileNew
                  uploadFunction={handleSelect}
                  disabled={!isUploadAllowed}
                  accept={AcceptAllowedGeneralDocumentsTypes}
                />
              </Box>
            </FadeUpWrapper>
            <FadeUpWrapper delay={250}>
              {values.files.allFiles.map((file, index) => {
                return (
                  <UploadFileDocumentPreviewItem
                    key={index}
                    fileName={file.file.name}
                    id={index}
                    deleteDocument={deleteFileHandlerNew}
                    fileURL={URL.createObjectURL(file.file)}
                  />
                );
              })}
            </FadeUpWrapper>
          </Box>
        </FormProvider>
      </Modal>
    );
  },
);
 
export default UploadStatement;