diff --git a/package-lock.json b/package-lock.json index 4c51c72..e0e15e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,9 +20,11 @@ "@fontsource/roboto": "^5.3.0", "@fontsource/roboto-mono": "^5.3.0", "material-icons": "^1.13.14", + "pdfmake": "0.3.14", "plotly.js-cartesian-dist-min": "4.1.2", "rxjs": "~7.8.0", - "tslib": "^2.3.0" + "tslib": "^2.3.0", + "write-excel-file": "4.1.1" }, "devDependencies": { "@angular/build": "^22.1.8", @@ -2701,6 +2703,30 @@ "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@oxc-parser/binding-android-arm-eabi": { "version": "0.142.0", "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.142.0.tgz", @@ -3697,6 +3723,12 @@ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", "license": "MIT" }, + "node_modules/@swc/helpers": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz", + "integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==", + "license": "Apache-2.0" + }, "node_modules/@tybys/wasm-util": { "version": "0.10.4", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", @@ -4011,6 +4043,15 @@ "node": ">=12" } }, + "node_modules/base64-js": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz", + "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/baseline-browser-mapping": { "version": "2.11.25", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz", @@ -4101,6 +4142,35 @@ "dev": true, "license": "ISC" }, + "node_modules/brotli": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz", + "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.1.2" + } + }, + "node_modules/brotli/node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/browserslist": { "version": "4.29.0", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz", @@ -4357,6 +4427,15 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, "node_modules/content-disposition": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", @@ -4560,6 +4639,12 @@ "node": ">=8" } }, + "node_modules/dfa": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", + "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==", + "license": "MIT" + }, "node_modules/dom-serializer": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", @@ -4921,7 +5006,6 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-string-truncated-width": { @@ -4986,6 +5070,12 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, "node_modules/finalhandler": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", @@ -5018,6 +5108,23 @@ "node": ">=6" } }, + "node_modules/fontkit": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz", + "integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==", + "license": "MIT", + "dependencies": { + "@swc/helpers": "^0.5.12", + "brotli": "^1.3.2", + "clone": "^2.1.2", + "dfa": "^1.2.0", + "fast-deep-equal": "^3.1.3", + "restructure": "^3.0.0", + "tiny-inflate": "^1.0.3", + "unicode-properties": "^1.4.0", + "unicode-trie": "^2.0.0" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -5862,6 +5969,16 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/linebreak": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", + "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==", + "license": "MIT", + "dependencies": { + "base64-js": "0.0.8", + "unicode-trie": "^2.0.0" + } + }, "node_modules/listr2": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/listr2/-/listr2-11.0.0.tgz", @@ -6373,6 +6490,12 @@ "@oxc-parser/binding-win32-x64-msvc": "0.142.0" } }, + "node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", + "license": "MIT" + }, "node_modules/parse5": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", @@ -6476,6 +6599,34 @@ "dev": true, "license": "MIT" }, + "node_modules/pdfkit": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz", + "integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==", + "license": "MIT", + "dependencies": { + "@noble/ciphers": "^1.3.0", + "@noble/hashes": "^1.8.0", + "fflate": "^0.8.3", + "fontkit": "^2.0.4", + "linebreak": "^1.1.0", + "png-js": "^2.0.0" + } + }, + "node_modules/pdfmake": { + "version": "0.3.14", + "resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz", + "integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==", + "license": "MIT", + "dependencies": { + "linebreak": "^1.1.0", + "pdfkit": "^0.20.2", + "xmldoc": "^2.0.3" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -6525,6 +6676,14 @@ "integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==", "license": "MIT" }, + "node_modules/png-js": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz", + "integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==", + "dependencies": { + "fflate": "^0.8.2" + } + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", @@ -6755,6 +6914,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/restructure": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz", + "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==", + "license": "MIT" + }, "node_modules/rolldown": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz", @@ -6853,6 +7018,15 @@ "@parcel/watcher": "^2.4.1" } }, + "node_modules/sax": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", + "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -7187,6 +7361,12 @@ "dev": true, "license": "MIT" }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -7350,6 +7530,46 @@ "node": ">=20.18.1" } }, + "node_modules/unicode-properties": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", + "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.0", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/unicode-properties/node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/unicode-trie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", + "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", + "license": "MIT", + "dependencies": { + "pako": "^0.2.5", + "tiny-inflate": "^1.0.0" + } + }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", @@ -8070,6 +8290,18 @@ "dev": true, "license": "ISC" }, + "node_modules/write-excel-file": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz", + "integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==", + "license": "MIT", + "dependencies": { + "fflate": "^0.8.2" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/xml-name-validator": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", @@ -8087,6 +8319,18 @@ "dev": true, "license": "MIT" }, + "node_modules/xmldoc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz", + "integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==", + "license": "MIT", + "dependencies": { + "sax": "^1.4.3" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index fdc26d4..12982e3 100644 --- a/package.json +++ b/package.json @@ -23,9 +23,11 @@ "@fontsource/roboto": "^5.3.0", "@fontsource/roboto-mono": "^5.3.0", "material-icons": "^1.13.14", + "pdfmake": "0.3.14", "plotly.js-cartesian-dist-min": "4.1.2", "rxjs": "~7.8.0", - "tslib": "^2.3.0" + "tslib": "^2.3.0", + "write-excel-file": "4.1.1" }, "devDependencies": { "@angular/build": "^22.1.8", diff --git a/src/app/app-encabezado.spec.ts b/src/app/app-encabezado.spec.ts new file mode 100644 index 0000000..24ab7a6 --- /dev/null +++ b/src/app/app-encabezado.spec.ts @@ -0,0 +1,90 @@ +// Covers the shell's header: on an indicators page it carries the platform title and the domain selector; on +// the institutional routes it keeps the breadcrumb. The pages are stubs: only the header and the router matter. +import { Component } from '@angular/core'; +import { Location } from '@angular/common'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter, Router } from '@angular/router'; +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting } from '@angular/common/http/testing'; +import { App } from './app'; +import { routes } from './app.routes'; +import { DOMINIOS } from './features/indicadores/indicadores.models'; + +@Component({ template: 'página', selector: 'app-stub' }) +class Stub {} + +describe('Encabezado del marco', () => { + const rutas = [ + { path: '', component: Stub }, + { path: 'conectar', component: Stub, data: { workspace: true, breadcrumb: 'Conectar datos' } }, + { path: 'gobernanza', component: Stub, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' } }, + ...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, component: Stub, data: { workspace: true, breadcrumb: 'Indicadores', dominio } })), + ]; + let fixture: ReturnType>, router: Router; + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [App], providers: [provideRouter(rutas), provideHttpClient(), provideHttpClientTesting()] }).compileComponents(); + fixture = TestBed.createComponent(App); router = TestBed.inject(Router); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); document.querySelectorAll('.cdk-overlay-container').forEach(e => e.replaceChildren()); }); + const root = () => fixture.nativeElement as HTMLElement; + async function ir(url: string) { await router.navigateByUrl(url); await fixture.whenStable(); fixture.detectChanges(); } + const selector = () => root().querySelector('.domain-selector') as HTMLButtonElement | null; + async function abrirMenu() { + selector()!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + return [...document.querySelectorAll('.mat-mdc-menu-panel a[mat-menu-item]')] as HTMLAnchorElement[]; + } + + it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => { + // Fails if the selector would point at a route the application does not have. + const paths = routes.map(r => r.path); + for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`); + }); + it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => { + await ir('/indicadores/' + dominio); + expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores'); + expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾'); + expect(root().querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON'); + // The breadcrumb is replaced, not duplicated beside the selector. + expect(root().querySelector('.site-header__nav')).toBeNull(); + expect(root().querySelector('.app-shell--indicadores')).not.toBeNull(); + }); + it('el selector tiene nombre accesible con el dominio actual y anuncia un menú', async () => { + await ir('/indicadores/cama'); + expect(selector()!.getAttribute('aria-label')).toBe('Dominio actual: Cáncer de mama. Cambiar dominio'); + expect(selector()!.getAttribute('aria-haspopup')).toBe('menu'); + expect(selector()!.tagName).toBe('BUTTON'); + expect(selector()!.tabIndex).toBeGreaterThanOrEqual(0); + }); + it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => { + await ir('/indicadores/cama'); + const items = await abrirMenu(); + expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']); + expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']); + expect(selector()!.getAttribute('aria-expanded')).toBe('true'); + }); + it('elegir otro dominio navega por el enrutador, actualiza el selector y deja una entrada en el historial', async () => { + await ir('/indicadores/cama'); + const items = await abrirMenu(); + items[1].click(); await fixture.whenStable(); fixture.detectChanges(); + expect(router.url).toBe('/indicadores/cacu'); + expect(selector()!.textContent).toContain('CaCu'); + // The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain. + const ubicacion = TestBed.inject(Location); + ubicacion.back(); await new Promise(r => setTimeout(r, 100)); + expect(ubicacion.path()).toBe('/indicadores/cama'); + }); + it.each(['/', '/conectar', '/gobernanza'])('en %s conserva el encabezado institucional sin selector', async url => { + // Fails if the indicators header leaks into the institutional routes. + await ir(url); + expect(selector()).toBeNull(); + expect(root().querySelector('.platform-title')).toBeNull(); + expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información'); + expect(root().querySelector('.app-shell--indicadores')).toBeNull(); + if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos'); + }); + it('una ruta parecida que no es de indicadores no activa el selector', async () => { + await router.navigateByUrl('/'); fixture.detectChanges(); + expect(selector()).toBeNull(); + }); +}); diff --git a/src/app/app.config.ts b/src/app/app.config.ts index d9c42bd..a8b7623 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -2,11 +2,21 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/ import { provideHttpClient } from '@angular/common/http'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; +import { IndicadoresService } from './features/indicadores/indicadores.service'; +import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos'; +import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service'; +import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir'; +import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir'; export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), provideRouter(routes), provideHttpClient(), + // The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract + // (`//indicadores//datos`, `/tea/seguimiento`). + { provide: IndicadoresService, useClass: FhirIndicadoresService }, + { provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos }, + { provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService }, ] }; diff --git a/src/app/app.html b/src/app/app.html index b41af08..7312335 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,15 +1,25 @@ -
+
diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 66070ed..feed61d 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -6,6 +6,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page'). export const routes: Routes = [ { path: '', component: Home, title: 'Análisis de información | ISSSTELEON' }, + { + path: 'indicadores/tea-estatus', + title: 'Casos por estatus | ISSSTELEON', + loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage), + data: { workspace: true, breadcrumb: 'Casos por estatus' }, + }, { path: 'conectar', title: 'Conectar datos | ISSSTELEON', @@ -26,6 +32,12 @@ export const routes: Routes = [ loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage), data: { workspace: true, breadcrumb: 'Bitácora de cargas' }, }, + { + path: 'kpis', + title: 'Indicadores | ISSSTELEON', + loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage), + data: { workspace: true, breadcrumb: 'Indicadores' }, + }, { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, ...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, diff --git a/src/app/app.scss b/src/app/app.scss index 234d0f1..504dc97 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -103,3 +103,26 @@ width: 155px; } } + +.platform-title { + color: var(--color-text); + font-family: var(--issste-font-heading); + font-size: 1.25rem; + font-weight: 500; + line-height: 1.15; + margin-inline-start: var(--issste-space-4); + margin-inline-end: auto; + overflow-wrap: anywhere; +} + +.domain-selector--espera { + align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto; + background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap; +} + +// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed. +@media (max-width: 599px) { + .app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; } + .app-shell--indicadores .brand { margin-inline-end: auto; } + .platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; } +} diff --git a/src/app/app.ts b/src/app/app.ts index b18cd4e..a494033 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -2,9 +2,11 @@ import { Component, computed, inject } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router'; import { filter, map } from 'rxjs'; +import { DomainSelector } from './domain-selector'; +import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models'; @Component({ - imports: [RouterLink, RouterOutlet], + imports: [RouterLink, RouterOutlet, DomainSelector], selector: 'app-root', styleUrl: './app.scss', templateUrl: './app.html', @@ -28,4 +30,13 @@ export class App { /** Full-height workspace routes (`data.workspace`) drop the marketing footer. */ readonly workspace = computed(() => !!this.leafRouteData()['workspace']); readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined); + + protected readonly title = 'Plataforma de Indicadores'; + protected readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' }; + private readonly url = toSignal(this.router.events.pipe( + filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url }); + /** On an indicators page the header names its domain and switches to the others. */ + protected readonly activeDomain = computed(() => + DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url()))); + protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain())); } diff --git a/src/app/connect/state/connect-workspace.store.ts b/src/app/connect/state/connect-workspace.store.ts index dc36115..8f07333 100644 --- a/src/app/connect/state/connect-workspace.store.ts +++ b/src/app/connect/state/connect-workspace.store.ts @@ -12,7 +12,7 @@ import { ImportFlow } from '../domain/import-flow'; export const DOMAINS: { id: Domain; label: string; description: string }[] = [ { id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' }, - { id: 'cama', label: 'CaMa', description: 'Cáncer de mama' }, + { id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' }, { id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' }, ]; diff --git a/src/app/domain-selector.scss b/src/app/domain-selector.scss new file mode 100644 index 0000000..d7c23ab --- /dev/null +++ b/src/app/domain-selector.scss @@ -0,0 +1,10 @@ +:host { display: contents; } +.domain-selector { + flex: 0 0 auto; + background-color: var(--issste-accent); + color: var(--issste-text); + font-weight: 700; + white-space: nowrap; +} +.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); } +.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } diff --git a/src/app/domain-selector.ts b/src/app/domain-selector.ts new file mode 100644 index 0000000..23f6bfb --- /dev/null +++ b/src/app/domain-selector.ts @@ -0,0 +1,28 @@ +import { Component, input } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { MatMenuModule } from '@angular/material/menu'; +import { Dominio } from './features/indicadores/indicadores.models'; + +/** The header's domain menu. Loaded deferred: Material's menu and overlay are not needed by the institutional routes. */ +@Component({ + selector: 'app-domain-selector', + imports: [RouterLink, MatButtonModule, MatMenuModule], + template: ` + + + @for (option of otros(); track option) { + {{ labels()[option] }} + } + + `, + styleUrl: './domain-selector.scss', +}) +export class DomainSelector { + readonly actual = input.required(); + readonly otros = input.required(); + readonly labels = input.required>(); +} diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index d6f1b6c..4fbd27f 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,7 +1,9 @@ -export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; } +export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } export interface SeguimientoStatus { codigo: string; etiqueta: string; } +// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`. export interface SeguimientoPaciente { - id_seudonimo: string; + pac_id?: string; + id_seudonimo?: string; grupo_edad: string; estatus: SeguimientoStatus; ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index a9d9924..53cf2da 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models'; +import { identidadDe, identidadesDe } from './paciente-identidad'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string'; const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; @@ -19,12 +20,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { || !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string)) || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages']) || !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => { - if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; + if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; const c = item['ultima_citologia'], h = item['ultimo_vph']; return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string')) && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); - })) throw new Error('Respuesta de seguimiento inválida'); + }) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as SeguimientoResponse; } @Injectable({ providedIn: 'root' }) diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index f3c85c8..b77f3a9 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => { afterEach(()=>{ fixture.destroy(); http.verify(); }); function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); } function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); } - it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => { + it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => { respond(); - const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement; - expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad'); - expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']); + expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull(); + expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull(); const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo); expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order); fixture.componentInstance.apply(); @@ -92,13 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow(); open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); }); - it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => { - fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true); - expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible'); - expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.'); - expect(fixture.nativeElement.querySelector('table')).not.toBeNull(); - expect(fixture.nativeElement.querySelector('caption')).toBeNull(); - }); it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => { const service=TestBed.inject(CacuSeguimientoService); for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow(); diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts new file mode 100644 index 0000000..f7bdef8 --- /dev/null +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -0,0 +1,20 @@ +// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received. +const EDADES: Readonly> = { + MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato', +}; +const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/; +const HISTOLOGIA: Readonly> = { + BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', + CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido', +}; + +/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ +export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; +/** «50-59» as «50 a 59 años». Any other text is returned as it came. */ +export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; +export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo; + +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia }; + +/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ +export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); diff --git a/src/app/features/indicadores/export/cell-sanitizer.ts b/src/app/features/indicadores/export/cell-sanitizer.ts new file mode 100644 index 0000000..725fef9 --- /dev/null +++ b/src/app/features/indicadores/export/cell-sanitizer.ts @@ -0,0 +1,7 @@ +// A cell that starts with one of these is read as a formula by spreadsheet programs once the text is pasted or converted. +const FORMULA_START = /^[=+\-@\t\r]/; + +/** Text that is safe to write into a spreadsheet cell: a leading formula character is neutralised with an apostrophe. */ +export function neutralizeFormula(text: string): string { + return FORMULA_START.test(text) ? `'${text}` : text; +} diff --git a/src/app/features/indicadores/export/download-file.ts b/src/app/features/indicadores/export/download-file.ts new file mode 100644 index 0000000..f04346c --- /dev/null +++ b/src/app/features/indicadores/export/download-file.ts @@ -0,0 +1,23 @@ +const pad = (n: number) => String(n).padStart(2, '0'); + +/** + * Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a + * patient identifier, because file names end up in download lists, backups and mail attachments. + */ +export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string { + const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`; + return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`; +} + +/** Hands a generated file to the browser's download. */ +export function downloadBlob(blob: Blob, filename: string): void { + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = filename; + link.rel = 'noopener'; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 0); +} diff --git a/src/app/features/indicadores/export/no-test-wording.spec.ts b/src/app/features/indicadores/export/no-test-wording.spec.ts new file mode 100644 index 0000000..989137f --- /dev/null +++ b/src/app/features/indicadores/export/no-test-wording.spec.ts @@ -0,0 +1,96 @@ +// Covers that nothing a user can read in the exports (PDF of the list, spreadsheet, PDF of one record) or in the +// individual record alludes to tests, simulation or a development environment, and that none carries a note line. Fixture: fixtures/cama_seguimiento.json. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { strFromU8, unzipSync } from 'fflate'; +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { CamaPatientCard } from '../paciente-detalle/cama/cama-patient-card'; +import { camaPatientDocument } from '../paciente-detalle/cama/cama-patient-pdf'; +import { toCamaPatientSummary } from '../paciente-detalle/cama/cama-patient.models'; +import { exportFilename } from './download-file'; +import { TrackingExportBar } from './tracking-export-bar'; +import { trackingDocument } from './tracking-pdf'; +import { buildTrackingXlsx } from './tracking-xlsx'; +import { TrackingSnapshot } from './tracking-export.models'; + +const NOTE_TEXT = 'Documento de consulta; verificar información con el expediente fuente'; +const FORBIDDEN = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|ejemplo|valor cl[ií]nico|test/i; +const r = seguimientoTablaResponse(structuredClone(fixtureData)); +const snapshot: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items }; +const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30)); +function texts(node: unknown, out: string[] = []): string[] { + if (typeof node === 'string') out.push(node); + else if (Array.isArray(node)) node.forEach(n => texts(n, out)); + else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out)); + return out; +} +// Every text a PDF definition can print: header, footer, content and document properties. +const pdfTexts = (d: Record) => [...texts(d['header']()), ...texts(d['footer'](1, 2)), ...texts(d['content']), ...texts(d['info'])]; + +describe('Documentos y ficha: sin leyendas alusivas a pruebas', () => { + // Fails if any text of the list PDF (frame, parameters, table, notes, properties) mentions tests or simulation. + it('the list PDF has no such wording and no note', () => { + const all = pdfTexts(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA') as Record); + expect(all.filter(t => FORBIDDEN.test(t))).toEqual([]); + expect(all).not.toContain(NOTE_TEXT); + }); + + // Fails if any cell, sheet name or parameter of the spreadsheet mentions tests or simulation. + it('the spreadsheet has no such wording and no note', async () => { + const files = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer())); + const strings = strFromU8(files['xl/sharedStrings.xml']), workbook = strFromU8(files['xl/workbook.xml']); + expect(FORBIDDEN.test(strings.replace(/<[^>]+>/g, ' '))).toBe(false); + expect(FORBIDDEN.test(workbook.replace(/xmlns[^ >]*/g, ''))).toBe(false); + expect(strings).not.toContain(NOTE_TEXT); + expect(strings).not.toContain('Tipo de datos'); + }); + + // Fails if the record's PDF mentions tests, simulation or the synthetic nature of the identifier. + it('the record PDF has no such wording and no note', () => { + const summary = toCamaPatientSummary(snapshot.items[0], snapshot.corte)!; + const all = pdfTexts(camaPatientDocument(summary, NOW, 'data:image/png;base64,AAAA') as Record); + expect(all.filter(t => FORBIDDEN.test(t))).toEqual([]); + expect(all).not.toContain(NOTE_TEXT); + }); + + // Fails if the record on screen or the export buttons mention tests or simulation. + it('the record and the export buttons show no such wording', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient()] }); + const card = TestBed.createComponent(CamaPatientCard); + card.componentRef.setInput('summary', toCamaPatientSummary(snapshot.items[0], snapshot.corte)!); + card.detectChanges(); + expect(FORBIDDEN.test(card.nativeElement.textContent)).toBe(false); + expect(card.nativeElement.textContent).not.toContain(NOTE_TEXT); + const bar = TestBed.createComponent(TrackingExportBar); + bar.componentRef.setInput('dominio', 'cama'); bar.componentRef.setInput('respuesta', r); + bar.detectChanges(); + expect(FORBIDDEN.test(bar.nativeElement.textContent)).toBe(false); + }); +}); + +describe('Documentos y ficha: nombre funcional del dominio', () => { + // Fails if "CaMa" (an internal name) or a wrong title reaches the titles, properties or text of a document. + it('both PDFs use the functional name, with accents, and never "CaMa"', () => { + const list = pdfTexts(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA') as Record); + const record = pdfTexts(camaPatientDocument(toCamaPatientSummary(snapshot.items[0], snapshot.corte)!, NOW, 'data:image/png;base64,AAAA') as Record); + expect(list).toContain('Cáncer de mama'); + expect(record).toContain('Ficha de paciente — Cáncer de mama'); + expect(list.filter(t => /cama/i.test(t))).toEqual([]); + expect(record.filter(t => /cama/i.test(t))).toEqual([]); + }); + + // Fails if the spreadsheet names the report or its sheets with the internal name. + it('the spreadsheet names the report "Cáncer de mama" and never "CaMa"', async () => { + const files = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer())); + const strings = strFromU8(files['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|'); + expect(strings).toContain('|Cáncer de mama|'); + expect(/cama/i.test(strings + strFromU8(files['xl/workbook.xml']).replace(/xmlns[^ >]*/g, ''))).toBe(false); + }); + + // Fails if a downloaded file name exposes the internal name or a patient. + it('file names use the functional name', () => { + expect(exportFilename('seguimiento-cancer-de-mama', snapshot.corte, 'xlsx', NOW)).not.toMatch(/cama|M-\d/i); + expect(exportFilename('ficha-cancer-de-mama', snapshot.corte, 'pdf', NOW)).not.toMatch(/cama|M-\d/i); + }); +}); \ No newline at end of file diff --git a/src/app/features/indicadores/export/pdf-engine.ts b/src/app/features/indicadores/export/pdf-engine.ts new file mode 100644 index 0000000..e6d32ed --- /dev/null +++ b/src/app/features/indicadores/export/pdf-engine.ts @@ -0,0 +1,18 @@ +export type PdfDefinition = Record; + +let fontsReady = false; + +/** Renders a pdfmake document definition. pdfmake and its Roboto fonts download only when the first PDF is made. */ +export async function renderPdf(definition: PdfDefinition): Promise { + const [{ default: pdfMake }, { default: roboto }] = await Promise.all([ + import('pdfmake/build/pdfmake'), + import('pdfmake/build/fonts/Roboto'), + ]); + if (!fontsReady) { + pdfMake.addFontContainer(roboto); + // A document only carries inline data; it must never make pdfmake fetch an address. + pdfMake.setUrlAccessPolicy(() => false); + fontsReady = true; + } + return pdfMake.createPdf(definition).getBlob(); +} diff --git a/src/app/features/indicadores/export/pdf-template.ts b/src/app/features/indicadores/export/pdf-template.ts new file mode 100644 index 0000000..5d3b3f7 --- /dev/null +++ b/src/app/features/indicadores/export/pdf-template.ts @@ -0,0 +1,88 @@ +import { PdfDefinition } from './pdf-engine'; + +export const PDF_CONFIDENTIAL = 'Confidencial · uso interno'; +export const LOGO_URL = 'assets/branding/isssteleon-logo.png'; +// The logo is 1125 x 358 pixels. +const LOGO_WIDTH = 110; + +export const COLORS = { ink: '#081839', accent: '#a8c243', muted: '#7a7a7a', rule: '#e3e7df', band: '#f0f3e8' } as const; + +export interface PdfTemplateOptions { + /** Title in the page header and in the document properties. */ + title: string; + /** Data URL of the institutional logo; without it the header shows the name as text. */ + logo?: string; + now: Date; + /** Page size: reports are landscape letter, individual records portrait. */ + orientation: 'landscape' | 'portrait'; +} + +/** The logo as a data URL, or `undefined` when it cannot be read (the header then falls back to text). */ +export async function loadLogo(url = LOGO_URL): Promise { + try { + const response = await fetch(url); + if (!response.ok) return undefined; + const blob = await response.blob(); + return await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result)); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); + } catch { + return undefined; + } +} + +export function formatGenerated(now: Date): string { + return new Intl.DateTimeFormat('es-MX', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Mexico_City' }).format(now); +} + +/** + * The institutional frame shared by every PDF: header with the logo, and the title on every + * page, footer with the generation time, the confidentiality line and "Página X de Y", and generic document properties + * (no author, no user). `content` is what goes between them. + */ +export function institutionalDocument(options: PdfTemplateOptions, content: unknown[]): PdfDefinition { + const margin = 36; + // Letter is 792 x 612 points; the header rule spans the page between its margins. + const usableWidth = (options.orientation === 'landscape' ? 792 : 612) - 2 * margin; + return { + pageSize: 'LETTER', + pageOrientation: options.orientation, + pageMargins: [margin, 84, margin, 52], + // Named, so the logo is embedded once and not again on every page. + images: options.logo ? { logo: options.logo } : {}, + info: { title: options.title, author: 'ISSSTELEON', creator: 'ISSSTELEON', producer: 'ISSSTELEON' }, + defaultStyle: { font: 'Roboto', fontSize: 9, color: COLORS.ink }, + styles: { + h1: { fontSize: 15, bold: true, margin: [0, 0, 0, 6] }, + h2: { fontSize: 11, bold: true, margin: [0, 10, 0, 4] }, + muted: { color: COLORS.muted }, + th: { bold: true, fillColor: COLORS.accent, color: COLORS.ink }, + small: { fontSize: 8, color: COLORS.muted }, + }, + header: () => ({ + margin: [margin, 20, margin, 0], + stack: [ + { + columns: [ + options.logo ? { image: 'logo', width: LOGO_WIDTH } : { text: 'ISSSTELEON', bold: true, fontSize: 14 }, + { text: options.title, alignment: 'center', width: '*', bold: true, fontSize: 12, margin: [0, 8, 0, 0] }, + { text: '', width: LOGO_WIDTH }, + ], + }, + { canvas: [{ type: 'line', x1: 0, y1: 8, x2: usableWidth, y2: 8, lineWidth: 1, lineColor: COLORS.accent }] }, + ], + }), + footer: (currentPage: number, pageCount: number) => ({ + margin: [margin, 14, margin, 0], + columns: [ + { text: `Generado: ${formatGenerated(options.now)} (hora de la Ciudad de México)`, style: 'small' }, + { text: PDF_CONFIDENTIAL, style: 'small', alignment: 'center' }, + { text: `Página ${currentPage} de ${pageCount}`, style: 'small', alignment: 'right' }, + ], + }), + content, + }; +} diff --git a/src/app/features/indicadores/export/pdfmake.d.ts b/src/app/features/indicadores/export/pdfmake.d.ts new file mode 100644 index 0000000..3fdb817 --- /dev/null +++ b/src/app/features/indicadores/export/pdfmake.d.ts @@ -0,0 +1,11 @@ +// pdfmake ships no type declarations; only the calls the export layer makes are declared. +declare module 'pdfmake/build/pdfmake' { + interface PdfDocumentHandle { getBlob(): Promise; getBuffer(): Promise; } + const pdfMake: { createPdf(definition: unknown): PdfDocumentHandle; addFontContainer(container: unknown): void; setUrlAccessPolicy(policy: (url: string) => boolean): void }; + export default pdfMake; +} + +declare module 'pdfmake/build/fonts/Roboto' { + const fontContainer: unknown; + export default fontContainer; +} diff --git a/src/app/features/indicadores/export/tracking-export-bar.spec.ts b/src/app/features/indicadores/export/tracking-export-bar.spec.ts new file mode 100644 index 0000000..adf8632 --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-bar.spec.ts @@ -0,0 +1,136 @@ +// Covers the export buttons of the follow-up table: when they are enabled, what they ask the service for, the file +// they hand to the browser, cancelling and the messages of each failure. Fixture: fixtures/cama_seguimiento.json. +// The service is a stub that pages the fixture; the download is observed through the anchor the browser would click. +import { TestBed } from '@angular/core/testing'; +import { Observable, of, Subject } from 'rxjs'; +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { TrackingExportBar } from './tracking-export-bar'; + +const base = () => structuredClone(fixtureData) as unknown as Record; +const respuesta = (extra: Record = {}) => seguimientoTablaResponse({ ...base(), ...extra }); + +describe('Exportación: botones', () => { + let requests: SeguimientoTablaQuery[], downloads: { name: string; blob: Blob }[], answers: (q: SeguimientoTablaQuery) => Observable; + let fixture: ReturnType>; + + beforeEach(() => { + requests = []; downloads = []; + // Like the API, the stub reports the filters it was asked to apply. + answers = q => of(respuesta({ filtros: { ...base()['filtros'], ...q.filtros }, paginacion: { page: q.page, page_size: q.page_size, total_items: 27, total_pages: 1 } })); + TestBed.configureTestingModule({ + providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => { requests.push(q); return answers(q); } } }], + }); + let pending: Blob | undefined; + vi.spyOn(URL, 'createObjectURL').mockImplementation(blob => { pending = blob as Blob; return 'blob:test'; }); + vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { downloads.push({ name: this.download, blob: pending! }); }); + }); + afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); }); + + function montar(response = respuesta(), habilitado = true) { + fixture = TestBed.createComponent(TrackingExportBar); + fixture.componentRef.setInput('dominio', 'cama'); + fixture.componentRef.setInput('respuesta', response); + fixture.componentRef.setInput('habilitado', habilitado); + fixture.detectChanges(); + return fixture.nativeElement as HTMLElement; + } + const boton = (root: HTMLElement, texto: string) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes(texto)) as HTMLButtonElement | undefined; + const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } }; + + // Fails if the buttons stop being a bare group (the title row of the table holds them) or bring back their own block. + it('has no block of its own: only the buttons, and messages after them', () => { + const root = montar(); + expect(root.querySelector('h3, section')).toBeNull(); + expect(root.firstElementChild!.classList.contains('actions')).toBe(true); + }); + + // Fails if the button stops being available for a query that fits the limit. + it('enables the spreadsheet export for a query within the limit', () => { + expect(boton(montar(), 'Excel')!.disabled).toBe(false); + }); + + // Fails if the export is allowed above the limit or the reason is not shown: the user would get a silent subset. + it('disables the export above the limit and says why', () => { + const root = montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 5001, total_pages: 101 } })); + expect(boton(root, 'Excel')!.disabled).toBe(true); + expect(root.textContent).toContain('admite hasta 5,000 registros'); + expect(root.textContent).toContain('Acota los filtros'); + }); + + // Fails if the PDF is allowed above its own, lower limit, or if hitting it also blocks the spreadsheet. + it('limits the PDF to 1,000 rows while the spreadsheet still accepts the query', () => { + const root = montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 1001, total_pages: 21 } })); + expect(boton(root, 'PDF')!.disabled).toBe(true); + expect(boton(root, 'Excel')!.disabled).toBe(false); + expect(root.textContent).toContain('PDF admite hasta 1,000 registros'); + }); + + // Fails if an empty result offers a file with no rows. + it('disables the export when there are no rows', () => { + expect(boton(montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 0, total_pages: 0 }, items: [] })), 'Excel')!.disabled).toBe(true); + }); + + // Fails if the export reads a query that is about to be replaced by the one being loaded. + it('disables the export while a page is loading', () => { + expect(boton(montar(respuesta(), false), 'Excel')!.disabled).toBe(true); + }); + + // Fails if the file is built from the form instead of the shown answer, or the name carries a patient id. + it('exports the shown query in full and downloads a file named without any patient', async () => { + const root = montar(respuesta({ filtros: { ...base()['filtros'], estatus: 'BENIGNO' } })); + boton(root, 'Excel')!.click(); + await esperar(); + expect(requests[0]).toMatchObject({ corte: '2026-10-20', meses: 3, page: 1, page_size: 200, filtros: { estatus: 'BENIGNO' } }); + expect(downloads).toHaveLength(1); + expect(downloads[0].name).toMatch(/^seguimiento-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/); + expect(downloads[0].name).not.toMatch(/M-\d/); + expect(downloads[0].blob.size).toBeGreaterThan(1000); + expect(root.textContent).toContain('Se generó el archivo con 27 registros'); + }); + + // Fails if the success message of one query stays on screen after another query is shown. + it('drops the result message when another query is shown, but keeps it while paging', async () => { + const root = montar(); + boton(root, 'Excel')!.click(); + await esperar(); + expect(root.textContent).toContain('Se generó el archivo'); + // Another page of the same query: the message stays. + fixture.componentRef.setInput('respuesta', respuesta({ items: [], paginacion: { page: 2, page_size: 10, total_items: 27, total_pages: 3 } })); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + expect(root.textContent).toContain('Se generó el archivo'); + // Another filter: the message goes. + fixture.componentRef.setInput('respuesta', respuesta({ filtros: { ...base()['filtros'], prioridad: 'ALTA' }, paginacion: { page: 1, page_size: 50, total_items: 9, total_pages: 1 } })); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + expect(root.textContent).not.toContain('Se generó el archivo'); + }); + + // Fails if cancelling leaves the export running or still downloads a file afterwards. + it('stops and downloads nothing when cancelled', async () => { + const never = new Subject(); + answers = () => never; + const root = montar(); + boton(root, 'Excel')!.click(); + fixture.detectChanges(); + expect(root.textContent).toContain('Preparando exportación'); + boton(root, 'Cancelar')!.click(); + fixture.detectChanges(); + never.next(respuesta()); + await esperar(); + expect(downloads).toEqual([]); + expect(boton(root, 'Cancelar')).toBeUndefined(); + expect(boton(root, 'Excel')!.disabled).toBe(false); + }); + + // Fails if a failed read is shown as success or leaves the buttons locked. + it('shows an error and unlocks the buttons when the service fails', async () => { + answers = () => { throw new Error('boom'); }; + const root = montar(); + boton(root, 'Excel')!.click(); + await esperar(); + expect(root.querySelector('[role="alert"]')!.textContent).toContain('No se pudo generar el archivo'); + expect(downloads).toEqual([]); + expect(boton(root, 'Excel')!.disabled).toBe(false); + }); +}); diff --git a/src/app/features/indicadores/export/tracking-export-bar.ts b/src/app/features/indicadores/export/tracking-export-bar.ts new file mode 100644 index 0000000..3e6f757 --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-bar.ts @@ -0,0 +1,145 @@ +import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { DecimalPipe } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription } from 'rxjs'; +import { Dominio } from '../indicadores.models'; +import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; +import { downloadBlob, exportFilename } from './download-file'; +import { EXPORT_LIMITS, ExportFormat, ExportInconsistent, ExportLimitExceeded, TrackingSnapshot } from './tracking-export.models'; +import { fetchAllTracking, queryOf } from './tracking-export-source'; + +type State = 'idle' | 'working' | 'error'; + +const FORMAT_LABEL: Record = { xlsx: 'Excel (.xlsx)', pdf: 'PDF' }; + +/** + * Export buttons of a follow-up list. They export the answer on screen (its cut-off, window and filters) and every + * row it matches, not the visible page; a query above a format's limit is refused with a message, never truncated. + */ +@Component({ + selector: 'app-seguimiento-exportar', + imports: [DecimalPipe], + template: ` +
+ @for (formato of formatos; track formato) { + + } + @if (estado() === 'working') { } +
+ @for (formato of formatos; track formato) { + @if (total() > limits[formato]) { +

{{ label[formato] }} admite hasta {{ limits[formato] | number }} registros; la consulta tiene {{ total() | number }}. Acota los filtros para exportar.

+ } + } + @if (estado() === 'working') {

{{ progressText() }}

} + @if (estado() === 'error') { } + @if (listo()) {

{{ listo() }}

} + `, + // The host takes no box of its own: the buttons sit in the title row that holds it, and each message + // takes a full line below that row. + styles: ` + :host { display: contents; } + .message { flex: 0 0 100%; margin: 0; } + .hint { color: var(--issste-text-secondary); } + .actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem; margin-inline-start: auto; } + button { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; + padding: .6rem 1rem; min-height: 44px; box-sizing: border-box; font: inherit; cursor: pointer; } + button:disabled { opacity: .5; cursor: default; } + button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } + `, +}) +export class TrackingExportBar { + readonly dominio = input.required(); + /** The answer on screen: its metadata says which query to export. */ + readonly respuesta = input.required(); + /** False while a page is being loaded, so the export never reads a query that is about to change. */ + readonly habilitado = input(true); + /** How the analysis named the selection this answer belongs to; it travels into the files. */ + readonly seleccion = input(undefined); + + private readonly service = inject(SeguimientoTablaService); + private subscription?: Subscription; + readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf']; + readonly label = FORMAT_LABEL; + readonly limits = EXPORT_LIMITS; + readonly estado = signal('idle'); + readonly mensaje = signal(''); + readonly listo = signal(''); + readonly progress = signal({ fetched: 0, total: 0 }); + readonly total = computed(() => this.respuesta().paginacion.total_items); + readonly progressText = computed(() => { + const { fetched, total } = this.progress(); + return total ? `Leyendo registros: ${fetched} de ${total}…` : 'Preparando exportación…'; + }); + + // Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it. + private readonly queryKey = computed(() => { + const r = this.respuesta(); + return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]); + }); + + constructor() { + inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe()); + // A result message belongs to the query it was made for: it goes away when another query is shown. An export still + // being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one. + effect(() => { + this.queryKey(); + untracked(() => { + if (this.estado() === 'working') { + this.subscription?.unsubscribe(); + this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.'); + } else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); } + }); + }); + } + + available(formato: ExportFormat): boolean { + return this.habilitado() && this.estado() !== 'working' && this.total() > 0 && this.total() <= EXPORT_LIMITS[formato]; + } + + exportar(formato: ExportFormat) { + if (!this.available(formato)) return; + this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 }); + this.subscription?.unsubscribe(); + const clave = this.queryKey(), seleccion = this.seleccion(); + this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({ + next: event => { + if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total }); + else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave); + }, + error: error => this.fallar(error), + }); + } + + cancelar() { + this.subscription?.unsubscribe(); + this.estado.set('idle'); + } + + private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) { + try { + // Each generator (and its library) downloads only when its button is used. + const blob = formato === 'xlsx' + ? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot) + : await (await import('./tracking-pdf')).buildTrackingPdf(snapshot); + // The query on screen changed while the file was being made: it is not the one that was asked for. + if (clave !== this.queryKey()) return; + downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato)); + this.estado.set('idle'); + this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`); + } catch { + this.fallar(new Error('generation')); + } + } + + private fallar(error: unknown) { + this.estado.set('error'); + const estatus = error instanceof HttpErrorResponse ? error.status : 0; + this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.' + : estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.' + : estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.' + : error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.' + : 'No se pudo generar el archivo. Intenta nuevamente.'); + } +} diff --git a/src/app/features/indicadores/export/tracking-export-seleccion.spec.ts b/src/app/features/indicadores/export/tracking-export-seleccion.spec.ts new file mode 100644 index 0000000..ef9f25c --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-seleccion.spec.ts @@ -0,0 +1,157 @@ +// Covers the files of a list opened from the analysis: they state the selection, the cut-off and «Toda la cohorte», and +// hold exactly the patients the table holds, over several pages; and an export never outlives the query it was made for. +// Fixture: fixtures/cama_seguimiento.json, whose rows are repeated to make a list of several pages. +import { TestBed } from '@angular/core/testing'; +import { Observable, of, Subject } from 'rxjs'; +import { strFromU8, unzipSync } from 'fflate'; +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { TrackingExportBar } from './tracking-export-bar'; +import { CONTEXTO } from '../indicadores-analisis.testing'; +import { fetchAllTracking, queryOf } from './tracking-export-source'; +import { TrackingSnapshot } from './tracking-export.models'; +import { trackingDocument } from './tracking-pdf'; +import { buildTrackingXlsx } from './tracking-xlsx'; + +const ETIQUETA = 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 5'; +const base = () => structuredClone(fixtureData) as unknown as Record; +// A cohort of `n` patients, M-0001 onwards, served in the pages that were asked for, with the filters it applied. +function cohorte(n: number) { + const plantilla = (base()['items'] as Record[])[0]; + const todos = Array.from({ length: n }, (_, i) => ({ ...plantilla, id_seudonimo: `M-${String(i + 1).padStart(4, '0')}` })); + return (q: SeguimientoTablaQuery): SeguimientoTablaResponse => seguimientoTablaResponse({ + ...base(), ventana: { meses: q.meses, desde: '2025-01-01', hasta: '2026-10-20' }, corte: q.corte ?? '2026-10-20', + filtros: { ...base()['filtros'], ...q.filtros }, ...(q.contexto ?? {}), + paginacion: { page: q.page, page_size: q.page_size, total_items: n, total_pages: Math.ceil(n / q.page_size) }, + items: todos.slice((q.page - 1) * q.page_size, q.page * q.page_size), + }); +} +const consulta = (extra: Partial = {}): SeguimientoTablaQuery => + ({ corte: '2026-10-20', meses: 0, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO, ...extra }); +const textos = (nodo: unknown, salida: string[] = []): string[] => { + if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida)); + return salida; +}; + +describe('Archivos de una selección del análisis', () => { + const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery) => of(cohorte(450)(q)) } as unknown as SeguimientoTablaService; + + it('el PDF y el XLSX dicen la selección, el corte y «Toda la cohorte», y traen los mismos pacientes que la tabla en todas sus páginas', async () => { + // Fails if a file loses the selection, calls the whole cohort «0 meses», or its patients differ from the table's pages. + const q = consulta(); + // The table, page by page (50 per page), as the user would walk it. + const filasTabla: string[] = []; + for (let p = 1; p <= 9; p++) filasTabla.push(...cohorte(450)({ ...q, page: p }).items.map(i => String(i['id_seudonimo']))); + let snapshot!: TrackingSnapshot; + await new Promise((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ + next: e => { if (e.kind === 'done') snapshot = { ...e.snapshot, seleccion: ETIQUETA }; }, error: fallo, complete: ok })); + expect(snapshot.items.map(i => String(i['id_seudonimo']))).toEqual(filasTabla); + expect(new Set(filasTabla).size).toBe(450); + + const pdf = textos(trackingDocument(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)), 'data:image/png;base64,AAAA')); + expect(pdf).toContain('Selección del análisis'); expect(pdf).toContain(ETIQUETA); + expect(pdf).toContain('Fecha de corte'); expect(pdf).toContain('2026-10-20'); + expect(pdf).toContain('Toda la cohorte, al 2026-10-20'); + expect(pdf.some(t => /0 meses/.test(t))).toBe(false); + expect(pdf.filter(t => /^M-\d{4}$/.test(t))).toEqual(filasTabla); + const PROHIBIDO = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|mock|valor cl[ií]nico/i; + expect(pdf.filter(t => PROHIBIDO.test(t))).toEqual([]); + + const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)))).arrayBuffer())); + const cadenas = strFromU8(hojas['xl/sharedStrings.xml']); + expect(cadenas).toContain(ETIQUETA); expect(cadenas).toContain('Selección del análisis'); expect(cadenas).toContain('Toda la cohorte, al 2026-10-20'); + expect(cadenas).not.toMatch(/0 meses/); + expect(cadenas.replace(/<[^>]+>/g, ' ')).not.toMatch(PROHIBIDO); + expect([...cadenas.matchAll(/M-\d{4}/g)].map(m => m[0]).filter((v, i, a) => a.indexOf(v) === i)).toEqual(filasTabla); + }); + it('sin una selección los archivos no llevan esa línea y conservan la ventana de meses', async () => { + // Fails if a plain list gets a selection line, or a window of months stops being written as dates and months. + const q = consulta({ meses: 3, filtros: {} }); + let snapshot!: TrackingSnapshot; + await new Promise((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = e.snapshot; }, error: fallo, complete: ok })); + const pdf = textos(trackingDocument(snapshot, new Date(), 'data:image/png;base64,AAAA')); + expect(pdf).not.toContain('Selección del análisis'); + expect(pdf).toContain('2025-01-01 al 2026-10-20 (3 meses)'); + }); + it('la consulta de una respuesta conserva la cohorte y su revisión, y todas las páginas del archivo la citan', async () => { + // Fails if the export reads a cohort's list without quoting its revision (the server refuses it) or from another one. + const respuesta = cohorte(450)(consulta()); + expect(queryOf(respuesta)).toMatchObject({ corte: '2026-10-20', meses: 0, page: 1, page_size: 200, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO }); + const pedidas: SeguimientoTablaQuery[] = []; + const espia = { consultar: (_d: string, q: SeguimientoTablaQuery) => { pedidas.push(q); return of(cohorte(450)(q)); } } as unknown as SeguimientoTablaService; + await new Promise((ok, fallo) => fetchAllTracking(espia, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok })); + expect(pedidas.map(q => q.page).sort()).toEqual([1, 2, 3]); + expect(pedidas.every(q => q.contexto?.revision === CONTEXTO.revision && q.contexto?.cohorte === CONTEXTO.cohorte && q.meses === 0)).toBe(true); + // A plain list quotes no cohort. + expect(queryOf(seguimientoTablaResponse(base())).contexto).toBeUndefined(); + }); + it('una página posterior de otra revisión hace fallar la lectura', async () => { + // Fails if a file mixes pages of two revisions of the cohort. + const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, contexto: { ...CONTEXTO, revision: 'f'.repeat(64) } }) : cohorte(450)(q)); + const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService; + const error = await new Promise(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) })); + expect(error).toBeInstanceOf(Error); + }); + it('una página posterior que pierde un filtro hace fallar la lectura: no se exporta un subconjunto de otra consulta', async () => { + // Fails if a file mixes the pages of the selection with a page of another population. + const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, filtros: {} }) : cohorte(450)(q)); + const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService; + const error = await new Promise(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) })); + expect(error).toBeInstanceOf(Error); + }); +}); + +describe('Exportación: la consulta cambia mientras se exporta', () => { + let respuestas: (q: SeguimientoTablaQuery) => Observable, descargas: string[]; + let fixture: ReturnType>; + beforeEach(() => { + descargas = []; + respuestas = q => of(cohorte(27)(q)); + TestBed.configureTestingModule({ providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } }] }); + vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test'); + vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); }); + }); + afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); }); + const montar = (r: SeguimientoTablaResponse, seleccion?: string) => { + fixture = TestBed.createComponent(TrackingExportBar); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('respuesta', r); + fixture.componentRef.setInput('seleccion', seleccion); fixture.detectChanges(); + return fixture.nativeElement as HTMLElement; + }; + const excel = (root: HTMLElement) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes('Excel')) as HTMLButtonElement; + const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } }; + + it('un archivo de una selección se llama como tal y no lleva a ningún paciente en el nombre', async () => { + // Fails if the file of a selection is told apart from a plain list by nothing, or names a patient. + const root = montar(cohorte(27)(consulta()), ETIQUETA); + excel(root).click(); await esperar(); + expect(descargas).toHaveLength(1); + expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/); + expect(descargas[0]).not.toMatch(/M-\d|cama/i); + }); + it('si la consulta en pantalla cambia mientras se lee, se cancela y no se descarga nada', async () => { + // Fails if a list read for the old selection is downloaded as the one now on screen. + const lenta = new Subject(); + respuestas = () => lenta; + const root = montar(cohorte(27)(consulta()), ETIQUETA); + excel(root).click(); fixture.detectChanges(); + expect(root.textContent).toContain('Preparando exportación'); + fixture.componentRef.setInput('respuesta', cohorte(27)(consulta({ filtros: { birads: 'BIRADS_6' } }))); + fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges(); + lenta.next(cohorte(27)(consulta())); + await esperar(); + expect(descargas).toEqual([]); + expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió; se canceló la exportación'); + expect(excel(root).disabled).toBe(false); + }); + it('si cambia mientras se genera el archivo, tampoco se descarga', async () => { + // Fails if a file finished after the selection changed still reaches the downloads. + const root = montar(cohorte(27)(consulta()), ETIQUETA); + excel(root).click(); + fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges(); + await esperar(); + expect(descargas).toEqual([]); + expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió'); + }); +}); diff --git a/src/app/features/indicadores/export/tracking-export-source.spec.ts b/src/app/features/indicadores/export/tracking-export-source.spec.ts new file mode 100644 index 0000000..38e3dc3 --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-source.spec.ts @@ -0,0 +1,122 @@ +// Covers the layer that reads every row of a follow-up query: the page size it asks for, the cut-off and filters it +// keeps, the limit that refuses instead of truncating, the checks that the pages form one list, and cancellation. +// Fixture: fixtures/cama_seguimiento.json (27 synthetic rows). `servidor` pages it like the API does and counts +// the requests it receives. +import { Observable, of, Subject, toArray, lastValueFrom } from 'rxjs'; +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent } from './tracking-export.models'; +import { fetchAllTracking, queryOf } from './tracking-export-source'; + +const base = () => structuredClone(fixtureData) as unknown as Record; +const TOTAL = (base()['items'] as unknown[]).length; + +// A server that pages the fixture. `tweak` can alter the answer of a page to simulate a list that changes, and +// `size` makes it serve smaller pages than asked for, so that 27 rows span several pages. +function servidor(tweak: (page: number, answer: Record) => Record = (_, a) => a, size?: number) { + const requests: SeguimientoTablaQuery[] = []; + const service = { + consultar(_dominio: string, q: SeguimientoTablaQuery): Observable { + requests.push(q); + const d = base(), all = d['items'] as unknown[], tam = size ?? q.page_size; + d['items'] = all.slice((q.page - 1) * tam, q.page * tam); + d['paginacion'] = { page: q.page, page_size: tam, total_items: all.length, total_pages: Math.max(1, Math.ceil(all.length / tam)) }; + d['corte'] = q.corte ?? d['corte']; + d['ventana'] = { ...d['ventana'], meses: q.meses }; + d['filtros'] = { ...d['filtros'], ...q.filtros }; + return of(seguimientoTablaResponse(tweak(q.page, d))); + }, + }; + return { service: service as unknown as SeguimientoTablaService, requests }; +} +const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5, filtros: { estatus: 'BENIGNO' } }; +const eventos = (obs: Observable) => lastValueFrom(obs.pipe(toArray())); + +describe('Exportación: lectura completa del seguimiento', () => { + // Fails if the layer asks for the page size the user was looking at instead of the largest one, or loses a row. + it('reads every row in pages of 200 and returns them in the server order, whatever page the user was on', async () => { + const { service, requests } = servidor(); + const out = await eventos(fetchAllTracking(service, 'cama', { ...consulta, page: 3 }, 5000)); + const done = out.at(-1)!; + expect(done.kind).toBe('done'); + if (done.kind !== 'done') return; + expect(done.snapshot.items).toHaveLength(TOTAL); + expect(done.snapshot.items.map(i => i['id_seudonimo'])).toEqual((base()['items'] as Record[]).map(i => i['id_seudonimo'])); + expect(requests.map(r => r.page_size)).toEqual([200]); + }); + + // Fails if later pages are asked without the first answer's cut-off and filters, which would mix two lists. + it('keeps the cut-off, window and filters of the shown query in every request', async () => { + const { service, requests } = servidor(undefined, 10); + await eventos(fetchAllTracking(service, 'cama', consulta, 5000)); + expect(requests).toHaveLength(3); + for (const r of requests) expect(r).toMatchObject({ corte: '2026-10-20', meses: 3, filtros: { estatus: 'BENIGNO' } }); + }); + + // Fails if progress stops being reported or does not end at the announced total. + it('reports progress up to the announced total and then the finished snapshot', async () => { + const { service } = servidor(); + const out = await eventos(fetchAllTracking(service, 'cama', consulta, 5000)); + expect(out[0]).toEqual({ kind: 'progress', fetched: TOTAL, total: TOTAL }); + expect(out.at(-1)!.kind).toBe('done'); + }); + + // Fails if a query above the limit starts downloading pages, or if it returns a subset without saying so. + it('refuses a query above the limit before asking for more pages and never returns a subset', async () => { + const { service, requests } = servidor(); + await expect(eventos(fetchAllTracking(service, 'cama', consulta, TOTAL - 1))).rejects.toBeInstanceOf(ExportLimitExceeded); + expect(requests).toHaveLength(1); + }); + + // Fails if the limit becomes exclusive: a list of exactly the limit must still be exported. + it('accepts a query that is exactly at the limit', async () => { + const { service } = servidor(); + const out = await eventos(fetchAllTracking(service, 'cama', consulta, TOTAL)); + expect(out.at(-1)!.kind).toBe('done'); + }); + + // Fails if an answer that did not apply the asked filter is accepted: the file would list other patients. + it('fails when the server does not report the filters that were asked for', async () => { + const { service } = servidor((_page, a) => ({ ...a, filtros: { ...a['filtros'], estatus: null } })); + await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent); + }); + + // Fails if a total that changes between pages is accepted: the file would mix two states of the list. + it('fails when the total changes between pages', async () => { + const { service } = servidor((page, a) => page === 1 ? a : { ...a, paginacion: { ...a['paginacion'], total_items: TOTAL + 1 } }, 10); + await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent); + }); + + // Fails if a repeated row (the same id on two pages) is accepted as if it were two patients. + it('fails when a row repeats across pages', async () => { + const { service } = servidor((page, a) => page === 1 ? a : { ...a, items: [(base()['items'] as unknown[])[0]] }, 10); + await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent); + }); + + // Fails if cancelling (unsubscribing) leaves requests pending or still emits events afterwards. + it('stops asking when the subscriber cancels', () => { + const first = new Subject(); + const requests: SeguimientoTablaQuery[] = []; + const service = { consultar: (_d: string, q: SeguimientoTablaQuery) => { requests.push(q); return first; } } as unknown as SeguimientoTablaService; + const seen: TrackingExportEvent[] = []; + const subscription = fetchAllTracking(service, 'cama', consulta, 5000).subscribe(e => seen.push(e)); + subscription.unsubscribe(); + first.next(seguimientoTablaResponse(base())); + expect(requests).toHaveLength(1); + expect(seen).toEqual([]); + }); + + // Fails if an invalid query reaches the network instead of failing inside the stream. + it('turns an invalid query into an error of the stream', async () => { + const real = { consultar: (_d: string, _q: SeguimientoTablaQuery) => { throw new Error('invalid'); } } as unknown as SeguimientoTablaService; + await expect(eventos(fetchAllTracking(real, 'cama', consulta, 5000))).rejects.toThrow('invalid'); + }); +}); + +describe('Exportación: consulta de una respuesta', () => { + // Fails if the export is built from the form being edited instead of what the shown answer says it applied. + it('rebuilds the query from the answer: cut-off, window months and only the filters that were applied', () => { + const answer = seguimientoTablaResponse({ ...base(), filtros: { estatus: 'BENIGNO', birads: null, grupo_edad: null, prioridad: null } }); + expect(queryOf(answer)).toEqual({ corte: answer.corte, meses: answer.ventana.meses, page: 1, page_size: 200, filtros: { estatus: 'BENIGNO' } }); + }); +}); diff --git a/src/app/features/indicadores/export/tracking-export-source.ts b/src/app/features/indicadores/export/tracking-export-source.ts new file mode 100644 index 0000000..c88b023 --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-source.ts @@ -0,0 +1,64 @@ +import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs'; +import { Dominio } from '../indicadores.models'; +import { identidadesDe } from '../paciente-identidad'; +import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; +import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models'; + +const CONCURRENCY = 3; + +/** The query that produced a shown answer: its cut-off, window and the filters the server applied. */ +export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQuery { + return { + corte: response.corte, + meses: response.ventana.meses, + page: 1, + page_size: PAGE_SIZE_MAX, + filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])), + // A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server. + contexto: contextoDe(response), + }; +} + +// The server must report having applied the window and the filters that were asked for; otherwise the file would +// hold rows of another query under the title of this one. +const sameQuery = consultaAplicada; + +/** + * Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer. + * Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list. + */ +export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable { + const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q)); + return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe( + switchMap(first => { + const { total_items: total, total_pages: pages } = first.paginacion; + if (!sameQuery(query, first)) throw new ExportInconsistent('The answer does not apply the query that was asked'); + if (total > limit) throw new ExportLimitExceeded(total, limit); + // The rest of the pages are asked for exactly what the first one was, with the cut-off it answered. + const pinned = { ...query, corte: first.corte, page_size: PAGE_SIZE_MAX }; + const collected = new Map([[1, first.items]]); + const count = () => [...collected.values()].reduce((sum, rows) => sum + rows.length, 0); + const rest = from(Array.from({ length: Math.max(0, pages - 1) }, (_, i) => i + 2)).pipe( + mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY), + tap(({ page, answer }) => { + if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages + || answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read'); + collected.set(page, answer.items); + }), + map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })), + ); + return rest.pipe( + startWith({ kind: 'progress', fetched: first.items.length, total }), + concatWith(defer(() => { + const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows); + // Every row has the identity the table shows, and no patient (or episode) appears on two pages. + if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total'); + return of({ + kind: 'done', + snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items }, + }); + })), + ); + }), + ); +} diff --git a/src/app/features/indicadores/export/tracking-export-table.spec.ts b/src/app/features/indicadores/export/tracking-export-table.spec.ts new file mode 100644 index 0000000..833e6ba --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-table.spec.ts @@ -0,0 +1,66 @@ +// Covers how a follow-up snapshot becomes table cells (shared by the spreadsheet and the PDF), the formula +// neutraliser and the file name policy. Fixture: fixtures/cama_seguimiento.json. +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { neutralizeFormula } from './cell-sanitizer'; +import { exportFilename } from './download-file'; +import { displayText, exportColumns, flatTable, UNAVAILABLE } from './tracking-export-table'; +import { TrackingSnapshot } from './tracking-export.models'; + +function snapshot(): TrackingSnapshot { + const r = seguimientoTablaResponse(structuredClone(fixtureData)); + return { corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items }; +} + +describe('Exportación: tabla plana', () => { + // Fails if a detail column is dropped or reordered: the spreadsheet would lose the date next to its value. + it('places each detail after its value, labelled with its column', () => { + const { columns } = flatTable(snapshot()); + expect(columns.map(c => c.key)).toEqual(['id_seudonimo', 'grupo_edad', 'estatus', 'birads', 'mastografia_fecha', 'biopsia', 'biopsia_fecha', 'dias_mastografia_diagnostico', 'prioridad']); + expect(columns.find(c => c.key === 'mastografia_fecha')!.label).toBe('Última mastografía: Fecha'); + }); + + // Fails if a number is exported as text (it could not be summed or sorted) or a text column as a number. + it('marks as numeric only the columns whose present values are all numbers', () => { + const { columns } = flatTable(snapshot()); + expect(columns.filter(c => c.numeric).map(c => c.key)).toEqual(['dias_mastografia_diagnostico']); + }); + + // Fails if a missing value is invented (0, '') instead of kept as null, which would pass as clinical data. + it('keeps a missing value as null and the rows in the snapshot order', () => { + const s = snapshot(); + const { columns, rows } = flatTable(s); + const at = columns.findIndex(c => c.key === 'biopsia'); + expect(rows).toHaveLength(s.items.length); + expect(rows.map(r => r[0])).toEqual(s.items.map(i => i['id_seudonimo'])); + expect(rows.some(r => r[at] === null)).toBe(true); + }); + + // Fails if the document and the screen stop agreeing on how a missing value reads. + it('reads a missing value as the table does', () => { + expect(displayText(null)).toBe(UNAVAILABLE); + expect(displayText(undefined)).toBe(UNAVAILABLE); + expect(displayText(12)).toBe('12'); + expect(exportColumns(snapshot()).find(c => c.key === 'birads')!.details).toEqual([{ key: 'mastografia_fecha', label: 'Fecha' }]); + }); +}); + +describe('Exportación: texto de celdas y nombres de archivo', () => { + // Fails if a value that starts like a formula is written as is: opening the file could run it. + it.each(['=1+1', '+SUM(A1)', '-2+3', '@cmd', '\tx', '\rx'])('neutralises %j', text => { + expect(neutralizeFormula(text)).toBe(`'${text}`); + }); + + // Fails if ordinary labels are altered by the neutraliser. + it('leaves ordinary text untouched', () => { + for (const text of ['Pendiente de biopsia', 'BI-RADS 4A', '2026-10-20', '']) expect(neutralizeFormula(text)).toBe(text); + }); + + // Fails if a file name carries a patient identifier or characters that are unsafe in a path. + it('names files after the report and the cut-off, never a patient', () => { + const name = exportFilename('seguimiento-cancer-de-mama', '2026-10-20', 'xlsx', new Date(2026, 10, 12, 15, 30)); + expect(name).toBe('seguimiento-cancer-de-mama_corte-2026-10-20_20261112-1530.xlsx'); + expect(exportFilename('ficha-cancer-de-mama', '../2026-10-20', 'pdf', new Date(2026, 0, 2, 3, 4))).toBe('ficha-cancer-de-mama_corte-2026-10-20_20260102-0304.pdf'); + expect(name).not.toMatch(/M-\d+/); + }); +}); diff --git a/src/app/features/indicadores/export/tracking-export-table.ts b/src/app/features/indicadores/export/tracking-export-table.ts new file mode 100644 index 0000000..2453415 --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-table.ts @@ -0,0 +1,36 @@ +import { SeguimientoValor } from '../seguimiento-tabla.service'; +import { TrackingSnapshot } from './tracking-export.models'; + +export const UNAVAILABLE = 'No disponible'; + +/** A column as the follow-up table shows it: the value and, under it, its labelled details. */ +export interface ExportColumn { key: string; label: string; details: { key: string; label: string }[]; } + +/** One flat column of a spreadsheet; a detail becomes a column of its own so it can be filtered and sorted. */ +export interface FlatColumn { key: string; label: string; numeric: boolean; } + +export interface FlatTable { columns: FlatColumn[]; rows: SeguimientoValor[][]; } + +/** The columns the answer announced, in its order. */ +export function exportColumns(snapshot: TrackingSnapshot): ExportColumn[] { + return snapshot.columnas.map(c => ({ key: c.clave, label: c.etiqueta, details: (c.detalles ?? []).map(d => ({ key: d.clave, label: d.etiqueta })) })); +} + +/** Text of a value as the table shows it, `null` included. */ +export function displayText(value: SeguimientoValor | undefined): string { + return value === null || value === undefined ? UNAVAILABLE : String(value); +} + +/** Every detail after its value, with a column numeric only when each present value is a number. */ +export function flatTable(snapshot: TrackingSnapshot): FlatTable { + const columns: FlatColumn[] = []; + for (const column of exportColumns(snapshot)) { + columns.push({ key: column.key, label: column.label, numeric: false }); + for (const detail of column.details) columns.push({ key: detail.key, label: `${column.label}: ${detail.label}`, numeric: false }); + } + for (const column of columns) { + const present = snapshot.items.map(item => item[column.key]).filter(v => v !== null && v !== undefined); + column.numeric = present.length > 0 && present.every(v => typeof v === 'number'); + } + return { columns, rows: snapshot.items.map(item => columns.map(column => item[column.key] ?? null)) }; +} diff --git a/src/app/features/indicadores/export/tracking-export.models.ts b/src/app/features/indicadores/export/tracking-export.models.ts new file mode 100644 index 0000000..6a7a77a --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export.models.ts @@ -0,0 +1,38 @@ +import { etiquetaVentana, SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service'; + +/** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */ +export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const; +export type ExportFormat = keyof typeof EXPORT_LIMITS; + +export type TrackingRow = Record; + +/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */ +export interface TrackingSnapshot { + /** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */ + seleccion?: string; + corte: string; + ventana: SeguimientoTablaResponse['ventana']; + filtros: SeguimientoTablaResponse['filtros']; + filtros_disponibles: SeguimientoTablaResponse['filtros_disponibles']; + columnas: SeguimientoTablaResponse['columnas']; + items: TrackingRow[]; +} + +/** The window as the files state it: the whole cohort up to the cut-off, or the dates and months of the window. */ +export function ventanaConsultada(snapshot: Pick): string { + const { meses, desde, hasta } = snapshot.ventana; + return meses === 0 ? `Toda la cohorte, al ${hasta}` : `${desde} al ${hasta} (${etiquetaVentana(meses)})`; +} + +export type TrackingExportEvent = + | { kind: 'progress'; fetched: number; total: number } + | { kind: 'done'; snapshot: TrackingSnapshot }; + +export class ExportLimitExceeded extends Error { + constructor(readonly total: number, readonly limit: number) { + super(`The query has ${total} rows and the limit is ${limit}`); + } +} + +/** The pages did not describe one stable list (the total changed, a page repeated or a row was lost). */ +export class ExportInconsistent extends Error {} diff --git a/src/app/features/indicadores/export/tracking-pdf.spec.ts b/src/app/features/indicadores/export/tracking-pdf.spec.ts new file mode 100644 index 0000000..67f03ee --- /dev/null +++ b/src/app/features/indicadores/export/tracking-pdf.spec.ts @@ -0,0 +1,112 @@ +// Covers the follow-up PDF: the institutional frame (logo, title, footer), the parameters it +// prints, the table that repeats its header across pages, and that the document really renders to a PDF file. +// Fixture: fixtures/cama_seguimiento.json. The logo is a 1x1 PNG data URL; the real logo is read in the browser. +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { COLORS, PDF_CONFIDENTIAL } from './pdf-template'; +import { buildTrackingPdf, trackingDocument } from './tracking-pdf'; +import { TrackingSnapshot } from './tracking-export.models'; + +const PIXEL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; +const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30)); + +function snapshot(mutate: (s: TrackingSnapshot) => void = () => undefined): TrackingSnapshot { + const r = seguimientoTablaResponse(structuredClone(fixtureData)); + const s: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: { ...r.filtros, prioridad: 'ALTA' }, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items }; + mutate(s); + return s; +} +// Every string of a nested document definition, to look for text without depending on its structure. +function texts(node: unknown, out: string[] = []): string[] { + if (typeof node === 'string') out.push(node); + else if (Array.isArray(node)) node.forEach(n => texts(n, out)); + else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out)); + return out; +} + +describe('Exportación: PDF de seguimiento', () => { + const definition = (s = snapshot()) => trackingDocument(s, NOW, PIXEL) as Record; + + // Fails if the report stops being landscape letter, which the nine columns need. + it('is a landscape letter document with generic properties', () => { + const d = definition(); + expect(d['pageSize']).toBe('LETTER'); + expect(d['pageOrientation']).toBe('landscape'); + expect(d['info']).toMatchObject({ author: 'ISSSTELEON', creator: 'ISSSTELEON', producer: 'ISSSTELEON', title: 'Cáncer de mama' }); + }); + + // Fails if the logo or the title are missing from the header: every page must carry them. + it('puts the logo and the title in the header of every page', () => { + const d = definition(); + const header = d['header'](); + const found = texts(header); + // The logo is named in the header and defined once, so it is embedded once however many pages there are. + expect(JSON.stringify(header)).toContain('"image":"logo"'); + expect(d['images']).toEqual({ logo: PIXEL }); + expect(found).toContain('Cáncer de mama'); + }); + + // Fails if the header breaks when the logo cannot be read: the report must still be produced. + it('falls back to the name as text when there is no logo', () => { + const d = trackingDocument(snapshot(), NOW) as Record; + expect(JSON.stringify(d['header']())).not.toContain('"image"'); + expect(texts(d['header']())).toContain('ISSSTELEON'); + }); + + // Fails if the footer loses the page count, the confidentiality line or the generation time. + it('has a footer with the generation time, the confidentiality line and "Página X de Y"', () => { + const found = texts(definition()['footer'](2, 7)); + expect(found).toContain('Página 2 de 7'); + expect(found).toContain(PDF_CONFIDENTIAL); + expect(found.some(t => t.startsWith('Generado: 12 nov 2026, 3:30 p.m.'))).toBe(true); + }); + + // Fails if the parameters stop saying what query the report answers. + it('prints the cut-off, the window, every filter with its option and the number of rows', () => { + const s = snapshot(); + const found = texts(definition(s)['content']); + for (const t of ['Fecha de corte', s.corte, `${s.ventana.desde} al ${s.ventana.hasta} (3 meses)`, 'Prioridad', 'Alta', 'Todos', 'Registros', String(s.items.length)]) expect(found).toContain(t); + }); + + // Fails if the table stops repeating its header across pages or lets a row split between two pages. + it('repeats the header row and keeps each row on one page', () => { + const table = definition()['content'].find((n: any) => n.table?.headerRows)!.table; + expect(table.headerRows).toBe(1); + expect(table.dontBreakRows).toBe(true); + expect(table.body).toHaveLength(snapshot().items.length + 1); + expect(table.body[0].map((cell: { text: string }) => cell.text)).toEqual(['Identificador seudónimo', 'Grupo de edad', 'Estatus de seguimiento', 'Última mastografía', 'Resultado histopatológico', 'Días de mastografía a diagnóstico', 'Prioridad']); + }); + + // Fails if details stop appearing under their value, or a missing value is drawn as something other than "No disponible". + it('shows each detail under its value and a missing value as "No disponible"', () => { + const s = snapshot(); + const found = texts(definition(s)['content']); + expect(found).toContain(`Fecha: ${s.items.find(i => i['mastografia_fecha'])!['mastografia_fecha']}`); + expect(found).toContain('No disponible'); + }); + + // Fails if the rows lose their alternating band, which keeps long rows readable across a page. + it('bands every other row and leaves the header row to its own style', () => { + const { layout } = definition()['content'].find((n: any) => n.table?.headerRows); + expect([layout.fillColor(0), layout.fillColor(1), layout.fillColor(2)]).toEqual([undefined, undefined, COLORS.band]); + }); + + // Fails if an empty query produces a table with only a header, which reads as a broken report. + it('says so when there are no rows', () => { + expect(texts(definition(snapshot(x => { x.items = []; }))['content'])).toContain('No hay registros para los filtros aplicados.'); + }); + + // Fails if pdfmake, its fonts or the document definition no longer produce a real, multipage PDF. The logo is left + // out because the test browser (jsdom) has no `Worker`, which pdfmake needs to decode a PNG; the image path is + // checked in a real browser. + it('renders a multipage PDF file for a long list', async () => { + const many = snapshot(x => { x.items = Array.from({ length: 120 }, (_, i) => ({ ...x.items[i % x.items.length], id_seudonimo: `M-${String(i).padStart(4, '0')}` })); }); + const blob = await buildTrackingPdf(many, NOW); + const bytes = new Uint8Array(await blob.arrayBuffer()); + const text = new TextDecoder('latin1').decode(bytes); + expect(blob.type === 'application/pdf' || blob.type === '').toBe(true); + expect(text.startsWith('%PDF-')).toBe(true); + expect(text.trimEnd().endsWith('%%EOF')).toBe(true); + expect((text.match(/\/Type \/Page\b/g) ?? []).length).toBeGreaterThan(3); + }, 30000); +}); diff --git a/src/app/features/indicadores/export/tracking-pdf.ts b/src/app/features/indicadores/export/tracking-pdf.ts new file mode 100644 index 0000000..ac8d13f --- /dev/null +++ b/src/app/features/indicadores/export/tracking-pdf.ts @@ -0,0 +1,63 @@ +import { renderPdf, PdfDefinition } from './pdf-engine'; +import { COLORS, institutionalDocument, loadLogo } from './pdf-template'; +import { displayText, exportColumns } from './tracking-export-table'; +import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models'; + +export const TRACKING_TITLE = 'Cáncer de mama'; + +const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 }; +const zebra = { ...rule, fillColor: (row: number) => (row === 0 ? undefined : row % 2 === 0 ? COLORS.band : undefined) }; + +/** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */ +function parameters(snapshot: TrackingSnapshot) { + const rows: unknown[][] = [ + ...(snapshot.seleccion ? [['Selección del análisis', snapshot.seleccion]] : []), + ['Fecha de corte', snapshot.corte], + ['Ventana consultada', ventanaConsultada(snapshot)], + ...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']), + ['Registros', String(snapshot.items.length)], + ]; + return { table: { widths: [130, '*'], body: rows.map(([k, v]) => [{ text: k, bold: true }, v]) }, layout: rule }; +} + +/** The follow-up table: the columns the answer announced, each value with its labelled details under it. */ +function dataTable(snapshot: TrackingSnapshot) { + const columns = exportColumns(snapshot); + const cell = (column: (typeof columns)[number], item: Record) => { + const value = item[column.key]; + const parts: unknown[] = [value === null || value === undefined ? { text: displayText(value), italics: true, color: COLORS.muted } : { text: String(value) }]; + for (const detail of column.details) { + const v = item[detail.key]; + if (v !== null && v !== undefined) parts.push({ text: `${detail.label}: ${v}`, style: 'small' }); + } + return parts.length === 1 ? parts[0] : { stack: parts }; + }; + return { + table: { + headerRows: 1, + dontBreakRows: true, + widths: columns.map((_, i) => (i === 0 ? 62 : '*')), + body: [ + columns.map(c => ({ text: c.label, style: 'th' })), + ...snapshot.items.map(item => columns.map(c => cell(c, item))), + ], + }, + layout: zebra, + }; +} + +/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */ +export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition { + return institutionalDocument({ title: TRACKING_TITLE, logo, now, orientation: 'landscape' }, [ + { text: 'Resultados de seguimiento', style: 'h1' }, + parameters(snapshot), + { text: 'Pacientes', style: 'h2' }, + snapshot.items.length ? dataTable(snapshot) : { text: 'No hay registros para los filtros aplicados.', style: 'muted' }, + { text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] }, + ]); +} + +/** A PDF with the follow-up rows over several pages, repeating the header row. */ +export async function buildTrackingPdf(snapshot: TrackingSnapshot, now = new Date(), logo?: string): Promise { + return renderPdf(trackingDocument(snapshot, now, logo ?? await loadLogo())); +} diff --git a/src/app/features/indicadores/export/tracking-xlsx.spec.ts b/src/app/features/indicadores/export/tracking-xlsx.spec.ts new file mode 100644 index 0000000..5c362cf --- /dev/null +++ b/src/app/features/indicadores/export/tracking-xlsx.spec.ts @@ -0,0 +1,119 @@ +// Covers the spreadsheet of a follow-up export by reading the generated file back: its sheets, native filter, frozen +// header, the simulated-data notice, numbers, empty cells, neutralised text and the absence of author metadata. +// The reader is `fflate`, the zip library `write-excel-file` itself uses. Fixture: fixtures/cama_seguimiento.json. +import { strFromU8, unzipSync } from 'fflate'; +import fixtureData from '../fixtures/cama_seguimiento.json'; +import { seguimientoTablaResponse } from '../seguimiento-tabla.service'; +import { buildTrackingXlsx, columnLetter, DATA_SHEET, PARAMETERS_SHEET } from './tracking-xlsx'; +import { TrackingSnapshot } from './tracking-export.models'; + +function snapshot(mutate: (s: TrackingSnapshot) => void = () => undefined): TrackingSnapshot { + const r = seguimientoTablaResponse(structuredClone(fixtureData)); + const s: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: { ...r.filtros, estatus: 'BENIGNO' }, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items }; + mutate(s); + return s; +} +async function leer(s: TrackingSnapshot) { + const blob = await buildTrackingXlsx(s, new Date(Date.UTC(2026, 10, 12, 21, 30))); + const files = unzipSync(new Uint8Array(await blob.arrayBuffer())); + const text = (name: string) => strFromU8(files[name]); + return { files, text, sheet1: text('xl/worksheets/sheet1.xml'), sheet2: text('xl/worksheets/sheet2.xml'), workbook: text('xl/workbook.xml'), strings: text('xl/sharedStrings.xml') }; +} + +describe('Exportación: archivo XLSX', () => { + // Fails if the file stops being a spreadsheet of two sheets, the data first and the parameters second. + it('has the data sheet first and the parameters sheet second', async () => { + const { workbook } = await leer(snapshot()); + expect(workbook.indexOf(`name="${DATA_SHEET}"`)).toBeGreaterThan(-1); + expect(workbook.indexOf(`name="${PARAMETERS_SHEET}"`)).toBeGreaterThan(workbook.indexOf(`name="${DATA_SHEET}"`)); + }); + + // Fails if the native filter is lost or placed outside the header row and the rows . + it('adds a native filter over the header and every row, starting at the header row', async () => { + const s = snapshot(); + const { sheet1, workbook } = await leer(s); + const last = columnLetter(9); + expect(sheet1).toContain(``); + // The schema orders the filter after the data: a wrong order makes Excel repair the file. + expect(sheet1.indexOf('')).toBeLessThan(sheet1.indexOf(''); + }); + + // Fails if the header row stops being frozen, which hides the column names while scrolling. + it('freezes the header row', async () => { + const { sheet1 } = await leer(snapshot()); + expect(sheet1).toContain('ySplit="1"'); + expect(sheet1).toContain('state="frozen"'); + }); + + // Fails if the file regains a note or banner row: the headers must be the first row of the data sheet. + it('starts the data sheet with the column headers and has no note anywhere', async () => { + const s = snapshot(); + const { strings, sheet1 } = await leer(s); + const shared = [...strings.matchAll(/(.*?)<\/si>/g)].map(m => m[1].replace(/<[^>]+>/g, '')); + expect(sheet1).toMatch(new RegExp(']*t="s">' + shared.indexOf('Identificador seudónimo') + '')); + expect(sheet1).not.toContain(' /^Nota$|Documento de consulta|expediente/i.test(x))).toEqual([]); + expect(shared).not.toContain('Tipo de datos'); + expect((sheet1.match(/ { + const s = snapshot(); + const { strings, sheet2 } = await leer(s); + for (const text of [s.corte, `${s.ventana.desde} al ${s.ventana.hasta}`, 'Estatus de seguimiento', 'Benigno, regresa a tamizaje', 'Todos', 'Cáncer de mama']) expect(strings).toContain(text); + expect(sheet2).toContain(`${s.items.length}`); + }); + + // Fails if the generation moment is written without the time zone it refers to. + it('writes the generation time in Mexico City time', async () => { + const { strings } = await leer(snapshot()); + expect(strings).toContain('hora de la Ciudad de México'); + // 21:30 UTC is 15:30 in Mexico City (UTC-6 in November). + expect(strings).toContain('3:30 p.m.'); + }); + + // Fails if a number is stored as text, or if a missing value becomes a value of its own. + it('stores days as numbers and leaves missing values as empty cells', async () => { + const s = snapshot(); + const { sheet1, strings } = await leer(s); + const days = s.items.filter(i => typeof i['dias_mastografia_diagnostico'] === 'number'); + expect(days.length).toBeGreaterThan(0); + expect(sheet1).toMatch(new RegExp(`]*>${days[0]['dias_mastografia_diagnostico']}`)); + expect(strings).not.toContain('No disponible'); + }); + + // Fails if text that starts like a formula reaches the file as it is. + it('neutralises a value that starts like a formula', async () => { + const s = snapshot(x => { x.items[0] = { ...x.items[0], biopsia: '=HYPERLINK("http://example.test")' }; }); + const { strings } = await leer(s); + expect(strings).toContain(`'=HYPERLINK`); + expect(strings).not.toMatch(/]*>=HYPERLINK/); + }); + + // Fails if the library starts writing author or application properties, which would leak who made the file. + it('carries no document properties that identify an author', async () => { + const { files } = await leer(snapshot()); + expect(Object.keys(files).filter(name => name.startsWith('docProps'))).toEqual([]); + }); + + // Fails if the sheet gains hidden sheets, external links or macros. + it('has no hidden sheets, external links or macros', async () => { + const { files, workbook } = await leer(snapshot()); + expect(workbook).not.toContain('state="hidden"'); + expect(Object.keys(files).filter(name => /externalLinks|vbaProject|activeX|embeddings/i.test(name))).toEqual([]); + }); + + // Fails if no rows turns into an invalid filter range or a failure instead of a file with headers. + it('produces a valid file when the query has no rows', async () => { + const { sheet1 } = await leer(snapshot(x => { x.items = []; })); + expect(sheet1).toContain(''); + }); + + // Fails if column letters beyond Z are wrong, which would put the filter on the wrong columns. + it('names columns past Z', () => { + expect([1, 26, 27, 52, 53].map(columnLetter)).toEqual(['A', 'Z', 'AA', 'AZ', 'BA']); + }); +}); diff --git a/src/app/features/indicadores/export/tracking-xlsx.ts b/src/app/features/indicadores/export/tracking-xlsx.ts new file mode 100644 index 0000000..e27245e --- /dev/null +++ b/src/app/features/indicadores/export/tracking-xlsx.ts @@ -0,0 +1,86 @@ +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', '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(); +} diff --git a/src/app/features/indicadores/fhir.ts b/src/app/features/indicadores/fhir.ts new file mode 100644 index 0000000..016d0fc --- /dev/null +++ b/src/app/features/indicadores/fhir.ts @@ -0,0 +1,54 @@ +// The parts of FHIR R4 the WebApi's `//fhir/` endpoints serve, read loosely: every field is optional and the +// readers below decide what a missing one means. + +export interface Coding { system?: string; code?: string; display?: string } +export interface Concept { coding?: Coding[]; text?: string } +export interface Quantity { value?: number; unit?: string } +export interface Extension { + url: string; + valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; + valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string }; + extension?: Extension[]; +} +export interface Resource { + resourceType: string; + id?: string; + meta?: { tag?: Coding[] }; + extension?: Extension[]; + [field: string]: unknown; +} +export interface Bundle extends Resource { + total?: number; + entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[]; +} + +export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/'; + +export function code(concept: Concept | undefined): string | undefined { + return concept?.coding?.[0]?.code; +} +export function display(concept: Concept | undefined): string | undefined { + return concept?.coding?.[0]?.display ?? concept?.text; +} +// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL). +export function codeIn(concept: Concept | undefined, system: string): string | undefined { + const url = system.includes('://') ? system : CODE_SYSTEM + system; + return concept?.coding?.find(c => c.system === url)?.code; +} +// The extensions named `name` (the last segment of their URL). +export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] { + return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name)); +} +export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined { + return extensions(owner, name)[0]; +} +export function resources(bundle: Bundle | undefined, type?: string): Resource[] { + return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type); +} +export function isSimulated(resource: Resource): boolean { + return !!resource.meta?.tag?.some(t => t.code === 'simulado'); +} +// `Patient/P-1` -> `P-1`. +export function referenceId(reference: { reference?: string } | undefined): string | undefined { + return reference?.reference?.split('/').pop(); +} diff --git a/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json new file mode 100644 index 0000000..d337f2a --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json @@ -0,0 +1,85 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 1, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3", + "date": "2026-11-08T06:47:32.900609+00:00", + "period": { + "start": "2025-07-01", + "end": "2025-12-31" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento", + "valueDate": "2026-11-08" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T06:47:32.766239+00:00" + } + ], + "group": [ + { + "id": "TOTAL", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "count": 2 + } + ], + "measureScore": { + "value": 100.5, + "unit": "d", + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/q1", + "valueDecimal": 70.25 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/q3", + "valueDecimal": 130.75 + } + ] + } + } + ], + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json new file mode 100644 index 0000000..d23a6f2 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json @@ -0,0 +1,127 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 1, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_EU13|0.3.2", + "date": "2026-11-08T00:28:51.413089+00:00", + "period": { + "start": "2025-01-01", + "end": "2025-06-30" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:51.351883+00:00" + } + ], + "group": [ + { + "id": "principal", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 0 + } + ], + "measureScore": { + "value": 0.0 + }, + "stratifier": [ + { + "code": [ + { + "text": "grupo_edad" + } + ], + "stratum": [ + { + "value": { + "text": "45-54" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 0 + } + ], + "measureScore": { + "value": 0.0 + } + } + ] + } + ] + } + ] + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json new file mode 100644 index 0000000..36b91a3 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json @@ -0,0 +1,295 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 2, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_EU7|0.3.3", + "date": "2026-11-08T00:28:56.089006+00:00", + "period": { + "start": "2025-01-01", + "end": "2025-06-30" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:56.025101+00:00" + } + ], + "group": [ + { + "id": "TOTAL", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "count": 4 + } + ], + "stratifier": [ + { + "code": [ + { + "text": "resultado" + } + ], + "stratum": [ + { + "value": { + "text": "LIEBG" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + }, + { + "value": { + "text": "NEGATIVO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 2 + } + ] + }, + { + "value": { + "text": "SIN_DATO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + } + ] + }, + { + "code": [ + { + "text": "grupo_edad" + } + ], + "stratum": [ + { + "value": { + "text": "45-54" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + } + ] + } + ] + } + ] + } + ] + } + }, + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_EU7|0.3.3", + "date": "2026-11-08T00:28:56.099338+00:00", + "period": { + "start": "2025-07-01", + "end": "2025-12-31" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 2 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:56.025101+00:00" + } + ], + "group": [ + { + "id": "TOTAL", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "count": 4 + } + ], + "stratifier": [ + { + "code": [ + { + "text": "resultado" + } + ], + "stratum": [ + { + "value": { + "text": "LIEAG" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + }, + { + "value": { + "text": "NEGATIVO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + }, + { + "value": { + "text": "SIN_DATO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 2 + } + ] + } + ] + }, + { + "code": [ + { + "text": "grupo_edad" + } + ], + "stratum": [ + { + "value": { + "text": "45-54" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + } + ] + } + ] + } + ] + } + ] + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json new file mode 100644 index 0000000..4615f5c --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json @@ -0,0 +1,155 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 2, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/IND1|0.3.2", + "date": "2026-11-08T00:28:50.038223+00:00", + "period": { + "start": "2025-01-01", + "end": "2025-06-30" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:49.977023+00:00" + } + ], + "group": [ + { + "id": "principal", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 1 + } + ], + "measureScore": { + "value": 0.25 + } + } + ], + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + } + } + }, + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/IND1|0.3.2", + "date": "2026-11-08T00:28:50.044435+00:00", + "period": { + "start": "2025-07-01", + "end": "2025-12-31" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 2 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:49.977023+00:00" + } + ], + "group": [ + { + "id": "principal", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 1 + } + ], + "measureScore": { + "value": 0.25 + } + } + ], + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json b/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json new file mode 100644 index 0000000..af53edb --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json @@ -0,0 +1,56 @@ +[ + { + "id": "cama_dias_resultado_diagnostico", + "titulo": "Tiempo de resultado a diagnóstico", + "version": "0.1.0", + "contrato": "C3r", + "unidad": "examen", + "sentido": "decrease", + "tipos_periodo": [ + "semestre", + "mes" + ], + "figuras": [ + "fig_c3r_caja" + ], + "estratos": [], + "filtros": [] + }, + { + "id": "cama_histopatologia_birads", + "titulo": "Histopatología por BI-RADS", + "version": "0.1.0", + "contrato": "C2", + "unidad": "paciente", + "sentido": null, + "tipos_periodo": [ + "semestre", + "mes" + ], + "figuras": [ + "fig_c2_barras", + "fig_c2_donas" + ], + "estratos": [ + "birads" + ], + "filtros": [] + }, + { + "id": "cama_tasa_deteccion_histopatologica", + "titulo": "Detección histopatológica", + "version": "0.1.0", + "contrato": "C1", + "unidad": "examen", + "sentido": null, + "tipos_periodo": [ + "semestre", + "mes" + ], + "figuras": [ + "fig_c1_puntos" + ], + "estratos": [], + "filtros": [] + } +] \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json b/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json new file mode 100644 index 0000000..18a0c34 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json @@ -0,0 +1,63 @@ +{ + "id": "cama_dias_resultado_diagnostico", + "titulo": "Tiempo de resultado a diagnóstico", + "version": "0.1.0", + "contrato": "C3r", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Días de resultado a diagnóstico" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Sin nota hasta el corte no hay observación. Convención provisional." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 71, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:26.219496+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "5e4badce17afe0141e8296c9edd88ff1ce50a21c8c278d1aad5327069830d251", + "parametros": { + "sql": { + "_catalogo": [], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "n": null, + "mediana": null, + "q1": null, + "q3": null, + "n_sin_evento": 0, + "n_excluido": 0, + "suprimido": 1, + "unidad": "dias" + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json b/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json new file mode 100644 index 0000000..313c6ae --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json @@ -0,0 +1,63 @@ +{ + "id": "cama_dias_resultado_diagnostico", + "titulo": "Tiempo de resultado a diagnóstico", + "version": "0.1.0", + "contrato": "C3r", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Días de resultado a diagnóstico" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Sin nota hasta el corte no hay observación. Convención provisional." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 71, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:38.264922+00:00", + "kit_version": "0.8.0", + "toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7", + "parametros_sha": "f26ecdc2fcef0aa015f8997b7c1aa2053678cb86ca9cff9b1524efaf000971ad", + "parametros": { + "sql": { + "_catalogo": [], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 1 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "n": 4, + "mediana": 6.5, + "q1": 2.25, + "q3": 12.5, + "n_sin_evento": 0, + "n_excluido": 1, + "suprimido": 0, + "unidad": "dias" + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json new file mode 100644 index 0000000..7a93d49 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json @@ -0,0 +1,477 @@ +{ + "id": "cama_histopatologia_birads", + "titulo": "Histopatología por BI-RADS", + "version": "0.1.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": "birads", + "valores_estrato": [ + "BIRADS_4", + "BIRADS_4A", + "BIRADS_4B", + "BIRADS_4C", + "BIRADS_5", + "BIRADS_6" + ], + "etiquetas_estrato": { + "BIRADS_4": "BI-RADS 4 sin subtipo", + "BIRADS_4A": "BI-RADS 4A", + "BIRADS_4B": "BI-RADS 4B", + "BIRADS_4C": "BI-RADS 4C", + "BIRADS_5": "BI-RADS 5", + "BIRADS_6": "BI-RADS 6" + }, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "BENIGNO": { + "etiqueta": "Benigno", + "color": "#9DBFE3", + "grupo": "NO_MALIGNO", + "gravedad": 1 + }, + "RIESGO_B3": { + "etiqueta": "Lesión de riesgo (B3)", + "color": "#2F6DB3", + "grupo": "NO_MALIGNO", + "gravedad": 2 + }, + "IN_SITU": { + "etiqueta": "Carcinoma in situ", + "color": "#D9822B", + "grupo": "MALIGNO", + "gravedad": 3 + }, + "INVASOR": { + "etiqueta": "Carcinoma invasor", + "color": "#B5482E", + "grupo": "MALIGNO", + "gravedad": 4 + }, + "SIN_BIOPSIA": { + "etiqueta": "Sin biopsia reportada", + "color": "#C9CDD2", + "grupo": null, + "gravedad": null + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_MALIGNO": "No maligno", + "MALIGNO": "Maligno", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 141, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2025-12-31", + "generado_en": "2026-11-12T16:33:37.621606+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe", + "parametros": { + "sql": { + "_catalogo": [ + "BENIGNO", + "RIESGO_B3", + "IN_SITU", + "INVASOR" + ], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2025-12-31", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "BENIGNO", + "n": 2, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "RIESGO_B3", + "n": 0, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "INVASOR", + "n": 2, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + } + ], + "totales_estrato": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "n": 7, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "n": 6, + "suprimido": 0 + } + ] +} diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json new file mode 100644 index 0000000..dac22f7 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json @@ -0,0 +1,150 @@ +{ + "id": "cama_histopatologia_birads", + "titulo": "Histopatología por BI-RADS", + "version": "0.1.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "BENIGNO": { + "etiqueta": "Benigno", + "color": "#9DBFE3", + "grupo": "NO_MALIGNO", + "gravedad": 1 + }, + "RIESGO_B3": { + "etiqueta": "Lesión de riesgo (B3)", + "color": "#2F6DB3", + "grupo": "NO_MALIGNO", + "gravedad": 2 + }, + "IN_SITU": { + "etiqueta": "Carcinoma in situ", + "color": "#D9822B", + "grupo": "MALIGNO", + "gravedad": 3 + }, + "INVASOR": { + "etiqueta": "Carcinoma invasor", + "color": "#B5482E", + "grupo": "MALIGNO", + "gravedad": 4 + }, + "SIN_BIOPSIA": { + "etiqueta": "Sin biopsia reportada", + "color": "#C9CDD2", + "grupo": null, + "gravedad": null + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_MALIGNO": "No maligno", + "MALIGNO": "Maligno", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 141, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2025-12-31", + "generado_en": "2026-11-12T16:33:37.621606+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe", + "parametros": { + "sql": { + "_catalogo": [ + "BENIGNO", + "RIESGO_B3", + "IN_SITU", + "INVASOR" + ], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2025-12-31", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "BENIGNO", + "n": 7, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "RIESGO_B3", + "n": 5, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "IN_SITU", + "n": 6, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "INVASOR", + "n": 7, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_BIOPSIA", + "n": 6, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_DATO", + "n": 6, + "orden": 5, + "suprimido": 0 + } + ], + "totales_estrato": [] +} diff --git a/src/app/features/indicadores/fixtures/cama_seguimiento-final.json b/src/app/features/indicadores/fixtures/cama_seguimiento-final.json new file mode 100644 index 0000000..0fde25b --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_seguimiento-final.json @@ -0,0 +1,235 @@ +{ + "campo_ventana": "mastografia_fecha", + "columnas": [ + { + "clave": "id_seudonimo", + "etiqueta": "Identificador seudónimo" + }, + { + "clave": "grupo_edad", + "etiqueta": "Grupo de edad" + }, + { + "clave": "estatus", + "etiqueta": "Estatus de seguimiento" + }, + { + "clave": "birads", + "detalles": [ + { + "clave": "mastografia_fecha", + "etiqueta": "Fecha" + } + ], + "etiqueta": "Última mastografía" + }, + { + "clave": "biopsia", + "detalles": [ + { + "clave": "biopsia_fecha", + "etiqueta": "Fecha de biopsia" + } + ], + "etiqueta": "Resultado histopatológico" + }, + { + "clave": "dias_mastografia_diagnostico", + "etiqueta": "Días de mastografía a diagnóstico" + }, + { + "clave": "prioridad", + "etiqueta": "Prioridad" + } + ], + "corte": "2026-10-20", + "filtros": { + "birads": null, + "estatus": null, + "grupo_edad": null, + "prioridad": null + }, + "filtros_disponibles": [ + { + "clave": "estatus", + "etiqueta": "Estatus de seguimiento", + "opciones": [ + { + "codigo": "PENDIENTE_BIOPSIA", + "etiqueta": "Pendiente de biopsia" + }, + { + "codigo": "BIOPSIA_SIN_RESULTADO", + "etiqueta": "Biopsia sin resultado" + }, + { + "codigo": "CANCER_CONFIRMADO", + "etiqueta": "Cáncer confirmado" + }, + { + "codigo": "BENIGNO", + "etiqueta": "Benigno, regresa a tamizaje" + }, + { + "codigo": "INFO_INSUFICIENTE", + "etiqueta": "Información insuficiente" + } + ] + }, + { + "clave": "birads", + "etiqueta": "Categoría BI-RADS", + "opciones": [ + { + "codigo": "BIRADS_4A", + "etiqueta": "BI-RADS 4A" + }, + { + "codigo": "BIRADS_4B", + "etiqueta": "BI-RADS 4B" + }, + { + "codigo": "BIRADS_4C", + "etiqueta": "BI-RADS 4C" + }, + { + "codigo": "BIRADS_5", + "etiqueta": "BI-RADS 5" + }, + { + "codigo": "BIRADS_6", + "etiqueta": "BI-RADS 6" + } + ] + }, + { + "clave": "grupo_edad", + "etiqueta": "Grupo de edad", + "opciones": [ + { + "codigo": "40-49", + "etiqueta": "40-49" + }, + { + "codigo": "50-59", + "etiqueta": "50-59" + }, + { + "codigo": "60-69", + "etiqueta": "60-69" + }, + { + "codigo": "70+", + "etiqueta": "70+" + } + ] + }, + { + "clave": "prioridad", + "etiqueta": "Prioridad", + "opciones": [ + { + "codigo": "ALTA", + "etiqueta": "Alta" + }, + { + "codigo": "MEDIA", + "etiqueta": "Media" + }, + { + "codigo": "BAJA", + "etiqueta": "Baja" + } + ] + } + ], + "items": [ + { + "biopsia": null, + "biopsia_fecha": null, + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "dias_mastografia_diagnostico": null, + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "id_seudonimo": "M-0001", + "mastografia_fecha": "2026-10-15", + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "biopsia": null, + "biopsia_fecha": "2026-10-18", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "dias_mastografia_diagnostico": null, + "estatus": "Biopsia sin resultado", + "estatus_codigo": "BIOPSIA_SIN_RESULTADO", + "grupo_edad": "40-49", + "grupo_edad_codigo": "40-49", + "id_seudonimo": "M-0002", + "mastografia_fecha": "2026-10-15", + "prioridad": "Media", + "prioridad_codigo": "MEDIA" + }, + { + "biopsia": "Benigno", + "biopsia_fecha": "2026-09-10", + "birads": "BI-RADS 4B", + "birads_codigo": "BIRADS_4B", + "dias_mastografia_diagnostico": 16, + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "id_seudonimo": "M-0003", + "mastografia_fecha": "2026-09-01", + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-08-22", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "dias_mastografia_diagnostico": 20, + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "grupo_edad": "70+", + "grupo_edad_codigo": "70+", + "id_seudonimo": "M-0004", + "mastografia_fecha": "2026-08-15", + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "biopsia": null, + "biopsia_fecha": null, + "birads": "BI-RADS 6", + "birads_codigo": "BIRADS_6", + "dias_mastografia_diagnostico": null, + "estatus": "Información insuficiente", + "estatus_codigo": "INFO_INSUFICIENTE", + "grupo_edad": "40-49", + "grupo_edad_codigo": "40-49", + "id_seudonimo": "M-0005", + "mastografia_fecha": "2026-07-21", + "prioridad": "Media", + "prioridad_codigo": "MEDIA" + } + ], + "paginacion": { + "page": 1, + "page_size": 50, + "total_items": 5, + "total_pages": 1 + }, + "simulado": true, + "ventana": { + "desde": "2026-07-21", + "hasta": "2026-10-20", + "meses": 3 + } +} diff --git a/src/app/features/indicadores/fixtures/cama_seguimiento-out-of-range.json b/src/app/features/indicadores/fixtures/cama_seguimiento-out-of-range.json new file mode 100644 index 0000000..4a15fdc --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_seguimiento-out-of-range.json @@ -0,0 +1,159 @@ +{ + "campo_ventana": "mastografia_fecha", + "columnas": [ + { + "clave": "id_seudonimo", + "etiqueta": "Identificador seudónimo" + }, + { + "clave": "grupo_edad", + "etiqueta": "Grupo de edad" + }, + { + "clave": "estatus", + "etiqueta": "Estatus de seguimiento" + }, + { + "clave": "birads", + "detalles": [ + { + "clave": "mastografia_fecha", + "etiqueta": "Fecha" + } + ], + "etiqueta": "Última mastografía" + }, + { + "clave": "biopsia", + "detalles": [ + { + "clave": "biopsia_fecha", + "etiqueta": "Fecha de biopsia" + } + ], + "etiqueta": "Resultado histopatológico" + }, + { + "clave": "dias_mastografia_diagnostico", + "etiqueta": "Días de mastografía a diagnóstico" + }, + { + "clave": "prioridad", + "etiqueta": "Prioridad" + } + ], + "corte": "2026-10-20", + "filtros": { + "birads": null, + "estatus": null, + "grupo_edad": null, + "prioridad": "ALTA" + }, + "filtros_disponibles": [ + { + "clave": "estatus", + "etiqueta": "Estatus de seguimiento", + "opciones": [ + { + "codigo": "PENDIENTE_BIOPSIA", + "etiqueta": "Pendiente de biopsia" + }, + { + "codigo": "BIOPSIA_SIN_RESULTADO", + "etiqueta": "Biopsia sin resultado" + }, + { + "codigo": "CANCER_CONFIRMADO", + "etiqueta": "Cáncer confirmado" + }, + { + "codigo": "BENIGNO", + "etiqueta": "Benigno, regresa a tamizaje" + }, + { + "codigo": "INFO_INSUFICIENTE", + "etiqueta": "Información insuficiente" + } + ] + }, + { + "clave": "birads", + "etiqueta": "Categoría BI-RADS", + "opciones": [ + { + "codigo": "BIRADS_4A", + "etiqueta": "BI-RADS 4A" + }, + { + "codigo": "BIRADS_4B", + "etiqueta": "BI-RADS 4B" + }, + { + "codigo": "BIRADS_4C", + "etiqueta": "BI-RADS 4C" + }, + { + "codigo": "BIRADS_5", + "etiqueta": "BI-RADS 5" + }, + { + "codigo": "BIRADS_6", + "etiqueta": "BI-RADS 6" + } + ] + }, + { + "clave": "grupo_edad", + "etiqueta": "Grupo de edad", + "opciones": [ + { + "codigo": "40-49", + "etiqueta": "40-49" + }, + { + "codigo": "50-59", + "etiqueta": "50-59" + }, + { + "codigo": "60-69", + "etiqueta": "60-69" + }, + { + "codigo": "70+", + "etiqueta": "70+" + } + ] + }, + { + "clave": "prioridad", + "etiqueta": "Prioridad", + "opciones": [ + { + "codigo": "ALTA", + "etiqueta": "Alta" + }, + { + "codigo": "MEDIA", + "etiqueta": "Media" + }, + { + "codigo": "BAJA", + "etiqueta": "Baja" + } + ] + } + ], + "items": [], + "paginacion": { + "page": 4, + "page_size": 1, + "total_items": 3, + "total_pages": 3 + }, + "simulado": true, + "ventana": { + "desde": "2025-10-21", + "hasta": "2026-10-20", + "meses": 12 + } +} diff --git a/src/app/features/indicadores/fixtures/cama_seguimiento.json b/src/app/features/indicadores/fixtures/cama_seguimiento.json new file mode 100644 index 0000000..f0fdce0 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_seguimiento.json @@ -0,0 +1,565 @@ +{ + "simulado": true, + "corte": "2026-10-20", + "ventana": { + "meses": 3, + "desde": "2026-07-21", + "hasta": "2026-10-20" + }, + "campo_ventana": "mastografia_fecha", + "filtros": { + "estatus": null, + "birads": null, + "grupo_edad": null, + "prioridad": null + }, + "filtros_disponibles": [ + { + "clave": "estatus", + "etiqueta": "Estatus de seguimiento", + "opciones": [ + { + "codigo": "PENDIENTE_BIOPSIA", + "etiqueta": "Pendiente de biopsia" + }, + { + "codigo": "BIOPSIA_SIN_RESULTADO", + "etiqueta": "Biopsia sin resultado" + }, + { + "codigo": "CANCER_CONFIRMADO", + "etiqueta": "Cáncer confirmado" + }, + { + "codigo": "BENIGNO", + "etiqueta": "Benigno, regresa a tamizaje" + }, + { + "codigo": "INFO_INSUFICIENTE", + "etiqueta": "Información insuficiente" + } + ] + }, + { + "clave": "birads", + "etiqueta": "Categoría BI-RADS", + "opciones": [ + { + "codigo": "BIRADS_4A", + "etiqueta": "BI-RADS 4A" + }, + { + "codigo": "BIRADS_4B", + "etiqueta": "BI-RADS 4B" + }, + { + "codigo": "BIRADS_4C", + "etiqueta": "BI-RADS 4C" + }, + { + "codigo": "BIRADS_5", + "etiqueta": "BI-RADS 5" + }, + { + "codigo": "BIRADS_6", + "etiqueta": "BI-RADS 6" + } + ] + }, + { + "clave": "grupo_edad", + "etiqueta": "Grupo de edad", + "opciones": [ + { + "codigo": "40-49", + "etiqueta": "40-49" + }, + { + "codigo": "50-59", + "etiqueta": "50-59" + }, + { + "codigo": "60-69", + "etiqueta": "60-69" + }, + { + "codigo": "70+", + "etiqueta": "70+" + } + ] + }, + { + "clave": "prioridad", + "etiqueta": "Prioridad", + "opciones": [ + { + "codigo": "ALTA", + "etiqueta": "Alta" + }, + { + "codigo": "MEDIA", + "etiqueta": "Media" + }, + { + "codigo": "BAJA", + "etiqueta": "Baja" + } + ] + } + ], + "columnas": [ + { + "clave": "id_seudonimo", + "etiqueta": "Identificador seudónimo" + }, + { + "clave": "grupo_edad", + "etiqueta": "Grupo de edad" + }, + { + "clave": "estatus", + "etiqueta": "Estatus de seguimiento" + }, + { + "clave": "birads", + "etiqueta": "Última mastografía", + "detalles": [ + { + "clave": "mastografia_fecha", + "etiqueta": "Fecha" + } + ] + }, + { + "clave": "biopsia", + "etiqueta": "Resultado histopatológico", + "detalles": [ + { + "clave": "biopsia_fecha", + "etiqueta": "Fecha de biopsia" + } + ] + }, + { + "clave": "dias_mastografia_diagnostico", + "etiqueta": "Días de mastografía a diagnóstico" + }, + { + "clave": "prioridad", + "etiqueta": "Prioridad" + } + ], + "paginacion": { + "page": 1, + "page_size": 50, + "total_items": 27, + "total_pages": 1 + }, + "items": [ + { + "id_seudonimo": "M-0081", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "mastografia_fecha": "2026-07-25", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0020", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Información insuficiente", + "estatus_codigo": "INFO_INSUFICIENTE", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-07-31", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0051", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-08-01", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0022", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "birads": "BI-RADS 6", + "birads_codigo": "BIRADS_6", + "mastografia_fecha": "2026-08-03", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0029", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Biopsia sin resultado", + "estatus_codigo": "BIOPSIA_SIN_RESULTADO", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-08-13", + "biopsia": null, + "biopsia_fecha": "2026-09-11", + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0019", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-08-21", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0064", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Información insuficiente", + "estatus_codigo": "INFO_INSUFICIENTE", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-08-22", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0048", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "estatus": "Biopsia sin resultado", + "estatus_codigo": "BIOPSIA_SIN_RESULTADO", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-09-01", + "biopsia": null, + "biopsia_fecha": "2026-10-07", + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0059", + "grupo_edad": "40-49", + "grupo_edad_codigo": "40-49", + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-09-05", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0050", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "estatus": "Información insuficiente", + "estatus_codigo": "INFO_INSUFICIENTE", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-09-06", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0084", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Biopsia sin resultado", + "estatus_codigo": "BIOPSIA_SIN_RESULTADO", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-09-08", + "biopsia": null, + "biopsia_fecha": "2026-09-18", + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0054", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "estatus": "Pendiente de biopsia", + "estatus_codigo": "PENDIENTE_BIOPSIA", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-10-04", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Alta", + "prioridad_codigo": "ALTA" + }, + { + "id_seudonimo": "M-0035", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Biopsia sin resultado", + "estatus_codigo": "BIOPSIA_SIN_RESULTADO", + "birads": "BI-RADS 4B", + "birads_codigo": "BIRADS_4B", + "mastografia_fecha": "2026-08-21", + "biopsia": null, + "biopsia_fecha": "2026-08-31", + "dias_mastografia_diagnostico": null, + "prioridad": "Media", + "prioridad_codigo": "MEDIA" + }, + { + "id_seudonimo": "M-0052", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Información insuficiente", + "estatus_codigo": "INFO_INSUFICIENTE", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "mastografia_fecha": "2026-10-01", + "biopsia": null, + "biopsia_fecha": null, + "dias_mastografia_diagnostico": null, + "prioridad": "Media", + "prioridad_codigo": "MEDIA" + }, + { + "id_seudonimo": "M-0033", + "grupo_edad": "40-49", + "grupo_edad_codigo": "40-49", + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-07-25", + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-09-03", + "dias_mastografia_diagnostico": 15, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0040", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "mastografia_fecha": "2026-07-25", + "biopsia": "Benigno", + "biopsia_fecha": "2026-08-16", + "dias_mastografia_diagnostico": 71, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0011", + "grupo_edad": "40-49", + "grupo_edad_codigo": "40-49", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4B", + "birads_codigo": "BIRADS_4B", + "mastografia_fecha": "2026-08-08", + "biopsia": "Benigno", + "biopsia_fecha": "2026-08-16", + "dias_mastografia_diagnostico": 46, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0047", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-08-28", + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-09-28", + "dias_mastografia_diagnostico": 36, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0038", + "grupo_edad": "60-69", + "grupo_edad_codigo": "60-69", + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "mastografia_fecha": "2026-08-29", + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-10-08", + "dias_mastografia_diagnostico": 42, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0072", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "mastografia_fecha": "2026-09-03", + "biopsia": "Benigno", + "biopsia_fecha": "2026-09-26", + "dias_mastografia_diagnostico": 49, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0021", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-09-07", + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-09-27", + "dias_mastografia_diagnostico": 56, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0039", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4C", + "birads_codigo": "BIRADS_4C", + "mastografia_fecha": "2026-09-08", + "biopsia": "Benigno", + "biopsia_fecha": "2026-09-17", + "dias_mastografia_diagnostico": 27, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0083", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "birads": "BI-RADS 5", + "birads_codigo": "BIRADS_5", + "mastografia_fecha": "2026-09-20", + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-09-27", + "dias_mastografia_diagnostico": 25, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0062", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4A", + "birads_codigo": "BIRADS_4A", + "mastografia_fecha": "2026-09-26", + "biopsia": "Benigno", + "biopsia_fecha": "2026-10-14", + "dias_mastografia_diagnostico": 19, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0032", + "grupo_edad": "40-49", + "grupo_edad_codigo": "40-49", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4B", + "birads_codigo": "BIRADS_4B", + "mastografia_fecha": "2026-10-07", + "biopsia": "Benigno", + "biopsia_fecha": "2026-10-20", + "dias_mastografia_diagnostico": 61, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0077", + "grupo_edad": "50-59", + "grupo_edad_codigo": "50-59", + "estatus": "Benigno, regresa a tamizaje", + "estatus_codigo": "BENIGNO", + "birads": "BI-RADS 4B", + "birads_codigo": "BIRADS_4B", + "mastografia_fecha": "2026-10-14", + "biopsia": "Lesión de riesgo (B3)", + "biopsia_fecha": "2026-10-20", + "dias_mastografia_diagnostico": 60, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + }, + { + "id_seudonimo": "M-0027", + "grupo_edad": "70+", + "grupo_edad_codigo": "70+", + "estatus": "Cáncer confirmado", + "estatus_codigo": "CANCER_CONFIRMADO", + "birads": "BI-RADS 4B", + "birads_codigo": "BIRADS_4B", + "mastografia_fecha": "2026-10-16", + "biopsia": "Carcinoma invasor", + "biopsia_fecha": "2026-10-20", + "dias_mastografia_diagnostico": 36, + "prioridad": "Baja", + "prioridad_codigo": "BAJA" + } + ] +} diff --git a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json new file mode 100644 index 0000000..7deccf8 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json @@ -0,0 +1,59 @@ +{ + "id": "cama_tasa_deteccion_histopatologica", + "titulo": "Detección histopatológica", + "version": "0.1.0", + "contrato": "C1", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "total": "Total" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Detección histopatológica" + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 127, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:31.282549+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "d909bc4a153b244533acde1f26ce8c4cfaaedf0d277239dd9b1ce9e9f65b23a9", + "parametros": { + "sql": { + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "total", + "estrato": null, + "numerador": null, + "denominador": null, + "valor": null, + "ic_bajo": null, + "ic_alto": null, + "suprimido": 1, + "n_sin_evento": 0, + "n_excluido": 0 + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json new file mode 100644 index 0000000..3fbe1b3 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json @@ -0,0 +1,59 @@ +{ + "id": "cama_tasa_deteccion_histopatologica", + "titulo": "Detección histopatológica", + "version": "0.1.0", + "contrato": "C1", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "total": "Total" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Detección histopatológica" + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 127, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:42.857591+00:00", + "kit_version": "0.8.0", + "toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7", + "parametros_sha": "7202a2779ae47c29a7659dd6fdfb77e8895d4d778a772ff13cc2ce93c5a6e871", + "parametros": { + "sql": { + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 1 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "total", + "estrato": null, + "numerador": 0, + "denominador": 1, + "valor": 0.0, + "ic_bajo": 0.0, + "ic_alto": 79.3450688208, + "suprimido": 0, + "n_sin_evento": 1, + "n_excluido": 0 + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index eb30893..062b9b9 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { By } from '@angular/platform-browser'; -import { MatSelect } from '@angular/material/select'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; @@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => { fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] }); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); } - function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); } function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } @@ -47,13 +45,9 @@ describe('UX-06E.D.2.1 selector de representación', () => { expect(fixture.componentInstance.indicador.contrato).toBe(contrato); http.expectNone(() => true); }); - it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => { + it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => { fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges(); - expect(select().options.map(option => [option.value, option.viewValue])).toEqual([ - ['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'], - ['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], - ]); http.expectNone(() => true); open(); request('fig_c1_grupos').flush({ data: [], layout: {} }); for (const [id, label] of [ @@ -62,7 +56,7 @@ describe('UX-06E.D.2.1 selector de representación', () => { ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], ]) { - select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges(); + fixture.componentInstance.selectFigure(id); fixture.detectChanges(); const pending = request(id); expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id); expect(pending.request.params.get('tema')).toBe('claro'); @@ -74,9 +68,9 @@ describe('UX-06E.D.2.1 selector de representación', () => { } http.expectNone(() => true); }); - it('una opción publicada está deshabilitada y sólo consulta esa figura', () => { - fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); - expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); + it('no ofrece selector de representación y sólo consulta la figura mostrada', () => { + fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); + request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); }); it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => { fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2', @@ -98,9 +92,8 @@ describe('UX-06E.D.2.1 selector de representación', () => { expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true); }); it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => { - open(); const first = request('f'); expect(select().disabled).toBe(false); - expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1); - select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges(); + open(); const first = request('f'); expect(panels()).toHaveLength(1); + fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1); expect(next.request.params.get('periodos')).toBe('2025-S1'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 25e56cd..7f23b76 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan import { catchError, of, Subscription } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatSelectModule } from '@angular/material/select'; import { MatIconModule } from '@angular/material/icon'; import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; @@ -20,12 +18,16 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; import { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; +import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama'; +import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama'; import { parTiempos } from './indicadores-tiempos-pareados'; +import { IndicadorConteosPareados } from './indicador-conteos-pareados'; +import { parConteos } from './indicadores-conteos-pareados'; @Component({ selector: 'app-indicador-catalog-card', - host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia], + host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' }, + imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados], template: `
@@ -33,13 +35,15 @@ import { parTiempos } from './indicadores-tiempos-pareados';

{{ indicador.titulo }}

- + @if (!sobrio) { + + }
- + @if (!sobrio) { } @if (isEu7) {
@@ -48,21 +52,19 @@ import { parTiempos } from './indicadores-tiempos-pareados';
+ } @else if (isHistopatologia) { +
+ +
} @else if (tiempos; as par) {
+ } @else if (conteos; as par) { +
+ +
} @else if (selectedFigure) { - @if (!pair.length || otherFigures.length) { - - Representación gráfica - - @if (pair.length) { Dona y barras } - @for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { {{ figureDisplayName(figure, indicador.figuras) }} } - - - }
@for (figure of displayFigures; track panelIdentity(figure)) {
@@ -103,7 +105,7 @@ import { parTiempos } from './indicadores-tiempos-pareados'; } .card-identity { min-width: 0; } h2, p { overflow-wrap: anywhere; } - h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; } + h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; } .pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto; min-width: 48px; min-height: 48px; color: var(--issste-text); } .pin-toggle mat-icon { flex-shrink: 0; } @@ -131,12 +133,17 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { if (this.indicador && this.applied) untracked(() => this.updateNumeric()); }); } + // CaMa's cards carry no pin, representation selector or figure count, as in the mockup. + get sobrio() { return this.dominio === 'cama'; } get pair() { return dualFigures(this.indicador); } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } + // CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu. + get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; } // Connected time pairs replace the diagnosis card with one coordinated box plot. get tiempos() { return parTiempos(this.dominio, this.indicador.id); } - get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } + // Exams and patients of the same finding, drawn together on the exams' card. + get conteos() { return parConteos(this.dominio, this.indicador.id); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } private updateNumeric() { diff --git a/src/app/features/indicadores/indicador-conteos-pareados.html b/src/app/features/indicadores/indicador-conteos-pareados.html new file mode 100644 index 0000000..22e0deb --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.html @@ -0,0 +1,57 @@ +
+ + @if (helpOpen) { +
+
+

Dona por categoría

+ @if (donutGuide; as guide) { + @if (guide.descripcion) {

{{ guide.descripcion }}

} + @if (guide.como_leer.length) {
    @for (line of guide.como_leer; track $index) {
  • {{ line }}
  • }
} + } @else if (!metadata) {

Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

} + @else {

El servicio no publica instrucciones de lectura para esta figura.

} +
+
+

{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}

+

Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.

+
+
+ } + @switch (status()) { + @case ('deferred') {

La vista se cargará al acercarse a esta región.

} + @case ('loading') {

Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…

} + @case ('empty') {

No hay periodos publicados por los dos conteos.

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + } + @if (status() === 'ready' && model; as m) { + @if (pages.length > 1) { + + } +
+

{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}

+ @if (total) { + + } @else {

{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}

} + @if (m.sinDato) {

Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.

} +
+

{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}

+ + @if (!m.pacientesVerificados) {

Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.

} +
+
+

Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.

+ @for (note of m.notas; track $index) {

{{ note }}

} +
Valores publicados +
+ + + @for (f of m.filas; track f.id) { } +
{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}
Familia de BI-RADS{{ par.unidades.pacientes | titlecase }}{{ par.unidades.examenes | titlecase }}
{{ f.etiqueta }}{{ textoPacientes(f.pacientes) }}{{ texto(f.examenes) }}
+
+
+ } +
diff --git a/src/app/features/indicadores/indicador-conteos-pareados.scss b/src/app/features/indicadores/indicador-conteos-pareados.scss new file mode 100644 index 0000000..632a2a3 --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.scss @@ -0,0 +1,22 @@ +:host { display: block; min-width: 0; } +.conteos { min-width: 0; padding-top: var(--issste-space-3); } +p, h3, summary { overflow-wrap: anywhere; } +.applied-summary, .note { color: var(--issste-text-secondary); } +.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +.reading-guide h3 { margin: 0 0 .25rem; } +.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; } +h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; } +.periods { display: flex; align-items: center; gap: var(--issste-space-3); } +.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; } +.periods button:disabled { opacity: .5; cursor: default; } +// The two figures share the card in equal halves; one above the other on a narrow card. +.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } +@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +app-plotly-chart { --plot-height: 400px; } +summary { cursor: pointer; padding-block: .75rem; } +summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.table-scroll { overflow: auto; } +table { border-collapse: collapse; width: 100%; margin-block: 1rem; } +th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } +caption { text-align: start; font-weight: 600; } diff --git a/src/app/features/indicadores/indicador-conteos-pareados.ts b/src/app/features/indicadores/indicador-conteos-pareados.ts new file mode 100644 index 0000000..b91c0c9 --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.ts @@ -0,0 +1,119 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { TitleCasePipe } from '@angular/common'; +import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados'; + +@Component({ + selector: 'app-indicador-conteos-pareados', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe], + templateUrl: './indicador-conteos-pareados.html', + styleUrl: './indicador-conteos-pareados.scss', +}) +export class IndicadorConteosPareados implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) par!: ParConteos; + // The card's indicator (the exams); its partner (the patients) has no card and is requested by id. + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); + message = ''; + periodIndex = 0; + pages: ModeloConteos[] = []; + donutFigure?: PlotlyFigure; + barsFigure?: PlotlyFigure; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + // On a narrow screen the donut's long label gives way to a legend under it. + private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined; + private readonly alCambiarAncho = () => { if (this.model) this.draw(); }; + constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); } + + get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; } + get total() { return this.model ? totalExamenes(this.model) : null; } + texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); } + textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); } + helpOpen = false; + // "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's + // description of its own bars does not apply to them and is not used. + get donutGuide() { + const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas'); + const descripcion = detail?.descripcion?.trim() ?? ''; + const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); + return descripcion || como_leer.length ? { descripcion, como_leer } : undefined; + } + toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + ngOnChanges(changes: SimpleChanges) { + const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]); + if (key !== this.key) { + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear(); + if (!this.visible) { this.status.set('deferred'); return; } + this.load(); + } else if (this.visible && !this.loaded) this.load(); + else if (this.model && changes['tema']) this.draw(); + } + retry() { if (this.visible) this.load(); } + private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; } + private load() { + this.subscription?.unsubscribe(); + this.loaded = true; this.clear(); + const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); + if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.'; + this.status.set('incompatible'); return; + } + const key = this.key; + const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = combineLatest([ + this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version), + this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods), + ]).pipe(timeout({ first: 40000 })).subscribe({ + next: ([examenes, pacientes]) => { + if (key !== this.key) return; + try { + this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo); + // The most recent period first; navigation goes back. + this.periodIndex = Math.max(0, this.pages.length - 1); + this.draw(); this.status.set(this.model ? 'ready' : 'empty'); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.clear(); + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' + : error instanceof ConteosIncompatibles ? error.message : httpMessage(error); + this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.draw(); + } + private draw() { + const m = this.model; + if (!m) return; + this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false); + this.barsFigure = barrasConteos(m, this.par, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); } +} diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index 817476f..406c5c4 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -83,7 +83,23 @@
} - @if (state.status === 'ready' && state.donutLegend?.length) { + @if (state.status === 'ready' && state.highlight; as h) { +
+

Selección: {{ highlightStatus }}

+ + @for (row of highlightRows(h); track row.group?.id ?? '') { +
+ @if (row.group; as g) { + + } + @for (c of row.items; track c.id) { + + } +
+ } +
+ } @else if (state.status === 'ready' && state.donutLegend?.length) {
@for (entry of state.donutLegend; track entry.label) { @@ -94,7 +110,7 @@ }
- +
}