Rapport_React/src/views/coachingtooldashboard/exportXlsx.js

71 lines
2.5 KiB
JavaScript

import { RATINGS, actionColumns, goalCount } from './helpers';
function fileStamp(now = new Date()) {
const day = String(now.getDate()).padStart(2, '0');
const month = String(now.getMonth() + 1).padStart(2, '0');
const year = String(now.getFullYear()).slice(2);
return `${day}-${month}-${year}`;
}
function countCell(value) {
if (value == null || value === '') return 0;
const number = Number(value);
return Number.isFinite(number) ? number : value;
}
function exportHeader(key) {
if (key === 'total') return 'Total';
return String(key).replaceAll('_', ' ').replace(/\b[a-z]/g, (letter) => letter.toUpperCase());
}
function exportMonth(month) {
if (!/^\d{4}-\d{2}$/.test(month)) return month;
const [year, mon] = month.split('-');
const label = new Date(Number(year), Number(mon) - 1, 1).toLocaleString('en-US', { month: 'short' });
return `${label}-${year}`;
}
async function downloadXlsx(filename, lines) {
const { default: ExcelJS } = await import('exceljs');
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('Worksheet');
lines.forEach((line) => sheet.addRow(line));
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const anchor = document.createElement('a');
anchor.href = URL.createObjectURL(blob);
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(anchor.href);
}
export async function exportActionPlan(report, rows) {
const columns = actionColumns();
const lines = [
[report.columnTitle, ...columns.map((column) => exportHeader(column))],
...rows.map((row) => [row.label, ...columns.map((column) => countCell(row[column]))]),
];
await downloadXlsx(`${report.exportFile}_${fileStamp()}.xlsx`, lines);
}
export async function exportGoalReport(report, grid) {
const header = [report.columnTitle];
const ratings = [''];
grid.months.forEach((month) => {
const label = exportMonth(month);
RATINGS.forEach(() => header.push(label));
RATINGS.forEach((rating) => ratings.push(rating));
});
const lines = [
header,
ratings,
...grid.goals.map((goalName) => [
goalName,
...grid.months.flatMap((month) => RATINGS.map((rating) => countCell(goalCount(grid.byMonth, month, goalName, rating)))),
]),
];
await downloadXlsx(`${report.exportFile}_${fileStamp()}.xlsx`, lines);
}