Преглед на файлове

Merge branch 'main' of https://git.2fi-solutions.com/wayne.lee/tsms

tags/Baseline_30082024_FRONTEND_UAT
cyril.tsui преди 1 година
родител
ревизия
ccf3d4e140
променени са 3 файла, в които са добавени 136 реда и са изтрити 90 реда
  1. +14
    -1
      src/app/api/reports/actions.ts
  2. +11
    -0
      src/app/api/reports/index.ts
  3. +111
    -89
      src/components/Report/ReportSearchBox/SearchBox.tsx

+ 14
- 1
src/app/api/reports/actions.ts Целия файл

@@ -1,7 +1,7 @@
"use server";

import { serverFetchBlob, serverFetchJson } from "@/app/utils/fetchUtil";
import { MonthlyWorkHoursReportRequest, ProjectCashFlowReportRequest } from ".";
import { MonthlyWorkHoursReportRequest, ProjectCashFlowReportRequest,LateStartReportRequest } from ".";
import { BASE_API_URL } from "@/config/api";

export interface FileResponse {
@@ -32,5 +32,18 @@ export const fetchMonthlyWorkHoursReport = async (data: MonthlyWorkHoursReportRe
},
);

return reportBlob
};

export const fetchLateStartReport = async (data: LateStartReportRequest) => {
const reportBlob = await serverFetchBlob<FileResponse>(
`${BASE_API_URL}/reports/downloadLateStartReport`,
{
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
},
);

return reportBlob
};

+ 11
- 0
src/app/api/reports/index.ts Целия файл

@@ -20,3 +20,14 @@ export interface MonthlyWorkHoursReportRequest {
yearMonth: string;
}

export interface LateStartReportFilter {
remainedDays: number;
overdueDays: number;
team: string[];
}

export interface LateStartReportRequest {
team: string[];
client: string[];
date: any;
}

+ 111
- 89
src/components/Report/ReportSearchBox/SearchBox.tsx Целия файл

@@ -113,113 +113,135 @@ function SearchBox<T extends string>({
onSearch(inputs);
};
const handleDownload = async () => {
//setIsLoading(true);

try {
const response = await fetch('/temp/AR01_Late Start Report.xlsx', {
const response = await fetch('/api/reports', {
method: 'POST',
headers: {
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Type': 'application/json',
},
body: JSON.stringify({ projectId: '123' }), // Example payload
});
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];
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
a.href = url;
a.download = "Project_Cash_Flow_Report.xlsx";
document.body.appendChild(a);
a.click();
a.remove();
} catch (error) {
console.error('Error downloading the file: ', error);
}
};
// 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 });
// // 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 });

// 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
}
};
}
// // 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 } };
}
});
// // 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 } }
}
};
}
}
// // 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 } }
// }
// };
// }
// }

const firstTableData = [
['Column1', 'Column2', 'Column3'], // Row 1
['Data1', 'Data2', 'Data3'], // Row 2
// ... more rows as needed
];
// Find the last row of the first table
let lastRowOfFirstTable = 6; // Starting row for data in the first table
while (worksheet[XLSX.utils.encode_cell({ c: 0, r: lastRowOfFirstTable })]) {
lastRowOfFirstTable++;
}
// const firstTableData = [
// ['Column1', 'Column2', 'Column3'], // Row 1
// ['Data1', 'Data2', 'Data3'], // Row 2
// // ... more rows as needed
// ];
// // Find the last row of the first table
// let lastRowOfFirstTable = 6; // Starting row for data in the first table
// while (worksheet[XLSX.utils.encode_cell({ c: 0, r: lastRowOfFirstTable })]) {
// lastRowOfFirstTable++;
// }
// Calculate the maximum length of content in each column and set column width
const colWidths: number[] = [];
// // 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);
});
});
// 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
});
// // 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
// });

// Format filename with date
const today = new Date().toISOString().split('T')[0].replace(/-/g, '_'); // Get current date and format as YYYY_MM_DD
const filename = `AR01_Late_Start_Report_${today}.xlsx`; // Append formatted date to the filename
// // Format filename with date
// const today = new Date().toISOString().split('T')[0].replace(/-/g, '_'); // Get current date and format as YYYY_MM_DD
// const filename = `AR01_Late_Start_Report_${today}.xlsx`; // Append formatted date to the filename

// Convert workbook back to XLSX file
XLSX.writeFile(workbook, filename);
} else {
throw new Error('Failed to load file');
}
};
reader.readAsArrayBuffer(data);
} catch (error) {
console.error('Error downloading the file: ', error);
}
// // Convert workbook back to XLSX file
// XLSX.writeFile(workbook, filename);
// } else {
// throw new Error('Failed to load file');
// }
// };
// reader.readAsArrayBuffer(data);
// } catch (error) {
// console.error('Error downloading the file: ', error);
// }

//setIsLoading(false);
};
// //setIsLoading(false);
// };
return (
<Card>
<CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>


Зареждане…
Отказ
Запис