From 521d783655af63ae187aff89c1f0e31af94c7411 Mon Sep 17 00:00:00 2001 From: leoho2fi Date: Fri, 24 May 2024 11:23:28 +0800 Subject: [PATCH] report update --- src/app/api/reports/actions.ts | 6 - src/app/api/reports/index.ts | 7 +- .../DownloadReportButton.tsx | 137 ------------------ .../LateStartReportGen/LateStartReportGen.tsx | 57 +++++--- .../LateStartReportGenWrapper.tsx | 5 +- .../Report/LateStartReportGen/index.ts | 1 - .../Report/ReportSearchBox/SearchBox.tsx | 5 +- src/components/SearchBox/SearchBox.tsx | 4 + 8 files changed, 49 insertions(+), 173 deletions(-) delete mode 100644 src/components/Report/LateStartReportGen/DownloadReportButton.tsx diff --git a/src/app/api/reports/actions.ts b/src/app/api/reports/actions.ts index 3d49a16..f86f044 100644 --- a/src/app/api/reports/actions.ts +++ b/src/app/api/reports/actions.ts @@ -54,12 +54,6 @@ export const fetchLateStartReport = async (data: LateStartReportRequest) => { body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, }); - // if (!response.ok) { - // const errorText = await response.text(); // Attempt to read the response text - // throw new Error(`Network response was not ok: ${response.status} - ${errorText}`); - // } - // const blob = await response.blob(); - // return { fileBlob: blob, fileName: 'Late_Start_Report.xlsx' }; return response }; diff --git a/src/app/api/reports/index.ts b/src/app/api/reports/index.ts index dd1afb8..fd10c99 100644 --- a/src/app/api/reports/index.ts +++ b/src/app/api/reports/index.ts @@ -33,7 +33,8 @@ export interface LateStartReportFilter { } export interface LateStartReportRequest { - team: string; - client: string; - date: any; + teamId: number; + clientId: number; + remainedDate: string; + remainedDateTo: string; } diff --git a/src/components/Report/LateStartReportGen/DownloadReportButton.tsx b/src/components/Report/LateStartReportGen/DownloadReportButton.tsx deleted file mode 100644 index 33691c0..0000000 --- a/src/components/Report/LateStartReportGen/DownloadReportButton.tsx +++ /dev/null @@ -1,137 +0,0 @@ -// DownloadReportButton.tsx -import React, { useState } from 'react'; -import * as XLSX from 'xlsx-js-style'; -//import { generateFakeData } from '../utils/generateFakeData'; -//import { downloadExcel } from '../utils/downloadExcel'; - -interface CellObject { - v?: string | number; // value of cell - s?: { // style of cell - font?: { - name: string; - sz: number; - bold?: boolean; - } - }; - } - -export const DownloadReportButton: React.FC = () => { - const [isLoading, setIsLoading] = useState(false); - - const handleDownload = async () => { - setIsLoading(true); - - try { - const response = await fetch('/temp/AR01_Late Start Report.xlsx', { - headers: { - 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - }, - }); - if (!response.ok) throw new Error('Network response was not ok.'); - - const data = await response.blob(); - const reader = new FileReader(); - reader.onload = (e) => { - if (e.target && e.target.result) { - const ab = e.target.result as ArrayBuffer; - const workbook = XLSX.read(ab, { type: 'array' }); - const firstSheetName = workbook.SheetNames[0]; - const worksheet = workbook.Sheets[firstSheetName]; - - // Add the current date to cell C2 - const cellAddress = 'C2'; - const date = new Date().toISOString().split('T')[0]; // Format YYYY-MM-DD - const formattedDate = date.replace(/-/g, '/'); // Change format to YYYY/MM/DD - XLSX.utils.sheet_add_aoa(worksheet, [[formattedDate]], { origin: cellAddress }); - - // Calculate the maximum length of content in each column and set column width - const colWidths: number[] = []; - - const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: "", blankrows: true }) as (string | number)[][]; - jsonData.forEach((row: (string | number)[]) => { - row.forEach((cell: string | number, index: number) => { - const valueLength = cell.toString().length; - colWidths[index] = Math.max(colWidths[index] || 0, valueLength); - }); - }); - - // Apply calculated widths to each column, skipping column A - worksheet['!cols'] = colWidths.map((width, index) => { - if (index === 0) { - return { wch: 8 }; // Set default or specific width for column A if needed - } - return { wch: width + 2 }; // Add padding to width - }); - - // Style for cell A1: Font size 16 and bold - if (worksheet['A1']) { - worksheet['A1'].s = { - font: { - bold: true, - sz: 16, // Font size 16 - //name: 'Times New Roman' // Specify font - } - }; - } - - // Apply styles from A2 to A4 (bold) - ['A2', 'A3', 'A4'].forEach(cell => { - if (worksheet[cell]) { - worksheet[cell].s = { font: { bold: true } }; - } - }); - - // Formatting from A6 to J6 - // Apply styles from A6 to J6 (bold, bottom border, center alignment) - for (let col = 0; col < 10; col++) { // Columns A to J - const cellRef = XLSX.utils.encode_col(col) + '6'; - if (worksheet[cellRef]) { - worksheet[cellRef].s = { - font: { bold: true }, - alignment: { horizontal: 'center' }, - border: { - bottom: { style: 'thin', color: { auto: 1 } } - } - }; - } - } - - // Convert workbook back to XLSX file - XLSX.writeFile(workbook, 'Updated_Report.xlsx'); - } else { - throw new Error('Failed to load file'); - } - }; - reader.readAsArrayBuffer(data); - } catch (error) { - console.error('Error downloading the file: ', error); - } - - setIsLoading(false); - }; - - return ( - - ); - }; - -// import React from 'react'; - -// export const DownloadReportButton: React.FC = () => { -// const handleDownload = () => { -// const link = document.createElement('a'); -// link.href = '/temp/AR01_Late Start Report.xlsx'; // Adjust the path as necessary -// link.download = 'AR01_Late Start Report.xlsx'; -// document.body.appendChild(link); -// link.click(); -// document.body.removeChild(link); -// }; - -// return ( -// -// ); -// }; \ No newline at end of file diff --git a/src/components/Report/LateStartReportGen/LateStartReportGen.tsx b/src/components/Report/LateStartReportGen/LateStartReportGen.tsx index 1cdab3d..b19bcf8 100644 --- a/src/components/Report/LateStartReportGen/LateStartReportGen.tsx +++ b/src/components/Report/LateStartReportGen/LateStartReportGen.tsx @@ -1,71 +1,84 @@ //src\components\LateStartReportGen\LateStartReportGen.tsx "use client"; import React, { useEffect, useMemo, useState } from "react"; -import SearchBox, { Criterion } from "../ReportSearchBox"; import { useTranslation } from "react-i18next"; import { LateStart } from "@/app/api/report"; //import { DownloadReportButton } from './DownloadReportButton'; // import axios from 'axios'; import { apiPath } from '../../../auth/utils'; import { fetchTeamCombo } from "@/app/api/team/actions"; +import SearchBox, { Criterion } from "@/components/SearchBox"; +import { combo, comboProp } from "@/app/api/team"; +import { Customer } from "@/app/api/customer"; +import { downloadFile } from "@/app/utils/commonUtil"; +import { fetchLateStartReport } from "@/app/api/reports/actions"; +import { LateStartReportRequest } from "@/app/api/reports"; //import { GET_QC_CATEGORY_COMBO } from 'utils/ApiPathConst'; interface Props { projects: LateStart[]; + customers: Customer[]; } -type SearchQuery = Partial>; +type SearchQuery = Partial>; type SearchParamNames = keyof SearchQuery; -const ProgressByClientSearch: React.FC = ({ projects }) => { +const ProgressByClientSearch: React.FC = ({ projects, customers }) => { + //console.log(customers) const { t } = useTranslation("projects"); - const [teamCombo, setteamCombo] = useState([]) - const [clientCombo, setclientCombo] = useState([]) + const [teamCombo, setteamCombo] = useState([]) const [isLoading, setIsLoading] = useState(true) - // const [teamCombo, setteamCombo] = useState([]); const getTeamCombo = async() => { try { const response = await fetchTeamCombo() - setteamCombo(response.records.map(record => record.label)) + console.log(response.records) + setteamCombo(response.records) setIsLoading(false) } catch (err) { console.log(err) } } - // const getClientCombo = async() => { - // try { - // const response = await fetchCombo() - // setclientCombo(response.records.map(record => record.label)) - // setIsLoading(false) - // } catch (err) { - // console.log(err) - // } - // } - useEffect(() => { getTeamCombo() }, []) const searchCriteria: Criterion[] = useMemo( () => [ - { label: "Team", paramName: "team", type: "select", options: teamCombo }, - { label: "Client", paramName: "client", type: "select", options: ["Cust A", "Cust B", "Cust C"] }, + { label: "Team", paramName: "teamId", type: "select", options: teamCombo.map(team => team.label) }, + { label: "Client", paramName: "clientId", type: "select", options: customers.map(customer => `${customer.code}-${customer.name}`) }, { label: "Remained Date From", label2: "Remained Date To", - paramName: "targetEndDate", + paramName: "remainedDate", type: "dateRange", }, ], - [t, teamCombo], + [t, teamCombo, customers], ); return ( <> {!isLoading && { + onSearch={async (query) => { console.log(query); + + try { + // const teamId = teamCombo.find(team => team.label === query.teamId)?.id!! + // const clientId = customers.find(customer => `${customer.code}-${customer.name}` === query.clientId)?.id!! + const teamId = teamCombo.find(team => team.label === query.teamId)?.id || 0; + const clientId = customers.find(customer => `${customer.code}-${customer.name}` === query.clientId)?.id || 0; + const remainedDate = query.remainedDate || "1900-01-01"; + const remainedDateTo = query.remainedDateTo || "2100-12-31"; + + const fileResponse = await fetchLateStartReport({teamId: teamId, clientId: clientId, remainedDate: remainedDate, remainedDateTo: remainedDateTo}); + if (fileResponse) { + downloadFile(new Uint8Array(fileResponse.blobValue), fileResponse.filename!!) + } + } catch (err) { + console.log(err) + } + //console.log(teamCombo.find(team => team.label === query.team)?.id); }} />} {/* */} diff --git a/src/components/Report/LateStartReportGen/LateStartReportGenWrapper.tsx b/src/components/Report/LateStartReportGen/LateStartReportGenWrapper.tsx index c85dc08..18f928a 100644 --- a/src/components/Report/LateStartReportGen/LateStartReportGenWrapper.tsx +++ b/src/components/Report/LateStartReportGen/LateStartReportGenWrapper.tsx @@ -1,8 +1,8 @@ -//src\components\LateStartReportGen\LateStartReportGenWrapper.tsx import { fetchProjectsLateStart } from "@/app/api/report"; import React from "react"; import LateStartReportGen from "./LateStartReportGen"; import LateStartReportGenLoading from "./LateStartReportGenLoading"; +import { fetchAllCustomers } from "@/app/api/customer"; interface SubComponents { Loading: typeof LateStartReportGenLoading; @@ -10,8 +10,9 @@ interface SubComponents { const LateStartReportGenWrapper: React.FC & SubComponents = async () => { const clentprojects = await fetchProjectsLateStart(); + const customers = await fetchAllCustomers(); - return ; + return ; }; LateStartReportGenWrapper.Loading = LateStartReportGenLoading; diff --git a/src/components/Report/LateStartReportGen/index.ts b/src/components/Report/LateStartReportGen/index.ts index 55e0f5d..82be5ed 100644 --- a/src/components/Report/LateStartReportGen/index.ts +++ b/src/components/Report/LateStartReportGen/index.ts @@ -1,2 +1 @@ -//src\components\LateStartReportGen\index.ts export { default } from "./LateStartReportGenWrapper"; diff --git a/src/components/Report/ReportSearchBox/SearchBox.tsx b/src/components/Report/ReportSearchBox/SearchBox.tsx index 22186da..15def7d 100644 --- a/src/components/Report/ReportSearchBox/SearchBox.tsx +++ b/src/components/Report/ReportSearchBox/SearchBox.tsx @@ -123,13 +123,14 @@ function SearchBox({ const handleDownload = async () => { try { // Create a request object, which includes the projectId + console.log(inputs) const abc = await fetchTeamCombo() //console.log(abc.records) const requestData: LateStartReportRequest = { team: 'Your Team Name', // Example value, adjust as necessary - client: 'Client Name', // Example value, adjust as necessary - date: new Date().toISOString() // Current date in ISO format, adjust as necessary + customer: 'Client Name', // Example value, adjust as necessary + project: new Date().toISOString() // Current date in ISO format, adjust as necessary }; // Call fetchLateStartReport and wait for the blob diff --git a/src/components/SearchBox/SearchBox.tsx b/src/components/SearchBox/SearchBox.tsx index 686eb8d..cd0de38 100644 --- a/src/components/SearchBox/SearchBox.tsx +++ b/src/components/SearchBox/SearchBox.tsx @@ -23,6 +23,10 @@ import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { Box } from "@mui/material"; import { DateCalendar } from "@mui/x-date-pickers"; +import { fetchLateStartReport } from "@/app/api/reports/actions"; +import { LateStartReportRequest } from "@/app/api/reports"; +import { fetchTeamCombo } from "@/app/api/team/actions"; +import { downloadFile } from "@/app/utils/commonUtil"; interface BaseCriterion { label: string;