WebApp shared: Plotly partial bundle, card actions, print report, export module

Plotly partial bundle (bar, scatter, box, pie, sankey, contour) replacing the cartesian dist; card-actions (published Measure definitions, settings, Volver); Descargar reporte with a print stylesheet; export module: xlsx with frozen header, autofilter, Parámetros sheet and 5,000-row cap, pdfmake documents with header/footer, allRows following next links, file names without patient identifiers; lazy-loaded export libraries.

Checks on milkpc (node:22): npm ci, ng build (initial 567 kB / 134 kB transfer), ng test 7 files passed.
This commit is contained in:
2026-11-30 13:36:35 -06:00
parent 5d03f333f7
commit 56d1ef2e8a
20 changed files with 2827 additions and 142 deletions
+53
View File
@@ -0,0 +1,53 @@
import { TestBed } from '@angular/core/testing';
import { MatDialog } from '@angular/material/dialog';
import { describe, expect, it, vi } from 'vitest';
import { CardActions } from './card-actions';
describe('CardActions', () => {
it('opens the published definition and emits back only through the filtered action', async () => {
const fixture = TestBed.createComponent(CardActions);
fixture.componentRef.setInput('measures', [
{
resourceType: 'Measure',
status: 'active',
title: 'Oportunidad',
description: 'Definición publicada',
group: [
{
population: [
{
code: { text: 'Numerador' },
criteria: { language: 'text/plain', description: 'Casos oportunos' },
},
{ criteria: { language: 'text/plain' } },
],
},
],
},
]);
const back = vi.fn();
fixture.componentInstance.back.subscribe(back);
fixture.detectChanges();
const host: HTMLElement = fixture.nativeElement;
expect(host.textContent).not.toContain('Volver');
host.querySelector<HTMLButtonElement>('[aria-label="Ver definición"]')!.click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = document.querySelector('[role="dialog"]')!;
expect(dialog.textContent).toContain('Oportunidad');
expect(dialog.textContent).toContain('Definición publicada');
expect(dialog.textContent).toContain('Numerador');
expect(dialog.textContent).toContain('Casos oportunos');
expect(dialog.textContent).toContain('Sin definición publicada');
TestBed.inject(MatDialog).closeAll();
fixture.componentRef.setInput('filtered', true);
fixture.detectChanges();
[...host.querySelectorAll('button')]
.find((button) => button.textContent?.trim() === 'Volver')!
.click();
expect(back).toHaveBeenCalledOnce();
});
});
+72
View File
@@ -0,0 +1,72 @@
import { Component, inject, input, output, TemplateRef } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatMenuModule } from '@angular/material/menu';
import type { Measure } from 'fhir/r4';
@Component({
selector: 'app-card-actions',
imports: [NgTemplateOutlet, MatButtonModule, MatDialogModule, MatMenuModule],
template: `
<button mat-icon-button type="button" aria-label="Ver definición" (click)="open(definition)">
?
</button>
@if (settings(); as content) {
<button mat-button type="button" [matMenuTriggerFor]="menu">Configuración</button>
<mat-menu #menu="matMenu">
<ng-template matMenuContent>
<ng-container [ngTemplateOutlet]="content" />
</ng-template>
</mat-menu>
}
@if (filtered()) {
<button mat-button type="button" (click)="back.emit()">Volver</button>
}
<ng-template #definition>
<h2 mat-dialog-title>Definición</h2>
<mat-dialog-content>
@for (measure of measures(); track $index) {
<h3>{{ measure.title }}</h3>
@if (measure.description) {
<p>{{ measure.description }}</p>
}
@for (group of measure.group ?? []; track $index) {
@for (population of group.population ?? []; track $index) {
<p>
@if (population.code?.text; as text) {
<strong>{{ text }}</strong>
}
@if (population.criteria.description; as description) {
{{ description }}
} @else if (!population.code?.text) {
Sin definición publicada
}
</p>
} @empty {
<p>Sin definición publicada</p>
}
} @empty {
<p>Sin definición publicada</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cerrar</button>
</mat-dialog-actions>
</ng-template>
`,
styles: ':host { display: inline-flex; align-items: center; gap: var(--space-1); }',
})
export class CardActions {
private readonly dialog = inject(MatDialog);
readonly measures = input.required<Measure[]>();
readonly settings = input<TemplateRef<unknown>>();
readonly filtered = input(false);
readonly back = output<void>();
protected open(template: TemplateRef<unknown>): void {
this.dialog.open(template);
}
}
+100
View File
@@ -0,0 +1,100 @@
import type { Bundle, Patient } from 'fhir/r4';
import { describe, expect, it, vi } from 'vitest';
import { allRows, downloadPdf, downloadXlsx, MAX_ROWS, safeName } from './index';
const mocks = vi.hoisted(() => {
const toFile = vi.fn();
const download = vi.fn();
return {
toFile,
write: vi.fn().mockReturnValue({ toFile }),
download,
createPdf: vi.fn().mockReturnValue({ download }),
addVirtualFileSystem: vi.fn(),
fonts: { 'Roboto-Regular.ttf': 'base64' },
};
});
vi.mock('write-excel-file/browser', () => ({ default: mocks.write }));
vi.mock('pdfmake/build/pdfmake', () => ({
default: { createPdf: mocks.createPdf, addVirtualFileSystem: mocks.addVirtualFileSystem },
}));
vi.mock('pdfmake/build/vfs_fonts', () => ({ default: mocks.fonts }));
const name = 'tea-indicadores-2026-11-30';
describe('export', () => {
it('writes capped data with a frozen header, a filter, and a parameters sheet', async () => {
const sheet = {
name: 'Indicadores',
columns: [{ header: 'Total', key: 'total', type: 'number' as const }],
rows: Array.from({ length: MAX_ROWS + 1 }, (_, total) => ({ total })),
};
await downloadXlsx(name, [sheet], { Periodo: '2026-11' });
expect(mocks.write).toHaveBeenCalledWith(
[
expect.objectContaining({ sheet: 'Indicadores', stickyRowsCount: 1 }),
expect.objectContaining({
sheet: 'Parámetros',
data: [expect.any(Array), ['Periodo', '2026-11']],
}),
],
expect.any(Object),
);
const [[dataSheet], options] = mocks.write.mock.calls[0];
expect(dataSheet.data).toHaveLength(MAX_ROWS + 2);
expect(dataSheet.data[MAX_ROWS]).toEqual([MAX_ROWS - 1]);
expect(dataSheet.data.at(-1)).toEqual([expect.stringContaining(String(MAX_ROWS))]);
const { transform } = options.features[0].files.transform['xl/worksheets/sheet{id}.xml'];
const xml = '<worksheet><sheetData><row/></sheetData></worksheet>';
expect(transform(xml, {}, { sheetIndex: 0 })).toContain(
`</sheetData><autoFilter ref="A1:A${MAX_ROWS + 1}"/>`,
);
expect(transform(xml, {}, { sheetIndex: 1 })).toBe(xml);
expect(mocks.toFile).toHaveBeenCalledWith(`${name}.xlsx`);
});
it('accepts domain, page, and date and refuses an id-like part', async () => {
expect(safeName(['tea', 'indicadores', '2026-11-30'])).toBe(name);
expect(() => safeName(['tea', 'patient-4821', '2026-11-30'])).toThrow();
await expect(downloadPdf('tea-patient-4821-2026-11-30', [])).rejects.toThrow();
});
it('follows next links, skipping empty entries and stopping inside the last page', async () => {
const patient = (id: string): Patient => ({ resourceType: 'Patient', id });
const bundle = (patients: Patient[], next: string): Bundle => ({
resourceType: 'Bundle',
type: 'searchset',
entry: [{}, ...patients.map((resource) => ({ resource }))],
link: [{ relation: 'next', url: next }],
});
const getPage = vi
.fn<(url: string) => Promise<Bundle>>()
.mockResolvedValueOnce(bundle([patient('1')], '/page/2'))
.mockResolvedValueOnce(bundle([patient('2'), patient('3')], '/page/3'));
await expect(allRows<Patient>('/page/1', getPage, 2)).resolves.toEqual([
patient('1'),
patient('2'),
]);
expect(getPage.mock.calls).toEqual([['/page/1'], ['/page/2']]);
});
it('passes the institutional header and generated timestamp footer to pdfmake', async () => {
const content = [{ text: 'Indicadores' }];
await downloadPdf(name, content);
expect(mocks.addVirtualFileSystem).toHaveBeenCalledWith(mocks.fonts);
expect(mocks.createPdf).toHaveBeenCalledWith(
expect.objectContaining({
content,
header: expect.objectContaining({ stack: ['ISSSTELEON', 'Plataforma de Indicadores'] }),
footer: expect.any(Function),
}),
);
const [definition] = mocks.createPdf.mock.calls[0];
expect(definition.footer(2, 4).text).toMatch(/^Página 2 de 4 · Generado el .+$/);
expect(mocks.download).toHaveBeenCalledWith(`${name}.pdf`);
});
});
+20
View File
@@ -0,0 +1,20 @@
import type { Bundle } from 'fhir/r4';
import { MAX_ROWS } from './xlsx';
export async function allRows<T>(
first: string,
getPage: (url: string) => Promise<Bundle>,
max = MAX_ROWS,
): Promise<T[]> {
const rows: T[] = [];
let next: string | undefined = first;
while (next && rows.length < max) {
const page = await getPage(next);
for (const { resource } of page.entry ?? []) {
if (resource) rows.push(resource as T);
if (rows.length >= max) return rows;
}
next = page.link?.find(({ relation }) => relation === 'next')?.url;
}
return rows;
}
+4
View File
@@ -0,0 +1,4 @@
export { allRows } from './fetch-all';
export { downloadPdf, type PdfContent } from './pdf';
export { safeName } from './safe-name';
export { downloadXlsx, MAX_ROWS, type Sheet } from './xlsx';
+31
View File
@@ -0,0 +1,31 @@
import type { Content } from 'pdfmake/interfaces';
import { validateName } from './safe-name';
export type { Content as PdfContent } from 'pdfmake/interfaces';
export async function downloadPdf(name: string, content: Content[]): Promise<void> {
const filename = `${validateName(name)}.pdf`;
const [{ default: pdfMake }, { default: fonts }] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
]);
pdfMake.addVirtualFileSystem(fonts);
const generatedAt = new Intl.DateTimeFormat('es-MX', {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date());
await pdfMake
.createPdf({
content,
pageMargins: [40, 65, 40, 45],
header: {
stack: ['ISSSTELEON', 'Plataforma de Indicadores'],
margin: [40, 20, 40, 0],
},
footer: (page, pages) => ({
text: `Página ${page} de ${pages} · Generado el ${generatedAt}`,
margin: [40, 10, 40, 0],
}),
})
.download(filename);
}
+34
View File
@@ -0,0 +1,34 @@
const domains = new Set(['cacu', 'cama', 'tea']);
const pages = new Set([
'indicadores',
'trazabilidad',
'riesgos',
'seguimiento',
'definiciones',
'gobernanza',
'revision',
'conectar',
]);
export function safeName(parts: string[]): string {
const [domain, page, date] = parts;
if (
parts.length !== 3 ||
!domains.has(domain) ||
!pages.has(page) ||
!/^\d{4}-\d{2}-\d{2}$/.test(date)
) {
throw new Error('El nombre debe contener un dominio, una página y una fecha.');
}
const parsed = new Date(date);
if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
throw new Error('La fecha del nombre no es válida.');
}
return parts.join('-');
}
export function validateName(name: string): string {
const match = /^([^-]+)-([^-]+)-(\d{4}-\d{2}-\d{2})$/.exec(name);
if (!match) throw new Error('El nombre de exportación no es válido.');
return safeName(match.slice(1));
}
+99
View File
@@ -0,0 +1,99 @@
import type { Cell, Row } from 'write-excel-file/browser';
import { validateName } from './safe-name';
export const MAX_ROWS = 5000;
export type Sheet = {
name: string;
columns: { header: string; key: string; type?: 'string' | 'number' | 'date' }[];
rows: Record<string, unknown>[];
};
function cell(value: unknown, type?: Sheet['columns'][number]['type']): Cell {
if (value == null || value === '') return null;
if (type === 'date' || (!type && value instanceof Date)) {
const date = value instanceof Date ? value : new Date(String(value));
return Number.isFinite(date.getTime()) ? { value: date, format: 'yyyy-mm-dd' } : null;
}
if (type === 'number') {
const number = typeof value === 'string' && value.trim() ? Number(value) : value;
return typeof number === 'number' && Number.isFinite(number) ? number : null;
}
if (!type && typeof value === 'number') return Number.isFinite(value) ? value : null;
if (!type && typeof value === 'boolean') return value;
return String(value);
}
function columnName(count: number): string {
let name = '';
while (count > 0) {
count--;
name = String.fromCharCode(65 + (count % 26)) + name;
count = Math.floor(count / 26);
}
return name;
}
function width(value: Cell): number {
if (value == null) return 0;
if (typeof value === 'object' && 'value' in value)
return value.value instanceof Date ? 10 : String(value.value).length;
return String(value).length;
}
export async function downloadXlsx(
name: string,
sheets: Sheet[],
parameters: Record<string, string>,
): Promise<void> {
const filename = `${validateName(name)}.xlsx`;
const { default: writeExcelFile } = await import('write-excel-file/browser');
const parameterSheet: Sheet = {
name: 'Parámetros',
columns: [
{ header: 'Parámetro', key: 'parameter' },
{ header: 'Valor', key: 'value' },
],
rows: Object.entries(parameters).map(([parameter, value]) => ({ parameter, value })),
};
const filterRanges: (string | undefined)[] = [];
const workbook = [...sheets, parameterSheet].map(({ name, columns, rows }, index) => {
const data: Row[] = [columns.map(({ header }) => ({ value: header, fontWeight: 'bold' }))];
for (const row of rows.slice(0, MAX_ROWS)) {
data.push(columns.map(({ key, type }) => cell(row[key], type)));
}
if (index < sheets.length && columns.length) {
filterRanges[index] = `A1:${columnName(columns.length)}${data.length}`;
}
if (rows.length >= MAX_ROWS) {
data.push([`Límite de exportación: ${MAX_ROWS} filas.`]);
}
return {
sheet: name,
data,
stickyRowsCount: 1,
columns: columns.map((_, column) => ({
width: Math.min(80, Math.max(10, ...data.map((row) => width(row[column]))) + 2),
})),
};
});
await writeExcelFile(workbook, {
features: [
{
files: {
transform: {
'xl/worksheets/sheet{id}.xml': {
transform: (xml, _, { sheetIndex }) => {
const ref = filterRanges[sheetIndex];
return ref
? xml.replace('</sheetData>', `</sheetData><autoFilter ref="${ref}"/>`)
: xml;
},
},
},
},
},
],
}).toFile(filename);
}
+12 -1
View File
@@ -3,6 +3,7 @@ import { MatTabsModule } from '@angular/material/tabs';
import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app';
import { Fhir, resources } from '../fhir';
import { ReportButton } from '../report-button';
import { TabDefiniciones } from './tab-definiciones';
import { TabIndicadores } from './tab-indicadores';
import { TabRiesgos } from './tab-riesgos';
@@ -14,6 +15,7 @@ import { TabTrazabilidad } from './tab-trazabilidad';
selector: 'app-indicadores',
imports: [
MatTabsModule,
ReportButton,
TabIndicadores,
TabTrazabilidad,
TabRiesgos,
@@ -22,7 +24,10 @@ import { TabTrazabilidad } from './tab-trazabilidad';
],
template: `
<section class="page">
<h1>{{ title() }}</h1>
<header class="page-header">
<h1>{{ title() }}</h1>
<app-report-button />
</header>
<p class="subtitle">
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
</p>
@@ -68,6 +73,12 @@ import { TabTrazabilidad } from './tab-trazabilidad';
:host {
display: block;
}
.page-header {
position: relative;
display: grid;
justify-items: center;
gap: var(--space-2);
}
h1 {
text-align: center;
}
+14 -1
View File
@@ -25,6 +25,12 @@
>
Aplicar
</button>
<span class="print-only"
>Intervalo de análisis: {{ type() === 'month' ? 'Mensual' : 'Semestral' }}</span
>
@if (chosen(); as selected) {
<span class="print-only">Periodo seleccionado: {{ label(selected) }}</span>
}
@if (applied(); as p) {
<span class="muted applied">Mostrando {{ label(p) }}</span>
}
@@ -39,8 +45,11 @@
<div class="kpis">
@for (m of kpis(); track m.id) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
<mat-card-content>
<mat-card-header>
<div class="kpi-title">{{ m.title }}</div>
<app-card-actions [measures]="[m]" />
</mat-card-header>
<mat-card-content>
<div class="kpi-value">{{ score(m) }}</div>
<div class="kpi-detail muted">{{ detail(m) }}</div>
</mat-card-content>
@@ -53,6 +62,10 @@
<mat-card appearance="outlined" class="route">
<mat-card-header>
<mat-card-title>Ruta del tamizaje</mat-card-title>
<app-card-actions [measures]="routeMeasures()" />
<span class="print-only">
{{ routeView() === 'sample' ? 'Acumulado desde la toma' : 'Por pasos' }}
</span>
<mat-button-toggle-group
[value]="routeView()"
(change)="routeView.set($event.value)"
+10
View File
@@ -5,6 +5,7 @@ import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { CardActions } from '../card-actions';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
@@ -29,6 +30,7 @@ import {
@Component({
selector: 'app-tab-indicadores',
imports: [
CardActions,
FormsModule,
MatButtonModule,
MatButtonToggleModule,
@@ -132,6 +134,14 @@ export class TabIndicadores {
this.chosen.set(this.options()[0]);
}
protected readonly routeMeasures = computed(() => {
const view = this.routeView();
const measures = this.layout()
.route.map((step) => this.byName().get(view === 'sample' ? step.fromSample : step.fromStep))
.filter((measure) => !!measure);
return [...new Set(measures)];
});
protected readonly route = computed<Figure>(() => {
const view = this.routeView();
return medians(
+5 -5
View File
@@ -1,6 +1,6 @@
import { Component, effect, ElementRef, input, OnDestroy, viewChild } from '@angular/core';
// The cartesian bundle: bars, lines, box and pie, as today's charts use.
import Plotly from 'plotly.js-cartesian-dist-min';
import type * as Plotly from 'plotly.js';
import plotly from './plotly-bundle';
export type Figure = { data: Partial<Plotly.Data>[]; layout?: Partial<Plotly.Layout> };
@@ -26,7 +26,7 @@ const LAYOUT: Partial<Plotly.Layout> = {
const CONFIG: Partial<Plotly.Config> = {
responsive: true,
displaylogo: false,
modeBarButtonsToRemove: ['sendDataToCloud', 'lasso2d', 'select2d'],
modeBarButtonsToRemove: ['lasso2d', 'select2d'],
};
/** One Plotly chart: the figure, drawn with the platform's layout and config. */
@@ -43,7 +43,7 @@ export class Plot implements OnDestroy {
constructor() {
effect(() => {
const { data, layout } = this.figure();
void Plotly.react(
void plotly.react(
this.host().nativeElement,
data as Plotly.Data[],
{ ...LAYOUT, ...layout },
@@ -53,6 +53,6 @@ export class Plot implements OnDestroy {
}
ngOnDestroy(): void {
Plotly.purge(this.host().nativeElement);
plotly.purge(this.host().nativeElement);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { describe, expect, it } from 'vitest';
import { TRACES } from './plotly-bundle';
describe('Plotly partial bundle', () => {
it('registers the Sankey and contour traces', () => {
const names = TRACES.map((trace) => (trace as { name?: string }).name);
expect(names).toEqual(expect.arrayContaining(['sankey', 'contour', 'bar', 'scatter', 'box', 'pie']));
});
});
+13
View File
@@ -0,0 +1,13 @@
import bar from 'plotly.js/lib/bar';
import box from 'plotly.js/lib/box';
import contour from 'plotly.js/lib/contour';
import Plotly from 'plotly.js/lib/core';
import pie from 'plotly.js/lib/pie';
import sankey from 'plotly.js/lib/sankey';
import scatter from 'plotly.js/lib/scatter';
export const TRACES = [bar, scatter, box, pie, sankey, contour];
Plotly.register(TRACES);
export default Plotly;
+13
View File
@@ -0,0 +1,13 @@
import { Component } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
@Component({
selector: 'app-report-button',
imports: [MatButtonModule],
template: '<button mat-flat-button type="button" (click)="print()">Descargar reporte</button>',
})
export class ReportButton {
protected print(): void {
window.print();
}
}
+7 -3
View File
@@ -1,5 +1,9 @@
// The cartesian bundle has plotly.js's API.
declare module 'plotly.js-cartesian-dist-min' {
import Plotly from 'plotly.js';
declare module 'plotly.js/lib/core' {
const Plotly: typeof import('plotly.js');
export default Plotly;
}
declare module 'plotly.js/lib/*' {
const trace: import('plotly.js').PlotlyModule;
export default trace;
}
+51
View File
@@ -0,0 +1,51 @@
nav,
body .shell > .header,
body .shell > .footer,
mat-toolbar,
.mat-mdc-tab-header,
button,
app-card-actions,
app-report-button,
.modebar,
.filters .field,
.filters input,
.filters select,
.filters mat-form-field,
mat-button-toggle-group {
display: none !important;
}
.print-only {
display: inline !important;
}
body .shell,
body .main,
body .kpis,
body .clinical {
display: block;
}
body .page,
mat-card,
.card {
box-sizing: border-box;
max-width: none;
width: 100%;
}
mat-card,
.card {
break-inside: avoid;
margin-bottom: 12px;
}
.mat-mdc-tab-body-wrapper,
.mat-mdc-tab-body.mat-mdc-tab-body-active,
.mat-mdc-tab-body-active .mat-mdc-tab-body-content {
overflow: visible;
}
app-plot {
display: block;
}
+9
View File
@@ -2,6 +2,7 @@
// Roboto for text and Rajdhani for headings, served from the app (internal network).
@use '@angular/material' as mat;
@use './theme-colors' as brand;
@use 'sass:meta';
:root {
--color-primary: #a8c243;
@@ -121,3 +122,11 @@ html {
.nowrap {
white-space: nowrap;
}
.print-only {
display: none;
}
@media print {
@include meta.load-css('print');
}