All files / pages/admin/Report ReportPage.tsx

73.01% Statements 46/63
75% Branches 21/28
64.28% Functions 9/14
73.01% Lines 46/63

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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 2181x 1x     1x   1x 1x 1x 1x   1x       16x 15x   15x             15x                           15x 6x     15x                                                 15x 7x             7x 4x 4x 4x                     4x 4x         15x                                                                                         15x         3x 3x 3x 3x 3x   3x   3x 1x 1x   1x   2x 1x 1x   1x     1x 1x 1x   1x       15x                                                     90x                           1x  
import CustomPagination from "@/components/Pagination/CustomPagination";
import { ReportAPICaller } from "@/services/apis/report.api";
import APIResponse from "@/types/APIResponse";
import { Report, ReportSearchParams, ReportSortParams } from "@/types/Report";
import { Button, Table, TableColumnsType, TableProps, message } from "antd";
import { SorterResult } from "antd/es/table/interface";
import { useEffect, useState } from "react";
import { useQuery } from "react-query";
import { useSearchParams } from "react-router-dom";
import dayjs from "dayjs";
 
const PAGE_SIZE = 20;
 
function ReportPage() {
  // state
  const [searchParams, setSearchParams] = useSearchParams();
  const [items, setItems] = useState<Report[]>([]);
 
  const params: ReportSearchParams = {
    sortBy: searchParams.get("sortBy") || undefined,
    sortDir: searchParams.get("sortDir") || undefined,
    pageNumber: Number(searchParams.get("page") || "1"),
    pageSize: PAGE_SIZE,
  };
 
  const sort: ReportSortParams = {
    sortBy: searchParams.get("sortBy") || undefined,
    sortDir: searchParams.get("sortDir") || undefined
  };
 
  // query
  const {
    data: queryData,
    isSuccess,
    isError,
    isLoading,
    error,
    isFetching,
    refetch,
  } = useQuery(["getReportsList", { params }], () =>
    ReportAPICaller.getReport(params)
  );
 
  const { isLoading: exportLoading, refetch: refetchExport } = useQuery(
    ["exportReport", {sort}],
    () => ReportAPICaller.exportReport(sort),
    {
      refetchOnWindowFocus: false,
      enabled: false,
      onSuccess(data) {
        const blob = new Blob([data?.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `report_${dayjs(Date.now()).format("YYYY-MM-DD")}.xlsx`;
        a.click();
      },
      onError(error) {
        const errorResponse = (error as { response: { data: APIResponse } })
          .response?.data;
        message.error(errorResponse?.message);
      },
    }
  );
 
  // effect
  useEffect(() => {
    Iif (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response?.data;
      message.error(errorResponse?.message);
      setItems([]);
    }
 
    if (isSuccess) {
      const pageCount = Math.ceil(queryData?.data.result.total / PAGE_SIZE);
      const currentPage = Number(searchParams.get("page")) || 1;
      Iif (
        pageCount < currentPage &&
        searchParams.get("page") !== "1" &&
        !isFetching
      ) {
        setSearchParams((p) => {
          p.set("page", pageCount === 0 ? "1" : pageCount.toString());
          return p;
        });
        refetch();
      }
      window.history.replaceState({}, "");
      setItems(queryData.data.result.data);
    }
  }, [error, isError, isSuccess, queryData]);
 
  // handlers
  const columns: TableColumnsType<Report> = [
    {
      title: "Category",
      dataIndex: "categoryName",
      sorter: true,
      key: "categoryName",
    },
    {
      title: "Total",
      dataIndex: "total",
      sorter: true,
      key: "total",
    },
    {
      title: "Assigned",
      dataIndex: "assignedCount",
      sorter: true,
      key: "assignedCount",
    },
    {
      title: "Available",
      dataIndex: "availableCount",
      sorter: true,
      key: "availableCount",
    },
    {
      title: "Not Available",
      dataIndex: "notAvailableCount",
      sorter: true,
      key: "notAvailableCount",
    },
    {
      title: "Waiting For Recycle",
      dataIndex: "waitingForRecycleCount",
      sorter: true,
      key: "waitingForRecycleCount",
    },
    {
      title: "Recycled",
      dataIndex: "recycledCount",
      sorter: true,
      key: "recycledCount",
    },
  ];
 
  const handleTableChange: TableProps<Report>["onChange"] = (
    _pagination,
    _filteers,
    sorter
  ) => {
    sorter = sorter as SorterResult<Report>;
    const { field, order } = sorter;
    const fieldString = sorter.columnKey?.toString() || (field as string);
    setSearchParams((searchParams) => {
      searchParams.set("orderBy", fieldString);
 
      return searchParams;
    });
    if (order === "ascend") {
      setSearchParams((searchParams) => {
        searchParams.set("sortDir", "asc");
 
        return searchParams;
      });
    } else if (order === "descend") {
      setSearchParams((searchParams) => {
        searchParams.set("sortDir", "desc");
 
        return searchParams;
      });
    } else
      setSearchParams((searchParams) => {
        searchParams.delete("sortDir");
        searchParams.delete("orderBy");
 
        return searchParams;
      });
  };
 
  return (
    <>
      <div>
        <h1 className="text-3xl font-bold text-red-500">Report</h1>
        <div className="flex  pt-2 ">
          <div className=" flex flex-1 justify-end space-x-5">
            <Button
              danger
              type="primary"
              className="text-[#cf2338]"
              color="#cf2338"
              loading={exportLoading}
              onClick={() => {
                refetchExport();
              }}
            >
              Export
            </Button>
          </div>
        </div>
        <div className="pt-8">
          <Table
            columns={columns}
            dataSource={items}
            loading={isLoading}
            pagination={false}
            onChange={handleTableChange}
            rowKey={(record) => record.categoryId}
          />{" "}
        </div>
        <div className="pt-8 flex justify-end">
          <CustomPagination
            totalItems={queryData?.data?.result?.total || 0}
            pageSize={PAGE_SIZE}
          />
        </div>
      </div>
    </>
  );
}
 
export default ReportPage;