import type { Feature, SheetData } from 'write-excel-file/browser'; import { neutralizeFormula } from './cell-sanitizer'; import { flatTable } from './tracking-export-table'; import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models'; export const DATA_SHEET = 'Seguimiento'; export const PARAMETERS_SHEET = 'Parámetros'; const INK = '#081839'; const ACCENT = '#a8c243'; const header = (value: string) => ({ value, fontWeight: 'bold' as const, textColor: INK, backgroundColor: ACCENT, wrap: true, alignVertical: 'center' as const }); /** Spreadsheet column letters: 1 is A, 27 is AA. */ export function columnLetter(n: number): string { let letters = ''; for (; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + ((n - 1) % 26)) + letters; return letters; } /** `write-excel-file` has no filter option: this extension adds the sheet's native filter over the header row. */ function nativeFilter(range: string): Feature { const [first, last] = range.split(':').map(cell => cell.replace(/([A-Z]+)(\d+)/, '$$$1$$$2')); return { files: { transform: { 'xl/worksheets/sheet{id}.xml': { transform: (content, _options, { sheetIndex }) => sheetIndex === 0 ? content.replace('', ``) : content, }, 'xl/workbook.xml': { transform: content => content.replace('', ``), }, }, }, }; } function generatedAt(now: Date): string { return new Intl.DateTimeFormat('es-MX', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Mexico_City' }).format(now) + ' (hora de la Ciudad de México)'; } /** The rows of the parameters sheet: what query this file answers and what its empty cells mean. */ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData { const row = (label: string, value: string | number) => [{ value: label, fontWeight: 'bold' as const }, typeof value === 'number' ? { value, type: Number } : { value: neutralizeFormula(value), type: String }]; const filters = snapshot.filtros_disponibles.map(f => { const code = snapshot.filtros[f.clave]; return row(f.etiqueta, f.opciones.find(o => o.codigo === code)?.etiqueta ?? 'Todos'); }); return [ [header('Parámetro'), header('Valor')], row('Reporte', snapshot.titulo ?? 'Cáncer de mama'), ...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []), row('Fecha de corte', snapshot.corte), row('Ventana consultada', ventanaConsultada(snapshot)), ...filters, row('Total de registros', snapshot.items.length), row('Generado', generatedAt(now)), row('Celdas vacías', 'Indican dato no registrado, no ausencia clínica.'), ] as SheetData; } function width(label: string, values: readonly unknown[]): number { const longest = values.reduce((max, v) => Math.max(max, v === null || v === undefined ? 0 : String(v).length), Math.min(label.length, 28)); return Math.min(40, Math.max(12, longest + 2)); } /** A spreadsheet with the follow-up rows (native filter, frozen header) and a sheet with the query's parameters. */ export async function buildTrackingXlsx(snapshot: TrackingSnapshot, now = new Date()): Promise { const { default: writeXlsxFile } = await import('write-excel-file/browser'); const { columns, rows } = flatTable(snapshot); const data = [ columns.map(c => header(c.label)), ...rows.map(row => row.map((value, i) => { if (value === null) return null; return columns[i].numeric ? { value: value as number, type: Number } : { value: neutralizeFormula(String(value)), type: String }; })), ] as SheetData; const range = `A1:${columnLetter(columns.length)}${rows.length + 1}`; return writeXlsxFile([ { sheet: DATA_SHEET, data, stickyRowsCount: 1, columns: columns.map((c, i) => ({ width: width(c.label, rows.map(r => r[i])) })), }, { sheet: PARAMETERS_SHEET, data: parameterRows(snapshot, now), columns: [{ width: 26 }, { width: 90 }] }, ], { features: [nativeFilter(range)] }).toBlob(); }