156 lines
5.2 KiB
TypeScript
156 lines
5.2 KiB
TypeScript
import type { TDocumentDefinitions } from 'pdfmake/interfaces';
|
|
import * as XLSX from 'xlsx';
|
|
import { MAX_PDF_EXPORT_ROWS } from '../utils/queryResilience';
|
|
import { formatUsdtRaw } from '../utils/usdtFormat';
|
|
import { formatReportDate } from '../utils/reportDateFormat';
|
|
import { formatCountryCode, getCountryNameMap } from '../utils/countryFormat';
|
|
|
|
// pdfmake ships Roboto TTF fonts (full Unicode) — required for French text and proper tables.
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
const pdfMake = require('pdfmake') as {
|
|
setFonts: (fonts: Record<string, unknown>) => void;
|
|
createPdf: (doc: TDocumentDefinitions) => { getBuffer: () => Promise<Buffer> };
|
|
};
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
const robotoFonts = require('pdfmake/fonts/Roboto') as Record<string, unknown>;
|
|
pdfMake.setFonts(robotoFonts);
|
|
|
|
export type ReportExportColumn = { field: string; headerName: string; type?: string };
|
|
|
|
export type ReportExportPayload = {
|
|
title: string;
|
|
reportKey: string;
|
|
columns: ReportExportColumn[];
|
|
items: Record<string, unknown>[];
|
|
};
|
|
|
|
export async function enrichReportExportItems(
|
|
items: Record<string, unknown>[],
|
|
columns: ReportExportColumn[]
|
|
): Promise<Record<string, unknown>[]> {
|
|
const countryColumns = columns.filter((c) => c.type === 'country');
|
|
if (countryColumns.length === 0) return items;
|
|
const countryMap = await getCountryNameMap();
|
|
return items.map((row) => {
|
|
const out = { ...row };
|
|
for (const col of countryColumns) {
|
|
if (col.field in out && out[col.field] != null) {
|
|
out[col.field] = formatCountryCode(String(out[col.field]), countryMap);
|
|
}
|
|
}
|
|
return out;
|
|
});
|
|
}
|
|
|
|
function cellValue(row: Record<string, unknown>, column: ReportExportColumn): string {
|
|
const v = row[column.field];
|
|
if (v == null) return '';
|
|
if (column.type === 'money') return formatUsdtRaw(v as string | number);
|
|
if (column.type === 'date') return formatReportDate(v as string | Date);
|
|
if (v instanceof Date) return formatReportDate(v);
|
|
return String(v);
|
|
}
|
|
|
|
function formatExportDate(d: Date): string {
|
|
return d.toLocaleString('fr-FR', {
|
|
dateStyle: 'short',
|
|
timeStyle: 'medium',
|
|
});
|
|
}
|
|
|
|
export function buildReportCsv(data: ReportExportPayload): string {
|
|
const header = data.columns.map((c) => c.headerName).join(',');
|
|
const lines = data.items.map((row) =>
|
|
data.columns
|
|
.map((c) => {
|
|
const s = cellValue(row, c);
|
|
return s.includes(',') || s.includes('"') || s.includes('\n')
|
|
? `"${s.replace(/"/g, '""')}"`
|
|
: s;
|
|
})
|
|
.join(',')
|
|
);
|
|
return '\uFEFF' + [header, ...lines].join('\n');
|
|
}
|
|
|
|
export function buildReportXlsxBuffer(data: ReportExportPayload): Buffer {
|
|
const rows = data.items.map((row) => {
|
|
const out: Record<string, string> = {};
|
|
for (const c of data.columns) out[c.headerName] = cellValue(row, c);
|
|
return out;
|
|
});
|
|
const ws = XLSX.utils.json_to_sheet(rows);
|
|
const wb = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(wb, ws, 'Report');
|
|
return Buffer.from(XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' }));
|
|
}
|
|
|
|
function columnWidths(columnCount: number): (string | number)[] {
|
|
if (columnCount <= 6) return Array(columnCount).fill('*');
|
|
if (columnCount <= 10) return Array(columnCount).fill('auto');
|
|
return Array(columnCount).fill(42);
|
|
}
|
|
|
|
export async function buildReportPdfBuffer(data: ReportExportPayload): Promise<Buffer> {
|
|
const exportItems =
|
|
data.items.length > MAX_PDF_EXPORT_ROWS ? data.items.slice(0, MAX_PDF_EXPORT_ROWS) : data.items;
|
|
const truncated = exportItems.length < data.items.length;
|
|
|
|
const headerRow = data.columns.map((c) => ({
|
|
text: c.headerName,
|
|
style: 'tableHeader',
|
|
}));
|
|
|
|
const bodyRows = exportItems.map((row) =>
|
|
data.columns.map((c) => ({
|
|
text: cellValue(row, c),
|
|
style: 'tableCell',
|
|
}))
|
|
);
|
|
|
|
const docDefinition: TDocumentDefinitions = {
|
|
pageOrientation: 'landscape',
|
|
pageMargins: [28, 36, 28, 36],
|
|
defaultStyle: {
|
|
font: 'Roboto',
|
|
fontSize: 8,
|
|
},
|
|
content: [
|
|
{ text: data.title, style: 'title' },
|
|
{
|
|
text: `Rapport : ${data.reportKey} · ${exportItems.length.toLocaleString('fr-FR')} ligne(s)${truncated ? ` (limité à ${MAX_PDF_EXPORT_ROWS.toLocaleString('fr-FR')} pour stabilité)` : ''} · ${formatExportDate(new Date())}`,
|
|
style: 'meta',
|
|
margin: [0, 4, 0, 12],
|
|
},
|
|
{
|
|
table: {
|
|
headerRows: 1,
|
|
dontBreakRows: true,
|
|
widths: columnWidths(data.columns.length),
|
|
body: [headerRow, ...bodyRows],
|
|
},
|
|
layout: {
|
|
fillColor: (rowIndex: number) => (rowIndex === 0 ? '#f0f0f0' : null),
|
|
hLineWidth: () => 0.5,
|
|
vLineWidth: () => 0.25,
|
|
hLineColor: () => '#cccccc',
|
|
vLineColor: () => '#e8e8e8',
|
|
paddingLeft: () => 4,
|
|
paddingRight: () => 4,
|
|
paddingTop: () => 3,
|
|
paddingBottom: () => 3,
|
|
},
|
|
},
|
|
],
|
|
styles: {
|
|
title: { fontSize: 14, bold: true, alignment: 'center' },
|
|
meta: { fontSize: 9, color: '#555555', alignment: 'center' },
|
|
tableHeader: { bold: true, fontSize: 8 },
|
|
tableCell: { fontSize: 7 },
|
|
},
|
|
};
|
|
|
|
const pdf = pdfMake.createPdf(docDefinition);
|
|
return pdf.getBuffer();
|
|
}
|