All files / src/components/ProfilePage/EnterpriseAgreement useEnterpriseAgreement.ts

71.42% Statements 30/42
70.58% Branches 12/17
66.66% Functions 6/9
70.73% Lines 29/41

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                                                                  19x         29x   29x 29x     29x   29x   29x         29x                 29x 29x   29x     29x   29x 7x 7x 7x     29x 25x     29x 5x 5x               29x                                                     29x           29x     29x                 19x       9x             19x 35x  
import { SubmitHandler, useForm } from "react-hook-form";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useCalculatePercentage } from "@common/SignUp/useCalculatePercentage";
import { useEffect, useRef } from "react";
import { cloneDeep, isEqual } from "lodash";
import { useUpdateMerchantInfo } from "@components/Merchants/MerchantPreview/hooks/useUpdateMerchantInfo";
import {
  TMerchantInfo,
  TPrimaryAccountHolder,
} from "@components/Merchants/MerchantPreview/data.types";
import { TMerchantAgreementPayload } from "@components/Merchants/CreateMerchantPanel/hooks/TMerchantAgreementPayload";
import { useQueryClient } from "react-query";
import { showMessage } from "@common/Toast";
import { QKEY_GET_MERCHANT_BY_ID } from "@constants/queryKeys";
import { useAsyncAction } from "@hooks/customReactCore";
import { useAddSignature as useAddSignatureNew } from "@hooks/upload-api/useAddSignature";
import { VALIDATION_MESSAGES } from "@validation/messages";
 
type FormInputs = {
  signature: File | string;
  hasAgreed: boolean;
};
 
type TData = {
  merchantInfo: TMerchantInfo;
  primaryAccountHolder: TPrimaryAccountHolder;
  merchantAgreement: TMerchantAgreementPayload;
  status: {
    statusName: string;
  };
};
 
const useEnterpriseAgreement = (
  handleUpdateStatusValue: (v: number) => void,
  data: TData,
  backLink: () => void,
) => {
  const merchantId = data.merchantInfo.merchantID;
  const { handleSubmit, isLoading: isLoadingInfo } =
    useUpdateMerchantInfo(merchantId);
  const [isLoading, triggerAction] = useAsyncAction();
 
  const { handleUploadSignature, isLoading: isLoadingSignature } =
    useAddSignatureNew();
 
  const queryClient = useQueryClient();
 
  const defaultValues = {
    hasAgreed: false,
    signature: "",
  };
 
  const methods = useForm<FormInputs>({
    resolver: yupResolver(schema),
    defaultValues,
  });
 
  const {
    watch,
    reset,
    formState: { dirtyFields },
  } = methods;
  const values = watch();
 
  const { calculatePercentageNested } = useCalculatePercentage({
    isEdit: false,
  });
  const savedData = useRef<FormInputs>();
 
  const calcPercentage = async () => {
    savedData.current = cloneDeep(values);
    const value = await calculatePercentageNested(schema, values);
    handleUpdateStatusValue(value);
  };
 
  useEffect(() => {
    if (!isEqual(values, savedData.current)) calcPercentage();
  }, [values]);
 
  useEffect(() => {
    Eif (data) {
      reset({
        ...defaultValues,
        hasAgreed: !!data.merchantAgreement.signatureURL,
        signature: data.merchantAgreement.signatureURL,
      });
    }
  }, [data]);
 
  const onSubmit: SubmitHandler<FormInputs> = async (data) => {
    if (!values.signature) {
      showMessage("Error", "Please sign the agreement");
      return;
    }
    if (!dirtyFields.signature) {
      backLink();
      return;
    }
 
    const signatureURL = await handleUploadSignature(
      merchantId,
      values.signature,
      false,
    );
    const payload = {
      msaHadAgreed: data.hasAgreed,
      signatureURL,
    };
 
    handleSubmit("merchant_agreement", payload, () => {
      backLink();
      queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]);
    });
  };
 
  const isSubmitDisabled =
    (!dirtyFields.signature && !validateSignature(values.signature)) ||
    !values?.hasAgreed ||
    isLoadingInfo ||
    isLoadingSignature ||
    isLoading;
 
  const handleTriggerSubmit = (data: any) =>
    triggerAction(onSubmit as any, data);
 
  return {
    methods,
    onSubmit: handleTriggerSubmit,
    isDisabled: isSubmitDisabled,
  };
};
 
export default useEnterpriseAgreement;
 
const schema = Yup.object().shape({
  signature: Yup.mixed<File | string>().test(
    "is-valid-signature",
    "The signature is not valid",
    (value) => validateSignature(value),
  ),
  hasAgreed: Yup.boolean()
    .required(VALIDATION_MESSAGES.AGREEMENT_REQUIRED)
    .oneOf([true], "Should Agree to proceed"),
});
 
export const validateSignature = (signature?: File | string) =>
  (typeof signature !== "string" && !!signature?.type) || !!signature;