Compare commits

...

19 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 7580319fc8 fix(cama): single vertical scroll in Análisis epidemiológico
The visually-hidden labels are absolutely positioned and had no positioned ancestor in the view, so they were laid out against the document and, with the table far down the page, gave the document its own vertical scroll next to the one of the page container. The view is now their containing block.
2026-11-14 07:56:33 -06:00
Angel Capetillo Zavala 7a2f0f42a9 feat(cama): Análisis epidemiológico frame with category cards, cut-off bar and the BI-RADS count 2026-11-14 00:14:53 -06:00
Angel Capetillo Zavala 01d6e71f07 Accept 64-bit patient identifiers 2026-11-13 18:23:45 -06:00
Angel Capetillo Zavala 3b246b4f1f Identify follow-up patients by pac_id
Rows name their patient with pac_id (a decimal string) or the legacy
id_seudonimo. pac_id wins; an invalid pac_id is never replaced by the
legacy field, and a page that repeats a patient or mixes both fields is
not drawn or exported. The table, patient record, PDF and spreadsheet
follow the announced identifier column and label. CaCu requests risk
only with a pac_id.
2026-11-13 18:19:27 -06:00
Angel Capetillo Zavala caf5f954b7 Proxy patient routes without the cohort access token 2026-11-13 18:19:26 -06:00
edgar edb868f372 Patient record reads its risk from GET /cacu/pacientes/<pac_id>/riesgo, by the id the follow-up list shows 2026-11-13 17:29:54 -06:00
Angel Capetillo Zavala 2e0938628c Merge commit '0acee49de2098b2f9d06607f7d374091a5f4b764' into dashboard-test
# Conflicts:
#	src/app/features/indicadores/etiquetas-cohorte.ts
#	src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts
2026-11-13 15:45:55 -06:00
Angel Capetillo Zavala 3783505dbd Use the regular window for breast follow-up 2026-11-13 15:44:01 -06:00
Angel Capetillo Zavala 0acee49de2 fix(cama): regular follow-up opens on the 3-month window and adopts the cohort the server returns
The follow-up list asks for the regular window without quoting a revision; when the answer
names a cohort the next pages and the files quote it. A new cut-off or a revision that changed
under the list is asked for again without the old revision (once, then reported). Leaving the
analysis' selection returns to the regular window. A server that does not answer from the cohort
keeps the plain list.

Histopathology codes are written with the catalog labels (Benigno, Carcinoma in situ, Carcinoma
invasor, Desconocido); other values stay as they arrive.
2026-11-13 15:43:02 -06:00
Angel Capetillo Zavala 18e9260705 Keep breast follow-up on the selected cohort 2026-11-13 15:32:39 -06:00
Angel Capetillo Zavala 3f4cf2217f Merge commit '7971a49dcda5f9759f6cf4693c1c725153172edb' into dashboard-test 2026-11-13 15:23:06 -06:00
Angel Capetillo Zavala 7971a49dcd feat(cama): regular follow-up read from the cohort, with the revision refreshed on a new cut-off
The follow-up tab of breast cancer now reads the cohort the analysis publishes: it asks for the
cohort's revision at today's cut-off and lists the whole cohort quoting it. Where the server does
not publish the cohort (404 or 503 on its aggregate) the plain follow-up list is read.

- Another cut-off in the form asks for that cut-off's revision before the list; a revision that
  changes under the list (409) is asked for again once and the same query repeated, and a conflict
  that persists is reported.
- "Quitar selección" returns to the whole cohort instead of another source.
- An empty whole cohort says "Sin pacientes para el corte seleccionado"; filters and windows keep
  the text of the filters.
- Filters, cut-off, page and rows are kept while a record is opened and closed.
- Page specs that open CaMa follow-up answer the aggregate first.
2026-11-13 15:18:11 -06:00
Angel Capetillo Zavala c06cce20df Pass synthetic cohort access through the server proxy 2026-11-13 15:17:14 -06:00
Angel Capetillo Zavala 2b0f6dfbed feat(cama): readable BI-RADS and age labels, the biopsy report date, and no export of a list that does not match its group
Contract review against WebApi 1d5f1e0 (webapi/cama_analysis.py, cama_cohort.py, docs/cama-cohort-api.md).

- The cohort's list is rewritten once on arrival so the table, the record and the PDF/XLSX show
  "BI-RADS 5" and "50 a 59 años" (also "Menores de 40 años", "70 años o más", "Sin dato"); the codes
  stay in `<clave>_codigo` and in the filter options, which are what the requests send. Only codes
  whose meaning the API's own code confirms are labelled; biopsy grades are left as they arrive.
- The record calls the biopsy date what the list calls it ("Fecha de reporte"): in the cohort it is
  the date of the biopsy report, which can be known while its result is not.
- With the same cohort revision, cut-off and filter the aggregate and the list are counted from the
  same rows, so a different total breaks the contract: the list shows an alert and its PDF/XLSX
  buttons are disabled.
- When no category is published the analysis says so and keeps "No publicado": the answer cannot
  tell an empty cohort from categories under the threshold.
- Tests: the chosen cut-off reaches the aggregate, the list, the record and every page of the file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:29:45 -06:00
Angel Capetillo Zavala 1d43ebff3b feat(indicadores): Análisis epidemiológico tab for breast cancer, and the way back from Seguimiento
A CaMa-only tab between Histórico and Seguimiento shows how many patients of the cohort fall in
each BI-RADS category at a cut-off (GET /cama/analisis/indicadores?corte=), as the cohort API
publishes it. It is a descriptive count, not an incidence or a survival estimate.

- Loading, pending (404), unavailable (503), error and out-of-contract states; the answer is
  validated as an aggregate (no patient rows, nothing published under the threshold).
- A suppressed category is drawn grey and says why; only a published category opens its patients
  in Seguimiento ("Ver pacientes" or a click on its bar).
- The page keeps the selection while the user moves between tabs, clears it on a domain change, and
  "Volver al análisis" returns to the analysis as it was, with the scroll and the focus on the
  control that opened the list, and no new request.
- Tables and figure scroll inside their own region at phone width. CaCu and TEA keep their three
  sections. Curves, the heatmap and the cohort diagnostics of the prototype wait for an API.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:34 -06:00
Angel Capetillo Zavala eb92b99a1d feat(seguimiento): list opened on a group of the cohort, with its window, cut-off, cohort and revision
The follow-up list of breast cancer can now be opened on a selection that the analysis names: the
whole cohort (window 0, offered only while the selection is active), the cut-off the analysis was
computed at, the group's filter, and the cohort with its revision, which the server requires and
repeats.

- A cohort's list quotes `cohorte`, `escenario` and `revision` (not filters) on every page and in the
  export; an answer that loses a filter, changes the window or the cut-off, or is another cohort or
  revision is not drawn and cannot be exported.
- A new selection cancels the previous request; while it loads, and when it fails (403, 409, 503),
  no list of the previous query stays on screen.
- Inside the cohort the form refines the same cohort and says so; "Quitar selección" leaves it.
- "Volver al análisis" and a note when the list holds a different number of patients than the
  analysis counted.
- PDF and XLSX state the selection, the cut-off and "Toda la cohorte"; the file name tells a
  selection apart; an export in progress is cancelled, and a finished one discarded, when the query
  on screen changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:31 -06:00
Angel Capetillo Zavala ee75e7a2a0 Chore: Visual fix. 2026-11-13 00:01:18 -06:00
Angel Capetillo Zavala b84d428814 Add breast cancer follow-up reports and patient record 2026-11-12 22:40:21 -06:00
Angel Capetillo Zavala 17a91d3924 style(indicadores): CaMa header, simplified general filters and collapsible suppressed-data notes
CaMa header reads "Sistema TNM de clasificación tumoral" without the top subtitle.
The general filters block is titled "Filtros generales" and drops the scope
description and the applied-filter summary. In the Histórico the suppressed-data
text becomes a collapsed footnote (details/summary) with the same full text.
CaCu and TEA headers and filters are unchanged.
2026-11-12 13:20:04 -06:00
78 changed files with 4404 additions and 167 deletions
+246 -2
View File
@@ -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",
+3 -1
View File
@@ -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",
@@ -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' },
];
@@ -1,7 +1,9 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: 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;
@@ -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<string, unknown> => !!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' })
@@ -0,0 +1,20 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
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<Record<string, string>> = {
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<Record<string, (codigo: string) => 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);
@@ -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;
}
@@ -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);
}
@@ -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<string, any>) => [...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<string, any>);
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<string, any>);
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<string, any>);
const record = pdfTexts(camaPatientDocument(toCamaPatientSummary(snapshot.items[0], snapshot.corte)!, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
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);
});
});
@@ -0,0 +1,18 @@
export type PdfDefinition = Record<string, unknown>;
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<Blob> {
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();
}
@@ -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<string | undefined> {
try {
const response = await fetch(url);
if (!response.ok) return undefined;
const blob = await response.blob();
return await new Promise<string>((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,
};
}
+11
View File
@@ -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<Blob>; getBuffer(): Promise<Uint8Array>; }
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;
}
@@ -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<string, any>;
const respuesta = (extra: Record<string, any> = {}) => seguimientoTablaResponse({ ...base(), ...extra });
describe('Exportación: botones', () => {
let requests: SeguimientoTablaQuery[], downloads: { name: string; blob: Blob }[], answers: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>;
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
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<SeguimientoTablaResponse>();
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);
});
});
@@ -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<ExportFormat, string> = { 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: `
<div class="actions" role="group" aria-label="Exportar resultados"
[attr.title]="'Se exportan los ' + (total() | number) + ' registros de la consulta mostrada, no solo la página visible.'">
@for (formato of formatos; track formato) {
<button type="button" [disabled]="!available(formato)" (click)="exportar(formato)">Exportar {{ label[formato] }}</button>
}
@if (estado() === 'working') { <button type="button" (click)="cancelar()">Cancelar</button> }
</div>
@for (formato of formatos; track formato) {
@if (total() > limits[formato]) {
<p class="message hint">{{ label[formato] }} admite hasta {{ limits[formato] | number }} registros; la consulta tiene {{ total() | number }}. Acota los filtros para exportar.</p>
}
}
@if (estado() === 'working') { <p class="message" role="status">{{ progressText() }}</p> }
@if (estado() === 'error') { <p class="message" role="alert">{{ mensaje() }}</p> }
@if (listo()) { <p class="message" role="status">{{ listo() }}</p> }
`,
// 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<Dominio>();
/** The answer on screen: its metadata says which query to export. */
readonly respuesta = input.required<SeguimientoTablaResponse>();
/** 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<string | undefined>(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<State>('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.');
}
}
@@ -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<string, any>;
// 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<string, unknown>[])[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> = {}): 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<void>((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<void>((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<void>((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<unknown>(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<unknown>(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<SeguimientoTablaResponse>, descargas: string[];
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
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<SeguimientoTablaResponse>();
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ó');
});
});
@@ -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<string, any>;
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<string, any>) => Record<string, any> = (_, a) => a, size?: number) {
const requests: SeguimientoTablaQuery[] = [];
const service = {
consultar(_dominio: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> {
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<TrackingExportEvent>) => 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<string, any>[]).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<SeguimientoTablaResponse>();
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' } });
});
});
@@ -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<TrackingExportEvent> {
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<number, TrackingRow[]>([[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<TrackingExportEvent>({ 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<TrackingExportEvent>({
kind: 'done',
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
});
})),
);
}),
);
}
@@ -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+/);
});
});
@@ -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)) };
}
@@ -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<string, SeguimientoValor>;
/** 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<TrackingSnapshot, 'ventana'>): 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 {}
@@ -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<string, any>;
// 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<string, any>;
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);
});
@@ -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<string, string | number | null>) => {
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<Blob> {
return renderPdf(trackingDocument(snapshot, now, logo ?? await loadLogo()));
}
@@ -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(`<autoFilter ref="A1:${last}${s.items.length + 1}"/>`);
// The schema orders the filter after the data: a wrong order makes Excel repair the file.
expect(sheet1.indexOf('</sheetData>')).toBeLessThan(sheet1.indexOf('<autoFilter'));
expect(workbook).toContain(`_xlnm._FilterDatabase`);
expect(workbook).not.toContain('<definedNames/>');
});
// 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>(.*?)<\/si>/g)].map(m => m[1].replace(/<[^>]+>/g, ''));
expect(sheet1).toMatch(new RegExp('<row r="1"><c r="A1"[^>]*t="s"><v>' + shared.indexOf('Identificador seudónimo') + '</v>'));
expect(sheet1).not.toContain('<mergeCells');
expect(shared.filter(x => /^Nota$|Documento de consulta|expediente/i.test(x))).toEqual([]);
expect(shared).not.toContain('Tipo de datos');
expect((sheet1.match(/<row /g) ?? []).length).toBe(s.items.length + 1);
});
// Fails if the headers, the sheet of parameters or the filter labels lose what query the file answers.
it('records the cut-off, the window, the filters applied and the total in the parameters sheet', async () => {
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(`<v>${s.items.length}</v>`);
});
// 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(`<c r="H\\d+"[^>]*><v>${days[0]['dias_mastografia_diagnostico']}</v></c>`));
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(/<t[^>]*>=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('<autoFilter ref="A1:I1"/>');
});
// 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']);
});
});
@@ -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<Blob | ArrayBuffer> {
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('</sheetData>', `</sheetData><autoFilter ref="${range}"/>`) : content,
},
'xl/workbook.xml': {
transform: content => content.replace('<definedNames/>',
`<definedNames><definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'${DATA_SHEET}'!${first}:${last}</definedName></definedNames>`),
},
},
},
};
}
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<number>((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<Blob> {
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();
}
@@ -38,6 +38,10 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
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; }
@@ -107,9 +111,9 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema);
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(); }
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
}
@@ -19,7 +19,6 @@
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
</div>
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
@if (availability) {
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
@else if (availability.status === 'error') {
@@ -0,0 +1,40 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { AnalisisAgregado } from './indicadores-analisis.service';
import { etiquetaBirads } from './etiquetas-cohorte';
export { etiquetaBirads };
const miles = (v: number) => v.toLocaleString('es-MX');
/** The code of the published bar that was clicked, from its `customdata`; a suppressed bar or an empty click gives nothing. */
export function grupoDelClic(evento: unknown, agregado: AnalisisAgregado | undefined): string | undefined {
const punto = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0];
const codigo = punto?.customdata;
return typeof codigo === 'string' && agregado?.grupos.some(g => g.codigo === codigo && !g.suprimido) ? codigo : undefined;
}
/**
* Patients per BI-RADS category. A suppressed category is drawn as an empty grey bar that says it is not published,
* never as a zero; each bar carries its code, so a click can only change the filters of the list, never read rows.
*/
export function gruposFigura(d: AnalisisAgregado, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), s = C2_PALETTE.states;
return {
data: [{
type: 'bar', x: d.grupos.map(g => etiquetaBirads(g.codigo)), y: d.grupos.map(g => g.suprimido ? 0 : g.n),
customdata: d.grupos.map(g => g.codigo),
marker: { color: d.grupos.map(g => g.suprimido ? s.noData : C2_PALETTE.series[0]) },
text: d.grupos.map(g => g.suprimido ? 'No publicado' : miles(g.n!)), textposition: 'outside', cliponaxis: false,
hovertemplate: d.grupos.map(g => g.suprimido
? `<b>${etiquetaBirads(g.codigo)}</b><br>Menos de ${d.umbral_supresion} pacientes: no se publica<extra></extra>`
: `<b>${etiquetaBirads(g.codigo)}</b><br>${miles(g.n!)} pacientes<extra></extra>`),
}],
layout: {
autosize: true, height: 360, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 32, l: 56, r: 16, b: 56 }, showlegend: false,
xaxis: { title: { text: 'Categoría BI-RADS' }, fixedrange: true, automargin: true },
yaxis: { title: { text: 'Pacientes' }, gridcolor: p.grid, zeroline: false, fixedrange: true, rangemode: 'tozero' },
},
config: { displayModeBar: false },
};
}
@@ -0,0 +1,57 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { Dominio, requireDominio } from './indicadores.models';
// The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many
// patients of the cohort fall in each BI-RADS category at a cut-off (`GET /<dominio>/analisis/indicadores?corte=`).
// It is a descriptive count, not an incidence or a survival estimate, and it never carries patient rows. The answer
// names the cohort, the scenario and a `revision` of the cohort that the patients' list must quote back: a list asked
// for with another revision is refused, so a group opened from this count is always the group that was counted.
export interface GrupoAnalisis { codigo: string; n: number | null; suprimido: boolean; }
export interface AnalisisAgregado {
simulado: true; cohorte: string; revision: string; escenario: string; corte: string; umbral_supresion: number;
unidad: string; denominador: string; grupos: GrupoAnalisis[];
}
/** What a patients' list must quote back to open a group of the aggregate. */
export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; }
/** Today as the date input writes it, in the user's own calendar day. */
export function hoyIso(ahora = new Date()) {
const dos = (n: number) => String(n).padStart(2, '0');
return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
function sinFilasDePaciente(v: unknown): boolean {
if (Array.isArray(v)) return v.every(sinFilasDePaciente);
if (!record(v)) return true;
return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
}
/** Validates the aggregate before anything is drawn: aggregates only, and nothing published under the threshold. */
export function analisisAgregado(v: unknown): AnalisisAgregado {
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
if (!record(v) || v['simulado'] !== true) return invalido();
const umbral = v['umbral_supresion'], grupos = v['grupos'];
if (!sinFilasDePaciente(v) || !text(v['cohorte']) || !text(v['escenario']) || !isoDate(v['corte']) || !text(v['unidad']) || !text(v['denominador'])
|| !text(v['revision']) || !/^[0-9a-f]{64}$/.test(v['revision']) || typeof umbral !== 'number' || !Number.isFinite(umbral) || umbral < 1
|| !Array.isArray(grupos) || !grupos.length
|| !grupos.every(g => record(g) && text(g['codigo']) && typeof g['suprimido'] === 'boolean'
&& (g['suprimido'] ? g['n'] === null : typeof g['n'] === 'number' && Number.isInteger(g['n']) && g['n'] >= umbral))
|| new Set(grupos.map(g => (g as GrupoAnalisis).codigo)).size !== grupos.length) return invalido();
return v as unknown as AnalisisAgregado;
}
@Injectable({ providedIn: 'root' })
export class AnalisisService {
private readonly http = inject(HttpClient);
agregado(dominio: Dominio, corte: string) {
if (!isoDate(corte)) throw new Error('Fecha de corte inválida');
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
}
}
@@ -0,0 +1,235 @@
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { analisisAgregado } from './indicadores-analisis.service';
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
// sends to Seguimiento, and the tab's requests and states. The fixtures are in indicadores-analisis.testing.ts.
describe('Respuesta del análisis', () => {
it('admite el agregado de la cohorte, con la extensión de grupos y el arreglo de indicadores vacío', () => {
// Fails if the real answer (with the fields the prototype leaves empty) stops being accepted.
expect(analisisAgregado(agregadoJson()).grupos).toHaveLength(6);
});
it('rechaza lo que no es un agregado: filas de paciente, un grupo suprimido con conteo o un grupo publicado bajo el umbral', () => {
// Fails if a guard stops rejecting patient rows at any depth, or a count that should be hidden.
expect(() => analisisAgregado({ ...agregadoJson(), simulado: false })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), pacientes: [] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false, items: [{ id_seudonimo: 'M-1' }] }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_4', n: 3, suprimido: true }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 4, suprimido: false }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_5', n: 7, suprimido: false }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), revision: 'abc' })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), corte: '2026-13-40' })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [] })).toThrow();
});
});
describe('Figura del análisis', () => {
it('dibuja una barra por categoría con sus pacientes y la suprimida vacía, gris y sin cifra', () => {
// Fails if a suppressed category is drawn as a zero count, or loses its explanation.
const fig = gruposFigura(agregado(), 'claro');
const barra = fig.data[0];
expect(barra['x']).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(barra['y']).toEqual([0, 0, 0, 0, 6, 0]);
expect((barra['text'] as string[]).filter(t => t === 'No publicado')).toHaveLength(5);
expect((barra['hovertemplate'] as string[])[0]).toContain('Menos de 5 pacientes: no se publica');
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
});
it('un clic solo da el código de una barra publicada', () => {
// Fails if a click on a suppressed or unknown bar could open its list.
expect(grupoDelClic({ points: [{ customdata: 'BIRADS_5' }] }, agregado())).toBe('BIRADS_5');
expect(grupoDelClic({ points: [{ customdata: 'BIRADS_4' }] }, agregado())).toBeUndefined();
expect(grupoDelClic({ points: [{ customdata: 'OTRO' }] }, agregado())).toBeUndefined();
expect(grupoDelClic({ points: [{}] }, agregado())).toBeUndefined();
expect(grupoDelClic(undefined, agregado())).toBeUndefined();
});
it('escribe los códigos como en la clínica', () => {
expect(etiquetaBirads('BIRADS_4A')).toBe('BI-RADS 4A');
expect(etiquetaBirads('OTRO')).toBe('OTRO');
});
});
describe('Selección que va a Seguimiento', () => {
it('un grupo publicado lleva su filtro, el corte, el nombre, cuántas pacientes cuenta y la cohorte con su revisión', () => {
// Fails if the list is opened without the cohort's revision, at another cut-off, or on another group.
expect(seleccionDeGrupo(agregado(), 'BIRADS_5')).toEqual({
filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 6, contexto: CONTEXTO });
});
it('un grupo suprimido o desconocido no abre nada y dice por qué', () => {
// Fails if the list of a group the answer hid could be opened.
expect(motivoSinLista(agregado(), 'BIRADS_4')).toBe(MOTIVO_GRUPO_SUPRIMIDO);
expect(seleccionDeGrupo(agregado(), 'BIRADS_4')).toBeUndefined();
expect(seleccionDeGrupo(agregado(), 'OTRO')).toBeUndefined();
expect(motivoSinLista(agregado(), 'BIRADS_5')).toBeUndefined();
});
it('hoy se escribe como la fecha de un campo de fecha, en el día del usuario', () => {
expect(hoyIso(new Date(2026, 10, 3, 23, 59))).toBe('2026-11-03');
});
});
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { readonly plotClick = output<unknown>(); }
describe('Pestaña Análisis epidemiológico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const text = () => root().textContent as string;
const pedido = (corte = hoyIso()) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte);
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
// The date goes in as the user would type it; ngModel writes its value in a microtask.
async function escribirCorte(valor: string) {
// A form control is registered in a microtask after its first render: it is only ready to be typed into after that.
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
const c = root().querySelector('input[name="corte"]') as HTMLInputElement;
c.value = valor; c.dispatchEvent(new Event('input', { bubbles: true })); c.dispatchEvent(new Event('change', { bubbles: true }));
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
expect(c.value, 'el campo conserva lo escrito').toBe(valor === '2026-02-31' ? '' : valor);
}
it('no pide nada hasta abrirse; luego pide el agregado al corte de hoy y lo dibuja con su tabla', () => {
// Fails if the tab loads while hidden, or its first request stops carrying a cut-off.
fixture.detectChanges();
http.expectNone(() => true);
abrir();
expect(text()).toContain('Pacientes por categoría BI-RADS');
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('No estima incidencia, recurrencia ni supervivencia.');
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => f.querySelector('th')!.textContent!.trim())).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(filas.map(f => f.children[1].textContent!.trim())).toEqual(['No publicado', 'No publicado', 'No publicado', 'No publicado', '6', 'No publicado']);
});
it('encabeza la vista y deriva las dos tarjetas de los estados de los grupos, sin sumar pacientes', () => {
// Fails if the cards count patients instead of categories, appear before an answer, or the heading and denominator are lost.
abrir();
expect(root().querySelector('h2')!.textContent).toBe('Análisis epidemiológico');
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const tarjetas = Array.from(root().querySelectorAll('app-indicador-kpi-card')) as HTMLElement[];
expect(tarjetas.map(t => t.querySelector('h3')!.textContent)).toEqual(['Categorías publicadas', 'Categorías no publicadas']);
expect(tarjetas.map(t => t.querySelector('.value')!.textContent!.trim())).toEqual(['1', '5']);
expect(tarjetas[0].textContent).toContain('de 6 categorías BI-RADS');
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('abrir la lista en Seguimiento');
});
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
// Fails if the cards stay on screen without an answer with categories.
abrir();
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
expect(Array.from(root().querySelectorAll('app-indicador-kpi-card .value')).map(v => v.textContent!.trim())).toEqual(['0', '6']);
fixture.componentInstance.consultar(); fixture.detectChanges();
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
});
it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => {
// Fails if a slow answer replaces the aggregate of a later cut-off.
abrir();
const primera = pedido(); primera.flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
await escribirCorte('2026-09-01');
expect(fixture.componentInstance.corte).toBe('2026-09-01');
boton('Consultar')!.click(); fixture.detectChanges();
const lenta = pedido('2026-09-01');
// The button is disabled while a query runs, so the later query comes from the code (a retry, a programmatic refresh).
expect(boton('Consultar')!.disabled).toBe(true);
await escribirCorte('2026-08-01'); fixture.componentInstance.consultar(); fixture.detectChanges();
expect(lenta.cancelled).toBe(true);
pedido('2026-08-01').flush(agregadoJson({ corte: '2026-08-01' })); fixture.detectChanges();
expect(text()).toContain('Fecha de corte: 2026-08-01.');
});
it('una fecha que no es de calendario no sale del navegador', async () => {
// Fails if an invalid cut-off is sent to the server.
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
await escribirCorte('2026-02-31'); boton('Consultar')!.click(); fixture.detectChanges();
http.expectNone(() => true);
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte');
});
it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => {
// Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost.
abrir();
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.');
expect(text()).not.toContain('Sin pacientes');
expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true);
});
it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => {
// Fails if the table offers the patients of a hidden group.
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
});
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
const emitidas: SeleccionPacientes[] = [];
fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
(root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement).click();
fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_5' }] });
fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_4' }] });
expect(emitidas).toHaveLength(2);
expect(emitidas[0]).toEqual(emitidas[1]);
expect(emitidas[0]).toMatchObject({ filtros: { birads: 'BIRADS_5' }, corte: hoyIso(), esperados: 6, contexto: { ...CONTEXTO } });
});
it('al volver restaura el foco en el control de origen y no repite ninguna consulta', () => {
// Fails if coming back from Seguimiento loses the focus or the answer already loaded.
fixture.componentInstance.verPacientes.subscribe(() => undefined);
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const origen = root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement;
origen.focus(); origen.click();
(document.activeElement as HTMLElement | null)?.blur();
fixture.componentInstance.restaurar();
http.expectNone(() => true);
expect(document.activeElement).toBe(origen);
expect(fixture.componentInstance.datos()?.grupos).toHaveLength(6);
});
it('sin endpoint publicado queda pendiente, sin mostrarse como un error', () => {
// Fails if a 404 is shown as a broken page instead of a feature not yet published.
abrir(); pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(text()).toContain('Funcionalidad pendiente de publicación');
expect(root().querySelector('[role=alert]')).toBeNull();
});
it('con la cohorte no disponible (503) lo dice y deja reintentar; el reintento repite la misma consulta', () => {
// Fails if a cohort that is not configured is hidden, or the retry asks for another date.
abrir(); pedido().flush({ error: 'Cohorte no disponible' }, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
expect(text()).toContain('La cohorte no está disponible en este momento.');
boton('Reintentar consulta')!.click(); fixture.detectChanges();
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
expect(root().querySelector('tbody')).not.toBeNull();
});
it('un error del servicio se muestra con su reintento y con el mensaje fijo, nunca con el cuerpo', () => {
// Fails if a real failure is swallowed or the server's own text reaches the page.
abrir(); pedido().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges();
expect(root().querySelector('[role=alert]')?.textContent).toContain('El servicio encontró un error interno');
expect(text()).not.toContain('detalle interno');
expect(boton('Reintentar consulta')).toBeDefined();
});
it('una respuesta fuera de contrato no se dibuja', () => {
// Fails if an answer with patient rows or counts under the threshold reaches the page.
abrir(); pedido().flush({ ...agregadoJson({ corte: hoyIso() }), pacientes: [{ id_seudonimo: 'M-0001' }] }); fixture.detectChanges();
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
expect(root().querySelector('tbody')).toBeNull();
expect(text()).not.toContain('M-0001');
});
});
@@ -0,0 +1,47 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
export const CORTE = '2026-10-20';
export const CONTEXTO = { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: REVISION };
/** One published category (BI-RADS 5, six patients) and five suppressed ones. */
export const agregado = (extra: Partial<AnalisisAgregado> = {}): AnalisisAgregado => ({
simulado: true, ...CONTEXTO, corte: CORTE, umbral_supresion: 5, unidad: 'paciente',
denominador: 'pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
grupos: [
{ codigo: 'BIRADS_4', n: null, suprimido: true }, { codigo: 'BIRADS_4A', n: null, suprimido: true }, { codigo: 'BIRADS_4B', n: null, suprimido: true },
{ codigo: 'BIRADS_4C', n: null, suprimido: true }, { codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_6', n: null, suprimido: true },
],
...extra,
});
/**
* The answer of the cohort's list as the API sends it: only the two filters it announces, with the code as their label,
* the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown),
* and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off.
*/
export function listaCohorte(o: { corte?: string; filtros?: Record<string, string>; page?: number; size?: number; n?: number; meses?: number; revision?: string } = {}): Record<string, any> {
const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0, revision = REVISION } = o;
const todos = Array.from({ length: n }, (_, i) => ({
id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01',
biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null,
}));
const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c }));
return {
simulado: true, ...CONTEXTO, revision, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha',
filtros: { birads: null, grupo_edad: null, ...filtros },
filtros_disponibles: [
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) },
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: opciones(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']) }],
columnas: [
{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
{ 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 reporte' }] }],
paginacion: { page, page_size: size, total_items: n, total_pages: Math.max(1, Math.ceil(n / size)) },
items: todos.slice((page - 1) * size, page * size),
};
}
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
@@ -0,0 +1,240 @@
import { Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, untracked } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service';
import { Dominio, Tema } from './indicadores.models';
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
/**
* The patients behind a group of the aggregate, for the page to open them in Seguimiento: the list's filters, how to
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
* patients the analysis counts there.
*/
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
export { hoyIso };
/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
const g = agregado.grupos.find(x => x.codigo === codigo);
return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
}
/** The selection of a published group: the whole group of the cohort at the cut-off it was counted at, nothing else. */
export function seleccionDeGrupo(agregado: AnalisisAgregado, codigo: string): SeleccionPacientes | undefined {
const g = agregado.grupos.find(x => x.codigo === codigo);
if (!g || motivoSinLista(agregado, codigo)) return undefined;
return { filtros: { birads: codigo }, etiqueta: `Categoría BI-RADS: ${etiquetaBirads(codigo)}`, corte: agregado.corte, esperados: g.n,
contexto: { cohorte: agregado.cohorte, escenario: agregado.escenario, revision: agregado.revision } };
}
/** The scrolling ancestor of an element, or the document's own scroller. */
function contenedorDeScroll(el: HTMLElement): HTMLElement {
for (let n = el.parentElement; n; n = n.parentElement) {
const overflow = getComputedStyle(n).overflowY;
if ((overflow === 'auto' || overflow === 'scroll') && n.scrollHeight > n.clientHeight) return n;
}
return (el.ownerDocument.scrollingElement ?? el.ownerDocument.documentElement) as HTMLElement;
}
// Epidemiological analysis of the breast cohort. For now: how many patients of the cohort are in each BI-RADS category at
// a cut-off, as a count (not an incidence or a survival estimate). A published category opens its patients in Seguimiento;
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
<p class="nota">Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.</p>
@if (datos(); as d) {
<p class="contexto">Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.</p>
<div class="tarjetas">
<app-indicador-kpi-card title="Categorías publicadas" [value]="publicadas()" state="Disponible" [quietWhenAvailable]="true"
[additionalInfo]="'de ' + d.grupos.length + ' categorías BI-RADS.'" />
<app-indicador-kpi-card title="Categorías no publicadas" [value]="d.grupos.length - publicadas()" state="Disponible" [quietWhenAvailable]="true"
[additionalInfo]="'Con menos de ' + d.umbral_supresion + ' pacientes: su conteo y su lista no se publican.'" />
</div>
}
<form class="controles" (ngSubmit)="consultar()">
<label>Fecha de corte <input name="corte" type="date" required [(ngModel)]="corte" [max]="hoy" /></label>
<button type="submit" mat-stroked-button [disabled]="carga().estado === 'cargando'">Consultar</button>
</form>
<article class="panel" aria-labelledby="birads-titulo">
<h3 id="birads-titulo">Pacientes por categoría BI-RADS</h3>
@switch (carga().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Consultando el análisis" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') {
<p role="status">La cohorte no está disponible en este momento.</p>
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
}
@case ('error') {
<div role="alert"><p>{{ $any(carga()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
}
}
@if (datos(); as d) {
@if (todasSuprimidas()) {
<p class="nota">Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.</p>
}
<p class="aviso" role="status">{{ aviso() }}</p>
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
label="Pacientes por categoría BI-RADS" />
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
<table>
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<tbody>
@for (g of d.grupos; track g.codigo) {
<tr [attr.data-grupo]="g.codigo">
<th scope="row">{{ etiqueta(g.codigo) }}</th>
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
</tr>
}
</tbody>
</table>
</div>
}
</article>
</section>
`,
styles: `
:host { display: block; min-width: 0; }
/* Positioned so the absolutely placed visually-hidden labels belong to this view: otherwise they are laid out against the document and give it a vertical scroll of its own. */
.analisis { position: relative; display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.analisis > * { margin: 0; }
/* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */
:host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2, h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-4); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; }
input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
/* The live region stays in the page, so what is written into it is announced; empty, it takes no room. */
.aviso { padding: var(--issste-space-2) var(--issste-space-3); border-left: 4px solid var(--issste-accent); font: var(--mat-sys-body-medium); }
.aviso:empty { padding: 0; border: 0; margin: 0; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
.tabla-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
td:nth-child(2) { font-variant-numeric: tabular-nums; }
td:last-child { min-width: 11rem; }
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@media (max-width: 600px) { .panel { padding: var(--issste-space-4); } .controles label, .controles input { width: 100%; } }
`,
})
export class IndicadoresAnalisis {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The patients of a group, for the page to open them in Seguimiento.
readonly verPacientes = output<SeleccionPacientes>();
readonly miles = (v: number) => v.toLocaleString('es-MX');
readonly etiqueta = etiquetaBirads;
readonly motivo = MOTIVO_GRUPO_SUPRIMIDO;
readonly hoy = hoyIso();
private readonly service = inject(AnalisisService);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly pedidos = new Subject<string>();
private abierto = false;
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; });
// How many categories the answer publishes; the rest are suppressed. Counts categories only, never patients.
readonly publicadas = computed(() => this.datos()?.grupos.filter(g => !g.suprimido).length ?? 0);
// The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published.
readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido));
readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; });
constructor() {
const destroy = inject(DestroyRef);
const cargar = (corte: string): Observable<Carga<AnalisisAgregado>> => {
let fuente: Observable<AnalisisAgregado>;
try { fuente = this.service.agregado(this.dominio(), corte); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); }
return fuente.pipe(
map((datos): Carga<AnalisisAgregado> => ({ estado: 'listo', datos })),
catchError(error => of(this.fallo(error))),
startWith<Carga<AnalisisAgregado>>({ estado: 'cargando' }));
};
this.pedidos.pipe(switchMap(cargar), takeUntilDestroyed(destroy)).subscribe(c => { this.aviso.set(''); this.carga.set(c); });
effect(() => {
if (!this.active() || this.abierto) return;
untracked(() => { this.abierto = true; this.consultar(); });
});
}
private fallo(error: unknown): Carga<AnalisisAgregado> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la fecha de corte. Revisa la fecha.' };
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
}
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
}
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.pedidos.next(this.corte);
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
// A click on a published bar is the same as its «Ver pacientes» button; a suppressed bar does nothing.
clicGrupo(evento: unknown) {
const codigo = grupoDelClic(evento, this.datos());
if (!codigo) return;
const fila = Array.from(this.host.nativeElement.querySelectorAll<HTMLElement>('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo);
this.verGrupo(codigo, fila?.querySelector<HTMLElement>('button.ver') ?? this.host.nativeElement.querySelector<HTMLElement>('.plot-viewport'));
}
// The patients of a published group: the page opens them in Seguimiento. Where the user was is kept for the way back.
verGrupo(codigo: string, origen?: EventTarget | null) {
const d = this.datos();
if (!d) return;
this.aviso.set(motivoSinLista(d, codigo) ?? '');
const seleccion = seleccionDeGrupo(d, codigo);
if (!seleccion) return;
const el = origen instanceof HTMLElement ? origen : null;
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
if (!r) return;
if (r.area.isConnected) r.area.scrollTop = r.arriba;
(r.origen?.isConnected ? r.origen : this.host.nativeElement.querySelector<HTMLElement>('input[name="corte"]'))?.focus({ preventScroll: true });
this.retorno = undefined;
}
}
@@ -149,6 +149,19 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2);
expect(graficas()).toHaveLength(3);
});
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
montar(false);
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
expect(notas).toHaveLength(2);
for (const nota of notas) {
expect(nota.open).toBe(false);
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
expect(nota.querySelector('p')!.textContent).toContain('Datos suprimidos, sombreados en la figura: 2025 S1.');
}
notas[0].open = true;
expect(notas[0].open).toBe(true);
expect(notas[1].open).toBe(false);
});
});
describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
@@ -259,13 +259,18 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(ids).toContain('cama_birads_456_mastografia');
expect(fixture.nativeElement.querySelector('.catalog-grid').textContent).not.toContain('Distribución de resultados de biopsia');
});
it('los rótulos de CaMa dicen «cáncer de mama»', () => {
it('la cabecera de CaMa dice «Cáncer de mama», sin subtítulo superior, y el bloque de filtros queda simplificado', () => {
load(KPI_BY_DOMAIN.cama);
const text = fixture.nativeElement.textContent as string;
expect(text).toContain('Cáncer de mama, investigación');
expect(fixture.nativeElement.querySelector('#dashboard-title').textContent.trim()).toBe('Cáncer de mama');
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
expect(text).not.toContain('Cáncer de mama, investigación');
expect(text).toContain('Explora los indicadores de cáncer de mama.');
expect(text).toContain('Filtros generales de cáncer de mama');
expect(text).toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros generales');
expect(fixture.nativeElement.querySelector('.global-filters .section-description')).toBeNull();
expect(text).not.toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
expect(text).not.toContain('Filtro general aplicado');
expect(text).not.toContain('Existe reporte en al menos un indicador del dominio.');
});
it('Disponible queda visualmente oculto y sigue en un único estado accesible en CaMa', () => {
const card = TestBed.createComponent(IndicadorKpiCard);
@@ -313,7 +318,8 @@ describe('Filtros generales de CaMa: periodo único', () => {
expect(text).not.toContain('Modalidad');
expect(text).not.toContain('Selección en edición');
expect(text).not.toContain('Sin cambios pendientes');
expect(text).toContain('Filtro general aplicado: 2025-S2. Existe reporte en al menos un indicador del dominio.');
expect(text).not.toContain('Filtro general aplicado');
expect(text).not.toContain('Existe reporte en al menos un indicador del dominio.');
});
it('elegir otro periodo deja un solo periodo en el borrador y avisa que hay cambios sin aplicar', () => {
// Fails if the control keeps more than one period, or if the pending notice is lost.
@@ -0,0 +1,136 @@
// Covers how the breast cohort is written for the user (BI-RADS and age groups), that the requests keep the codes, that
// the cut-off the user chose reaches the list, the record and the files, and what the record says of a biopsy whose
// report date is known while its result is not. Fixture: listaCohorte() in indicadores-analisis.testing.ts.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { strFromU8, unzipSync } from 'fflate';
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 { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
import { fetchAllTracking, queryOf } from './export/tracking-export-source';
import { trackingDocument } from './export/tracking-pdf';
import { buildTrackingXlsx } from './export/tracking-xlsx';
const CORTE_ELEGIDO = '2026-09-01';
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('Etiquetas de la cohorte', () => {
it('escribe las categorías BI-RADS y los grupos de edad como en la clínica, y deja lo demás como llegó', () => {
// Fails if a confirmed code is shown raw, or a code whose meaning is not confirmed is invented.
expect(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'].map(etiquetaBirads)).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO'].map(etiquetaEdad)).toEqual(
['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(etiquetaBirads('BIRADS_7')).toBe('BIRADS_7'); expect(etiquetaEdad('OTRO')).toBe('OTRO');
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
});
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
const r = seguimientoTablaResponse(listaCohorte());
expect(r.filtros_disponibles[0].opciones.map(o => [o.codigo, o.etiqueta]).slice(0, 2)).toEqual([['BIRADS_4', 'BI-RADS 4'], ['BIRADS_4A', 'BI-RADS 4A']]);
expect(r.filtros_disponibles[1].opciones.map(o => o.etiqueta)).toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(r.items[0]).toMatchObject({ birads: 'BI-RADS 5', birads_codigo: 'BIRADS_5', grupo_edad: '50 a 59 años', grupo_edad_codigo: '50-59' });
const histo = listaCohorte();
(histo['items'] as Record<string, unknown>[])[0]['biopsia'] = 'CARCINOMA_INVASOR';
expect(seguimientoTablaResponse(histo).items[0]).toMatchObject({ biopsia: 'Carcinoma invasor', biopsia_codigo: 'CARCINOMA_INVASOR' });
expect(r.filtros).toEqual({ birads: null, grupo_edad: null });
const plana = listaCohorte(); delete plana['cohorte'];
expect(seguimientoTablaResponse(plana).items[0]).toMatchObject({ birads: 'BIRADS_5', grupo_edad: '50-59' });
});
});
describe('La lista de la cohorte con etiquetas legibles y el corte elegido', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('active', false);
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const seleccion = (esperados = 6): SeleccionSeguimiento => ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE_ELEGIDO, esperados, contexto: CONTEXTO, id: 1 });
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const celdas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent!.replace(/\s+/g, ' ').trim()));
it('muestra BI-RADS y grupos de edad legibles en las filas y en los filtros, pero la petición sigue enviando los códigos', async () => {
// Fails if the user reads codes, or a filter chosen by its label is sent as text instead of its code.
fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion()); fixture.detectChanges();
let r = solicitud();
expect(parametros(r)).toMatchObject({ corte: CORTE_ELEGIDO, birads: 'BIRADS_5', meses: '0', ...CONTEXTO });
r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await asentar();
expect(celdas()[1].slice(1, 3)).toEqual(['60 a 69 años', 'BI-RADS 5 Fecha: 2025-02-01']);
expect(root().textContent).not.toMatch(/BIRADS_5|60-69/);
expect([...campo('Grupo de edad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
const s = campo('Grupo de edad').querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === '60 a 69 años')!.value;
s.dispatchEvent(new Event('change')); await asentar();
[...root().querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); fixture.detectChanges();
r = solicitud();
expect(parametros(r)).toMatchObject({ grupo_edad: '60-69', birads: 'BIRADS_5', corte: CORTE_ELEGIDO });
r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5', grupo_edad: '60-69' } }));
});
it('el corte elegido en el análisis llega a la lista, a la ficha y a todas las páginas de la exportación', async () => {
// Fails if the list, the record or a page of the file is read at another cut-off than the one the user chose.
fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion(450)); fixture.detectChanges();
solicitud().flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); await asentar();
// The record, opened from the row that was clicked.
(root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar();
expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE_ELEGIDO}.`);
// The files: every page asks for the same cut-off, and the answer must give it back.
const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 }));
const pedidas: SeguimientoTablaQuery[] = [];
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> => {
pedidas.push(q); return of(seguimientoTablaResponse(listaCohorte({ corte: q.corte, filtros: q.filtros as Record<string, string>, page: q.page, size: q.page_size, n: 450 }))); } } as unknown as SeguimientoTablaService;
expect(queryOf(respuesta)).toMatchObject({ corte: CORTE_ELEGIDO, meses: 0, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
expect(pedidas.map(q => q.corte)).toEqual([CORTE_ELEGIDO, CORTE_ELEGIDO, CORTE_ELEGIDO]);
});
});
describe('Ficha y archivos de una fila con biopsia reportada y resultado desconocido', () => {
const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO }));
const fila = (i: number) => respuesta.items[i];
const NOW = new Date(Date.UTC(2026, 10, 13, 18, 0));
it('la ficha dice «Fecha de reporte», conserva «No disponible» para el resultado, el estatus y la prioridad, y escribe BI-RADS y edad legibles', () => {
// Fails if the date of a biopsy report is called the date of the biopsy, or an unknown result is filled in.
const resumen = toCamaPatientSummary(fila(2), CORTE_ELEGIDO, respuesta.columnas)!;
expect(resumen).toMatchObject({ birads: 'BI-RADS 5', ageGroup: '50 a 59 años', histopathology: null, biopsyDate: '2025-02-15', biopsyDateLabel: 'Fecha de reporte', status: null, priority: null });
TestBed.configureTestingModule({ providers: [provideHttpClient()] });
const card = TestBed.createComponent(CamaPatientCard);
card.componentRef.setInput('summary', resumen); card.detectChanges();
const t = (card.nativeElement.textContent as string).replace(/\s+/g, ' ');
expect(t).toContain('Resultado: No disponible'); expect(t).toContain('Fecha de reporte: 2025-02-15');
expect(t).toContain('Categoría BI-RADS: BI-RADS 5'); expect(t).toContain('50 a 59 años');
expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).toMatch(/Prioridad\s*No disponible/); expect(t).toMatch(/Días de mastografía a diagnóstico\s*No disponible/);
expect(t).not.toContain('Fecha de biopsia');
const pdf = textos(camaPatientDocument(resumen, NOW, 'data:image/png;base64,AAAA'));
expect(pdf).toContain('Fecha de reporte'); expect(pdf).not.toContain('Fecha de biopsia');
// A list whose columns do not rename the date keeps the record's own wording.
expect(toCamaPatientSummary(fila(2), CORTE_ELEGIDO)!.biopsyDateLabel).toBeUndefined();
});
it('los archivos escriben las etiquetas, no los códigos, y la fila con fecha de reporte sin resultado sale con la celda vacía', async () => {
// Fails if a file carries codes the user cannot read, or invents a result for a report whose result is unknown.
const snapshot = { corte: respuesta.corte, ventana: respuesta.ventana, filtros: respuesta.filtros, filtros_disponibles: respuesta.filtros_disponibles, columnas: respuesta.columnas, items: respuesta.items, seleccion: 'Categoría BI-RADS: BI-RADS 5' };
const pdf = textos(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA'));
expect(pdf).toContain('BI-RADS 5'); expect(pdf).toContain('50 a 59 años'); expect(pdf.some(t => /BIRADS_|50-59/.test(t))).toBe(false);
expect(pdf).toContain('Fecha de reporte: 2025-02-15');
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|');
expect(cadenas).toContain('|BI-RADS 5|'); expect(cadenas).toContain('|60 a 69 años|'); expect(cadenas).not.toMatch(/BIRADS_|\|50-59\|/);
expect(cadenas).toContain('Resultado histopatológico: Fecha de reporte');
});
});
@@ -91,6 +91,49 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
});
});
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
type Figura = { data: Record<string, any>[]; layout: { annotations: Record<string, any>[]; margin: Record<string, number>; showlegend: boolean } };
const dona = (compacta = false) => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro', compacta) as unknown as Figura;
// Fails if the long label of the 4 without subcategory goes back inside the ring (where it is cut), loses its
// percentage or its guide line, or if the short labels or the centre total change.
it('2025-S2: la etiqueta larga sale del anillo, horizontal y con línea guía; las cortas y el total se conservan', () => {
const f = dona(), t = f.data[0], llamada = f.layout.annotations[1];
expect(t['text'][0]).toBe('');
expect(t['text'][1]).toBe('');
expect(t['text'][4]).toMatch(/^BI-RADS 5<br>54[.,]5 %$/);
expect(t['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations[0]['text']).toBe('<b>33</b><br>mastografías');
expect(f.layout.annotations).toHaveLength(2);
expect(llamada['text']).toBe('BI-RADS 4<br>(sin subcategoría)<br>45.5 %');
// A guide line: an arrow without head from the label to a point inside the slice, and no text rotation.
expect(llamada['showarrow']).toBe(true);
expect(llamada['arrowhead']).toBe(0);
expect(llamada['textangle']).toBeUndefined();
});
// Fails if the label can reach the neighbouring chart: its side must keep a margin, and it sits on the side of its slice.
it('reserva espacio del lado de la etiqueta y la coloca del lado de su segmento', () => {
const f = dona(), llamada = f.layout.annotations[1];
// The slice is 45 % of a clockwise ring: its middle points right, so label and margin are on the right.
expect(llamada['xanchor']).toBe('left');
expect(llamada['ax']).toBeGreaterThan(0);
expect(f.layout.margin['r']).toBeGreaterThanOrEqual(110);
expect(f.layout.margin['l']).toBeLessThan(20);
expect(f.layout.showlegend).toBe(false);
});
// Fails if a narrow screen keeps a label that needs side room instead of moving to a legend under the donut.
it('en pantalla estrecha no hay llamada: la dona usa una leyenda debajo', () => {
const f = dona(true);
expect(f.layout.annotations).toHaveLength(1);
expect(f.layout.showlegend).toBe(true);
expect((f.layout as Record<string, any>)['legend']['orientation']).toBe('h');
expect(f.layout.margin['r']).toBeLessThan(20);
expect(f.data[0]['values']).toEqual([15, 0, 0, 0, 18, 0]);
});
});
describe('Conteos pareados de CaMa: lo que no se calcula', () => {
it('no hay razón de mastografías por paciente en la figura ni en el modelo', () => {
// Fails if a "≈ x por paciente" annotation comes back: exams of a category include those of patients whose
@@ -44,6 +44,8 @@ export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly strin
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
const COLOR_NEUTRO = '#8A9199';
// Labels longer than «BI-RADS 4A» do not fit inside the ring.
const LARGO_ETIQUETA_INTERIOR = 12;
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
@@ -102,19 +104,49 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
// Geometry the callouts rely on. The ring is height-bound (a 400 px figure with a 10 px margin above and below and
// the pie over 90 % of that height), so its radius does not depend on the width of the card.
const ALTO_DONA = 400, MARGEN_VERTICAL = 10, RADIO_DONA = Math.round((ALTO_DONA - 2 * MARGEN_VERTICAL) * .9 / 2);
const MARGEN_ROTULO = 120, SALIDA_ROTULO = 28;
/**
* Exams by category around their total; nothing is drawn when a cell is unknown. A long label does not fit in the
* ring: it is drawn outside, horizontal and on two lines, joined to its slice by a guide line, on the side of the
* slice with room reserved for it so it never reaches the neighbouring chart. On a narrow card (`compacta`) the
* callouts give way to a legend under the donut.
*/
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, compacta = false): PlotlyFigure {
const total = totalExamenes(m);
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
const larga = (i: number) => m.examenes[i].etiqueta.length > LARGO_ETIQUETA_INTERIOR && n[i] > 0;
const porcentaje = (i: number) => percentNumber(100 * n[i] / total) + ' %';
const dibujadas = (i: number) => !larga(i) && n[i] / total >= .05;
// Each long label is a callout whose guide line ends inside its slice.
let antes = 0;
const llamadas = n.flatMap((v, i) => {
const angulo = 2 * Math.PI * (antes + v / 2) / total;
antes += v;
if (compacta || !larga(i)) return [];
const seno = Math.sin(angulo), coseno = Math.cos(angulo), dentro = Math.round(RADIO_DONA * .8), fuera = RADIO_DONA + SALIDA_ROTULO - dentro;
const etiqueta = escapar(m.examenes[i].etiqueta), corte = etiqueta.indexOf(' (');
return [{ x: .5, y: .5, xref: 'paper', yref: 'paper', xshift: Math.round(dentro * seno), yshift: Math.round(dentro * coseno),
ax: Math.round(fuera * seno), ay: Math.round(-fuera * coseno), axref: 'pixel', ayref: 'pixel', showarrow: true, arrowhead: 0, arrowwidth: 1, arrowcolor: p.text,
text: (corte > 0 ? etiqueta.slice(0, corte) + '<br>' + etiqueta.slice(corte + 1) : etiqueta) + '<br>' + porcentaje(i),
align: seno >= 0 ? 'left' : 'right', xanchor: seno >= 0 ? 'left' : 'right', yanchor: 'middle', font: { size: 12, color: p.text }, lado: seno >= 0 ? 'r' : 'l' }];
});
const lado = (l: string) => llamadas.some(a => a.lado === l) ? MARGEN_ROTULO : 10;
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
text: n.map((_, i) => dibujadas(i) ? escapar(m.examenes[i].etiqueta) + '<br>' + porcentaje(i) : ''),
domain: { x: [0, 1], y: [.05, .95] },
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
layout: { autosize: true, height: compacta ? ALTO_DONA + 40 : ALTO_DONA, showlegend: compacta, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_VERTICAL, b: compacta ? 70 : MARGEN_VERTICAL, l: lado('l'), r: lado('r') },
...(compacta ? { legend: { orientation: 'h', x: .5, xanchor: 'center', y: -.02, yanchor: 'top', font: { size: 12 } } } : {}),
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }, ...llamadas.map(({ lado: _lado, ...a }) => a)] }, config: { displayModeBar: false } };
}
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
@@ -58,7 +58,8 @@ describe('D.2 integración de autoridad global y consumidores', () => {
load(undefined, domain);
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]);
expect(sections[0].textContent).toContain(domain === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + page.domainLabels[domain]);
if (domain === 'cama') expect(sections[0].textContent).not.toContain('Filtros generales de ');
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
expect(page.filters!.applied.selection.mode).toBe('todos');
@@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => {
http.match(() => true);
}
it('CaMa: Resumen, Histórico, Seguimiento y Datos y definiciones, en ese orden', () => {
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
});
it.each(['tea', 'cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
@@ -72,7 +72,10 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
[label]="'Histórico de ' + panel.titulo + (panel.rango ? ', ' + panel.rango : '')" />
<p class="nota">{{ panel.figura.comoLeer }}</p>
@if (panel.figura.suprimidos.length) {
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.figura.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
<details class="nota-pie">
<summary>Datos suprimidos</summary>
<p>Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.figura.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
</details>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
}
@@ -91,6 +94,10 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.nota-pie { margin-top: var(--issste-space-3); padding-top: var(--issste-space-2); border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font-size: 0.8125rem; line-height: 1.4; }
.nota-pie summary { width: fit-content; cursor: pointer; }
.nota-pie summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.nota-pie p { margin-top: var(--issste-space-2); font: inherit; }
app-plotly-chart { margin-top: var(--issste-space-3); }
mat-form-field { min-width: 18rem; }
`,
@@ -2,10 +2,10 @@
<header>
@if (fichaPacienteAbierta()) {
<h1 id="dashboard-title">Ficha del paciente</h1>
<p>Consulta individual de seguimiento de cáncer cervicouterino</p>
<p>Consulta individual de seguimiento de {{ dominio === 'cama' ? domainLabels.cama : 'cáncer cervicouterino' }}</p>
} @else {
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
<h1 id="dashboard-title">Indicadores</h1>
@if (dominio !== 'cama') { <span class="domain">{{ domainTitles[dominio] }}, investigación</span> }
<h1 id="dashboard-title">{{ dominio === 'cama' ? 'Sistema TNM de clasificación tumoral' : 'Indicadores' }}</h1>
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
}
</header>
@@ -43,8 +43,10 @@
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
@if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : dominio === 'cama' ? 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
<h2 id="global-filters-title" class="section-title">{{ dominio === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + domainLabels[dominio] }}</h2>
@if (dominio !== 'cama') {
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
}
<app-indicador-period-filters [state]="state" [compact]="dominio === 'cama'" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" />
@@ -142,8 +144,15 @@
</section>
}
@if (conAnalisis) {
<section id="panel-analisis" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-analisis" tabindex="0" [hidden]="activeSection() !== 'analisis'">
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" (verPacientes)="verPacientes($event)" />
</section>
}
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
[seleccion]="seleccionSeguimiento()" (volverAlAnalisis)="volverAlAnalisis()"
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
</section>
@@ -10,8 +10,7 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.state { padding: 1.25rem; margin: 0; }
// CaMa's filter block is one compact row, as in the reference.
.global-filters[data-domain='cama'] { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); }
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; }
.global-filters[data-domain='cama'] .section-description { margin: var(--issste-space-1) 0 var(--issste-space-2); font: var(--mat-sys-body-small); }
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
.kpi-section, .graphic-section { min-width: 0; }
@@ -28,11 +28,13 @@ import { httpMessage } from './indicadores-http';
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
@@ -40,19 +42,36 @@ const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
{ id: 'datos', label: 'Datos y definiciones' },
];
const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]];
// The epidemiological analysis is CaMa's: between its history and its follow-up list.
const SECCIONES_CON_ANALISIS: readonly { id: DashboardSection; label: string }[] = [
SECCIONES_CON_HISTORICO[0], SECCIONES_CON_HISTORICO[1], { id: 'analisis', label: 'Análisis epidemiológico' }, SECCIONES_CON_HISTORICO[2], SECCIONES_CON_HISTORICO[3]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico, IndicadoresAnalisis],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
// The history tab is CaMa's; the other domains keep their three sections.
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
// The history and the analysis tabs are CaMa's; the other domains keep their three sections.
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conAnalisis ? SECCIONES_CON_ANALISIS : this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
get conHistorico() { return this.dominio === 'cama'; }
get conAnalisis() { return this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
private readonly analisis = viewChild(IndicadoresAnalisis);
// The patients of a curve or a heatmap cell, opened in Seguimiento; the id makes a repeated click apply again.
// It belongs to the domain it was made in and stays while the user moves between the tabs.
readonly seleccionSeguimiento = signal<SeleccionSeguimiento | undefined>(undefined);
verPacientes(seleccion: SeleccionPacientes) {
this.seleccionSeguimiento.set({ ...seleccion, id: (this.seleccionSeguimiento()?.id ?? 0) + 1 });
this.changeSection('seguimiento');
}
// Back to the analysis: the part, the scroll and the focus where the user left them.
volverAlAnalisis() {
this.changeSection('analisis');
afterNextRender(() => this.analisis()?.restaurar(), { injector: this.injector });
}
setFichaPacienteAbierta(open: boolean) {
this.fichaPacienteAbierta.set(open);
if (open) this.closeGraphicNavigation(false, false);
@@ -538,6 +557,7 @@ export class IndicadoresPage {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.closeGraphicNavigation(false, false);
this.activeSection.set('resumen');
this.seleccionSeguimiento.set(undefined);
this.searchQuery.set('');
this.filtersEdited();
this.filters = undefined;
@@ -0,0 +1,178 @@
// Covers the journey of breast cancer on the page: Análisis → «Ver pacientes» → Seguimiento on the group → record →
// «Volver al análisis», with the analysis as it was and the focus on the control that opened the list; the selection going
// with the domain; CaCu and TEA keeping their three sections; and the wording of every screen of the journey.
// Fixtures: indicadores-analisis.testing.ts (the aggregate) and fixtures/cama_seguimiento.json (the list).
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from '../../app.routes';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import fixtureData from './fixtures/cama_seguimiento.json';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis';
import { IndicadorFigureCard } from './indicador-figure-card';
import { agregadoJson, CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { readonly plotClick = output<unknown>(); }
const catalogoCama: Indicador[] = [{ id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras'], tipos_periodo: ['mes'] }];
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
// What the cohort's list answers to the group BI-RADS 5: the whole cohort, the cut-off asked for, the filter applied and the cohort quoted back.
const cohorte = (corte: string) => ({ ...base(), ...CONTEXTO, corte, ventana: { meses: 0, desde: '2025-01-01', hasta: corte },
filtros: { ...base()['filtros'], birads: 'BIRADS_5' } });
// Nothing a user can read or a screen reader announces refers to tests, simulation, a development environment or the mock.
const PROHIBIDO = /mock|demostraci|simulad|sint[eé]tic|ficticio|entorno|\bdev\b/i;
function legible(root: HTMLElement): string[] {
const textos = [root.textContent ?? ''];
root.querySelectorAll('[aria-label], [title], [alt]').forEach(el => ['aria-label', 'title', 'alt'].forEach(a => { const v = el.getAttribute(a); if (v) textos.push(v); }));
return textos;
}
describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () => {
let http: HttpTestingController;
const corte = hoyIso();
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
async function entrar() {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage);
http.expectOne('/cama/indicadores').flush(catalogoCama); harness.detectChanges();
const root = harness.routeNativeElement!;
const tab = (id: string) => root.querySelector<HTMLButtonElement>('#tab-' + id)!;
const panel = (id: string) => root.querySelector<HTMLElement>('#panel-' + id)!;
const asentar = async () => { harness.detectChanges(); await harness.fixture.whenStable(); harness.detectChanges(); };
return { harness, page, root, tab, panel, asentar };
}
async function abrirAnalisis(e: Awaited<ReturnType<typeof entrar>>) {
e.tab('analisis').click(); e.harness.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte).flush(agregadoJson({ corte })); await e.asentar();
}
const lista = () => http.expectOne(q => q.url === '/cama/seguimiento');
const parametros = (r: ReturnType<typeof lista>) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
it('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => {
// Fails if any step of the journey drops the selection, repeats a request, loses the focus or the answer already loaded.
const e = await entrar();
await abrirAnalisis(e);
const origen = e.root.querySelector<HTMLButtonElement>('#birads-titulo ~ .tabla-scroll tr[data-grupo="BIRADS_5"] button.ver')!;
origen.focus(); origen.click(); e.harness.detectChanges();
// Seguimiento on the whole cohort of the group, at the analysis' cut-off, quoting its cohort and revision.
expect(e.page.activeSection()).toBe('seguimiento');
const r = lista();
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte, ...CONTEXTO, birads: 'BIRADS_5' });
r.flush(cohorte(corte)); await e.asentar();
expect(e.panel('seguimiento').hidden).toBe(false); expect(e.panel('analisis').hidden).toBe(true);
expect(e.panel('seguimiento').textContent).toContain('Categoría BI-RADS: BI-RADS 5');
expect(e.panel('seguimiento').textContent).toContain('Toda la cohorte');
expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección y la lista muestra 27. No coinciden');
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
// The record opens over the list and gives it back.
e.root.querySelector<HTMLButtonElement>('.patient-link')!.click(); await e.asentar();
expect(e.root.querySelector('#dashboard-title')?.textContent).toBe('Ficha del paciente');
expect(e.root.querySelector('.section-tabs')).toBeNull();
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
[...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar();
expect(e.root.querySelector('.section-tabs')).not.toBeNull();
expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5');
// Back to the analysis: same answer, no new request, the focus where the user left it.
[...e.panel('seguimiento').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Volver al análisis')!.click(); await e.asentar();
expect(e.page.activeSection()).toBe('analisis');
expect(e.tab('analisis').getAttribute('aria-selected')).toBe('true');
expect(e.panel('analisis').hidden).toBe(false);
http.expectNone(q => q.url.startsWith('/cama/analisis'));
expect(e.panel('analisis').querySelectorAll('tbody tr')).toHaveLength(6);
expect(document.activeElement).toBe(origen);
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
// Seguimiento keeps the selection for the user who goes back to its tab.
e.tab('seguimiento').click(); await e.asentar();
http.expectNone(q => q.url === '/cama/seguimiento');
expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5');
});
it('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => {
// Fails if any step of the journey is read at another cut-off than the chosen one, or the file does not say it.
const ELEGIDO = '2026-09-01';
const descargas: string[] = [];
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); });
const e = await entrar();
await abrirAnalisis(e);
const entrada = e.root.querySelector<HTMLInputElement>('#panel-analisis input[name="corte"]')!;
entrada.value = ELEGIDO; entrada.dispatchEvent(new Event('input')); await e.asentar();
[...e.panel('analisis').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); e.harness.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === ELEGIDO).flush(agregadoJson({ corte: ELEGIDO })); await e.asentar();
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ corte: ELEGIDO, meses: '0', birads: 'BIRADS_5', ...CONTEXTO });
r.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await e.asentar();
expect(e.panel('seguimiento').textContent).toContain(`corte ${ELEGIDO}`);
// The record.
e.root.querySelector<HTMLButtonElement>('.patient-link')!.click(); await e.asentar();
expect(e.root.querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${ELEGIDO}.`);
[...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar();
// The file: the pages are read at the same cut-off, and the file says so.
[...e.panel('seguimiento').querySelectorAll('app-seguimiento-exportar button')].find(b => b.textContent!.includes('Excel'))!.dispatchEvent(new Event('click'));
const pagina = http.expectOne(q => q.url === '/cama/seguimiento');
expect(parametros(pagina)).toMatchObject({ corte: ELEGIDO, page_size: '200', meses: '0', birads: 'BIRADS_5', ...CONTEXTO });
pagina.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' }, size: 200 }));
for (let i = 0; i < 30 && !descargas.length; i++) { await new Promise(res => setTimeout(res, 20)); e.harness.detectChanges(); }
expect(descargas).toHaveLength(1);
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-09-01_/);
});
it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => {
// Fails if a stale revision shows rows, or the way back to the analysis is lost with the error.
const e = await entrar();
await abrirAnalisis(e);
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
lista().flush({ error: 'La cohorte cambió; actualiza el análisis' }, { status: 409, statusText: 'Conflict' }); await e.asentar();
expect(e.panel('seguimiento').querySelector('[role="alert"]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis');
expect(e.panel('seguimiento').querySelector('table')).toBeNull();
expect(e.panel('seguimiento').querySelector('app-seguimiento-exportar')).toBeNull();
[...e.panel('seguimiento').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Volver al análisis')!.click(); await e.asentar();
expect(e.panel('analisis').querySelectorAll('tbody tr')).toHaveLength(6);
});
it('al cambiar de dominio la selección se limpia; CaCu y TEA no tienen Análisis y conservan sus tres secciones', async () => {
// Fails if a selection survives into another domain, or the analysis tab leaks into CaCu or TEA.
const e = await entrar();
await abrirAnalisis(e);
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
lista().flush(cohorte(corte)); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeDefined();
for (const dominio of ['cacu', 'tea'] as const) {
e.page.changeDominio(dominio); e.harness.detectChanges();
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(e.root.querySelector('#panel-analisis')).toBeNull();
}
e.page.changeDominio('cama'); e.harness.detectChanges();
http.expectOne('/cama/indicadores').flush(catalogoCama); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(e.root.querySelector('.seleccion')).toBeNull();
});
it('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => {
// Fails if the missing endpoint is hidden or shown as a broken page, or the wording leaks the environment.
const e = await entrar();
e.tab('analisis').click(); e.harness.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); await e.asentar();
expect(e.panel('analisis').textContent).toContain('Funcionalidad pendiente de publicación');
expect(e.panel('analisis').querySelector('[role="alert"]')).toBeNull();
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
});
});
@@ -37,8 +37,8 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// CaMa also has Histórico, between Resumen and Seguimiento.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
// CaMa also has Histórico and Análisis epidemiológico, between Resumen and Seguimiento; CaCu and TEA keep their three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
@@ -60,13 +60,12 @@ describe('Secciones compartidas por dominio', () => {
}
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
if (domain === 'cacu') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else if (domain === 'cama') {
// Pending integration: the form is gone with no table, and the retry is offered.
expect(tracking.textContent).toContain('Funcionalidad pendiente de publicación');
// An unavailable cohort has no table and offers a retry.
expect(tracking.querySelector('table')).toBeNull();
expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull();
expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento');
@@ -0,0 +1,162 @@
// Covers the habitual access to Seguimiento of breast cancer: the list opens on the regular window and, when the server
// answers from the cohort, adopts the cohort and its revision for the next pages and the files; a cut-off or a changed
// revision is asked for without the old revision; and the filters, the cut-off, the page and the rows are kept while the
// record is opened and closed. Fixtures: indicadores-analisis.testing.ts (listaCohorte) and fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import fixtureData from './fixtures/cama_seguimiento.json';
import { CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
const OTRA = 'a'.repeat(64);
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
describe('Seguimiento de CaMa: acceso habitual', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama');
fixture.componentRef.setInput('active', false); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const lista = () => http.expectOne(r => r.url === '/cama/seguimiento');
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim());
async function escribir(nombre: string, valor: string) {
const c = root().querySelector(`input[name="${nombre}"]`) as HTMLInputElement; c.value = valor; c.dispatchEvent(new Event('input')); await asentar();
}
async function elegir(etiqueta: string, valor: string) {
const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar();
}
// The list opens on the regular window of 3 months and the cohort answers with its revision.
async function abierta(extra: Parameters<typeof listaCohorte>[0] = {}) {
abrir(); lista().flush(listaCohorte({ meses: 3, n: 27, ...extra })); await asentar();
}
it.each([404, 503])('informa que la cohorte no está disponible ante %s y no cambia de fuente', async status => {
// Fails if an unavailable source is reported as an empty list or another source is queried.
abrir(); lista().flush({ error: 'x' }, { status, statusText: 'Unavailable' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible');
http.expectNone(r => r.url === '/cama/seguimiento');
});
it('abre en la ventana habitual de 3 meses sin citar ninguna revisión, y adopta la cohorte que el servidor devuelve', async () => {
// Fails if the habitual access asks for another window, or needs a revision it cannot have yet, or shows an analysis banner.
http.expectNone(() => true);
abrir();
const r = lista();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush(listaCohorte({ meses: 3, n: 27, size: 10 })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
expect(root().textContent).toContain('Ventana consultada: 2025-02-01 al 2026-10-20.');
// The next page quotes the cohort the first answer named, with the same window and cut-off.
boton('Siguiente')!.click(); fixture.detectChanges();
const p2 = lista();
expect(parametros(p2)).toEqual({ meses: '3', page: '2', page_size: '10', corte: CORTE, ...CONTEXTO });
p2.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2 })); await asentar();
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
});
it('«Toda la cohorte» pide la ventana 0 citando la cohorte', async () => {
// Fails if the whole cohort is asked for without the revision the server requires for it.
await abierta();
await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO });
r.flush(listaCohorte({ meses: 0, n: 43 })); await asentar();
expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.');
expect(root().querySelector('nav')?.textContent).toContain('43 registros');
});
it('un servidor sin cohorte responde la lista de siempre: sin «Toda la cohorte» y sin citar nada', async () => {
// Fails if a deployment without the cohort provider loses its follow-up list or is sent parameters it does not know.
abrir(); lista().flush(base()); await asentar();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
boton('Consultar')!.click(); fixture.detectChanges();
expect(parametros(lista())).not.toHaveProperty('revision');
});
it('si el usuario cambia el corte, la consulta no cita la revisión del corte anterior y adopta la nueva', async () => {
// Fails if a list at another cut-off is asked for with the revision of the previous one.
await abierta();
await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ corte: '2026-09-01', meses: '3' });
expect(parametros(r)).not.toHaveProperty('revision');
r.flush(listaCohorte({ meses: 3, n: 27, corte: '2026-09-01', revision: OTRA })); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
expect(parametros(lista())).toMatchObject({ corte: '2026-09-01', revision: OTRA });
});
it('si la cohorte cambia bajo la lista (409), repite la misma consulta una vez sin la revisión vieja; un segundo 409 sí se dice', async () => {
// Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops.
await abierta({ size: 10 });
boton('Siguiente')!.click(); fixture.detectChanges();
lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ page: '2', meses: '3' });
expect(parametros(r)).not.toHaveProperty('revision');
r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, revision: OTRA })); await asentar();
expect(root().querySelector('[role=alert]')).toBeNull();
// A conflict that persists is reported, not retried forever.
boton('Consultar')!.click(); fixture.detectChanges();
lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges();
lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis');
expect(root().querySelector('table')).toBeNull();
});
it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => {
// Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow window as an empty cohort.
await abierta({ n: 0 });
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 0 })); await asentar();
expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.');
expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true);
await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar();
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
});
it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => {
// Fails if opening the record resets the form, the page or the rows the user was reading.
await abierta({ size: 10 });
await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 3, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar();
boton('Siguiente')!.click(); fixture.detectChanges();
const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: CORTE, ...CONTEXTO });
r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar();
const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim());
(root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar();
expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE}.`);
([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar();
http.expectNone(() => true);
expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes);
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement;
expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años');
expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(CORTE);
});
it('con una selección del análisis, «Quitar selección» regresa a la lista habitual: 3 meses, sin filtros ni revisión citada', async () => {
// Fails if leaving the selection keeps its filter, its window or the old revision.
await abierta();
fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 43, contexto: { ...CONTEXTO, revision: REVISION }, id: 1 });
fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 43, filtros: { birads: 'BIRADS_5' } })); await asentar();
expect(root().querySelector('.seleccion')).not.toBeNull();
boton('Quitar selección')!.click(); fixture.detectChanges();
const r = lista(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE });
r.flush(listaCohorte({ meses: 3, n: 27 })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
});
it('la biopsia se escribe con las etiquetas del catálogo y un valor desconocido queda como llegó', async () => {
// Fails if a source code is remapped to a diagnosis the catalog does not name, or the code is lost.
abrir();
const r = listaCohorte({ meses: 3, n: 4 }); const v = ['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'OTRO_VALOR']; r['items'].forEach((i: any, k: number) => { i['biopsia'] = v[k]; });
lista().flush(r); await asentar();
expect([...root().querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.replace(/\s+/g, ' ').trim().split(' Fecha')[0])).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'OTRO_VALOR']);
});
});
@@ -0,0 +1,121 @@
// Covers how CaMa's follow-up table opens and closes an individual record: the control that opens it, what stays in
// the table while the record is open (page, filters), that no request is made, the focus on return, and the page
// being told. Fixture: fixtures/cama_seguimiento.json, served as the first page of 5 rows.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import fixtureData from './fixtures/cama_seguimiento.json';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresTracking } from './indicadores-tracking';
const pagina = () => {
const d = structuredClone(fixtureData) as unknown as Record<string, any>, todos = d['items'] as unknown[];
d['items'] = todos.slice(0, 5);
d['paginacion'] = { page: 1, page_size: 5, total_items: todos.length, total_pages: Math.ceil(todos.length / 5) };
return d;
};
describe('Seguimiento de CaMa: ficha del paciente', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController, abierta: boolean[];
beforeEach(async () => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
abierta = [];
fixture.componentInstance.fichaAbierta.subscribe(v => abierta.push(v));
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina());
await asentar();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const tabla = () => root().querySelector('div[hidden], div:not([hidden])')!.parentElement!.querySelector('form')!.parentElement as HTMLElement;
const enlace = (n = 0) => root().querySelectorAll<HTMLButtonElement>('.patient-link')[n];
const ficha = () => root().querySelector('app-cama-patient-card');
// Fails if the export buttons leave the title row or come back under the table.
it('has the export buttons in the row of the section title, and nothing after the pagination', () => {
const row = root().querySelector('.title-row')!;
expect(row.querySelector('h2')!.textContent).toContain('Seguimiento de');
expect([...row.querySelectorAll('button')].map(b => b.textContent!.trim())).toEqual(['Exportar Excel (.xlsx)', 'Exportar PDF']);
expect(root().querySelector('nav')!.nextElementSibling).toBeNull();
expect(root().textContent).not.toContain('Exportar resultados');
});
// Fails if the identifier stops being a control, which leaves the record reachable only by mouse.
it('draws each identifier as a button named after the patient', () => {
expect(root().querySelectorAll('.patient-link')).toHaveLength(5);
expect(enlace().getAttribute('aria-label')).toBe(`Ver ficha del paciente ${enlace().textContent!.trim()}`);
});
// Fails if opening a record fetches anything: the card reads only the row, and no identifier may travel to a server.
it('opens the record of the patient from the row, with no request', async () => {
const id = enlace(1).textContent!.trim();
enlace(1).click(); await asentar();
expect(ficha()!.querySelector('h2')!.textContent).toContain(`Paciente ${id}`);
expect(abierta).toEqual([true]);
http.expectNone(() => true);
});
// Fails if the list is replaced instead of hidden: returning would lose the page and the filters being looked at.
it('hides the table while the record is open and shows the same table afterwards', async () => {
const before = root().querySelector('tbody')!;
enlace().click(); await asentar();
const wrapper = root().querySelector('form')!.parentElement as HTMLElement;
expect(wrapper.hidden).toBe(true);
[...ficha()!.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await asentar();
expect(ficha()).toBeNull();
expect(wrapper.hidden).toBe(false);
expect(root().querySelector('tbody')).toBe(before);
expect(abierta).toEqual([true, false]);
});
// Fails if focus is lost on return, which strands keyboard users at the top of the page.
it('returns focus to the identifier that opened the record', async () => {
enlace(2).click(); await asentar();
[...ficha()!.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await asentar();
await new Promise(r => setTimeout(r));
expect(document.activeElement).toBe(enlace(2));
});
// Fails if a click on the row (outside its button) stops opening the record, or if opening happens twice.
it('also opens the record from a click on the row, once', async () => {
const fila = root().querySelectorAll<HTMLElement>('tbody tr')[3];
fila.querySelector<HTMLElement>('td:nth-child(2)')!.click(); await asentar();
expect(ficha()).not.toBeNull();
expect(abierta).toEqual([true]);
});
// Fails if the page stays titled for a record after the domain changed and the record went away.
it('closes the record and tells the page when the domain changes', async () => {
enlace().click(); await asentar();
fixture.componentRef.setInput('dominio', 'cacu'); fixture.detectChanges(); await asentar();
// The table asks for the new domain's list; that answer is not what this test is about.
http.match(r => r.url === '/cacu/seguimiento').forEach(r => r.flush({ error: 'not under test' }, { status: 500, statusText: 'Server Error' }));
expect(ficha()).toBeNull();
expect(abierta).toEqual([true, false]);
});
});
describe('Seguimiento: ficha de CaMa y cambio de dominio', () => {
// Fails if switching domain with CaMa's record open leaves the page titled for a record that no longer shows:
// the table that held the record is removed without being told, so the section above it must tell the page.
it('tells the page that no record shows when the domain changes while one is open', async () => {
TestBed.configureTestingModule({ imports: [IndicadoresTracking], providers: [provideHttpClient(), provideHttpClientTesting()] });
const fixture = TestBed.createComponent(IndicadoresTracking), http = TestBed.inject(HttpTestingController);
const abierta: boolean[] = [];
fixture.componentInstance.fichaPacienteAbierta.subscribe(v => abierta.push(v));
fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina());
await fixture.whenStable(); fixture.detectChanges();
(fixture.nativeElement as HTMLElement).querySelector<HTMLButtonElement>('.patient-link')!.click();
await fixture.whenStable(); fixture.detectChanges();
expect(abierta).toEqual([true]);
expect((fixture.nativeElement as HTMLElement).querySelector('.title-row')!.closest('[hidden]')).not.toBeNull();
fixture.componentRef.setInput('dominio', 'tea'); fixture.detectChanges();
expect(abierta).toEqual([true, false]);
http.verify(); fixture.destroy();
});
});
@@ -0,0 +1,226 @@
// Covers the follow-up list when the epidemiological analysis opens it on a group of the cohort: what it asks for (whole
// cohort, the analysis' cut-off, the group's filter and the cohort with its revision), what the user reads, how the
// selection is kept, refined and removed, and that a list which does not belong to the selection on screen is never
// drawn. Fixture: fixtures/cama_seguimiento.json shaped like the cohort's list (two filters, the cohort quoted back).
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import fixtureData from './fixtures/cama_seguimiento.json';
import { CONTEXTO, CORTE } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
const NULOS = { birads: null, grupo_edad: null };
const OPCIONES = { birads: ['BIRADS_4', 'BIRADS_5', 'BIRADS_6'], grupo_edad: ['40-49', '50-59', '60-69'] };
// The cohort's answer: only the two filters it announces, the cohort quoted back, window 0 and the filters it applied.
function cohorte(filtros: Record<string, string>, pagina = 1, tam = 50, extra: Record<string, any> = {}) {
const d = base(), todos = d['items'] as unknown[];
d['items'] = todos.slice((pagina - 1) * tam, pagina * tam);
d['paginacion'] = { page: pagina, page_size: tam, total_items: todos.length, total_pages: Math.max(1, Math.ceil(todos.length / tam)) };
d['corte'] = CORTE; d['ventana'] = { meses: 0, desde: '2025-01-01', hasta: CORTE };
d['filtros'] = { ...NULOS, ...filtros };
d['filtros_disponibles'] = [
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: OPCIONES.birads.map(c => ({ codigo: c, etiqueta: c })) },
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: OPCIONES.grupo_edad.map(c => ({ codigo: c, etiqueta: c })) }];
return { ...d, ...CONTEXTO, ...extra };
}
const seleccion = (id: number, extra: Partial<SeleccionSeguimiento> = {}): SeleccionSeguimiento =>
({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id, ...extra });
const PARAMS = { meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO, birads: 'BIRADS_5' };
describe('Seguimiento de CaMa abierto desde el análisis', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama');
fixture.componentRef.setInput('active', false); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = (dominio = 'cama') => http.expectOne(r => r.url === `/${dominio}/seguimiento`);
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const abrirCon = (sel: SeleccionSeguimiento) => { fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', sel); fixture.detectChanges(); };
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
async function elegir(etiqueta: string, valor: string) {
const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor || o.value.endsWith(valor))!.value;
s.dispatchEvent(new Event('change')); await asentar();
}
const banner = () => root().querySelector('.seleccion')?.textContent?.replace(/\s+/g, ' ').trim();
const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim());
const exportar = () => root().querySelector('app-seguimiento-exportar');
it('pide toda la cohorte con el corte del análisis, el filtro del grupo y la cohorte con su revisión, y lo dice con su etiqueta y un camino de regreso', async () => {
// Fails if the list opens on another window, cut-off, group or cohort revision, or hides where it came from.
http.expectNone(() => true);
abrirCon(seleccion(1));
const r = solicitud();
expect(parametros(r)).toEqual(PARAMS);
r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico: Categoría BI-RADS: BI-RADS 5. Toda la cohorte, corte 2026-10-20.');
expect(boton('Volver al análisis')).toBeDefined(); expect(boton('Quitar selección')).toBeDefined();
expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.');
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
expect(fixture.componentInstance.etiquetaDatos()).toBe('Categoría BI-RADS: BI-RADS 5');
expect(exportar()).not.toBeNull();
});
it('sin una selección la ventana no ofrece «Toda la cohorte» y la consulta no cita ninguna cohorte', async () => {
// Fails if the whole cohort becomes a plain window of the list, or a plain query quotes a revision.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const r = solicitud();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush({ ...base() }); await asentar();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
expect(root().querySelector('.seleccion')).toBeNull();
});
it('si la lista no tiene tantos pacientes como contó el análisis para la misma selección y revisión, lo avisa y no deja exportarla; si coinciden, calla y exporta', async () => {
// Fails if a list that breaks the contract can be exported as if it were the group that was counted.
abrirCon(seleccion(1, { esperados: 30 }));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(root().querySelector('.diferencia')?.getAttribute('role')).toBe('alert');
expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección y la lista muestra 27. No coinciden, por lo que este resultado no se puede exportar.');
expect([...exportar()!.querySelectorAll('button')].every(b => b.disabled)).toBe(true);
expect(root().querySelector('table')).not.toBeNull();
fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges();
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(root().querySelector('.diferencia')).toBeNull();
expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true);
});
it('una respuesta que pierde el filtro, cambia la ventana o el corte, o no es la cohorte ni la revisión pedidas no se dibuja ni se puede exportar', async () => {
// Fails if rows of another population or of another revision are shown (or exported) under the name of the analysis' group.
for (const [mal, respuesta] of [
['pierde el filtro', cohorte({})],
['cambia la ventana', cohorte({ birads: 'BIRADS_5' }, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })],
['cambia el corte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { corte: '2026-09-01' })],
['otra revisión', cohorte({ birads: 'BIRADS_5' }, 1, 50, { revision: 'f'.repeat(64) })],
['otra cohorte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { cohorte: 'otra' })],
['sin cohorte', (() => { const d: Record<string, any> = cohorte({ birads: 'BIRADS_5' }); delete d['revision']; return d; })()],
] as const) {
fixture.componentRef.setInput('active', true);
fixture.componentRef.setInput('seleccion', seleccion(mal.length * 7 + mal.charCodeAt(1)));
fixture.detectChanges();
solicitud().flush(respuesta); await asentar();
expect(root().querySelector('[role=alert]')?.textContent, mal).toContain('no corresponde a la selección consultada');
expect(root().querySelector('table'), mal).toBeNull();
expect(exportar(), mal).toBeNull();
expect(root().textContent, mal).not.toContain('M-0081');
}
});
it('403, 409 y 503 dicen qué pasó, no dejan ninguna lista a la vista y no exponen el cuerpo del servidor', async () => {
// Fails if a refused list is explained with the server's text, or the previous rows stay under the failed selection.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
for (const [status, texto] of [[403, 'no hay acceso, o la selección tiene muy pocos pacientes'], [409, 'La cohorte cambió desde que se calculó el análisis'],
[503, 'La cohorte no está disponible en este momento']] as const) {
const c = root().querySelector('input[name="corte"]') as HTMLInputElement;
c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
const r = solicitud();
expect(r.request.params.get('corte'), String(status)).toBe(c.value);
r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar();
const alerta = root().querySelector('[role=alert]')?.textContent;
expect(alerta, String(status)).toContain(texto);
expect(alerta, String(status)).not.toContain('detalle interno');
expect(root().querySelector('table'), String(status)).toBeNull();
expect(exportar(), String(status)).toBeNull();
}
});
it('una selección nueva cancela la anterior: su respuesta tardía no se dibuja y mientras carga no queda la lista anterior', async () => {
// Fails if a slow answer replaces the list of a later selection, or the old rows stay under the new banner.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(root().querySelector('table')).not.toBeNull();
fixture.componentRef.setInput('seleccion', seleccion(2, { filtros: { birads: 'BIRADS_6' }, etiqueta: 'Categoría BI-RADS: BI-RADS 6' })); fixture.detectChanges();
const r2 = solicitud();
expect(root().querySelector('table')).toBeNull();
expect(root().textContent).toContain('Cargando seguimiento');
fixture.componentRef.setInput('seleccion', seleccion(3, { filtros: { birads: 'BIRADS_4' }, etiqueta: 'Categoría BI-RADS: BI-RADS 4' })); fixture.detectChanges();
const r3 = solicitud();
expect(r2.cancelled).toBe(true);
expect(() => r2.flush(cohorte({ birads: 'BIRADS_6' }))).toThrow();
r3.flush(cohorte({ birads: 'BIRADS_4' })); await asentar();
expect(banner()).toContain('BI-RADS 4');
expect(banner()).not.toContain('BI-RADS 6');
expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 4');
});
it('al paginar conserva la selección, el corte, el filtro y la cohorte, y el nombre sigue a las filas', async () => {
// Fails if a later page is asked without the group's filter or the cohort's revision, or loses the name of the selection.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' }, 1, 10)); await asentar();
boton('Siguiente')!.click(); fixture.detectChanges();
const r = solicitud();
expect(parametros(r)).toEqual({ ...PARAMS, page: '2', page_size: '10' });
r.flush(cohorte({ birads: 'BIRADS_5' }, 2, 10)); await asentar();
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 5');
expect(banner()).toContain('BI-RADS 5');
});
it('la selección sobrevive a salir de la pestaña y volver, sin pedir otra vez; «Volver al análisis» avisa a la página', async () => {
// Fails if coming back to the tab repeats the request, drops the selection or the way back stops working.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
let volvio = 0; fixture.componentInstance.volverAlAnalisis.subscribe(() => volvio++);
fixture.componentRef.setInput('active', false); fixture.detectChanges();
fixture.componentRef.setInput('active', true); fixture.detectChanges();
http.expectNone(() => true);
expect(banner()).toContain('BI-RADS 5');
expect(root().querySelector('table')).not.toBeNull();
boton('Volver al análisis')!.click();
expect(volvio).toBe(1);
expect(banner()).toContain('BI-RADS 5');
});
it('«Consultar» sin cambios repite la misma selección; con otro filtro refina la misma cohorte, citando su revisión, y lo dice', async () => {
// Fails if the banner keeps naming a group after the user narrowed the list, or a refinement leaves the cohort.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
let r = solicitud();
expect(parametros(r)).toEqual(PARAMS);
r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico');
await elegir('Grupo de edad', '50-59'); boton('Consultar')!.click(); fixture.detectChanges();
r = solicitud();
expect(parametros(r)).toEqual({ ...PARAMS, grupo_edad: '50-59' });
r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' })); await asentar();
expect(banner()).toContain('Pacientes de la cohorte del análisis epidemiológico, corte 2026-10-20. Los filtros y la ventana son los de esta consulta.');
expect(banner()).not.toContain('selección del análisis');
expect(exportar()).not.toBeNull();
expect(fixture.componentInstance.etiquetaDatos()).toBe('Cohorte del análisis epidemiológico');
expect(root().querySelector('.diferencia')).toBeNull();
expect(ventanas()).toContain('Toda la cohorte');
});
it('«Quitar selección» vuelve a la lista habitual: 3 meses, sin filtros ni nombre, y sin citar la revisión anterior', async () => {
// Fails if removing the selection leaves its filter, the whole-cohort window or the old revision behind.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
boton('Quitar selección')!.click(); fixture.detectChanges();
const r = solicitud();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE });
r.flush(cohorte({}, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined();
expect(exportar()).not.toBeNull();
});
it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => {
// Fails if a selection (or its cohort) made in one domain survives into another.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
fixture.componentRef.setInput('seleccion', undefined); fixture.componentRef.setInput('dominio', 'cacu'); fixture.detectChanges();
expect(root().querySelector('.seleccion')).toBeNull();
expect(root().querySelector('table')).toBeNull();
const r = solicitud('cacu');
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush('', { status: 404, statusText: 'Not Found' });
});
it('una selección que llega con la pestaña inactiva espera a que se abra', async () => {
// Fails if the list is asked for while its tab is hidden.
fixture.componentRef.setInput('seleccion', seleccion(1)); fixture.detectChanges();
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
solicitud().flush(cohorte({ birads: 'BIRADS_5' }));
});
});
@@ -1,30 +1,73 @@
import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core';
import { afterNextRender, Component, DestroyRef, inject, Injector, Input, OnChanges, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { Dominio } from './indicadores.models';
import { columnaEnlace, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { TrackingExportBar } from './export/tracking-export-bar';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import {
MESES_VENTANA, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse,
SeguimientoTablaService, SeguimientoValor,
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor,
} from './seguimiento-tabla.service';
type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error';
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string };
interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; filtros: Record<string, string | undefined>; }
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string; estatus?: number };
/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */
type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string };
// What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the
// list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click.
export interface SeleccionSeguimiento {
filtros: Record<string, string>; etiqueta: string; corte?: string; esperados?: number | null; contexto?: ContextoLista; id: number;
}
const ETIQUETA_COHORTE = 'Cohorte del análisis epidemiológico';
/** The answer does not apply the cut-off, window or filters that were asked for: it is neither shown nor exported. */
export class SeguimientoNoCoincide extends Error {}
interface Borrador { corte?: string; meses: MesesVentana; page_size: number; filtros: Record<string, string | undefined>; }
const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string, string | undefined>) => {
const f = (x: Record<string, string | undefined>) => JSON.stringify(Object.entries(x).filter(([, v]) => !!v).sort(([k], [l]) => k.localeCompare(l)));
return f(a) === f(b);
};
/**
* Follow-up list of a domain, drawn from what `GET /<dominio>/seguimiento` announces: the filters, the columns
* and their details come with the answer. Nothing is requested until the tab is opened.
* and their details come with the answer. Nothing is requested until the tab is opened. The analysis can open it
* on a selection (a published group, whole cohort); the list keeps it until it is removed or the domain changes.
*/
@Component({
selector: 'app-seguimiento-tabla',
imports: [FormsModule],
imports: [FormsModule, TrackingExportBar, CamaPatientCard],
template: `
@if (ficha(); as patient) {
<app-cama-patient-card [summary]="patient" (back)="cerrarFicha()" />
}
<div [hidden]="!!ficha()">
<div class="title-row">
<h2>Seguimiento de {{ domainLabel }}</h2>
@if (data(); as respuesta) {
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
}
</div>
@if (seleccionMostrada(); as sel) {
<div class="seleccion" role="status">
@if (seleccionExacta()) {
<span>Pacientes de la selección del análisis epidemiológico: <strong>{{ sel }}</strong>. {{ etiquetaVentana(0) }}@if (corteSeleccion()) {, corte {{ corteSeleccion() }}}.</span>
} @else {
<span>Pacientes de la cohorte del análisis epidemiológico@if (corteSeleccion()) {, corte {{ corteSeleccion() }}}. Los filtros y la ventana son los de esta consulta.</span>
}
<button type="button" class="volver" (click)="volverAlAnalisis.emit()">Volver al análisis</button>
<button type="button" (click)="quitarSeleccion()">Quitar selección</button>
</div>
@if (diferencia(); as d) { <p class="diferencia" role="alert">{{ d }}</p> }
}
<form (ngSubmit)="aplicar()">
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
@for (m of ventanas; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
@for (m of ventanas(); track m) { <option [ngValue]="m">{{ etiquetaVentana(m) }}</option> }
</select></label>
@for (filtro of filtros(); track filtro.clave) {
<label>{{ filtro.etiqueta }} <select [name]="'filtro-' + filtro.clave" [(ngModel)]="draft.filtros[filtro.clave]">
@@ -47,19 +90,19 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
}
}
@if (data(); as respuesta) {
<p>Ventana consultada: {{ respuesta.ventana.desde }} al {{ respuesta.ventana.hasta }}.</p>
<p>Ventana consultada: {{ respuesta.ventana.meses === 0 ? etiquetaVentana(0) + ', al ' + respuesta.ventana.hasta : respuesta.ventana.desde + ' al ' + respuesta.ventana.hasta }}.</p>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr>@for (c of respuesta.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
<tbody>
@for (item of respuesta.items; track item['id_seudonimo']) {
<tr>
@for (item of respuesta.items; track identidad(item).id) {
<tr tabindex="-1" [attr.data-paciente]="identidad(item).id" (click)="abrirFicha(item, $event)">
@for (c of respuesta.columnas; track c.clave) {
<td>{{ texto(item[c.clave]) }}@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
<td>@if (c.clave === claveEnlace(respuesta, item)) { <button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirFicha(item, $event)">{{ texto(item[c.clave]) }}</button> } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
}
</tr>
} @empty { <tr><td [attr.colspan]="respuesta.columnas.length">No hay registros para los filtros aplicados.</td></tr> }
} @empty { <tr><td [attr.colspan]="respuesta.columnas.length">{{ textoVacio(respuesta) }}</td></tr> }
</tbody>
</table>
</div>
@@ -69,10 +112,13 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
<button type="button" [disabled]="respuesta.paginacion.page >= respuesta.paginacion.total_pages || estado() === 'loading'" (click)="ir(respuesta.paginacion.page + 1)">Siguiente</button>
</nav>
}
</div>
`,
styles: `
:host { display: block; min-width: 0; }
p { color: var(--issste-text-secondary); }
.title-row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem 1rem; margin-bottom: 1rem; }
.title-row h2 { margin: 0; margin-inline-end: auto; }
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
input, select, button { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px;
@@ -86,58 +132,157 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
th { background: var(--issste-background); font-weight: 600; }
small { display: block; margin-top: .35rem; }
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent);
font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
.seleccion { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-bottom: 1rem; padding: .5rem .75rem;
border-left: 4px solid var(--issste-accent); background: var(--issste-surface); color: var(--issste-text); }
.seleccion span { overflow-wrap: anywhere; min-width: 0; }
.diferencia { margin: 0 0 1rem; overflow-wrap: anywhere; }
@media (max-width: 600px) { .title-row { gap: .5rem; } form label, form input, form select { width: 100%; } }
`,
})
export class IndicadoresSeguimientoTabla implements OnChanges {
@Input({ required: true }) dominio!: Dominio;
@Input() active = false;
/** Domain name for the section title, which sits in the same row as the export buttons. */
@Input() domainLabel = '';
// The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again.
@Input() seleccion?: SeleccionSeguimiento;
private readonly service = inject(SeguimientoTablaService);
private readonly consultas = new Subject<SeguimientoTablaQuery | null>();
readonly ventanas = MESES_VENTANA;
private readonly injector = inject(Injector);
/** Tells the page that an individual record replaced the list, so it can retitle itself. */
readonly fichaAbierta = output<boolean>();
/** The way back to the analysis the selection came from. */
readonly volverAlAnalisis = output<void>();
readonly ficha = signal<CamaPatientSummary | undefined>(undefined);
private controlFicha?: HTMLElement;
private readonly consultas = new Subject<Consulta | null>();
readonly etiquetaVentana = etiquetaVentana;
readonly tamanoMaximo = PAGE_SIZE_MAX;
readonly estado = signal<Estado>('idle');
readonly mensaje = signal('');
readonly data = signal<SeguimientoTablaResponse | undefined>(undefined);
/** The name of the selection the list on screen was asked for; it is set with the answer, never ahead of it. */
readonly etiquetaDatos = signal<string | undefined>(undefined);
/** The selection of the query now applied (what the banner says). */
readonly seleccionMostrada = signal<string | undefined>(undefined);
/** Whether the list is still exactly the analysis' group (its filters, whole cohort, its cut-off) and not a refinement of the cohort. */
readonly seleccionExacta = signal(false);
readonly corteSeleccion = signal<string | undefined>(undefined);
readonly filtros = signal<SeguimientoTablaResponse['filtros_disponibles']>([]);
draft: Borrador = { meses: 3, page_size: 50, filtros: {} };
// The last query that was sent: the pages and the retry go from it, not from what is being edited.
private applied: SeguimientoTablaQuery = { meses: 3, page: 1, page_size: 50 };
private appliedEtiqueta?: string;
private activa?: SeleccionSeguimiento;
/** The cohort the list is read from while the analysis' selection is active; every query quotes it. */
private contextoActivo?: ContextoLista;
private seleccionAplicada?: number;
private iniciado = false;
private previo?: Dominio;
/** «Toda la cohorte» is offered while the analysis' cohort is active (or the form still holds it), never as a plain window. */
ventanas() { return this.contextoActivo || this.draft.meses === 0 ? MESES_VENTANA : MESES_VENTANA.filter(m => m !== 0); }
/**
* What the list says when it does not hold as many patients as the analysis counted for the selection. With the same
* cohort revision, cut-off and filter the server counts both from the same rows, so a difference breaks the contract:
* the list stays visible, but it is not exported as if it were the group that was counted.
*/
diferencia() {
const esperados = this.activa?.esperados, total = this.data()?.paginacion.total_items;
if (!this.seleccionExacta() || this.estado() !== 'ready' || esperados == null || total === undefined || esperados === total) return undefined;
return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`;
}
// The cut-off of the cohort's revision: another cut-off is another cohort at that date, so its revision is not quoted.
private contextoCorte?: string;
// A cohort that changed under a plain list is read again once, without the old revision, before it is reported.
private reintentoHecho = false;
/** The list of one query, as the server answers it (without the loading state). */
private lista(c: Consulta): Observable<Resultado> {
const { q, etiqueta } = c;
let peticion: Observable<SeguimientoTablaResponse>;
// An invalid query never leaves the browser; it reads like the server's own 400.
try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); }
return peticion.pipe(
// A selection names its patients: an answer that does not apply its window, cut-off and every filter is dropped,
// because its rows would pass for the analysis' group. A plain query shows what the answer says it applied.
map((data): Resultado => {
if ((etiqueta || q.contexto) && !consultaAplicada(q, data)) throw new SeguimientoNoCoincide('La respuesta no corresponde a la consulta');
return { estado: 'ready', data, mensaje: '', etiqueta };
}),
catchError(error => of(this.fallo(error, q))));
}
constructor() {
this.consultas.pipe(
switchMap((q): Observable<Resultado> => {
if (!q) return of({ estado: 'idle', mensaje: '' });
let peticion: Observable<SeguimientoTablaResponse>;
// An invalid query never leaves the browser; it reads like the server's own 400.
try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); }
return peticion.pipe(
map((data): Resultado => ({ estado: 'ready', data, mensaje: '' })),
catchError(error => of(this.fallo(error, q))),
startWith<Resultado>({ estado: 'loading', mensaje: '' }));
switchMap((c): Observable<Resultado> => {
if (!c) return of({ estado: 'idle', mensaje: '' });
return this.lista(c).pipe(startWith<Resultado>({ estado: 'loading', mensaje: '' }));
}),
takeUntilDestroyed(inject(DestroyRef)),
).subscribe(r => {
// The cohort changed under a plain list: the same query is asked again, once, without the old revision, before the user hears of it.
if (r.estatus === 409 && !this.activa && this.contextoActivo && !this.reintentoHecho) {
this.reintentoHecho = true;
this.consultas.next({ q: { ...this.applied, contexto: undefined }, etiqueta: this.appliedEtiqueta });
return;
}
if (r.estado === 'ready') this.reintentoHecho = false;
this.estado.set(r.estado);
this.mensaje.set(r.mensaje);
if (r.estado === 'idle') { this.data.set(undefined); this.filtros.set([]); }
if (r.data) this.recibir(r.data);
if (r.estado === 'idle') { this.data.set(undefined); this.etiquetaDatos.set(undefined); this.filtros.set([]); }
// In the analysis' cohort a query that fails (or whose answer does not match) leaves no list on screen: the rows
// of the previous query would pass for the one the banner names.
if ((r.estado === 'error' || r.estado === 'pending') && (this.contextoActivo || r.mensaje === MENSAJE_NO_COINCIDE)) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
if (r.data) { this.recibir(r.data); this.etiquetaDatos.set(r.etiqueta); }
});
}
ngOnChanges() {
if (this.previo !== this.dominio) {
if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); }
this.previo = this.dominio; this.iniciado = false; this.consultas.next(null);
this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 };
// The selection belongs to the domain it was made in.
this.appliedEtiqueta = undefined; this.activa = undefined; this.contextoActivo = undefined; this.seleccionAplicada = undefined;
this.contextoCorte = undefined; this.reintentoHecho = false;
this.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined);
}
const sel = this.seleccion;
if (this.active && sel && sel.id !== this.seleccionAplicada) {
this.seleccionAplicada = sel.id; this.iniciado = true; this.activa = sel; this.contextoActivo = sel.contexto; this.contextoCorte = sel.corte;
this.reintentoHecho = false;
// Whatever was on screen belongs to another query: it goes before the selection is asked for.
this.data.set(undefined); this.etiquetaDatos.set(undefined);
if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); }
this.draft = { ...this.draft, meses: 0, corte: sel.corte ?? this.draft.corte, filtros: { ...sel.filtros } };
this.aplicar(sel.etiqueta);
return;
}
if (this.active && !this.iniciado) {
this.iniciado = true;
this.consultas.next({ q: this.applied });
}
if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(this.applied); }
}
private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado {
return { ...this.falloBase(error, q), estatus: error instanceof HttpErrorResponse ? error.status : undefined };
}
private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado {
if (error instanceof HttpErrorResponse && error.status === 404 && this.dominio === 'cama') return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' };
// A first page that does not exist yet is the list's own pending state; a later page that fails is an error.
if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' };
if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' };
// A cohort's list: the group was too small to publish or access was not granted; the cohort changed after the count; or it is not configured.
if (error instanceof HttpErrorResponse && error.status === 403) return { estado: 'error', mensaje: 'Esta lista no está disponible: no hay acceso, o la selección tiene muy pocos pacientes para publicarse.' };
if (error instanceof HttpErrorResponse && error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió desde que se calculó el análisis. Vuelve al análisis, consúltalo de nuevo y abre otra vez el grupo.' };
if (error instanceof HttpErrorResponse && error.status === 503) return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' };
if (error instanceof SeguimientoNoCoincide) return { estado: 'error', mensaje: MENSAJE_NO_COINCIDE };
if (error instanceof SeguimientoInvalido) return { estado: 'error', mensaje: 'La respuesta del servicio no tiene el formato esperado.' };
return { estado: 'error', mensaje: 'No se pudo consultar el seguimiento. Intenta nuevamente.' };
}
@@ -149,15 +294,69 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size,
filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) };
this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size;
// A list read from the cohort says which one (and its revision): the next pages and the files quote it.
this.contextoActivo = contextoDe(data); this.contextoCorte = data.corte;
this.applied = { ...this.applied, contexto: this.contextoActivo };
}
aplicar() {
// The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort
// included; anything else is the user's own query, with a window of months.
aplicar(seleccion?: string) {
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros };
const activa = this.activa, contexto = this.contextoActivo;
const exacta = !!seleccion || (!!activa && this.draft.meses === 0 && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte));
// In the cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months.
// The banner names the analysis' selection, or the cohort of the analysis once the user has refined it.
const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto && activa ? ETIQUETA_COHORTE : undefined);
if (!contexto && this.draft.meses === 0) this.draft = { ...this.draft, meses: 3 };
this.seleccionMostrada.set(etiqueta);
this.seleccionExacta.set(!!etiqueta && exacta);
this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined);
this.appliedEtiqueta = etiqueta;
// Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one.
const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte;
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros,
contexto: otroCorte ? undefined : contexto };
// A new query of the cohort starts from nothing on screen: what was there belongs to the previous one.
if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
this.applied = q;
this.consultas.next(q);
this.consultas.next({ q, etiqueta });
}
// Leaving the analysis' selection returns to the habitual list: the regular window, no filters, the cohort's new revision.
quitarSeleccion() {
this.draft = { ...this.draft, meses: 3, filtros: {} };
this.activa = undefined; this.contextoActivo = undefined;
this.aplicar();
}
ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); }
reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta }); }
abrirFicha(item: Record<string, SeguimientoValor>, evento: Event) {
const origen = evento.target instanceof HTMLElement ? evento.target : null;
// A click on the row opens the record unless it landed on another control; the id button always does.
if (evento.currentTarget instanceof HTMLTableRowElement && origen?.closest('button, a, input, select, textarea')) return;
const corte = this.data()?.corte;
const resumen = corte ? toCamaPatientSummary(item, corte, this.data()?.columnas) : null;
if (!resumen || this.estado() !== 'ready') return;
evento.stopPropagation();
this.controlFicha = evento.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined;
this.ficha.set(resumen);
this.fichaAbierta.emit(true);
}
cerrarFicha() {
this.ficha.set(undefined);
this.fichaAbierta.emit(false);
const control = this.controlFicha;
afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector });
}
// The cohort answers an empty page only for a whole cohort without filters that has no patient at the cut-off.
textoVacio(r: SeguimientoTablaResponse) {
const sinFiltros = Object.values(r.filtros).every(v => !v);
return r.cohorte && r.ventana.meses === 0 && sinFiltros ? 'Sin pacientes para el corte seleccionado.' : 'No hay registros para los filtros aplicados.';
}
ir(page: number) { if (page >= 1) this.consultas.next(this.applied = { ...this.applied, page }); }
reintentar() { this.consultas.next(this.applied); }
detalles(c: SeguimientoColumna) { return c.detalles ?? []; }
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(item: Record<string, SeguimientoValor>): IdentidadPaciente { return identidadDe(item)!; }
claveEnlace(r: SeguimientoTablaResponse, item: Record<string, SeguimientoValor>) { return columnaEnlace(r.columnas, this.identidad(item).campo); }
texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); }
}
const MENSAJE_NO_COINCIDE = 'La respuesta del servicio no corresponde a la selección consultada, por lo que no se muestra. Intenta nuevamente.';
@@ -4,9 +4,10 @@
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
}
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
<h2>Seguimiento de {{ domainLabel }}</h2>
@if (dominio !== 'cama') { <h2>Seguimiento de {{ domainLabel }}</h2> }
@if (dominio === 'cama') {
<app-seguimiento-tabla [dominio]="dominio" [active]="active" />
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
(volverAlAnalisis)="volverAlAnalisis.emit()" />
} @else if (dominio !== 'cacu') {
<p>El seguimiento aún no está disponible.</p>
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
@@ -37,14 +38,14 @@
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
@if (data; as response) {
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
<tbody>
@for (item of response.items; track item.id_seudonimo) {
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="item.id_seudonimo">
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirPaciente(item, $event)">{{ item.id_seudonimo }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
@for (item of response.items; track identidad(item).id) {
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
@@ -1,4 +1,4 @@
import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Injector, Input, OnChanges, output } from '@angular/core';
import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Injector, Input, OnChanges, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@@ -7,9 +7,10 @@ import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimient
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { MatButtonModule } from '@angular/material/button';
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service';
@Component({
@@ -23,6 +24,10 @@ export class IndicadoresTracking implements OnChanges {
@Input({ required: true }) domainLabel = '';
@Input() dominio: Dominio = 'tea';
@Input() active = false;
/** CaMa: the patients of a curve or a cell of the analysis, for its follow-up list. */
@Input() seleccion?: SeleccionSeguimiento;
/** CaMa: the way back to the analysis the selection came from. */
readonly volverAlAnalisis = output<void>();
private readonly service = inject(CacuSeguimientoService);
private readonly indicators = inject(IndicadoresService);
private readonly destroy = inject(DestroyRef);
@@ -30,6 +35,9 @@ export class IndicadoresTracking implements OnChanges {
private readonly injector = inject(Injector);
readonly pacienteDetalle = inject(PacienteDetalleState);
readonly fichaPacienteAbierta = output<boolean>();
/** CaMa's record opens inside its own table; this hides the section title while it does. */
readonly camaFichaAbierta = signal(false);
cambiaFichaCama(abierta: boolean) { this.camaFichaAbierta.set(abierta); this.fichaPacienteAbierta.emit(abierta); }
private controlPaciente?: HTMLElement;
private readonly requests = new Subject<SeguimientoQuery | null>();
private initialized = false;
@@ -70,7 +78,9 @@ export class IndicadoresTracking implements OnChanges {
}
ngOnChanges() {
if (this.previousDomain !== this.dominio) {
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
// Changing domain removes the table that holds CaMa's record, so the page is told here that no record shows.
if (this.pacienteDetalle.estado().tipo !== 'cerrado' || this.camaFichaAbierta()) this.fichaPacienteAbierta.emit(false);
this.camaFichaAbierta.set(false);
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined;
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
@@ -88,6 +98,10 @@ export class IndicadoresTracking implements OnChanges {
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
this.load({ ...this.applied, page });
}
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(paciente: SeguimientoPaciente): IdentidadPaciente { return identidadDe(paciente)!; }
// The rows of a page identify their patient by one field; an empty page keeps the legacy wording.
etiquetaIdentidad(respuesta: SeguimientoResponse) { return ETIQUETA_IDENTIDAD[respuesta.items[0] ? this.identidad(respuesta.items[0]).campo : 'id_seudonimo']; }
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return;
evento.stopPropagation();
@@ -0,0 +1,47 @@
@let p = summary();
<div class="toolbar">
<button class="back-button" mat-stroked-button type="button" (click)="back.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
<button class="export-button" mat-stroked-button type="button" [disabled]="generating()" (click)="exportPdf()"><mat-icon aria-hidden="true">picture_as_pdf</mat-icon><span>Exportar ficha PDF</span></button>
@if (generating()) { <p class="toolbar-message" role="status">Generando PDF…</p> }
@if (failed()) { <p class="toolbar-message" role="alert">No se pudo generar el PDF. Intenta nuevamente.</p> }
</div>
<header>
<h2 #title tabindex="-1">Paciente {{ p.patientId }}</h2>
<p>Fecha de corte: {{ p.cutoff }}.</p>
<dl class="summary">
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
</dl>
</header>
<div class="detail-grid">
<mat-card class="mammography-card" appearance="outlined" aria-labelledby="mastografia-title">
<mat-card-header><h3 id="mastografia-title">Mastografía</h3></mat-card-header>
<mat-card-content>
<ul>
<li><strong>Última mastografía</strong><span>Categoría BI-RADS: {{ p.birads ?? notAvailable }}</span><span>Fecha: {{ p.mammographyDate ?? notAvailable }}</span></li>
</ul>
</mat-card-content>
</mat-card>
<mat-card class="histopathology-card" appearance="outlined" aria-labelledby="histopatologia-title">
<mat-card-header><h3 id="histopatologia-title">Histopatología</h3></mat-card-header>
<mat-card-content>
<ul>
<li><strong>Resultado histopatológico</strong><span>Resultado: {{ p.histopathology ?? notAvailable }}</span><span>{{ p.biopsyDateLabel ?? 'Fecha de biopsia' }}: {{ p.biopsyDate ?? notAvailable }}</span></li>
</ul>
</mat-card-content>
</mat-card>
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
<mat-card-content>
<ul>
@for (item of placeholders; track item.key) {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
}
</ul>
<p class="availability">{{ recommendationsUnavailable }}</p>
</mat-card-content>
</mat-card>
</div>
@@ -0,0 +1,26 @@
:host { display: block; min-width: 0; color: var(--issste-text); overflow-wrap: anywhere; }
header { margin-block: 1.5rem; }
h2 { margin-block: .5rem 1rem; font-size: 1.65rem; }
h3 { margin-block: 0 1rem; font-size: 1.2rem; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem 1rem; }
.toolbar-message { flex: 0 0 100%; margin: 0; }
.export-button { margin-inline-start: auto; }
.back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; }
.back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; }
.availability { margin-block: .75rem; color: var(--issste-text-secondary); }
.summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; }
dt { color: var(--issste-text-secondary); font-size: .9rem; }
dd { margin: .4rem 0 0; font-weight: 600; }
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "mammography histopathology" "prognosis prognosis"; gap: 1rem; align-items: start; }
mat-card { min-width: 0; background: var(--issste-surface); color: inherit; border-color: var(--issste-border); }
.mammography-card { grid-area: mammography; }
.histopathology-card { grid-area: histopathology; }
.prognosis-card { grid-area: prognosis; }
ul { list-style: none; padding: 0; margin: 0; }
li { padding-block: .75rem; border-top: 1px solid var(--issste-border); }
li:first-child { border-top: 0; }
li span { display: block; margin-top: .4rem; }
button { min-height: 44px; color: var(--issste-text); border-color: var(--issste-border); }
@media (max-width: 48rem) {
.detail-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "mammography" "histopathology" "prognosis"; }
}
@@ -0,0 +1,129 @@
// Covers CaMa's individual record: how a follow-up row becomes its summary, what the card shows (only fields the list
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { CamaPatientCard } from './cama-patient-card';
import { CamaPatientSummary, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
const complete = () => rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!;
const incomplete = () => rows().find(r => r['biopsia'] === null)!;
describe('Ficha CaMa: resumen', () => {
// Fails if a field of the row is mapped to another one or lost on the way to the card.
it('reads every field the follow-up row carries', () => {
const row = complete();
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
});
});
// Fails if a missing value is turned into text or a number (for example 0 days), which would read as clinical data.
it('keeps a missing value as null', () => {
const summary = toCamaPatientSummary(incomplete(), '2026-10-20')!;
expect(summary.histopathology).toBeNull();
expect(summary.daysMammographyToDiagnosis).toBeNull();
});
// Fails if a row without an identifier opens a record for nobody.
it('has no summary for a row without an identifier', () => {
expect(toCamaPatientSummary({ ...complete(), id_seudonimo: null }, '2026-10-20')).toBeNull();
expect(toCamaPatientSummary({ ...complete(), id_seudonimo: '' }, '2026-10-20')).toBeNull();
});
});
describe('Ficha CaMa: componente', () => {
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
const root = () => fixture.nativeElement as HTMLElement;
function montar(summary: CamaPatientSummary) {
fixture = TestBed.createComponent(CamaPatientCard);
fixture.componentRef.setInput('summary', summary);
fixture.detectChanges();
}
afterEach(() => fixture?.destroy());
// Fails if a note or warning line comes back to the record.
it('has no note or warning line', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
expect(root().querySelector('.note, [role="note"]')).toBeNull();
expect(root().textContent).not.toContain('Documento de consulta');
});
// Fails if the card shows something other than what the list carried, or hides the identifier and cut-off.
it('shows the summary, the mammography and the histopathology of the row', () => {
const row = complete();
montar(toCamaPatientSummary(row, '2026-10-20')!);
const text = root().textContent!.replace(/\s+/g, ' ');
for (const value of [`Paciente ${row['id_seudonimo']}`, 'Fecha de corte: 2026-10-20', String(row['estatus']), String(row['prioridad']), String(row['birads']),
String(row['mastografia_fecha']), String(row['biopsia']), String(row['biopsia_fecha']), String(row['dias_mastografia_diagnostico'])]) expect(text).toContain(value);
});
// Fails if a missing value is left blank or invented instead of reading "No disponible".
it('reads each missing value as "No disponible"', () => {
montar(toCamaPatientSummary(incomplete(), '2026-10-20')!);
const text = root().textContent!;
expect(text).toContain('Resultado: No disponible');
expect(text).toContain('Fecha de biopsia: No disponible');
expect(text).toContain('Días de mastografía a diagnóstico');
});
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const items = [...root().querySelectorAll('[data-pronostico]')];
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']);
for (const item of items) {
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
expect(item.textContent).not.toMatch(/\d/);
}
expect(root().textContent).toContain(RECOMMENDATIONS_UNAVAILABLE);
});
// Fails if the record opens without moving focus to its title, which strands keyboard and screen-reader users.
it('moves focus to its title when it opens', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
expect(document.activeElement).toBe(root().querySelector('h2'));
});
// Fails if the PDF button stops downloading, or the file name starts carrying the patient identifier.
it('downloads the record as a PDF named without the patient', async () => {
const downloads: string[] = [];
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { downloads.push(this.download); });
const summary = toCamaPatientSummary(complete(), '2026-10-20')!;
montar(summary);
[...root().querySelectorAll('button')].find(b => b.textContent!.includes('Exportar ficha PDF'))!.click();
for (let i = 0; i < 100 && !downloads.length; i++) await new Promise(r => setTimeout(r, 50));
expect(downloads).toHaveLength(1);
expect(downloads[0]).toMatch(/^ficha-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.pdf$/);
expect(downloads[0]).not.toContain(summary.patientId);
vi.restoreAllMocks();
}, 30000);
// Fails if the two buttons leave the row above the title: back on the left, the PDF export on the right.
it('puts "Regresar" first and "Exportar ficha PDF" last in one row above the identifier', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const row = root().querySelector('.toolbar')!;
const buttons = [...row.querySelectorAll('button')];
expect(buttons).toHaveLength(2);
expect(buttons[0].textContent).toContain('Regresar');
expect(buttons[1].textContent).toContain('Exportar ficha PDF');
expect(row.compareDocumentPosition(root().querySelector('h2')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(root().querySelector('header')!.querySelector('button')).toBeNull();
});
// Fails if the back button stops telling the list to return.
it('emits back when "Regresar" is pressed', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
let backs = 0;
fixture.componentInstance.back.subscribe(() => backs++);
[...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click();
expect(backs).toBe(1);
});
});
@@ -0,0 +1,48 @@
import { AfterViewInit, Component, ElementRef, input, output, signal, viewChild } from '@angular/core';
import { downloadBlob, exportFilename } from '../../export/download-file';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
/**
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
* survival and prognostic factors are placeholders until a validated model supplies them.
*/
@Component({
selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule],
templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss',
})
export class CamaPatientCard implements AfterViewInit {
readonly summary = input.required<CamaPatientSummary>();
readonly back = output<void>();
readonly notAvailable = NOT_AVAILABLE;
readonly placeholders = PROGNOSIS_PLACEHOLDERS;
readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE;
readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE;
private readonly title = viewChild<ElementRef<HTMLElement>>('title');
readonly generating = signal(false);
readonly failed = signal(false);
ngAfterViewInit() { this.title()?.nativeElement.focus(); }
/** Downloads the record as a PDF. The file name carries the report and the cut-off, never the patient. */
async exportPdf() {
if (this.generating()) return;
this.generating.set(true); this.failed.set(false);
try {
const patient = this.summary();
// The PDF library downloads only when the button is used.
const blob = await (await import('./cama-patient-pdf')).buildCamaPatientPdf(patient);
downloadBlob(blob, exportFilename('ficha-cancer-de-mama', patient.cutoff, 'pdf'));
} catch {
this.failed.set(true);
} finally {
this.generating.set(false);
}
}
}
@@ -0,0 +1,69 @@
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
// the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { PDF_CONFIDENTIAL } from '../../export/pdf-template';
import { buildCamaPatientPdf, camaPatientDocument, PATIENT_TITLE } from './cama-patient-pdf';
import { PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30));
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
const complete = () => toCamaPatientSummary(rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!, '2026-10-20')!;
const incomplete = () => toCamaPatientSummary(rows().find(r => r['biopsia'] === null)!, '2026-10-20')!;
const definition = (p = complete(), logo?: string) => camaPatientDocument(p, NOW, logo) as Record<string, any>;
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('Ficha CaMa: PDF individual', () => {
// Fails if the record stops sharing the report's frame (header, footer, properties) or leaves portrait.
it('uses the institutional frame in portrait, with the title in the header and the confidentiality line in the footer', () => {
const d = definition(complete(), 'data:image/png;base64,AAAA');
expect(d['pageOrientation']).toBe('portrait');
expect(d['info']).toMatchObject({ title: PATIENT_TITLE, author: 'ISSSTELEON' });
expect(texts(d['header']())).toEqual(expect.arrayContaining([PATIENT_TITLE]));
expect(JSON.stringify(d['header']())).toContain('"image":"logo"');
expect(texts(d['footer'](1, 1))).toEqual(expect.arrayContaining(['Página 1 de 1', PDF_CONFIDENTIAL]));
});
// Fails if a field of the record is left out of the document or printed under another label.
it('prints each field of the record under its label', () => {
const p = complete();
const found = texts(definition(p)['content']);
for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia', 'Días de mastografía a diagnóstico']) expect(found).toContain(t);
});
// Fails if a missing value is printed as something other than "No disponible".
it('prints a missing value as "No disponible"', () => {
const found = texts(definition(incomplete())['content']);
expect(found.filter(t => t === 'No disponible').length).toBeGreaterThanOrEqual(2);
});
// Fails if a placeholder gains a figure or an explanation other than "unavailable".
it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => {
const found = texts(definition()['content']);
for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3);
});
// Fails if the document carries a platform identifier field.
it('contains no platform identifier', () => {
const p = complete();
expect(texts(definition(p)['info'])).not.toContain('pac_id');
});
// Fails if the document no longer renders to a real PDF file.
it('renders a PDF file', async () => {
const blob = await buildCamaPatientPdf(complete(), NOW);
const bytes = new TextDecoder('latin1').decode(new Uint8Array(await blob.arrayBuffer()));
expect(bytes.startsWith('%PDF-')).toBe(true);
expect(bytes.trimEnd().endsWith('%%EOF')).toBe(true);
expect((bytes.match(/\/Type \/Page\b/g) ?? []).length).toBe(1);
}, 30000);
});
@@ -0,0 +1,41 @@
import { renderPdf, PdfDefinition } from '../../export/pdf-engine';
import { COLORS, institutionalDocument, loadLogo } from '../../export/pdf-template';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
export const PATIENT_TITLE = 'Ficha de paciente — Cáncer de mama';
const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 };
const value = (v: string | number | null) => (v === null ? { text: NOT_AVAILABLE, italics: true, color: COLORS.muted } : { text: String(v) });
const section = (title: string, rows: [string, string | number | null][]) => [
{ text: title, style: 'h2' },
{ table: { widths: [170, '*'], body: rows.map(([label, v]) => [{ text: label, bold: true }, value(v)]) }, layout: rule },
];
/** The document definition of one patient's record. Exported so its content can be checked without rendering. */
export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo?: string): PdfDefinition {
return institutionalDocument({ title: PATIENT_TITLE, logo, now, orientation: 'portrait' }, [
{ text: `Paciente ${patient.patientId}`, style: 'h1' },
{ text: `Fecha de corte: ${patient.cutoff}`, style: 'muted' },
...section('Resumen', [
[patient.idLabel, patient.patientId],
['Grupo de edad', patient.ageGroup],
['Estatus de seguimiento', patient.status],
['Prioridad', patient.priority],
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
]),
...section('Mastografía', [['Categoría BI-RADS', patient.birads], ['Fecha de la mastografía', patient.mammographyDate]]),
...section('Histopatología', [['Resultado histopatológico', patient.histopathology], [patient.biopsyDateLabel ?? 'Fecha de biopsia', patient.biopsyDate]]),
...section('Pronóstico y recomendaciones', [
...PROGNOSIS_PLACEHOLDERS.map(p => [p.label, PROGNOSIS_UNAVAILABLE] as [string, string]),
['Recomendaciones', RECOMMENDATIONS_UNAVAILABLE],
]),
{ text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] },
]);
}
/** A one-patient PDF with the same frame as the follow-up report. */
export async function buildCamaPatientPdf(patient: CamaPatientSummary, now = new Date(), logo?: string): Promise<Blob> {
return renderPdf(camaPatientDocument(patient, now, logo ?? await loadLogo()));
}
@@ -0,0 +1,63 @@
import { TrackingRow } from '../../export/tracking-export.models';
import { CampoIdentidad, ETIQUETA_IDENTIDAD, identidadDe } from '../../paciente-identidad';
export const NOT_AVAILABLE = 'No disponible';
/**
* What the CaMa follow-up list says about one patient, read from the row that was clicked. `patientId` is the
* identifier the row carries (`idField` says which field); the record only shows it.
*/
export interface CamaPatientSummary {
patientId: string;
idField: CampoIdentidad;
/** What the identifier is called on screen and in the file. */
idLabel: string;
cutoff: string;
ageGroup: string | null;
status: string | null;
priority: string | null;
birads: string | null;
mammographyDate: string | null;
histopathology: string | null;
biopsyDate: string | null;
/** What the list calls that date: the cohort's list gives the date of the biopsy report, which can be known before its result is. */
biopsyDateLabel?: string;
daysMammographyToDiagnosis: number | null;
}
/** Placeholders for results that exist only once a validated model and its clinical definition do. */
export const PROGNOSIS_PLACEHOLDERS = [
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
{ key: 'survival', label: 'Supervivencia' },
{ key: 'factors', label: 'Factores pronóstico' },
] as const;
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
export const RECOMMENDATIONS_UNAVAILABLE = 'Recomendaciones no disponibles.';
const text = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : null);
/**
* The patient summary of a follow-up row, or `null` when the row has no identity that can be trusted. `columnas` are the ones the
* list announced: the label it gives to the biopsy date is kept, so the record says the same as the list.
*/
export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: readonly { clave: string; detalles?: readonly { clave: string; etiqueta: string }[] }[] = []): CamaPatientSummary | null {
const identity = identidadDe(row);
if (!identity) return null;
const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta;
const days = row['dias_mastografia_diagnostico'];
return {
patientId: identity.id,
idField: identity.campo,
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
cutoff,
ageGroup: text(row['grupo_edad']),
status: text(row['estatus']),
priority: text(row['prioridad']),
birads: text(row['birads']),
mammographyDate: text(row['mastografia_fecha']),
histopathology: text(row['biopsia']),
biopsyDate: text(row['biopsia_fecha']),
...(etiquetaFecha ? { biopsyDateLabel: etiquetaFecha } : {}),
daysMammographyToDiagnosis: typeof days === 'number' && Number.isFinite(days) ? days : null,
};
}
@@ -1,10 +1,10 @@
@if (estado.tipo !== 'cerrado') {
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
<header>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.id_seudonimo }}</h2>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.identidad.id }}</h2>
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
<dl class="summary">
<div><dt>Identificador seudónimo</dt><dd>{{ estado.resumen.id_seudonimo }}</dd></div>
<div><dt>{{ etiquetaIdentidad }}</dt><dd>{{ estado.resumen.identidad.id }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
@@ -79,7 +79,7 @@
</mat-card>
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
<mat-card-content><app-paciente-riesgo-tabla /></mat-card-content>
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
</mat-card>
</div>
}
@@ -1,8 +1,9 @@
import { Observable } from 'rxjs';
import { IdentidadPaciente } from '../paciente-identidad';
/** Snapshot of the received row, independent of the Seguimiento transport contract. */
export interface PacienteResumen {
id_seudonimo: string;
identidad: IdentidadPaciente;
grupoEdad: string | null;
estatus: string | null;
corte: string;
@@ -27,7 +28,8 @@ export interface PacienteDetalle {
}
export interface PacienteDetalleProvider {
obtener(idSeudonimo: string): Observable<PacienteDetalle | null>;
/** `id` is the patient identifier of the row; a patient the provider does not know is `null`. */
obtener(id: string): Observable<PacienteDetalle | null>;
}
export type PacienteDetalleEstado =
@@ -5,9 +5,9 @@ import { PacienteDetalleProvider } from './paciente-detalle.models';
@Injectable({ providedIn: 'root' })
export class PacienteDetalleMockProvider implements PacienteDetalleProvider {
obtener(idSeudonimo: string) {
obtener(id: string) {
return defer(() => {
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo);
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === id);
// Each read owns its data; consumers cannot mutate another selection or the fixtures.
return of(detalle ? structuredClone(detalle) : null);
});
@@ -3,6 +3,7 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Subject, of, throwError } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
@@ -10,9 +11,9 @@ import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.mod
import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
describe('Proveedor de detalle sintético', () => {
it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => {
@@ -59,7 +60,7 @@ describe('Estado de selección del paciente', () => {
const estado = state.estado();
expect(estado.tipo).toBe('no-disponible');
if (estado.tipo !== 'cerrado') {
expect(estado.resumen.id_seudonimo).toBe('001');
expect(estado.resumen.identidad.id).toBe('001');
expect(estado.resumen.vph?.resultado).toBe('NEGATIVO');
expect(estado.resumen.vph?.genotipo16y18).toBeNull();
expect(estado.resumen.diasTomaDiagnostico).toBe(0);
@@ -108,7 +109,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
let root: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
fixture = TestBed.createComponent(IndicadoresTracking);
root = fixture.nativeElement;
http = TestBed.inject(HttpTestingController);
@@ -166,7 +168,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
fixture.detectChanges();
const estado = fixture.componentInstance.pacienteDetalle.estado();
expect(estado.tipo).toBe('disponible');
if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo);
if (estado.tipo === 'disponible') expect(estado.resumen.identidad.id).toBe(pacientes[1].id_seudonimo);
volver();
expect(row).toBe(document.activeElement);
http.expectNone(() => true);
@@ -238,20 +240,15 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
http.expectNone(() => true);
});
it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => {
// Fails if a row that only has id_seudonimo asks the risk route (which takes a pac_id) or leaves no «no disponible» state.
it('una ficha de un renglón con solo id_seudonimo no consulta el riesgo y lo declara no disponible', () => {
const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
const obtener = vi.spyOn(provider, 'obtener');
try {
const detail = abrir();
const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Información simulada');
expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
expect(obtener).toHaveBeenCalledExactlyOnceWith();
volver();
const otra = abrir(1);
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
const tarjeta = abrir().querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(tarjeta.querySelector('table')).toBeNull();
expect(obtener).not.toHaveBeenCalled();
http.expectNone(() => true);
} finally { obtener.mockRestore(); }
});
@@ -2,6 +2,7 @@ import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core'
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, catchError, defer, map, of, switchMap } from 'rxjs';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { identidadDe } from '../paciente-identidad';
import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models';
import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider';
import { AltaRegistroTemporal } from './paciente-registro.models';
@@ -17,14 +18,14 @@ export class PacienteDetalleState {
readonly estado = this.actual.asReadonly();
readonly registrosTemporales = computed(() => {
const estado = this.actual();
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo);
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.identidad.id);
});
constructor() {
this.seleccion.pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.identidad.id)).pipe(
map(detalle => {
if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) {
if (detalle && (detalle.id_seudonimo !== resumen.identidad.id || detalle.origen !== 'sintetico')) {
throw new Error('Detalle incompatible con la selección');
}
return detalle
@@ -38,8 +39,10 @@ export class PacienteDetalleState {
}
abrir(paciente: SeguimientoPaciente, corte: string) {
const identidad = identidadDe(paciente);
if (!identidad) return;
const resumen: PacienteResumen = {
id_seudonimo: paciente.id_seudonimo,
identidad,
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
estatus: paciente.estatus.etiqueta,
corte,
@@ -65,7 +68,7 @@ export class PacienteDetalleState {
agregarRegistro(alta: AltaRegistroTemporal) {
const estado = this.actual();
if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false;
return this.sesion.agregar(alta.id_seudonimo, alta.registro);
if (estado.tipo === 'cerrado' || estado.resumen.identidad.id !== alta.paciente.id) return false;
return this.sesion.agregar(alta.paciente.id, alta.registro);
}
}
@@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente } from '../paciente-identidad';
import { PacienteDetalleEstado } from './paciente-detalle.models';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
@@ -31,19 +32,22 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
ngOnDestroy() { this.dialogoActivo?.close(); }
get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; }
/** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */
get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; }
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
abrirRegistro(tipo: TipoRegistroTemporal) {
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
const id_seudonimo = this.estado.resumen.id_seudonimo;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; id_seudonimo: string }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
const paciente = this.estado.resumen.identidad;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, paciente }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false,
});
this.dialogoActivo = ref;
ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => {
this.dialogoActivo = undefined;
if (registro) this.registroAgregado.emit({ id_seudonimo, registro });
if (registro) this.registroAgregado.emit({ paciente, registro });
});
}
etiquetaCitologia(resultado: string | null, calidad: string | null) {
@@ -1,7 +1,7 @@
<h2 mat-dialog-title>{{ titulo }}</h2>
<form [formGroup]="form" (ngSubmit)="agregar()">
<mat-dialog-content>
<p>Paciente {{ data.id_seudonimo }}</p>
<p>Paciente {{ data.paciente.id }}</p>
<div class="fields">
<mat-form-field appearance="outline">
<mat-label>{{ etiquetaTipo }}</mat-label>
@@ -1,4 +1,5 @@
import { Component, DestroyRef, inject } from '@angular/core';
import { IdentidadPaciente } from '../paciente-identidad';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -10,7 +11,7 @@ import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO,
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; }
export interface RegistroDialogData { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente; }
const opcionValida = (catalogo: Readonly<Record<string, string>>): ValidatorFn =>
control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true };
@@ -7,17 +7,21 @@ import { MatSelectHarness } from '@angular/material/select/testing';
import { MatInputHarness } from '@angular/material/input/testing';
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
import { MatDialog } from '@angular/material/dialog';
import { firstValueFrom } from 'rxjs';
import { firstValueFrom, of } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
import { TipoRegistroTemporal } from './paciente-registro.models';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
@@ -31,7 +35,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
let dialog: MatDialog;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
http = TestBed.inject(HttpTestingController);
dialog = TestBed.inject(MatDialog);
montarTracking();
@@ -130,7 +135,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo);
expect(almacenado.paciente).toBe(pacientes[0].id_seudonimo);
expect(almacenado.origen).toBe('sesion-demostracion');
expect(almacenado.fecha).toBe('2026-10-26');
http.expectNone(() => true);
@@ -274,7 +279,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
const a = primero.get(PacienteDetalleState);
const b = segundo.get(PacienteDetalleState);
a.abrir(pacientes[0], fixtureData.corte);
expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
expect(a.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
a.cerrar();
expect(a.registrosTemporales()).toEqual([]);
primero.destroy();
@@ -282,7 +287,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
expect(b.registrosTemporales()).toHaveLength(1);
b.abrir(pacientes[1], fixtureData.corte);
expect(b.registrosTemporales()).toEqual([]);
expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
expect(b.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
} finally {
if (!primero.destroyed) primero.destroy();
segundo.destroy();
@@ -1,3 +1,4 @@
import { IdentidadPaciente } from '../paciente-identidad';
import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos';
type ResultadoDemo = {
@@ -14,11 +15,12 @@ export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo'];
/** Independiente del resumen recibido y del historial inicial del proveedor. */
export type RegistroTemporal = Readonly<NuevoRegistroTemporal & {
id: number;
id_seudonimo: string;
/** Identifier of the patient the record was added to. */
paciente: string;
origen: 'sesion-demostracion';
}>;
export interface AltaRegistroTemporal {
id_seudonimo: string;
paciente: IdentidadPaciente;
registro: NuevoRegistroTemporal;
}
@@ -5,6 +5,7 @@ import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
describe('Fecha de calendario de registros temporales', () => {
it('acepta días reales, incluyendo años bisiestos y límites de año', () => {
@@ -35,7 +36,7 @@ describe.each(casos)('Formulario de $tipo', caso => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, paciente: identidadDe({ id_seudonimo: '001' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -82,7 +83,7 @@ describe('Resultados dependientes del estudio', () => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', paciente: identidadDe({ id_seudonimo: 'A' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
const fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -132,7 +133,7 @@ describe('Memoria de registros temporales', () => {
const sesion = TestBed.inject(PacienteRegistrosSesion);
for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true);
expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']);
expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true);
expect(sesion.paraPaciente('001').every(r => r.paciente === '001' && r.origen === 'sesion-demostracion')).toBe(true);
for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]);
sesion.agregar('toString', casos[0].registro);
expect(sesion.paraPaciente('toString')).toHaveLength(1);
@@ -11,21 +11,21 @@ export class PacienteRegistrosSesion {
private readonly registros = signal<ReadonlyMap<string, readonly RegistroTemporal[]>>(new Map());
private siguienteId = 0;
paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] {
return this.registros().get(idSeudonimo) ?? SIN_REGISTROS;
paraPaciente(id: string): readonly RegistroTemporal[] {
return this.registros().get(id) ?? SIN_REGISTROS;
}
agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean {
if (!idSeudonimo || !nuevo) return false;
agregar(id: string, nuevo: NuevoRegistroTemporal): boolean {
if (!id || !nuevo) return false;
const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion
: nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio;
const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : '');
if (!validado) return false;
const registro: RegistroTemporal = Object.freeze({
...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion',
...validado, id: ++this.siguienteId, paciente: id, origen: 'sesion-demostracion',
});
this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([
...(actual.get(idSeudonimo) ?? []), registro,
this.registros.update(actual => new Map(actual).set(id, Object.freeze([
...(actual.get(id) ?? []), registro,
])));
return true;
}
@@ -4,7 +4,6 @@
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@case ('no-disponible') {
<p role="status">Riesgo individual no disponible para esta paciente.</p>
<p class="availability">La consulta de riesgo individual aún no está habilitada.</p>
}
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
@@ -1,4 +1,4 @@
import { Component, inject } from '@angular/core';
import { Component, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@@ -11,6 +11,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
styleUrl: './paciente-riesgo-tabla.scss',
})
export class PacienteRiesgoTabla {
readonly estado = inject(PacienteRiesgoState).estado;
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>();
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
constructor() {
effect(() => this.state.pacId.set(this.pacId()));
}
}
@@ -40,9 +40,9 @@ export interface RiesgoPacienteCacu {
riesgo: LoteRiesgoCacu | null;
}
/** Deliberately no patient argument until secure identity resolution is authorized. */
/** `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(): Observable<unknown>;
obtener(pacId: string): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -1,8 +1,16 @@
import { InjectionToken } from '@angular/core';
import { of } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
},
});
@@ -12,6 +12,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
fixture.componentRef.setInput('pacId', '42');
fixture.detectChanges();
fixture.detectChanges();
return fixture;
}
@@ -20,14 +22,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify();
});
it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
const f = setup(), root: HTMLElement = f.nativeElement;
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
f.detectChanges();
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('aún no está habilitada');
expect(root.textContent).toContain('Recomendaciones no disponibles');
expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/);
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull());
});
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
@@ -35,7 +38,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith();
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
expect(root.querySelectorAll('thead th')).toHaveLength(4);
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
@@ -134,7 +137,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
expect(otra.nativeElement.querySelector('table')).toBeNull();
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
@@ -1,16 +1,23 @@
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of } from 'rxjs';
import { Injectable, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' };
@Injectable()
export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
// `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
), { initialValue: CARGANDO });
}
@@ -0,0 +1,216 @@
// Covers how a follow-up row identifies its patient (`pac_id`, or the legacy `id_seudonimo`): the rule itself, the CaMa
// table and record, the files built from the same rows, and CaCu's risk request. Fixtures: fixtures/cama_seguimiento.json
// (27 synthetic rows) rewritten to carry `pac_id`, and fixtures/cacu_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { lastValueFrom, Observable, of, toArray } from 'rxjs';
import camaData from './fixtures/cama_seguimiento.json';
import cacuData from './fixtures/cacu_seguimiento.json';
import { ExportInconsistent } from './export/tracking-export.models';
import { fetchAllTracking } from './export/tracking-export-source';
import { flatTable } from './export/tracking-export-table';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresTracking } from './indicadores-tracking';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-detalle/paciente-riesgo.provider';
import { columnaEnlace, identidadDe, identidadesDe } from './paciente-identidad';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
describe('Identidad de un renglón', () => {
// Fails if `pac_id` stops winning over the legacy field, or stops being kept as the text the server sent.
it('uses pac_id when the row has it, and the legacy id_seudonimo otherwise', () => {
expect(identidadDe({ pac_id: '42', id_seudonimo: 'P-X' })).toEqual({ campo: 'pac_id', id: '42' });
expect(identidadDe({ id_seudonimo: 'P-X' })).toEqual({ campo: 'id_seudonimo', id: 'P-X' });
expect(identidadDe({ pac_id: null, id_seudonimo: 'P-X' })?.campo).toBe('id_seudonimo');
});
// Fails if a number, a padded value or a pseudonym in `pac_id` is accepted, or if an invalid pac_id falls back to the pseudonym.
it('refuses a pac_id that is not a plain decimal string, without falling back to id_seudonimo', () => {
for (const malo of [42, '042', '-1', '4 2', '1e3', '', 'P-X', '12345678901234567890', {}]) expect(identidadDe({ pac_id: malo, id_seudonimo: 'P-X' })).toBeNull();
expect(identidadDe({ pac_id: '0' })?.id).toBe('0');
expect(identidadDe({ pac_id: '9223372036854775807' })?.id).toBe('9223372036854775807');
});
// Fails if a row with no identifier opens a record for nobody.
it('has no identity without an identifier', () => {
expect(identidadDe({})).toBeNull();
expect(identidadDe({ id_seudonimo: '' })).toBeNull();
expect(identidadDe({ id_seudonimo: 7 })).toBeNull();
});
// Fails if a page that repeats a patient, or identifies rows by different fields, can be shown.
it('refuses a page with a repeated patient or with mixed identifier fields', () => {
expect(identidadesDe([{ pac_id: '7' }, { pac_id: '8' }])).toHaveLength(2);
expect(identidadesDe([{ pac_id: '7' }, { pac_id: '7' }])).toBeNull();
expect(identidadesDe([{ pac_id: '7' }, { id_seudonimo: 'P-8' }])).toBeNull();
expect(identidadesDe([])).toEqual([]);
});
// Fails if the link moves to a column that is not the identifier when the answer announces it.
it('puts the link on the identifier column of the row, else on any identifier column, else on the first', () => {
expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }, { clave: 'pac_id' }], 'pac_id')).toBe('pac_id');
expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }], 'pac_id')).toBe('id_seudonimo');
expect(columnaEnlace([{ clave: 'a' }, { clave: 'b' }], 'pac_id')).toBe('a');
});
});
/** The CaMa fixture with `pac_id` (1..n) instead of the pseudonym. */
function conPacId(): Record<string, any> {
const d = structuredClone(camaData) as unknown as Record<string, any>;
d['columnas'][0] = { clave: 'pac_id', etiqueta: 'Identificador de paciente' };
d['items'] = (d['items'] as Record<string, any>[]).map((item, i) => {
const { id_seudonimo: _, ...rest } = item;
return { pac_id: String(i + 1), ...rest };
});
return d;
}
describe('Tabla de seguimiento con pac_id', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];
// Fails if the header or the link stop following the column the answer announces for the identifier.
it('shows the announced pac_id column and links each row by it', () => {
cargar(conPacId());
expect([...root().querySelectorAll('thead th')][0].textContent!.trim()).toBe('Identificador de paciente');
expect(enlaces().slice(0, 3).map(b => b.textContent!.trim())).toEqual(['1', '2', '3']);
expect(enlaces()[0].getAttribute('aria-label')).toBe('Ver ficha del paciente 1');
expect(root().querySelector('tbody tr')?.getAttribute('data-paciente')).toBe('1');
});
// Fails if the row that was used opens the record of another row, shows the legacy label, or the focus does not go
// back to the control that was used.
it('opens the record of the row that was used and returns focus to it', async () => {
const datos = conPacId(), items = datos['items'] as Record<string, any>[];
cargar(datos);
for (const indice of [2, 0]) {
enlaces()[indice].click(); fixture.detectChanges();
const ficha = root().querySelector('app-cama-patient-card')!;
expect(ficha.querySelector('h2')!.textContent!.trim()).toBe(`Paciente ${items[indice]['pac_id']}`);
expect(ficha.textContent).toContain(items[indice]['birads']);
expect(ficha.textContent).toContain('Identificador de paciente');
expect(ficha.textContent).not.toContain('Identificador seudónimo');
ficha.querySelector<HTMLButtonElement>('.back-button')!.click(); fixture.detectChanges();
await fixture.whenStable(); fixture.detectChanges();
expect(document.activeElement).toBe(enlaces()[indice]);
}
});
// Fails if a page that repeats a patient, or mixes pac_id with the legacy field, is drawn: its rows would open the same record.
it('does not draw an answer whose rows cannot be told apart or identify patients by different fields', () => {
const repetida = conPacId(); repetida['items'][1]['pac_id'] = repetida['items'][0]['pac_id'];
cargar(repetida);
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
expect(enlaces()).toHaveLength(0);
});
// Fails if a numeric pac_id is accepted: the contract is a decimal string.
it('does not draw an answer whose pac_id is a number', () => {
const numerica = conPacId(); numerica['items'][0]['pac_id'] = 1;
cargar(numerica);
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
});
// Fails if the legacy contract stops working while the server still sends only id_seudonimo.
it('still draws and opens a row that only has id_seudonimo', () => {
cargar(structuredClone(camaData) as unknown as Record<string, any>);
enlaces()[0].click(); fixture.detectChanges();
expect(root().querySelector('app-cama-patient-card h2')!.textContent).toContain('Paciente ' + (camaData.items[0] as any).id_seudonimo);
expect(root().querySelector('app-cama-patient-card')!.textContent).toContain('Identificador seudónimo');
});
});
describe('Archivos con pac_id', () => {
// A server over `todas`, `tam` rows a page.
function servidor(todas: Record<string, any>[], tam: number) {
return {
consultar(_d: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> {
const d = conPacId(); d['items'] = todas.slice((q.page - 1) * tam, q.page * tam);
d['paginacion'] = { page: q.page, page_size: tam, total_items: todas.length, total_pages: Math.ceil(todas.length / tam) };
return of(seguimientoTablaResponse(d));
},
} as unknown as SeguimientoTablaService;
}
const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5 };
// Fails if the file holds other rows, or the same rows in another order, than the pages of the table.
it('hands the files the same rows in the same order as the pages of the table', async () => {
const todas = conPacId()['items'] as Record<string, any>[];
const salida = await lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()));
const hecho = salida.at(-1)!;
expect(hecho.kind).toBe('done');
if (hecho.kind !== 'done') return;
expect(hecho.snapshot.items.map(i => i['pac_id'])).toEqual(todas.map(i => i['pac_id']));
const plana = flatTable(hecho.snapshot);
expect(plana.columns[0]).toMatchObject({ key: 'pac_id', label: 'Identificador de paciente' });
expect(plana.rows.map(f => f[0])).toEqual(todas.map(i => i['pac_id']));
});
// Fails if a patient that appears on two pages is exported twice as if it were two patients.
it('refuses a list in which the same patient is on two pages', async () => {
const todas = conPacId()['items'] as Record<string, any>[];
todas[7] = { ...todas[7], pac_id: todas[0]['pac_id'] };
await expect(lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()))).rejects.toBeInstanceOf(ExportInconsistent);
});
});
describe('Riesgo de CaCu por pac_id', () => {
let http: HttpTestingController;
const solicitudes: string[] = [];
function montar(items: Record<string, any>[]) {
solicitudes.length = 0;
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: (id: string) => { solicitudes.push(id); return of(null); } } }] });
const fixture = TestBed.createComponent(IndicadoresTracking);
http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('domainLabel', 'CaCu'); fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...structuredClone(cacuData), items });
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
fixture.detectChanges();
return fixture;
}
const filas = () => (structuredClone(cacuData) as unknown as { items: Record<string, any>[] }).items;
const primerEncabezado = (f: ReturnType<typeof montar>) => [...f.nativeElement.querySelectorAll('thead th')][0].textContent.trim();
const abrirSegunda = (f: ReturnType<typeof montar>) => { (f.nativeElement.querySelectorAll('tbody button.patient-link')[1] as HTMLButtonElement).click(); f.detectChanges(); };
afterEach(() => http.verify());
// Fails if the record asks for the risk with something other than the row's pac_id, or shows the legacy label for it.
it('requests the risk with the pac_id of the row and labels the identifier as the patient identifier', () => {
const items = filas().slice(0, 2).map(({ id_seudonimo: _, ...r }, i) => ({ pac_id: String(40 + i), ...r }));
const fixture = montar(items);
expect(primerEncabezado(fixture)).toBe('Identificador de paciente');
abrirSegunda(fixture);
expect(solicitudes).toEqual(['41']);
expect(fixture.nativeElement.querySelector('app-paciente-detalle h2').textContent).toContain('Paciente 41');
fixture.destroy();
});
// Fails if the migration alias wins over pac_id: a hash kept in id_seudonimo must never reach the risk route.
it('prefers pac_id over the legacy alias that rows carry during the migration', () => {
const items = filas().slice(0, 2).map((r, i) => ({ ...r, pac_id: String(40 + i) }));
const fixture = montar(items);
expect(primerEncabezado(fixture)).toBe('Identificador de paciente');
abrirSegunda(fixture);
expect(solicitudes).toEqual(['41']);
fixture.destroy();
});
// Fails if a legacy value is sent to the risk route, which only accepts a pac_id.
it('does not request the risk of a row that only has id_seudonimo', () => {
const fixture = montar(filas().slice(0, 2));
expect(primerEncabezado(fixture)).toBe('Identificador seudónimo');
abrirSegunda(fixture);
expect(solicitudes).toEqual([]);
expect(fixture.nativeElement.querySelector('app-paciente-riesgo-tabla').textContent).toContain('Riesgo individual no disponible');
fixture.destroy();
});
});
@@ -0,0 +1,54 @@
// How a follow-up row says who its patient is: `pac_id`, or the legacy `id_seudonimo` that servers may still send.
/** The fields that can identify a patient on a row, in order of precedence. */
export const CAMPOS_IDENTIDAD = ['pac_id', 'id_seudonimo'] as const;
export type CampoIdentidad = typeof CAMPOS_IDENTIDAD[number];
export interface IdentidadPaciente {
/** The field the identifier came from: `pac_id` wins over the legacy `id_seudonimo`. */
campo: CampoIdentidad;
/** The identifier as sent, scoped to the domain it was read in. `pac_id` is a decimal string. */
id: string;
}
/** What the row's identifier is called on screen and in the files, by the field it comes from. */
export const ETIQUETA_IDENTIDAD: Readonly<Record<CampoIdentidad, string>> = {
pac_id: 'Identificador de paciente',
id_seudonimo: 'Identificador seudónimo',
};
// No leading zeros and no sign: the value is compared and sent as text, so it has one spelling.
const PAC_ID = /^(0|[1-9][0-9]{0,18})$/;
/** The fields of a row that matter here; a typed row or a plain record both fit. */
export interface FilaConIdentidad { readonly pac_id?: unknown; readonly id_seudonimo?: unknown }
const texto = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
/**
* The identity of a row, or `null` when it has none that can be trusted: a `pac_id` that is not a decimal string
* (a number is refused, not converted) or no identifier at all. A present `pac_id` is never replaced by
* `id_seudonimo` when it is invalid.
*/
export function identidadDe(fila: FilaConIdentidad): IdentidadPaciente | null {
const pacId = fila.pac_id;
if (pacId !== undefined && pacId !== null) return typeof pacId === 'string' && PAC_ID.test(pacId) ? { campo: 'pac_id', id: pacId } : null;
return texto(fila.id_seudonimo) ? { campo: 'id_seudonimo', id: fila.id_seudonimo } : null;
}
/**
* The identities of a page of rows, or `null` when the page cannot be shown: a row without identity, rows that do not
* identify their patient by the same field, or two rows of the same patient (they would open the same record).
*/
export function identidadesDe(filas: readonly FilaConIdentidad[]): IdentidadPaciente[] | null {
const identidades = filas.map(identidadDe);
if (identidades.some(i => i === null)) return null;
const validas = identidades as IdentidadPaciente[];
if (validas.some(i => i.campo !== validas[0].campo)) return null;
return new Set(validas.map(i => i.id)).size === validas.length ? validas : null;
}
/** The column that holds the link to the record: the one of the row's own field, else any identifier column, else the first. */
export function columnaEnlace(columnas: readonly { clave: string }[], campo: CampoIdentidad): string | undefined {
return columnas.find(c => c.clave === campo)?.clave
?? columnas.find(c => (CAMPOS_IDENTIDAD as readonly string[]).includes(c.clave))?.clave
?? columnas[0]?.clave;
}
@@ -2,6 +2,8 @@ import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { Dominio, requireDominio } from './indicadores.models';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
@@ -11,27 +13,37 @@ export interface SeguimientoOpcion { codigo: string; etiqueta: string; }
// `detalles` are shown under the value, each with its label (for example the date of a result).
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[]; }
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoOpcion[]; }
// What a list of a cohort quotes back so that it opens the cohort that was counted: the cohort, its scenario and the
// revision of its rows. They are not filters; the answer repeats them, and a list that does not is not the one asked for.
export interface ContextoLista { cohorte: string; escenario: string; revision: string; }
export const CLAVES_CONTEXTO = ['cohorte', 'escenario', 'revision'] as const;
export interface SeguimientoTablaQuery {
corte?: string; meses: 1 | 3 | 6 | 12; page: number; page_size: number;
corte?: string; meses: MesesVentana; page: number; page_size: number;
// The filters the list announces in `filtros_disponibles`, by key; an empty value is no filter.
filtros?: Record<string, string | undefined>;
contexto?: ContextoLista;
}
export interface SeguimientoTablaResponse {
export interface SeguimientoTablaResponse extends Partial<ContextoLista> {
simulado: true;
corte: string;
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
ventana: { meses: MesesVentana; desde: string; hasta: string };
filtros: Record<string, string | null>;
filtros_disponibles: SeguimientoFiltro[];
columnas: SeguimientoColumna[];
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
// Every item names its patient (`pac_id`, or the legacy `id_seudonimo`); the rest are the columns' keys and their details.
items: Record<string, SeguimientoValor>[];
}
export class SeguimientoInvalido extends Error {}
export const MESES_VENTANA = [1, 3, 6, 12] as const;
// 0 is the whole list, without a time window: what a curve or a heatmap cell of the analysis opens. The list offers
// it only while such a selection is active.
export const MESES_VENTANA = [1, 3, 6, 12, 0] as const;
export type MesesVentana = typeof MESES_VENTANA[number];
/** What the window is called on screen and in the files: the whole cohort or a number of months. */
export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`;
export const PAGE_SIZE_MAX = 200;
const RESERVADAS = ['meses', 'page', 'page_size', 'corte'];
const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
@@ -43,7 +55,27 @@ const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiquet
export function validQuery(q: SeguimientoTablaQuery) {
return (!q.corte || isoDate(q.corte)) && (MESES_VENTANA as readonly number[]).includes(q.meses) && integer(q.page, 1)
&& integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX && Object.keys(q.filtros ?? {}).every(clave);
&& integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX && Object.keys(q.filtros ?? {}).every(clave)
// A cohort's list needs a cut-off: the revision belongs to it.
&& (!q.contexto || (!!q.corte && CLAVES_CONTEXTO.every(k => text(q.contexto![k]))));
}
/**
* Whether an answer says it applied the window and the filters that were asked for (and the cut-off, when one was
* asked, and the cohort, scenario and revision of a cohort's list). A list or a file must not show rows of another
* query under the title of this one.
*/
export function consultaAplicada(query: SeguimientoTablaQuery, answer: SeguimientoTablaResponse): boolean {
const entries = (filters: Record<string, string | null | undefined>) =>
JSON.stringify(Object.entries(filters).filter(([, v]) => !!v).sort(([a], [b]) => a.localeCompare(b)));
return answer.ventana.meses === query.meses && (!query.corte || answer.corte === query.corte)
&& entries(query.filtros ?? {}) === entries(answer.filtros)
&& (!query.contexto || CLAVES_CONTEXTO.every(k => answer[k] === query.contexto![k]));
}
/** The cohort an answer belongs to, when it names one: what the next pages and the files must quote back. */
export function contextoDe(answer: SeguimientoTablaResponse): ContextoLista | undefined {
return answer.cohorte && answer.escenario && answer.revision ? { cohorte: answer.cohorte, escenario: answer.escenario, revision: answer.revision } : undefined;
}
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
@@ -54,18 +86,45 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
&& Array.isArray(f['opciones']) && f['opciones'].every(opcion)) && new Set(available.map(f => (f as Record<string, unknown>)['clave'])).size === available.length;
const columnasOk = Array.isArray(columns) && columns.length > 0 && columns.every(c => record(c) && text(c['clave']) && text(c['etiqueta'])
&& (c['detalles'] === undefined || (Array.isArray(c['detalles']) && c['detalles'].every(d => record(d) && text(d['clave']) && text(d['etiqueta'])))));
if (CLAVES_CONTEXTO.some(k => v[k] !== undefined && !text(v[k]))) throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
if (!isoDate(v['corte']) || !record(window) || !(MESES_VENTANA as readonly number[]).includes(window['meses'] as number)
|| !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || p['page_size'] > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|| !filtrosOk || !columnasOk
|| !record(filters) || !Object.entries(filters).every(([k, f]) => (f === null || typeof f === 'string') && (available as Record<string, unknown>[]).some(a => a['clave'] === k))
|| !Array.isArray(v['items']) || v['items'].length > p['page_size']
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
}
return v as unknown as SeguimientoTablaResponse;
const respuesta = v as unknown as SeguimientoTablaResponse;
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
}
/**
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays
* in `<clave>_codigo` and in the filters' options, which are what the requests send.
*/
export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
const claves = Object.keys(ETIQUETADAS);
return {
...r,
filtros_disponibles: r.filtros_disponibles.map(f => claves.includes(f.clave)
? { ...f, opciones: f.opciones.map(o => o.etiqueta === o.codigo ? { ...o, etiqueta: etiquetaDeFiltro(f.clave, o.codigo) } : o) } : f),
items: r.items.map(item => {
const nuevo = { ...item };
for (const k of claves) {
const valor = item[k];
if (typeof valor !== 'string' || etiquetaDeFiltro(k, valor) === valor) continue;
if (nuevo[k + '_codigo'] === undefined) nuevo[k + '_codigo'] = valor;
nuevo[k] = etiquetaDeFiltro(k, valor);
}
return nuevo;
}),
};
}
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {
private readonly http = inject(HttpClient);
@@ -73,6 +132,7 @@ export class SeguimientoTablaService {
if (!validQuery(query)) throw new SeguimientoInvalido('Parámetros de seguimiento inválidos');
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
if (query.corte) params = params.set('corte', query.corte);
if (query.contexto) for (const k of CLAVES_CONTEXTO) params = params.set(k, query.contexto[k]);
for (const [k, v] of Object.entries(query.filtros ?? {})) if (v) params = params.set(k, v);
return this.http.get<unknown>(`/${requireDominio(dominio)}/seguimiento`, { params }).pipe(map(seguimientoTablaResponse));
}