Feature: Exportar Excel
This commit is contained in:
Generated
+14
-1
@@ -18,7 +18,8 @@
|
||||
"@angular/router": "^22.1.0",
|
||||
"plotly.js-basic-dist-min": "^4.1.1",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"tslib": "^2.3.0",
|
||||
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.1.8",
|
||||
@@ -8033,6 +8034,18 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/xlsx": {
|
||||
"version": "0.20.3",
|
||||
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
||||
"integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"xlsx": "bin/xlsx.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
|
||||
+2
-1
@@ -21,7 +21,8 @@
|
||||
"@angular/router": "^22.1.0",
|
||||
"plotly.js-basic-dist-min": "^4.1.1",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"tslib": "^2.3.0",
|
||||
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.1.8",
|
||||
|
||||
+1
-1
@@ -541,7 +541,7 @@ describe('App', () => {
|
||||
detect();
|
||||
expect(options()[0].getAttribute('aria-pressed')).toBe('false');
|
||||
expect(options()[1].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(overlay.querySelector('.export-dialog__submit')?.hasAttribute('disabled')).toBe(true);
|
||||
expect(overlay.querySelector<HTMLButtonElement>('.export-dialog__submit')?.disabled).toBe(false);
|
||||
overlay.querySelector<HTMLButtonElement>('.export-dialog__cancel')!.click();
|
||||
fixture.detectChanges();
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<div class="dashboard__kpis" aria-label="Indicadores de demostración">
|
||||
@for (kpi of result.kpis; track kpi.label) {
|
||||
<article class="kpi">
|
||||
<p class="kpi__value">{{ kpi.value }}</p>
|
||||
<p class="kpi__value">{{ formatKpi(kpi) }}</p>
|
||||
<h2 class="kpi__label">{{ kpi.label }}</h2>
|
||||
</article>
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Datos exclusivos de demostración. No representan resultados clínicos ni un contrato de WebApi.
|
||||
export interface MockAnalysisResult {
|
||||
analysisType: 'CAMA';
|
||||
kpis: ReadonlyArray<{ label: string; value: string }>;
|
||||
export interface AnalysisResult {
|
||||
analysisType: string;
|
||||
kpis: ReadonlyArray<{ label: string; value: number; unit?: '%' }>;
|
||||
charts: {
|
||||
categories: ReadonlyArray<{ label: string; value: number }>;
|
||||
composition: ReadonlyArray<{ label: string; value: number }>;
|
||||
@@ -9,12 +9,12 @@ export interface MockAnalysisResult {
|
||||
};
|
||||
}
|
||||
|
||||
export const mockAnalysisResult: MockAnalysisResult = {
|
||||
export const mockAnalysisResult: AnalysisResult = {
|
||||
analysisType: 'CAMA',
|
||||
kpis: [
|
||||
{ label: 'Indicador 1', value: '1,248' },
|
||||
{ label: 'Indicador 2', value: '64.2 %' },
|
||||
{ label: 'Indicador 3', value: '327' },
|
||||
{ label: 'Indicador 1', value: 1248 },
|
||||
{ label: 'Indicador 2', value: 64.2, unit: '%' },
|
||||
{ label: 'Indicador 3', value: 327 },
|
||||
],
|
||||
charts: {
|
||||
categories: [
|
||||
@@ -38,3 +38,7 @@ export const mockAnalysisResult: MockAnalysisResult = {
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export function formatKpi(kpi: AnalysisResult['kpis'][number]): string {
|
||||
return `${new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 }).format(kpi.value)}${kpi.unit ? ` ${kpi.unit}` : ''}`;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Router } from '@angular/router';
|
||||
import { take } from 'rxjs';
|
||||
import { mockAnalysisResult } from './dashboard.mock';
|
||||
import { formatKpi, mockAnalysisResult } from './dashboard.mock';
|
||||
import { ChartFigure, PlotlyChart } from './plotly-chart';
|
||||
import { InformationUploadDialog } from '../information-upload-dialog';
|
||||
import { ExportResultsDialog } from './export-results-dialog';
|
||||
@@ -26,12 +26,14 @@ export class Dashboard {
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly router = inject(Router);
|
||||
readonly result = mockAnalysisResult;
|
||||
readonly formatKpi = formatKpi;
|
||||
|
||||
returnHome(): void { void this.router.navigateByUrl('/'); }
|
||||
|
||||
openExportDialog(): void {
|
||||
if (this.dialog.openDialogs.length > 0) return;
|
||||
this.dialog.open(ExportResultsDialog, {
|
||||
data: this.result,
|
||||
width: '640px', maxWidth: 'calc(100vw - 32px)',
|
||||
autoFocus: 'first-tabbable', restoreFocus: true,
|
||||
panelClass: 'export-results-dialog-panel',
|
||||
|
||||
@@ -4,16 +4,16 @@
|
||||
<h2 id="export-title">Exportar resultados</h2>
|
||||
<p id="export-description">Selecciona el formato en el que deseas exportar los resultados del análisis.</p>
|
||||
</div>
|
||||
<button class="export-dialog__close" type="button" aria-label="Cerrar diálogo" (click)="close()"><mat-icon aria-hidden="true">close</mat-icon></button>
|
||||
<button class="export-dialog__close" type="button" aria-label="Cerrar diálogo" [disabled]="generating()" (click)="close()"><mat-icon aria-hidden="true">close</mat-icon></button>
|
||||
</header>
|
||||
|
||||
<div class="export-options" role="group" aria-label="Formato de exportación">
|
||||
<button class="export-option" [class.export-option--selected]="selection() === 'pdf'" [attr.aria-pressed]="selection() === 'pdf'" type="button" (click)="select('pdf')">
|
||||
<button class="export-option" [class.export-option--selected]="selection() === 'pdf'" [attr.aria-pressed]="selection() === 'pdf'" [disabled]="generating()" type="button" (click)="select('pdf')">
|
||||
<mat-icon class="export-option__icon" aria-hidden="true">picture_as_pdf</mat-icon>
|
||||
<span class="export-option__copy"><strong>PDF</strong><span>Reporte visual del análisis y sus gráficas.</span></span>
|
||||
@if (selection() === 'pdf') { <mat-icon class="export-option__check" aria-hidden="true">check_circle</mat-icon> }
|
||||
</button>
|
||||
<button class="export-option" [class.export-option--selected]="selection() === 'excel'" [attr.aria-pressed]="selection() === 'excel'" type="button" (click)="select('excel')">
|
||||
<button class="export-option" [class.export-option--selected]="selection() === 'excel'" [attr.aria-pressed]="selection() === 'excel'" [disabled]="generating()" type="button" (click)="select('excel')">
|
||||
<mat-icon class="export-option__icon" aria-hidden="true">table_chart</mat-icon>
|
||||
<span class="export-option__copy"><strong>Excel</strong><span>Datos utilizados por los indicadores y las gráficas.</span></span>
|
||||
@if (selection() === 'excel') { <mat-icon class="export-option__check" aria-hidden="true">check_circle</mat-icon> }
|
||||
@@ -21,10 +21,13 @@
|
||||
</div>
|
||||
|
||||
<footer class="export-dialog__footer">
|
||||
<p>La generación del archivo se implementará en la siguiente fase.</p>
|
||||
<div class="export-dialog__messages">
|
||||
@if (selection() === 'pdf') { <p>La generación de PDF está pendiente.</p> }
|
||||
@if (error()) { <p class="export-dialog__error" role="alert">No fue posible generar el archivo. Intenta nuevamente.</p> }
|
||||
</div>
|
||||
<div class="export-dialog__actions">
|
||||
<button class="export-dialog__cancel" type="button" (click)="close()">Cancelar</button>
|
||||
<button class="export-dialog__submit" type="button" disabled>Exportar</button>
|
||||
<button class="export-dialog__cancel" type="button" [disabled]="generating()" (click)="close()">Cancelar</button>
|
||||
<button class="export-dialog__submit" type="button" [disabled]="selection() !== 'excel' || generating()" (click)="submit()">{{ generating() ? 'Generando...' : 'Exportar' }}</button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
.export-option__check { color: #52691f; flex: 0 0 auto; font-size: 20px; height: 20px; margin-left: auto; width: 20px; }
|
||||
.export-dialog__footer { align-items: flex-end; border-top: 1px solid var(--color-border); display: flex; gap: 16px; justify-content: space-between; padding-top: 18px; }
|
||||
.export-dialog__footer p { color: var(--color-text-secondary); font-size: 12px; line-height: 1.4; margin: 0; max-width: 240px; }
|
||||
.export-dialog__messages { max-width: 240px; }
|
||||
.export-dialog__messages .export-dialog__error { color: #a12b2b; }
|
||||
.export-dialog button:disabled { cursor: not-allowed; }
|
||||
.export-dialog__actions { display: flex; flex: 0 0 auto; gap: 10px; }
|
||||
.export-dialog__actions button { border-radius: 7px; cursor: pointer; font: inherit; font-weight: 600; min-height: 44px; padding: 10px 18px; }
|
||||
.export-dialog__cancel { background: #fff; border: 1px solid var(--color-border-subtle); color: var(--color-text); }
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { vi } from 'vitest';
|
||||
import { mockAnalysisResult } from './dashboard.mock';
|
||||
import { EXCEL_EXPORT, ExportResultsDialog } from './export-results-dialog';
|
||||
|
||||
describe('ExportResultsDialog', () => {
|
||||
const open = (runExport: (result: typeof mockAnalysisResult) => Promise<void>) => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ExportResultsDialog],
|
||||
providers: [{ provide: EXCEL_EXPORT, useValue: runExport }],
|
||||
});
|
||||
const dialog = TestBed.inject(MatDialog);
|
||||
const ref = dialog.open(ExportResultsDialog, { data: mockAnalysisResult });
|
||||
const detect = () => ref.componentRef!.changeDetectorRef.detectChanges();
|
||||
const root = () => document.querySelector('.cdk-overlay-container')!;
|
||||
detect();
|
||||
return { ref, detect, root };
|
||||
};
|
||||
|
||||
it('keeps PDF unavailable and enables Excel', () => {
|
||||
const { ref, detect, root } = open(vi.fn());
|
||||
const options = root().querySelectorAll<HTMLButtonElement>('.export-option');
|
||||
options[0].click(); detect();
|
||||
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(true);
|
||||
expect(root().textContent).toContain('La generación de PDF está pendiente.');
|
||||
options[1].click(); detect();
|
||||
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(false);
|
||||
ref.close();
|
||||
});
|
||||
|
||||
it('prevents duplicate generation and closes only after success', async () => {
|
||||
let finish!: () => void;
|
||||
const runExport = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));
|
||||
const { ref, detect, root } = open(runExport);
|
||||
root().querySelectorAll<HTMLButtonElement>('.export-option')[1].click(); detect();
|
||||
const submit = root().querySelector<HTMLButtonElement>('.export-dialog__submit')!;
|
||||
submit.click(); detect();
|
||||
expect(runExport).toHaveBeenCalledWith(mockAnalysisResult);
|
||||
expect(submit.disabled).toBe(true);
|
||||
expect(submit.textContent).toContain('Generando...');
|
||||
expect(root().querySelectorAll<HTMLButtonElement>('.export-option')[0].disabled).toBe(true);
|
||||
await ref.componentInstance.submit();
|
||||
expect(runExport).toHaveBeenCalledOnce();
|
||||
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(1);
|
||||
finish();
|
||||
await new Promise<void>((resolve) => ref.afterClosed().subscribe(() => resolve()));
|
||||
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('keeps the dialog open and allows retry after an error', async () => {
|
||||
const runExport = vi.fn().mockRejectedValueOnce(new Error('failure')).mockResolvedValueOnce(undefined);
|
||||
const { ref, detect, root } = open(runExport);
|
||||
root().querySelectorAll<HTMLButtonElement>('.export-option')[1].click(); detect();
|
||||
await ref.componentInstance.submit(); detect();
|
||||
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(1);
|
||||
expect(root().querySelector('[role="alert"]')?.textContent).toContain('No fue posible generar el archivo');
|
||||
expect(root().querySelector<HTMLButtonElement>('.export-dialog__submit')!.disabled).toBe(false);
|
||||
await ref.componentInstance.submit();
|
||||
expect(runExport).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,11 @@
|
||||
import { Component, signal } from '@angular/core';
|
||||
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { Component, inject, InjectionToken, signal } from '@angular/core';
|
||||
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import type { AnalysisResult } from './dashboard.mock';
|
||||
import { exportExcel } from './exports/excel-export';
|
||||
|
||||
export type ExportFormat = 'pdf' | 'excel';
|
||||
export const EXCEL_EXPORT = new InjectionToken<typeof exportExcel>('EXCEL_EXPORT', { factory: () => exportExcel });
|
||||
|
||||
@Component({
|
||||
imports: [MatDialogModule, MatIconModule],
|
||||
@@ -12,9 +15,34 @@ export type ExportFormat = 'pdf' | 'excel';
|
||||
})
|
||||
export class ExportResultsDialog {
|
||||
readonly selection = signal<ExportFormat | null>(null);
|
||||
readonly generating = signal(false);
|
||||
readonly error = signal(false);
|
||||
private readonly result = inject<AnalysisResult>(MAT_DIALOG_DATA);
|
||||
private readonly runExcelExport = inject(EXCEL_EXPORT);
|
||||
|
||||
constructor(private readonly dialogRef: MatDialogRef<ExportResultsDialog>) {}
|
||||
|
||||
select(format: ExportFormat): void { this.selection.set(format); }
|
||||
close(): void { this.dialogRef.close(); }
|
||||
select(format: ExportFormat): void {
|
||||
if (this.generating()) return;
|
||||
this.selection.set(format);
|
||||
this.error.set(false);
|
||||
}
|
||||
|
||||
close(): void { if (!this.generating()) this.dialogRef.close(); }
|
||||
|
||||
async submit(): Promise<void> {
|
||||
if (this.generating() || this.selection() !== 'excel') return;
|
||||
this.generating.set(true);
|
||||
this.error.set(false);
|
||||
this.dialogRef.disableClose = true;
|
||||
try {
|
||||
await this.runExcelExport(this.result);
|
||||
this.dialogRef.close();
|
||||
} catch {
|
||||
this.error.set(true);
|
||||
} finally {
|
||||
this.generating.set(false);
|
||||
this.dialogRef.disableClose = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { read, utils, write } from 'xlsx';
|
||||
import { vi } from 'vitest';
|
||||
import { mockAnalysisResult } from '../dashboard.mock';
|
||||
import { buildWorkbook, excelFilename, exportExcel } from './excel-export';
|
||||
|
||||
describe('Excel export', () => {
|
||||
it('builds four sheets from the same result used by the Dashboard', () => {
|
||||
const workbook = buildWorkbook(mockAnalysisResult, utils);
|
||||
expect(workbook.SheetNames).toEqual(['Resumen', 'Distribución', 'Composición', 'Evolución']);
|
||||
const rows = (name: string) => utils.sheet_to_json<(string | number)[]>(workbook.Sheets[name], { header: 1 });
|
||||
expect(rows('Resumen')).toEqual([
|
||||
['Área de análisis', 'CAMA'],
|
||||
[],
|
||||
['Tipo de datos', 'Datos de demostración'],
|
||||
[],
|
||||
['Indicador', 'Valor'],
|
||||
...mockAnalysisResult.kpis.map((kpi) => [kpi.label, kpi.unit === '%' ? kpi.value / 100 : kpi.value]),
|
||||
]);
|
||||
expect(workbook.Sheets['Resumen']['B7'].z).toBe('0.0%');
|
||||
expect(rows('Distribución').slice(1)).toEqual(mockAnalysisResult.charts.categories.map((item) => [item.label, item.value]));
|
||||
expect(rows('Composición').slice(1)).toEqual(mockAnalysisResult.charts.composition.map((item) => [item.label, item.value]));
|
||||
expect(rows('Evolución').slice(1)).toEqual(mockAnalysisResult.charts.periods.map((item) => [item.label, item.value]));
|
||||
});
|
||||
|
||||
it('requests an xlsx download with a sanitized analysis filename', async () => {
|
||||
const writeFileXLSX = vi.fn();
|
||||
await exportExcel(mockAnalysisResult, async () => ({ utils, writeFileXLSX }));
|
||||
expect(writeFileXLSX).toHaveBeenCalledOnce();
|
||||
expect(writeFileXLSX.mock.calls[0][1]).toBe('ISSSTELEON_CAMA_resultados_demo.xlsx');
|
||||
expect(excelFilename({ ...mockAnalysisResult, analysisType: 'CAMA/otro:*' })).toBe('ISSSTELEON_CAMA_otro_resultados_demo.xlsx');
|
||||
});
|
||||
|
||||
it('produces an XLSX that SheetJS can read with the four sheets intact', () => {
|
||||
const bytes = write(buildWorkbook(mockAnalysisResult, utils), { type: 'array', bookType: 'xlsx' });
|
||||
const opened = read(bytes, { type: 'array' });
|
||||
expect(opened.SheetNames).toEqual(['Resumen', 'Distribución', 'Composición', 'Evolución']);
|
||||
expect(opened.Sheets['Resumen']['B7'].v).toBeCloseTo(0.642);
|
||||
expect(opened.Sheets['Evolución']['A7'].v).toBe('Periodo 6');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { WorkBook, WorkSheet } from 'xlsx';
|
||||
import type { AnalysisResult } from '../dashboard.mock';
|
||||
|
||||
type SheetUtils = typeof import('xlsx')['utils'];
|
||||
type Writer = Pick<typeof import('./sheetjs-write-wrapper'), 'utils' | 'writeFileXLSX'>;
|
||||
|
||||
export function buildWorkbook(result: AnalysisResult, utils: SheetUtils): WorkBook {
|
||||
const workbook = utils.book_new();
|
||||
const summary = utils.aoa_to_sheet([
|
||||
['Área de análisis', result.analysisType],
|
||||
[],
|
||||
['Tipo de datos', 'Datos de demostración'],
|
||||
[],
|
||||
['Indicador', 'Valor'],
|
||||
...result.kpis.map((kpi) => [kpi.label, kpi.unit === '%' ? kpi.value / 100 : kpi.value]),
|
||||
]);
|
||||
summary['!cols'] = [{ wch: 25 }, { wch: 24 }];
|
||||
result.kpis.forEach((kpi, index) => {
|
||||
if (kpi.unit === '%') {
|
||||
const cell = summary[`B${index + 6}`];
|
||||
if (cell) cell.z = '0.0%';
|
||||
}
|
||||
});
|
||||
utils.book_append_sheet(workbook, summary, 'Resumen');
|
||||
|
||||
const appendData = (name: string, heading: string, rows: ReadonlyArray<{ label: string; value: number }>): void => {
|
||||
const sheet: WorkSheet = utils.aoa_to_sheet([[heading, 'Valor'], ...rows.map(({ label, value }) => [label, value])]);
|
||||
sheet['!cols'] = [{ wch: 25 }, { wch: 16 }];
|
||||
utils.book_append_sheet(workbook, sheet, name);
|
||||
};
|
||||
appendData('Distribución', 'Categoría', result.charts.categories);
|
||||
appendData('Composición', 'Segmento', result.charts.composition);
|
||||
appendData('Evolución', 'Periodo', result.charts.periods);
|
||||
return workbook;
|
||||
}
|
||||
|
||||
export function excelFilename(result: AnalysisResult): string {
|
||||
const safeType = result.analysisType.normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-zA-Z0-9_-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 50) || 'analisis';
|
||||
return `ISSSTELEON_${safeType}_resultados_demo.xlsx`;
|
||||
}
|
||||
|
||||
export async function exportExcel(
|
||||
result: AnalysisResult,
|
||||
loadWriter: () => Promise<Writer> = () => import('./sheetjs-write-wrapper'),
|
||||
): Promise<void> {
|
||||
const { utils, writeFileXLSX } = await loadWriter();
|
||||
writeFileXLSX(buildWorkbook(result, utils), excelFilename(result));
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { utils, writeFileXLSX } from 'xlsx';
|
||||
|
||||
export { utils, writeFileXLSX };
|
||||
Reference in New Issue
Block a user