All files / src/hooks/upload-api useAddSignature.ts

36% Statements 9/25
13.33% Branches 2/15
50% Functions 2/4
37.5% Lines 9/24

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                    47x 378x                 47x   378x 378x 378x 378x   378x                                                                             378x          
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import {
  AcceptAllowedImagesTypes,
  useUploadSingleImage,
} from "@hooks/upload-api/uploadHooks";
import { useIsValidFile } from "@hooks/upload-api/useIsValidFile";
 
import { updateMerchant } from "@services/api/upload/uploadEndpoints";
import { useMutation, useQueryClient } from "react-query";
 
const useUpdateMerchant = () => {
  return useMutation(({ merchantId, signatureURL, ...rest }: any) => {
    return updateMerchant({
      merchantId,
      signatureURL,
      ...rest,
    });
  });
};
 
export const useAddSignature = () => {
  const { mutateAsync, isLoading: isLoadingUpdateMerchant } =
    useUpdateMerchant();
  const queryClient = useQueryClient();
  const { handleUpload, isLoading } = useUploadSingleImage();
  const { isValidFile } = useIsValidFile();
 
  const handleUploadSignature = async (
    merchantId: number,
    signature: { file: File } | File | any,
    updateMerchant = true,
    payload?: any,
  ) => {
    if (!signature) return "";
    let file;
    if (signature instanceof Blob) {
      file = signature;
    }
    if (signature.file) {
      file = signature.file;
    }
 
    if (
      !isValidFile({
        file,
        allowedTypes: Object.keys(AcceptAllowedImagesTypes),
      })
    ) {
      return "";
    }
    const url = await handleUpload({ file, formType: "customer_avatar" });
    if (updateMerchant && url) {
      try {
        await mutateAsync({ signatureURL: url, merchantId, ...payload });
        queryClient.invalidateQueries([
          MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET,
          merchantId,
        ]);
      } catch (err) {
        return "";
      }
    }
 
    return url;
  };
 
  return {
    handleUploadSignature,
    isLoading: isLoadingUpdateMerchant || isLoading,
  };
};