Source

pages/Dashboard/Report/Report.jsx

import React, { useMemo } from "react";
import { useState, useEffect } from "react";
import { Link, NavLink } from "react-router-dom";
import { Worker } from "@react-pdf-viewer/core";
import { Viewer } from "@react-pdf-viewer/core";
import "../Report/report.css";

import "@react-pdf-viewer/core/lib/styles/index.css";
import LoadingAnimation from "../Loading/LoadingAnimation";
import Search from "../../../component/Search/Search";
import { useGetReports } from "../../../apis/Reports";
import { Select } from "antd";
const companies = [
  {
    label: "All",
    value: "",
  },
  {
    label: "RKD Holdings Limited",
    value: "RKD Holdings Limited",
  },
  {
    label: "Tourism Investement Fund Limited",
    value: "Tourism Investement Fund Limited",
  },
  {
    label: "Bandipur Cable Car & Tourism Limited",
    value: "Bandipur Cable Car & Tourism Limited",
  },
  {
    label: "Panchase Cable Car and Tours Limited",
    value: "Panchase Cable Car and Tours Limited",
  },
  {
    label: "Bizbazar Limited",
    value: "Bizbazar Limited",
  },
];
const report_types = [
  {
    label: "All",
    value: "",
  },
  {
    label: "AGM Report",
    value: "AGM_REPORT",
  },
  {
    label: "Audit Report",
    value: "AUDIT_REPORT",
  },
  {
    label: "Others",
    value: "OTHERS",
  },
];
/**
 * Represents a Report page component
 * @module Report
 * @return {JSX.Element} - JSX component
 */
const Report = () => {
  /**
   * React useState for filter dropdown
   * @name filterDropdown
   * @memberof module:Report
   * @type {Boolean}
   * @default false
   */
  const [filterDropdown, setFilterDropdown] = useState(false);
  /**
   * React state to handle grid view
   * @name gridView
   * @memberof module:Report
   * @type {Boolean}
   * @default true
   *
   */
  const [gridView, setGridVied] = useState(true);
  /**
   * React useState for search input
   * @name searchInput
   * @memberof module:Report
   * @type {String}
   * @default ""
   */
  const [searchInput, setSearchInput] = useState("");
  /**
   * React useState for sort by
   * @name sortBy
   * @memberof module:Report
   * @type {String}
   * @default ""
   */
  const [sortBy, setSortBy] = useState("");
  /**
   * React useState for company
   * @name company
   * @memberof module:Report
   * @type {String}
   *
   * @default ""
   *
   */
  const [company, setCompany] = useState("");
  /**
   * React useState for report type
   * @name reportType
   * @memberof module:Report
   * @type {String}
   * @default ""
   *
   */
  const [reportType, setReportType] = useState("");
  /**
   * React query hook for getting reports
   * @name useGetReports
   * @memberof module:Report
   * @type {Function}
   * @return {object} - React query data object for reports
   */
  const { data: reportData, isLoading } = useGetReports();
  /**
   * React useState for Selected Year
   * @name selectedYear
   * @memberof module:Report
   * @type {String}
   * @default ""
   */
  const [selectedYear, setSelectedYear] = useState("");
  /**
   * Constant that holds the current year
   * @name currentYear
   * @memberof module:Report
   * @type {number}
   */
  const currentYear = new Date().getFullYear();
  /**
   * Constant that holds the list of fiscal years
   * @name fiscalYears
   * @memberof module:Report
   * @type {number}
   */
  const fiscalYears = generateFiscalYears(currentYear);
  /**
   * Function to handle year change
   * @function handleYearChange
   * @param event {Event}  Html event object
   */
  const handleYearChange = (event) => {
    setSelectedYear(event.target.value);
  };

  /**
   * React useMemo for getting reports list
   * @name reports
   * @memberof module:Report
   * @type {Array.<object>}
   */
  // Getting reports list
  const reports = useMemo(() => {
    let temp = reportData?.data?.data?.results || [];
    temp = [...temp].reverse();
    // Search with name;
    if (searchInput) {
      const filteredList = temp.filter((item) =>
        item.company.toLowerCase().includes(searchInput.toLowerCase())
      );
      temp = filteredList;
    }

    //handle company select
    if (company) {
      const filteredList = temp.filter((item) => item.company === company);
      temp = filteredList;
    }
    //handle report type select
    if (reportType) {
      const filteredList = temp.filter(
        (item) => item.report_type === reportType
      );
      temp = filteredList;
    }
    //handle fiscal year select
    if (selectedYear) {
      let filteredList = temp.filter((item) => {
        let start_date = new Date(item?.fiscal_year?.start_date);
        const year = start_date.getFullYear();
        if (parseInt(year) === parseInt(String(selectedYear).split("-")[0])) {
          return true;
        }
        return false;
      });
      temp = filteredList;
    }
    // Sorting reports
    switch (sortBy) {
      case "OLD":
        let revisedData = temp.map((el, i) => ({
          ...el,
          date: new Date(el?.created),
        }));
        temp = revisedData.slice().sort((a, b) => a.date - b.date);
        return temp;
      case "RECENT":
        let revisedRecentData = temp.map((el, i) => ({
          ...el,
          date: new Date(el?.created),
        }));
        temp = revisedRecentData.slice().sort((a, b) => b.date - a.date);
        return temp;
    }
    return temp;
  }, [
    reportData?.data,
    searchInput,
    sortBy,
    company,
    reportType,
    selectedYear,
  ]);
  /**
   * Constant that holds the file extension
   * @name fileExtension
   * @memberof module:Report
   * @type {void|any|null}
   */
  // working with file extension
  const fileExtension = reports?.fileName?.includes(".")
    ? fileName.split(".").pop()
    : null;
  /**
   * Function to handle download the report
   * @function handleDownload
   * @param name {String}  Name of the report
   * @param pdfUrl {String}  Url of the report
   */
  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 />;
  }
  return (
    <div className="report_container">
      <div className="navigation_for_mobile px-3">
        <div className="left_mobile_navigation  ">
          <input
            type="text"
            placeholder="search"
            onChange={(e) => setSearchInput(e.target.value)}
          />
          <ion-icon name="search-outline"></ion-icon>
        </div>
        <div className="right_mobile_navigation">
          <ul>
            <li>
              <ion-icon name="options"></ion-icon>
            </li>
          </ul>
        </div>
      </div>
      <div className="report_heading">
        <h2 className="main-title">Reports</h2>
        <div className="report_heading_body flex gap-2 justify-between flex-wrap align-items-end w-100 mt-3">
          <div className="report_selectors flex gap-2 flex-wrap justify-end">
            <div className="single_selector ">
              <div className="selector_label text-center">Company</div>
              <Select
                style={{
                  width: 200,
                }}
                placeholder="All"
                className="report_company_selector parent_select "
                onChange={(value) => setCompany(value)}
                options={companies}
              />
            </div>{" "}
            <div className="single_selector ">
              <div className="selector_label text-center">Report Type</div>
              <Select
                name="report_type"
                placeholder="All"
                className="report_company_selector parent_select "
                style={{
                  width: 200,
                }}
                onChange={(value) => setReportType(value)}
                options={report_types}
              />
            </div>{" "}
            <div className="single_selector ">
              <div className="selector_label text-center">Fiscal Year</div>
              <select
                className="fiscal_year_selector"
                value={selectedYear}
                onChange={handleYearChange}
              >
                <option value="">Select Fiscal Year</option>
                {fiscalYears.map((year) => (
                  <option key={year} value={year}>
                    {year}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <div className="right_report_search">
            <Search
              setSearchInput={setSearchInput}
              gridView={gridView}
              setGridView={setGridVied}
              filterDropdown={filterDropdown}
              setFilterDropdown={setFilterDropdown}
              setSortBy={setSortBy}
            />
          </div>
        </div>
      </div>
      <div className="report_body mt-3">
        {reports?.length === 0 ? (
          <div className="empty_document_container">
            <div className="report_logo">
              <ion-icon name="document-text-outline"></ion-icon>
              <h3>No reports added yet</h3>
              <div className="add_new_document">
                <p>Stay informed with the latest insights and analysis.</p>
              </div>
            </div>
          </div>
        ) : (
          <div className="reports_div">
            {gridView ? (
              <div className="documents_divfor_grid_view">
                {reports?.map((dat, i) => {
                  return (
                    <div className="individual_report_card" key={i}>
                      {/* <NavLink to={`/dashboard/reports/reports/${dat.id}`}>
                        <div className="report_wrapper"></div>
                      </NavLink> */}
                      <div className="report_card_body">
                        {dat?.report_file &&
                        dat?.report_file.split(".").pop() === "pdf" ? (
                          <div className="pdf_img">
                            <img src="/pdf_logo.jpg" alt="PDF icon" />
                          </div>
                        ) : (
                          <div className="report_thumbnail">
                            {fileExtension === "pdf" ? (
                              <>
                                <Worker workerUrl="https://unpkg.com/pdfjs-dist@3.4.120/build/pdf.worker.min.js">
                                  <Viewer fileUrl={dat?.report_file} />
                                </Worker>
                              </>
                            ) : (
                              <div>
                                <img src={dat?.report_file} alt="report" />
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                      <div className="report_card_footer">
                        <div className="report_card_footer_content mt-3 flex justify-between">
                          <div className="report_card_footer_content_left  ">
                            <div className="footer_left_meta d-flex align-items-center mb-1" >
                                   {/* <b>Company : </b> */}
                              <ion-icon
                                     className="custom_icon"
                                     name="home-outline"
                              ></ion-icon>
                              <span> {dat?.company}</span>
                            </div>
                           
                          
                          <div className="footer_left_meta d-flex align-items-center">
                               {/* <b>Created : </b> */}
                               <ion-icon
                              className="custom_icon"
                              name="calendar-clear-outline"
                            ></ion-icon>
                              <span className="ms-2">
                                {dat?.created_bs} B.S
                              </span>{" "}
                          </div>
                            
                          </div>
                          <div className="report_card_footer_content_right text-right ">
                            <div
                              className="readmore_list_view"
                              onClick={() =>
                                handleDownload(dat?.name, dat?.report_file)
                              }
                            >
                              <p>Download</p>
                              <ion-icon name="save-outline"></ion-icon>
                            </div>

                            <NavLink
                              to={`/dashboard/reports/reports/${dat.id}`}
                            >
                              <div className="readmore_list_view mt-2">
                                <p>Preview</p>
                                <ion-icon name="eye-outline"></ion-icon>
                              </div>
                            </NavLink>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="documents_divfor_list_view">
                {reports?.map((dat, i) => {
                  return (
                    <div className="individual_list_report" key={i}>
                      <div className="left_individual_list">
                        <h3>{dat?.company}</h3>
                        <div className="report_tags">
                          <p>Created: {dat?.created_bs} Bs</p>
                        </div>
                      </div>
                      <div className="right_individual_list">
                        <div
                          className="readmore_list_view"
                          onClick={() =>
                            handleDownload(dat?.name, dat?.report_file)
                          }
                        >
                          <p>Download</p>
                          <ion-icon name="save-outline"></ion-icon>
                        </div>
                        <NavLink to={`/dashboard/reports/reports/${dat.id}`}>
                          <div className="readmore_list_view">
                            <p>Preview</p>
                            <ion-icon
                              className="custom_icon"
                              name="eye-outline"
                            ></ion-icon>
                          </div>
                        </NavLink>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};
// Function to generate a list of fiscal years starting from the given year
const generateFiscalYears = (startYear) => {
  const fiscalYears = [];
  for (let i = 0; i < 90; i++) {
    const fiscalYear = `${startYear - 20 + i}-${startYear - 20 + i + 1}`;
    fiscalYears.push(fiscalYear);
  }
  return fiscalYears;
};
export default Report;