All files / src/hooks/onboarding useAddOnboardingBankAccounts.tsx

53.84% Statements 28/52
49.2% Branches 31/63
46.15% Functions 6/13
54.9% Lines 28/51

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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                                                                                28x 25x               25x               25x     28x                 15x 15x   15x                 15x   15x       15x                           15x     2x         2x                   2x     2x                             15x         15x 15x 15x   15x   15x     15x 15x       15x                                                                                                                                                                 15x                         15x       15x                                    
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { SubmitHandler, useForm } from "react-hook-form";
import { usePlaidService } from "@hooks/merchant-api/BankAccounts";
import { useMutation } from "react-query";
import { customInstance } from "@services/api";
import { AxiosError } from "axios";
import { showMessage } from "@common/Toast";
import { buildMerchantEndpoints } from "@services/api/utils.api";
import { StatusValue } from "react-dropzone-uploader";
import { useGetBankFiles } from "../merchant-api/BankAccounts/useGetBankFiles";
import { useRef } from "react";
import { challengeSlugs } from "@constants/challengeSlugs";
import {
  useUploadFiles,
  useUploadPresignedDocument,
} from "@hooks/upload-api/uploadHooks";
import { BANK_ACCOUNT_NUMBER_REGEX } from "@validation/regex";
import { createRoutingNumberValidator } from "@validation/fields";
import { VALIDATION_MESSAGES } from "@validation/messages";
import { getValidBankAccountNumber } from "@utils/bankAccountUtils";
import { BankAccountType } from "@redux/slices/enterprise/BankAccountType";
import { FileAttachmentType } from "@hooks/upload-api/uploadHooks";
 
export type TBankFormInputsNew = Omit<BankAccountType, "files"> & {
  files: {
    allFiles: {
      file: File;
      id: any;
    }[];
  };
};
export type TBankFormInputsOld = Omit<BankAccountType, "files"> & {
  files: {
    fileWithMeta: any | null;
    status: StatusValue;
    allFiles: any[];
  };
};
 
export const useBankAccountMutations = (bankAccountId?: number) => {
  const create = useMutation((data: any) =>
    customInstance({
      url: buildMerchantEndpoints("bank-accounts"),
      method: "POST",
      data,
    }),
  );
 
  const update = useMutation((data: any) =>
    customInstance({
      url: buildMerchantEndpoints(`bank-accounts/${bankAccountId}`),
      method: "PATCH",
      data: data?.params,
    }),
  );
 
  return { create, update };
};
 
const useAddOnboardingBankAccounts = (
  merchantId: number,
  backLink: () => void,
  firstAccount: any,
) => {
  const {
    open: startPlaidService,
    data: plaidData,
    isCreatingAccount,
  } = usePlaidService();
  const isForceError = useRef<boolean>(false);
 
  const { data: bankFiles, isLoading: bankFilesLoading } = useGetBankFiles({
    enabled: !!firstAccount,
    bankAccountId: firstAccount?.id,
    merchantId: merchantId,
  });
 
  const {
    create: createBankAccountMutation,
    update: updateBankAccountMutation,
  } = useBankAccountMutations(firstAccount?.id);
 
  const initialAccountNumber = firstAccount?.numberLast4
    ? `•••• ${firstAccount.numberLast4}`
    : "";
 
  const initialValues = {
    name: firstAccount?.name || "",
    accountType: firstAccount?.type?.toLocaleLowerCase() || "checking",
    routingNumber: firstAccount?.routingNumber || "",
    accountNumber: initialAccountNumber,
    notes: firstAccount?.notes || "",
    statements: [],
    files: {
      fileWithMeta: null,
      status: "started" as const,
      allFiles: [],
    },
  };
 
  const schema = Yup.object({
    ...(firstAccount?.status != "approved" && {
      name: Yup.string().when([], {
        is: () => Boolean(plaidData),
        then: Yup.string().nullable(),
        otherwise: Yup.string().required(VALIDATION_MESSAGES.REQUIRED),
      }),
      accountNumber: Yup.string().when([], {
        is: () => Boolean(firstAccount?.numberLast4),
        then: Yup.string(),
        otherwise: Yup.string()
          .required(VALIDATION_MESSAGES.REQUIRED)
          .matches(
            BANK_ACCOUNT_NUMBER_REGEX,
            VALIDATION_MESSAGES.INVALID_ACCOUNT_NUMBER,
          ),
      }),
      routingNumber: Yup.string().when([], {
        is: () => Boolean(plaidData),
        then: () => Yup.string().nullable(),
        otherwise: () =>
          createRoutingNumberValidator({
            required: true,
            requiredMessage: VALIDATION_MESSAGES.REQUIRED,
            invalidMessage: VALIDATION_MESSAGES.INVALID_ROUTING_NUMBER,
          }),
      }),
    }),
    notes: Yup.string(),
    ...((!bankFiles || bankFiles?.total < 1) && {
      files: Yup.object({
        allFiles: Yup.array<any>().min(1, VALIDATION_MESSAGES.REQUIRED),
      }).required(VALIDATION_MESSAGES.REQUIRED),
    }),
  });
 
  const methods = useForm<TBankFormInputsNew | TBankFormInputsOld>({
    resolver: yupResolver(schema),
    defaultValues: initialValues,
  });
 
  const { watch, setError } = methods;
  const values = watch();
  const { handleUpload, isLoading: uploadLoading } = useUploadFiles();
  const { handleUpload: uploadPresigned, isLoading: presignedLoading } =
    useUploadPresignedDocument();
 
  const isLoading = uploadLoading || presignedLoading;
 
  const hasFiles =
    (bankFiles?.total || 0 + values?.files?.allFiles.length || 0) > 0;
  const formDirty = firstAccount ? methods.formState.isDirty : true;
 
  const onSubmit: SubmitHandler<
    TBankFormInputsNew | TBankFormInputsOld
  > = async (data) => {
    if (firstAccount?.status !== "approved" && !hasFiles) return;
    if (plaidData) {
      await handleUpload({
        list: data.files?.allFiles,
        attachmentType: "bank_account",
        merchantId: merchantId,
        resourceID: plaidData.id,
        label: "bank account document",
        tag: FileAttachmentType.BankAccountConfirm,
      });
 
      backLink();
      return;
    }
 
    let uploadRes: string[] | "upload_failed" = [];
    if (!firstAccount && data.files?.allFiles?.length > 0) {
      uploadRes = await uploadPresigned({
        list: data.files?.allFiles,
        attachmentType: "bank_account",
      });
    }
    if (firstAccount && data.files?.allFiles?.length > 0) {
      await handleUpload(
        {
          list: data.files?.allFiles,
          merchantId: merchantId,
          resourceID: +firstAccount?.id,
          attachmentType: "bank_account",
          label: FileAttachmentType.BankAccountConfirm,
          tag: FileAttachmentType.BankAccountConfirm,
        },
        challengeSlugs.BANK_ACCOUNT_2,
      );
    }
 
    const customData = {
      routingNumber: data.routingNumber,
      ...(firstAccount?.status != "approved" && {
        name: data.name,
        type: data.accountType,
        ...getValidBankAccountNumber({
          isForceError,
          setError,
          accountNumber: data?.accountNumber,
          defaultAccountNumber: initialAccountNumber,
        }),
      }),
      notes: data.notes,
      status:
        firstAccount?.status === "approved" ? "approved" : "pending_review",
      ...(!firstAccount?.id && {
        isDefault: true,
      }),
      ...(Array.isArray(uploadRes) && {
        statements: uploadRes,
      }),
    };
 
    !isForceError.current &&
      (firstAccount
        ? updateBankAccountMutation
        : createBankAccountMutation
      ).mutate(
        { params: customData },
        {
          onError: (error: unknown) => {
            const axiosError = error as AxiosError;
            const errorMessage =
              (axiosError.response?.data as any)?.message ||
              "Whoops.. an error occured. Please try again";
            showMessage("Error", errorMessage);
          },
          onSuccess: async (res) => {
            backLink();
          },
        },
      );
  };
 
  const plaidHandler = async () => {
    if (plaidData) {
      await customInstance({
        url: buildMerchantEndpoints(`bank-accounts/${plaidData.id}`),
        method: "DELETE",
      });
 
      backLink();
    } else {
      startPlaidService();
    }
  };
 
  const isValidForm = plaidData
    ? true
    : values.name && values.accountNumber && values.routingNumber;
 
  return {
    isCreatingAccount,
    methods,
    onSubmit,
    plaidHandler,
    plaidData,
    isDisabled:
      !isValidForm ||
      (firstAccount?.status !== "approved" && !hasFiles) ||
      isLoading ||
      !formDirty ||
      createBankAccountMutation.isLoading,
    bankFiles,
    bankFilesLoading,
  };
};
 
export default useAddOnboardingBankAccounts;