All files / src/features/MerchantPortal/ManageMoney/modals GiveUploadStatementModal.tsx

70.45% Statements 31/44
68.42% Branches 13/19
50% Functions 5/10
69.76% Lines 30/43

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                                                                        1x   9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x               9x     9x       9x         9x                 9x 9x   9x               9x   1x 1x 1x                     1x                                   9x                                                 9x 1x                                 9x 3x     9x                                                                                                                                              
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import { GiveDocumentUploadDisclaimer } from "@components/ProfilePage/BankAccountSetup/GiveOnboardingBankStatement";
import { useFileUploadContext } from "@components/UploadFile/FileUploadContext";
import { GiveUploadFileNew } from "@components/UploadFile/Rebranded/GiveUploadFileNew";
import NiceModal from "@ebay/nice-modal-react";
import { Box, Stack } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
import { checkPortals } from "@utils/routing";
import { useGetCurrentMerchantId } from "@hooks/common";
import { SubmitHandler, useForm, FormProvider } from "react-hook-form";
import { useUploadFiles } from "@hooks/upload-api/uploadHooks";
import { customInstance } from "@services/api";
import { QKEY_LIST_ALL_BANK_ACCOUNTS } from "@constants/queryKeys";
import { useMutation, useQueryClient } from "react-query";
import { uniqueId } from "lodash";
import { selectUser } from "@redux/slices/auth/auth";
import { useAppSelector } from "@redux/hooks";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import { CircularProgress } from "@mui/material";
import { useAppTheme } from "@theme/v2/Provider";
import { useEffect } from "react";
import useDeleteDocument from "@features/Merchants/MerchantSidePanel/GiveMerchantFile/hooks/useDeleteDocument";
import { FileAttachmentType } from "@hooks/upload-api/uploadHooks";
 
type IFormInputs = {
  files: { id: string; createdAt: Date; createdBy: string; file: File }[];
  removedExistingFiles: { id: number | string; name: string }[];
};
 
type Props = {
  bankAccountId: number;
};
 
const GiveUploadStatementModal = NiceModal.create(
  ({ bankAccountId }: Props) => {
    const { open, onClose } = useNiceModal();
    const { isMobileView } = useCustomThemeV2();
    const { isUploadAllowed } = useFileUploadContext();
    const { isEnterprisePortal } = checkPortals();
    const { merchantId } = useGetCurrentMerchantId();
    const user = useAppSelector(selectUser);
    const { handleUpload, isLoading: uploadLoading } = useUploadFiles();
    const queryClient = useQueryClient();
    const { palette } = useAppTheme();
    const { deleteDocument } = useDeleteDocument();
 
    const updateBankAccountMutation = useMutation((data: any) => {
      return customInstance({
        url: `/merchants/${merchantId}/bank-accounts/${bankAccountId}`,
        method: "PATCH",
        data,
      });
    });
 
    const isLoading = uploadLoading || updateBankAccountMutation.isLoading;
 
    const documentType =
      UploadDocumentTypes[
        isEnterprisePortal ? "providerBankAccount" : "merchantBankAccount"
      ];
 
    const defaultValues = {
      files: [],
      removedExistingFiles: [],
    };
 
    const methods = useForm<IFormInputs>({
      defaultValues,
    });
 
    const {
      watch,
      setValue,
      reset,
      formState: { isDirty },
    } = methods;
    const values = watch();
 
    const refetchFiles = () => {
      queryClient.invalidateQueries([
        MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_BANK_FILES,
        merchantId,
        bankAccountId,
      ]);
    };
 
    const onSubmit: SubmitHandler<IFormInputs> = async (submittedData) => {
      let uploadRes;
      Eif (submittedData.files?.length > 0) {
        uploadRes = await handleUpload({
          list: submittedData.files?.map((item) => ({
            file: item.file,
            id: item.id,
          })),
          merchantId: merchantId,
          resourceID: +bankAccountId,
          attachmentType: "bank_account",
          label: FileAttachmentType.BankAccountConfirm,
          tag: FileAttachmentType.BankAccountConfirm,
        });
      }
      Eif (uploadRes === "upload_failed") return;
 
      await updateBankAccountMutation.mutateAsync({ status: "pending_review" });
 
      submittedData.removedExistingFiles.map((file) => {
        deleteDocument(
          merchantId,
          { fileName: file.name, id: +file.id },
          refetchFiles,
          true,
        );
      });
 
      queryClient.invalidateQueries(QKEY_LIST_ALL_BANK_ACCOUNTS);
      refetchFiles();
      onClose();
    };
 
    const deleteFileHandlerNew = (
      id: string | number,
      name: string,
      isExist: boolean,
    ) => {
      if (isExist) {
        setValue(
          "removedExistingFiles",
          [...values.removedExistingFiles, { id, name }],
          {
            shouldDirty: true,
          },
        );
        return;
      }
 
      setValue(
        "files",
        values.files.filter((file) => file.id !== id),
        {
          shouldDirty: true,
        },
      );
    };
 
    const handleSelect = (file: File | File[]) => {
      setValue(
        "files",
        [
          ...values.files,
          {
            id: uniqueId(),
            createdAt: new Date(),
            createdBy: `${user.globalName.firstName} ${user.globalName.lastName}`,
            file: file as File,
          },
        ],
        {
          shouldDirty: true,
        },
      );
    };
 
    useEffect(() => {
      reset(defaultValues);
    }, [open]);
 
    return (
      <GiveBaseModal
        open={open}
        title="Upload Bank Statement"
        width={isMobileView ? "100%" : "720px"}
        height="fit-content"
        onClose={onClose}
        buttons={
          <Stack direction="row" spacing={1.5} justifyContent="flex-end">
            <GiveButton
              variant="ghost"
              size="large"
              label="Cancel"
              disabled={isLoading}
              onClick={onClose}
            />
            <GiveButton
              size="large"
              variant="filled"
              label="Upload"
              disabled={isLoading || !isDirty || values.files.length === 0}
              type="submit"
              form="upload-statement"
              endIcon={
                isLoading ? (
                  <CircularProgress
                    size={14}
                    style={{
                      color: palette.primitive?.neutral?.[0],
                    }}
                  />
                ) : undefined
              }
            />
          </Stack>
        }
      >
        <FormProvider {...methods}>
          <GiveDocumentUploadDisclaimer stepCount={0} isUploadStatement />
          <Box
            component="form"
            id="upload-statement"
            onSubmit={methods.handleSubmit(onSubmit)}
            mt={2.5}
            sx={{
              "& .dzu-dropzone": {
                minWidth: "0 !important",
              },
              "& input": {
                height: "0px !important",
              },
            }}
          >
            <GiveUploadFileNew
              disabled={!isUploadAllowed || isLoading}
              documentType={documentType}
              merchantId={merchantId}
              bankAccountId={bankAccountId}
              uploadLocalFile={handleSelect}
              deleteLocalFile={deleteFileHandlerNew}
              localFiles={values.files}
              removedExistingFiles={values.removedExistingFiles}
            />
          </Box>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
export default GiveUploadStatementModal;