Source

pages/Dashboard/Report/ReportSinglePage.jsx

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import LoadingAnimation from "../Loading/LoadingAnimation";
import baseUrl from "../../../array/base/config";
import "../Documents/documents.css";
import { Worker } from "@react-pdf-viewer/core";
import { Viewer } from "@react-pdf-viewer/core";

import "@react-pdf-viewer/core/lib/styles/index.css";

/**
 * Represents  ReportSingle page component
 * @module ReportSinglePage
 * @return {JSX.Element}
 */
const ReportSinglePage = () => {
  /**
   * React useState for report file
   * @name reportFile
   * @memberof module:ReportSinglePage
   * @type {object}
   * @default useState({}
   */
  const [reportFile, setReportFile] = useState({});
  /**
   * React useState for is loading
   * @name isLoading
   * @memberof module:ReportSinglePage
   * @type {object}
   * @default useState(true)
   */
  const [isLoading, setIsLoading] = useState(true);
  /**
   * React useParams for getting id
   * @name useParams
   * @memberof module:ReportSinglePage
   * @type {object}
   *
   */
  const { id } = useParams();

  useEffect(() => {
    singleDocumentApicall();
  }, []);

  /**
   * Function for single document api call
   * @name singleDocumentApicall
   * @memberof module:ReportSinglePage
   * @function singleDocumentApicall
   * @returns {void}
   */
  const singleDocumentApicall = () => {
    const detail = localStorage.getItem("token");
    axios({
      method: "get",
      url: `${baseUrl}/api/companyreport/${id}/`,
      headers: {
        Authorization: `Token ${detail}`,
      },
    })
      .then((res) => {
        setReportFile(res?.data?.data);
        setIsLoading(false);
      })
      .catch((err) => console.log(err));
  };

  /**
   * Function for handle download
   * @name handleDownload
   * @function handleDownload
   * @memberof module:ReportSinglePage
   * @param name {string} name of the file
   * @param pdfUrl {string} pdf url
   */
  const handleDownload = (name, pdfUrl) => {
    try {
      const downloadLink = document.createElement("a");
      downloadLink.href = pdfUrl;
      downloadLink.download = name + ".pdf";
      downloadLink.target = "_blank";
      // Trigger a click event on the anchor element
      document.body.appendChild(downloadLink);
      downloadLink.click();

      // Clean up and remove the anchor element
      document.body.removeChild(downloadLink);
    } catch (err) {
      console.log(err.message);
    }
  };
  if (isLoading) {
    return <LoadingAnimation />;
  }

  /**
   * Constant for file extension
   * @name fileExtension
   * @memberof module:ReportSinglePage
   * @type {void|any|null}
   */
  const fileExtension =
    reportFile?.report_file && reportFile?.report_file.includes(".")
      ? reportFile?.report_file.split(".").pop()
      : null;

  return (
    <div>
      <div className="report_download_button flex justify-end my-2">
        <div
          className="readmore_list_view"
          onClick={() =>
            handleDownload(reportFile?.name, reportFile?.report_file)
          }
        >
          <p>Download</p>
          <ion-icon name="save-outline"></ion-icon>
        </div>
      </div>
      <div className="dodument_single_page">
        {fileExtension === "pdf" ? (
          <>
            <Worker workerUrl="https://unpkg.com/pdfjs-dist@3.4.120/build/pdf.worker.min.js">
              <Viewer fileUrl={reportFile?.report_file} />
            </Worker>
          </>
        ) : (
          <>{reportFile && <img src={reportFile} alt="Document" />}</>
        )}
        {!reportFile?.report_file && (
          <div className="empty_document_container">
            <div className="document_logo">
              <img src="/document.png" alt="" />
              <h3>Error</h3>
              <div className="add_new_document">
                <p>
                  Unable <ion-icon name="refresh-outline"></ion-icon> to load
                  file
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ReportSinglePage;