All files / src/hooks/common/documents utils.tsx

16.45% Statements 13/79
12.82% Branches 5/39
8.33% Functions 1/12
17.33% Lines 13/75

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              121x           2x 2x 2x     2x                           121x               121x                     121x                           121x                 121x                                                           121x                                                                                               121x             121x                          
import { showMessage } from "@common/Toast";
import { TPosition } from "@common/Toast/ShowToast";
import { deleteDocumentAPI } from "@components/Settings/Business/Documents/utils";
import NiceModal from "@ebay/nice-modal-react";
import { customInstance } from "@services/api";
import { DELETE_CONFIRMATION_MODAL } from "modals/modal_names";
 
export const deleteDocument = (
  merchantID: number,
  document: { fileName: string; id: number },
  onEnd?: () => void,
  { isTmpFile = false, hideModal = false } = {},
) => {
  const { fileName, id } = document;
  const deleteHandler = () => deleteDocumentAPI(merchantID, id, onEnd, true);
  Iif (hideModal) {
    deleteHandler();
  } else {
    NiceModal.show(DELETE_CONFIRMATION_MODAL, {
      variant: "document",
      deleteHandler: isTmpFile ? onEnd : deleteHandler,
      itemName: fileName,
    });
  }
};
 
type TFile = {
  fileName: string;
  fileURL: string;
  label?: string;
};
 
const getToastPosition = (isDesktop?: boolean): TPosition | undefined =>
  !isDesktop
    ? {
        position: "top-left",
        style: { top: "47px", left: "7px" },
      }
    : undefined;
 
const showError = (fileName: string, message: string, isDesktop?: boolean) => {
  showMessage(
    "Warning",
    `Failed to download ${fileName}: ${message || "Unknown error"}`,
    false,
    "",
    undefined,
    getToastPosition(isDesktop),
  );
};
 
const ensureFileNameHasExtension = (fileName: string, label?: string) => {
  const hasExtension = /\.[0-9a-z]+$/i.test(fileName);
  if (hasExtension || !label) return fileName;
 
  const labelExtensionMatch = label.match(/\.[0-9a-z]+$/i);
  if (labelExtensionMatch) {
    return fileName + labelExtensionMatch[0];
  } else if (/^[0-9a-z]+$/i.test(label)) {
    return fileName + `.${label}`;
  }
 
  return fileName;
};
 
const triggerDownload = (blobURL: string, fileName: string) => {
  const link = document.createElement("a");
  link.href = blobURL;
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  link.remove();
};
 
export const downloadBase64Document = async (
  file: TFile,
  isDesktop?: boolean,
) => {
  const fileName = ensureFileNameHasExtension(file.fileName, file.label);
 
  try {
    const response = await fetch(file.fileURL, {
      credentials: "omit",
    });
 
    if (!response.ok) {
      const errorText = await response.text();
      showError(fileName, errorText, isDesktop);
      return;
    }
 
    const blob = await response.blob();
    const blobURL = URL.createObjectURL(blob);
    triggerDownload(blobURL, fileName);
    URL.revokeObjectURL(blobURL);
  } catch (error: any) {
    if (error?.name !== "AbortError") {
      const message =
        error?.response?.data?.message || error?.message || "Unknown error";
      showError(fileName, message, isDesktop);
    }
  }
};
 
export const downloadDocument = async (
  file: TFile,
  isDesktop?: boolean,
  isDirectDownload = false,
) => {
  const fileName = ensureFileNameHasExtension(file.fileName, file.label);
 
  // when we dont need to manipulate the file before downloading it, we can use the direct presigned URL
  if (isDirectDownload) {
    try {
      if (!document?.body) return;
 
      const link = document.createElement("a");
      link.href = file.fileURL;
      link.download = fileName;
 
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error: any) {
      showError(fileName, error?.message, isDesktop);
    }
    return;
  }
 
  try {
    // Fetch the file as a blob first to avoid navigation issues with presigned URLs
    const response = await fetch(file.fileURL, {
      credentials: "omit",
    });
 
    if (!response.ok) {
      showError(fileName, "Invalid image URL", isDesktop);
      return;
    }
 
    const blob = await response.blob();
    const blobURL = URL.createObjectURL(blob);
    triggerDownload(blobURL, fileName);
    setTimeout(() => URL.revokeObjectURL(blobURL), 100);
  } catch (error: any) {
    if (error?.name !== "AbortError") {
      const message = error?.response?.data?.message || error?.message;
      showError(file?.fileName, message, isDesktop);
    }
  }
};
 
export const updateFile = (merchantID: number, documentID: number, data: any) =>
  customInstance({
    url: `/accounts/${merchantID}/files/${documentID}`,
    method: "PATCH",
    data,
  });
 
export const followLink = (
  url: string,
  attributes?: Record<string, string>,
) => {
  const link = document.createElement("a");
  if (attributes) {
    Object.entries(attributes).forEach(([key, value]) =>
      link.setAttribute(key, value),
    );
  }
  link.href = url;
  link.click();
};