Files
crosscode-platform/apps/events/frontend/src/lib/export.ts
T

233 lines
8.9 KiB
TypeScript

export type TableRow = Record<string, unknown>;
export function downloadCsv(filename: string, rows: TableRow[], columns?: { key: string; label?: string }[]) {
const cols = columns && columns.length > 0 ? columns : Object.keys(rows[0] || {}).map(k => ({ key: k, label: k }));
const header = cols.map(c => escapeCsv(c.label || c.key)).join(',');
const lines = rows.map(r => cols.map(c => escapeCsv(valueToString(r[c.key]))).join(','));
const csv = [header, ...lines].join('\r\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = ensureCsvExt(filename);
a.click();
setTimeout(() => URL.revokeObjectURL(url), 2000);
}
function ensureCsvExt(name: string) {
return name.toLowerCase().endsWith('.csv') ? name : name + '.csv';
}
function escapeCsv(v: string) {
if (v == null) return '';
if (/[",\n]/.test(v)) return '"' + v.replace(/"/g, '""') + '"';
return v;
}
function valueToString(v: unknown): string {
if (v == null) return '';
if (v instanceof Date) return v.toISOString();
if (typeof v === 'object') return JSON.stringify(v);
return String(v);
}
// New: server-side PDF/Excel generation and email helpers
export type ReportStat = { label: string; value: string; tone?: 'green' | 'blue' | 'violet' | 'amber' | 'rose' | 'gray' };
export type ReportChartDatum = { label: string; value: number; displayValue?: string };
export type ReportPdfPayload = {
title: string;
subtitle?: string;
kind: 'table' | 'layered';
orientation?: 'portrait' | 'landscape';
// Optional visual sections rendered above the table/layered body — mirrors the on-screen
// report's stat tiles / bar chart / explanatory note, so exported PDF/Excel/email/WhatsApp
// all look like the same report the web UI shows, not a plain data dump.
stats?: ReportStat[];
chart?: { title?: string; data: ReportChartDatum[] };
note?: string;
table?: { columns: string[]; rows: (string | number)[][] };
layered?: { header?: string; sections: { title: string; items: string[] }[] };
// Additional titled tables rendered below the main table/layered body — e.g. Master Orders'
// separate "Donations made" breakdown, which isn't part of the Orders table itself.
extraTables?: { title: string; columns: string[]; rows: (string | number)[][] }[];
};
/** The message in a v2 error body (or the text as it came). */
function v2ErrorText(text: string): string {
try { const j = JSON.parse(text); return j?.error?.message || j?.message || text; } catch { return text; }
}
export async function downloadReportPdf(apiBase: string, authToken: string, payload: ReportPdfPayload) {
const url = `${apiBase}/api/v2/reports/pdf`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload)
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(v2ErrorText(text) || `Failed to generate PDF (${res.status})`);
}
const blob = await res.blob();
const dl = document.createElement('a');
const objUrl = URL.createObjectURL(blob);
dl.href = objUrl;
const safe = (payload.title || 'report').replace(/[^a-z0-9]/gi, '_').toLowerCase();
dl.download = `${safe}.pdf`;
dl.click();
setTimeout(() => URL.revokeObjectURL(objUrl), 2000);
}
// Downloads a styled .xlsx mirroring the same branded look as the PDF (colored header,
// stat rows, a data-bar chart, banded table with a highlighted total row).
export async function downloadReportExcel(apiBase: string, authToken: string, payload: ReportPdfPayload) {
const url = `${apiBase}/api/v2/reports/excel`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload)
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(v2ErrorText(text) || `Failed to generate Excel file (${res.status})`);
}
const blob = await res.blob();
const dl = document.createElement('a');
const objUrl = URL.createObjectURL(blob);
dl.href = objUrl;
const safe = (payload.title || 'report').replace(/[^a-z0-9]/gi, '_').toLowerCase();
dl.download = `${safe}.xlsx`;
dl.click();
setTimeout(() => URL.revokeObjectURL(objUrl), 2000);
}
export async function emailReportPdf(apiBase: string, authToken: string, payload: ReportPdfPayload & { subject?: string; body?: string }) {
const url = `${apiBase}/api/v2/reports/email`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload)
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(v2ErrorText(text) || `Failed to email PDF (${res.status})`);
}
return (await res.json()).data;
}
// Sends the report PDF to the current user's own WhatsApp number (same self-service pattern as
// emailReportPdf — no recipient picker needed).
export async function whatsappReportPdf(apiBase: string, authToken: string, payload: ReportPdfPayload & { caption?: string }) {
const url = `${apiBase}/api/v2/reports/whatsapp`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload)
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(v2ErrorText(text) || `Failed to send PDF via WhatsApp (${res.status})`);
}
return (await res.json()).data;
}
// "Print": fetches the same PDF as downloadReportPdf but opens it in a new tab instead of
// downloading, so the browser's built-in PDF viewer's print button handles printing.
export async function viewReportPdf(apiBase: string, authToken: string, payload: ReportPdfPayload) {
const url = `${apiBase}/api/v2/reports/pdf`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload)
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(v2ErrorText(text) || `Failed to generate PDF (${res.status})`);
}
const blob = await res.blob();
const objUrl = URL.createObjectURL(blob);
window.open(objUrl, '_blank');
setTimeout(() => URL.revokeObjectURL(objUrl), 60000);
}
// Legacy (used elsewhere). Kept in case other code paths still rely on print flow.
export function openPrintWindow(title: string, htmlContent: string) {
const w = window.open('', '_blank');
if (!w) return;
w.document.write(`<!doctype html><html><head><title>${title}</title>
<style>
@page { size: A4; margin: 12mm; }
html, body { height: auto; }
body{font-family: Arial, Helvetica, sans-serif; padding:16px}
table{border-collapse: collapse; width: 100%;}
th, td{border:1px solid #e5e7eb; padding:6px 8px; font-size:12px;}
th{background:#f3f4f6; text-align:left}
h2{margin:0 0 12px 0}
.note{color:#6b7280; font-size:12px; margin-bottom:8px}
*{ box-sizing: border-box; }
.section{ page-break-inside: avoid; margin-bottom: 10px; }
@media print{ .no-print{ display:none !important } }
</style>
</head><body>
<h2>${title}</h2>
${htmlContent}
</body></html>`);
w.document.close();
w.focus();
}
export function mailtoReport(subject: string, body: string) {
const url = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
window.location.href = url;
}
// Fetches a file (PDF, Excel…) from the API with the user's token.
export async function fetchApiFile(apiBase: string, authToken: string, path: string, init: { method?: string; body?: unknown } = {}): Promise<Blob> {
const res = await fetch(`${apiBase}${path}`, {
method: init.method || 'GET',
headers: {
'Authorization': `Bearer ${authToken}`,
...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
},
...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
});
if (!res.ok) {
const text = await res.text().catch(() => '');
let message = text;
try { const j = JSON.parse(text); message = j?.error?.message || j?.message || text; } catch { /* not JSON */ }
throw new Error(message || `Download failed (${res.status})`);
}
return res.blob();
}
export function saveBlob(blob: Blob, filename: string) {
const dl = document.createElement('a');
const objUrl = URL.createObjectURL(blob);
dl.href = objUrl;
dl.download = filename;
dl.click();
setTimeout(() => URL.revokeObjectURL(objUrl), 2000);
}
export function openBlob(blob: Blob) {
const objUrl = URL.createObjectURL(blob);
window.open(objUrl, '_blank');
setTimeout(() => URL.revokeObjectURL(objUrl), 60000);
}