All files / src/sections/VerifyAccountHolder_v2/hooks useManageApi.ts

87.5% Statements 14/16
52.94% Branches 9/17
83.33% Functions 5/6
87.5% Lines 14/16

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                        27x 3x   116x 115x 3x             115x             3x   3x   3x                           3x   2x 2x 2x                       115x          
import { FormInputs } from "../form/form.type";
import { useMutation, useQueryClient } from "react-query";
import { customInstance } from "@services/api";
import { showMessage } from "@common/Toast";
import { isEmpty, isFunction } from "lodash";
import { toISODateString } from "@utils/date.helpers";
import {
  QKEY_BUSINESS_PROFILE_BY_ID,
  QKEY_GET_MERCHANT_BY_ID,
} from "@constants/queryKeys";
import moment from "moment";
 
const isValidDate = (date: string | Date | null) =>
  date instanceof Date && !isNaN(date.getTime());
export default function useManageApi(merchantId: number) {
  const queryClient = useQueryClient();
  const { mutate, isLoading } = useMutation((data: any) => {
    return customInstance({
      url: `/merchants/${merchantId}`,
      method: "PATCH",
      data,
    });
  });
 
  const onSubmitInformation = async (
    data:
      | Partial<FormInputs & { principalId?: number; legalEntityId?: number }>
      | any = {},
    onSuccess?: (data: FormInputs) => void,
    onError?: (error: any) => void,
  ) => {
    const phoneNumber = data?.base?.phoneNumber?.replace(/[\s+]/g, "") || "";
 
    const dateOfBirth = data?.base?.dob ?? data?.base?.dateOfBirth;
 
    const payload = {
      owner: {
        firstName: data?.base?.firstName,
        lastName: data?.base?.lastName,
        phoneNumber: isEmpty(phoneNumber) ? null : phoneNumber,
        citizenship: data?.base?.citizenship,
        countryOfResidence: data?.base?.countryOfResidence,
        dateOfBirth: isValidDate(dateOfBirth as Date)
          ? toISODateString(dateOfBirth as Date)
          : null,
      },
      ownerIsManagerialAuthority: data.base?.isManager,
    } as any;
 
    mutate(payload, {
      onSuccess() {
        queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]);
        queryClient.invalidateQueries(QKEY_BUSINESS_PROFILE_BY_ID);
        isFunction(onSuccess) && onSuccess(data);
      },
      onError(error: any, variables, context) {
        isFunction(onError) && onError(error);
        showMessage(
          "Error",
          error?.response?.data?.message ||
            "Something went wrong while saving informations.",
        );
      },
    });
  };
  return {
    onSubmitInformation,
    informationsAreLoading: isLoading,
  };
}