Compare commits

...

102 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
Angel Capetillo Zavala cda3563184 Verify follow-up against final API responses 2026-11-12 11:57:48 -06:00
Angel Capetillo Zavala 7a6f87d141 Remove demonstration notices from CaMa views 2026-11-12 11:57:47 -06:00
Angel Capetillo Zavala 78313adb4a style(indicadores): CaMa histopathology rates stay readable at phone width
The rates figure lets the category labels size their own margin, shortens the
axis title, keeps few ticks and wraps «BI-RADS 4 sin subtipo» when the window is
600 px wide or less, and is redrawn when the window crosses that width. Values
and states are unchanged. The reading text keeps the capitals of a category
code inside a sentence («lesión de riesgo (B3)»).
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 7dc420773f feat(indicadores): CaMa detection and result-to-diagnosis indicators wired with real payloads
CAM-01 and CAM-02 already had their KPI cards and history panels waiting for the
catalog; they are now covered with the answers WebApi gives for the synthetic
base, both visible (lowered suppression threshold) and suppressed (normal
threshold). Once published they draw only their KPI card in the summary, as the
mockup does, instead of an extra generic figure card; their evolution stays in
the history.

The stacked history figure now keeps a category the catalog announces even when
no row carries it, so a missing category is named under the figure instead of
silently disappearing. The integration specs also cover the summary and the
history with CAM-01, CAM-02 and CAM-03 published.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 552e2c194f feat(indicadores): CaMa histopathology by BI-RADS drawn from the published matrix
The card for cama_histopatologia_birads now shows rates with their Wilson
interval per BI-RADS category and a two-ring donut of the biopsy result, with
group and category selection, period navigation and the published values table.
A pure adapter turns the stratified C2 response into rows and figures; the view
only asks for the data and draws what the adapter returns.

BI-RADS 4 is a row of its own. The denominator is benign, B3, in situ and
invasive; no biopsy and no data are reported apart. A published zero is a zero,
a suppressed cell is suppressed, and a cell or stratum the response does not
carry is unavailable, never zero: no rate or donut total is drawn over an
incomplete matrix. The card keeps its place first in the summary and stays
pending while the catalog does not publish the indicator.

The `birads` stratum is added to the accepted dimensions of the data request.
The CaCu cytology confirmation view is not touched.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 8f01f8693d feat(indicadores): CaMa follow-up tab drawn from the announced filters and columns
The tab asks GET /cama/seguimiento when it is first opened and draws the form,
the table, the details and the pagination from what the answer announces, so a
later change of source behind the endpoint needs no change here. It shows the
demonstration notice when the answer is simulated, a clear pending state while
the endpoint is not published (404 on the first page), and error, empty and
retry states. Stale requests are cancelled.

The sections, CaCu and initial-integration specs now expect the CaMa request
when the tab opens.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala ad8444a788 feat(indicadores): generic follow-up client with a strict response contract
GET /<dominio>/seguimiento with the window, page, size, cut-off date and the filters the list announces. Filters and columns come with the answer; only demonstration answers (simulado: true) are accepted and anything outside the contract is rejected before it reaches a view. The fixture is the synthetic answer of the reference prototype and is used by tests only.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala f78db1ae37 feat(indicadores): CaMa KPI cards show only their own line, as in the reference
The kit's notes are no longer appended to CaMa's opportunity cards (they stay in the figure footers, Histórico and Datos y definiciones). The four cards measure 308 x 220 px at 1366 px, like the reference. TEA keeps its notes and CaCu already hid them.
2026-11-12 11:35:27 -06:00
Angel Capetillo Zavala 0914b8db23 feat(indicadores): CaMa summary keeps the paired card and a pending histopathology card
Confirmation, screening-to-diagnosis and exam-to-result cards leave the summary (they stay in Histórico and Datos y definiciones). The histopathological result by BI-RADS keeps its place and structure as a pending card, with no figure or number, until the catalog publishes its indicator. The patients KPI uses the reference's wording.
2026-11-12 11:35:26 -06:00
Angel Capetillo Zavala 8aa66c6277 style(indicadores): CaMa's filter block as one compact row, as in the reference
Fields and Aplicar at 40 px, tighter padding and a small description. Only the CaMa block changes; CaCu and TEA keep their filters.
2026-11-12 11:35:26 -06:00
Angel Capetillo Zavala 1e1999f264 style(indicadores): Roboto headings, 4 px corners and the reference's title and card sizes, scoped to the indicators pages
Tokens are set on body when the indicators header is present, so menus, selects and dialogs share them; the other routes keep Rajdhani and their shapes.

(cherry picked from commit f5103b483d9d7188b4feffe91beda38d997004d4)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala e95c175f9b fix(shell): load the domain menu deferred and let the header wrap on narrow screens
The menu and its overlay were in the initial bundle of every route (+183 kB); they now load in their own chunk, with a same-size placeholder. On phones the title moves to a second row instead of being squeezed beside the selector.

(cherry picked from commit 2ccddf80dbbe41a328281fcdc1c95ebe421f4191)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala ff03a88ea0 feat(indicadores): domain navigation moves to the header; searchVisible reads the catalog before the domain
The in-page domain buttons are removed, since the header selector replaces them. Also fixes a computed that, after a visit to CaMa, never became true again, so CaCu and TEA lost their search box when switched to from CaMa.

(cherry picked from commit 3678c3653b33fcb98ba2334ca8f03f838dc86440)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala d761a6fb1a feat(shell): indicators header with the platform title and a domain selector
On /indicadores/<dominio> the header shows «Plataforma de Indicadores» and a menu button with the current domain (TEA, CaCu, Cáncer de mama) that links to the other two through the router. Institutional routes keep their breadcrumb header.

(cherry picked from commit 79a18fd7a8ed1a3a58201e7cc24c9692b53dbc47)
2026-11-12 01:43:27 -06:00
Angel Capetillo Zavala 2982d482bf feat(indicadores): CaMa history tab with the charts the published contracts support
A Histórico tab between Resumen and Seguimiento, for CaMa only: monthly or semestral interval, how many periods to show, and a custom period dialog. Counts are stacked, rates draw their confidence band and medians their quartile band; suppressed periods are shaded and listed, and a rate over no denominator or a median over no observations is no value. Five charts use published indicators; the three whose indicator the catalog does not publish are drawn as pending panels.

(cherry picked from commit 268d7443e0a89da8d6bc67ecb2b5db2715236f93)
2026-11-12 01:43:26 -06:00
Angel Capetillo Zavala 5e16f5454b fix(indicadores): reconcile CaMa period selection and contracts 2026-11-12 00:39:57 -06:00
Angel Capetillo Zavala ce3ed34fbf feat(indicadores): CaMa paired card of mammograms and patients by BI-RADS
One card draws the exams by category as a donut and, per BI-RADS family, the patients next to the exams. Patients come from cama_birads_456_paciente (each patient once per period, in the category of the most severe exam), so its exclusive categories are added within that indicator only, for the verified version 0.2.0; other versions, suppressed or missing cells leave the figure unknown. No exams-per-patient ratio is computed and patients are never derived from exams. The patients' indicator has no card of its own while the exams' one is published.

(cherry picked from commit b7bafd178896cb2715049d5c8293185f31391c92)
2026-11-12 00:29:14 -06:00
Angel Capetillo Zavala d159067efd feat(indicadores): CaMa clinical section heading and counter, without search, pins, navigation or representation selector
CaMa's graphic section reads «Indicadores clínicos» and counts the indicators it draws. The search box, pins, floating navigation, representation selector and figure count are not drawn for CaMa; CaCu and TEA keep them.

(cherry picked from commit e54ee5a55aa3722f6895300fa7e8cefb28f12ebb)
2026-11-12 00:29:14 -06:00
Angel Capetillo Zavala 7b8fd9e01d feat(indicadores): CaMa labels, single-period filters and the four-card strip
CaMa reads «cáncer de mama» everywhere on the indicators page and uses the compact filter: interval, one period and Aplicar on one row, without the mode selector, the multiple selection or the editing summaries. The opportunity strip is the four cards only, and the biopsy distribution card is no longer drawn in the summary (it stays in Datos y definiciones). Other domains keep their filter and strip.

(cherry picked from commit 7c9dcf634e5870fec35ab96347b0863b2e3bb86e)
2026-11-12 00:29:08 -06:00
Angel Capetillo Zavala 8a3f68df6b fix(indicadores): guard invalid C1 denominators and preserve status 2026-11-11 23:56:32 -06:00
Angel Capetillo Zavala bc75c058e1 feat(indicadores): CaMa's four opportunity cards, pending where the catalog lacks the indicator
Cards: patients with BI-RADS 4, 5 and 6, histopathological detection rate, screening to result and result to diagnosis times. The detection rate and the result-to-diagnosis time are not published by the catalog yet, so they are drawn as explicit pending cards and are queried once the catalog lists them. cama_eu38a is added to the CaMa KPIs.
2026-11-11 23:56:32 -06:00
Roberto Treviño Cervantes f4d2a3e85f add bitacora page, self-hosted fonts/icons, review fixes for the install package 2026-10-30 11:19:34 -06:00
Roberto Treviño Cervantes 8c63ed83ac preliminary release 2026-10-29 12:14:56 -06:00
Roberto Treviño Cervantes e6e6fb7210 preliminary release 2026-10-29 12:12:15 -06:00
angel 82efba35cb Merge pull request 'Feature/eu7 transiciones animadas' (#8) from feature/eu7-transiciones-animadas into dev
Reviewed-on: #8
2026-10-28 17:18:12 +00:00
Angel Capetillo Zavala 26fe1ccbb3 feat(cacu): preparar interfaz de riesgo individual de paciente 2026-10-28 10:36:58 -06:00
Angel Capetillo Zavala 94c63c460c feat(eu7): incorporar transiciones animadas en dona y barras 2026-10-28 09:45:00 -06:00
angel 05a9967906 Merge pull request 'feat(indicadores): integrar ajustes CaCu, ficha de paciente y mejoras de navegación' (#7) from feature/detalle-paciente-cacu into dev
Reviewed-on: #7
2026-10-27 21:26:28 +00:00
Angel Capetillo Zavala 1c0bdf6184 feat(indicadores): completar ficha CaCu y navegación clínica 2026-10-27 14:46:51 -06:00
edgar 70aa739f97 Bitácora: IND1 ya no cita kpi_catalog.yaml en la ficha
CSO5.5
2026-10-25 21:25:26 +00:00
edgar 394f2c626b fix(indicadores): «Valores publicados» y la tabla de contingencia plegada
Las tablas desplegables decían «Valores publicados y celdas suprimidas» o «… y cajas no disponibles», que confundía: ahora dicen «Valores publicados». La tabla de contingencia de citología y biopsia estaba siempre a la vista; ahora va plegada bajo «Valores publicados», como las demás. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 19:43:19 +00:00
edgar 644803cf21 docs: pendiente de IND1 (fecha de corte y calidad del espécimen)
CSO5.5
2026-10-25 19:33:54 +00:00
edgar 8e9a40dec4 docs: pendientes de los textos de Tiempo de tamizaje a diagnóstico
CSO5.5
2026-10-25 18:58:40 +00:00
edgar 1bdec1b838 docs: pendientes de la ficha técnica y de la consulta de calidad satisfactoria
El método estadístico y los campos nuevos de la ficha se posponen; los textos dirán «calidad de espécimen satisfactoria» y la consulta se alineará después.

CSO5.5
2026-10-25 18:36:30 +00:00
edgar 220d5b9d26 fix(indicadores): decir qué junta «Sin dato» bajo la dona de resultados citológicos
«Sin resultado válido en el periodo» no decía qué es un resultado válido. La nota ahora dice «con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte», que es lo que cuenta la consulta. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 18:08:00 +00:00
edgar fbfd97ec31 fix(indicadores): decir cáncer cervicouterino en lugar de CaCu en pantalla
CaCu es el nombre que le dimos nosotros, no el que busca un médico. Las etiquetas de la página dicen «cáncer cervicouterino», con mayúscula donde abre el texto (la línea «Cáncer cervicouterino, investigación», que ya no dice «Dominio»). El botón del encabezado para cambiar de proyecto sigue diciendo «CaCu», provisional; las direcciones no cambian (/indicadores/cacu). El encabezado dice «Indicadores» en lugar de «Dashboard de indicadores» y el subtítulo «Explora los indicadores de …» sin mencionar el servicio de reportes. «Datos y definiciones» ya no repite «Dominio: …» bajo su título. TEA y CaMa conservan su nombre. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 17:47:14 +00:00
edgar 18692acc88 fix(indicadores): tarjetas de CaCu sin el pie de las figuras y con cuartiles escritos
Las tarjetas de indicadores de oportunidad de CaCu mostraban, después de su línea, las notas del kit (el pie de las figuras): repetían la definición y, en los tiempos, hablaban de la caja. Ahora dicen solo su línea: «Pacientes con citología tomada en el periodo.» y «n citologías; primer cuartil: x días; tercer cuartil: y días.», sin Q1 ni Q3. El número de Pacientes evaluadas no cambia; «Datos y definiciones» de CaCu aclara que incluye las citologías con espécimen insatisfactorio. TEA y CaMa no cambian. Registrado en docs/bitacora-textos.md.

CSO5.5
2026-10-25 17:18:24 +00:00
edgar 6c84dab730 refactor(indicadores): quitar interpretación y metodología de datos y definiciones
La sección general de advertencias al final de Datos y definiciones repetía avisos genéricos (nulos, periodos, intervalos, uso para investigación) que no son de ningún indicador y solo agregaban ruido; la interpretación de cada gráfica está en su botón Cómo leer. Se quita solo la sección de la plantilla y la aserción de la prueba que buscaba su texto.

CSO5.5
2026-10-25 01:46:37 +00:00
edgar 12ce93f58c fix(indicadores): conservar el pie del kit y la lectura de la fecha de corte
El kit no cambia el formato del pie de las figuras: sigue publicando «<fuente> · Fecha de corte: AAAA-MM-DD» y la misma fuente de TEA. Se revierten la expresión regular que valida el pie de TEA, la extracción de la fecha de corte bajo la gráfica, los fixtures sintéticos y sus specs a como estaban. El cambio de textos de pantalla queda solo en los literales que se muestran o se leen en aria-label, sin tocar la lógica que compara o valida.

CSO5.5
2026-10-25 01:40:17 +00:00
edgar dcaf1a8832 fix(indicadores): quitar flechas, rayas y puntos medios de los textos de pantalla
Los textos que ve una persona, visibles o en aria-label, ya no usan flechas ni rayas o puntos medios como separador: se separan con comas o se reescribe la frase (por ejemplo «Días de toma a resultado (laboratorio)», «Último dato visible, 2025-S1», «Dominio CaCu, investigación», «2025-S2, 1 de 3» o «Datos y definiciones de CaCu»). El pie que publica el kit cambia al mismo estilo, así que la validación del pie de TEA y la lectura de la fecha de corte reconocen el formato nuevo con comas y siguen aceptando el anterior para no romper con un kit previo. Se ajustan los fixtures sintéticos y las specs a los textos nuevos.

CSO5.5
2026-10-25 01:37:53 +00:00
edgar 04d529392e refactor(indicadores): quitar el resumen de indicadores del final de la página
La tabla de resumen repetía en formato largo los valores de todas las figuras; cada figura ya trae su propia tabla de valores. Se quitan el componente indicadores-numeric-summary y sus filas (indicadores-numeric-rows), y las pruebas que dependían de ellos.

CSO5.5
2026-10-25 01:19:07 +00:00
edgar 6f3e7e22f9 fix(indicadores): decir intervalo de tiempo en lugar de granularidad
El filtro general y sus mensajes de compatibilidad nombran «Intervalo de tiempo» (semestre o mes) en lugar de «Granularidad», que no es un término clínico. Cambian la etiqueta del selector y los cinco mensajes que la mencionan; las pruebas que citaban esos textos se ajustan.

CSO5.5
2026-10-25 01:04:14 +00:00
edgar 12a0398903 refactor(indicadores): quitar la tabla de reglas de datos y definiciones
Las reglas de cálculo que publica el kit en `parametros` (clave, valor, estado y fuente) irán en un apéndice o manual técnico aparte, no en la pestaña «Datos y definiciones». Se quita la tabla «Reglas» y su formato de valores, y la pestaña conserva la ficha técnica, las referencias y las poblaciones. También se retiran el tipo y la validación estricta de `parametros` en el servicio: ya nadie los usa y una lista mal formada bloqueaba los metadatos completos. Si el servidor envía `parametros`, se ignoran.

CSO5.5
2026-10-24 22:11:33 +00:00
edgar 03e51c07cc feat(indicadores): panel de tasa de confirmación histopatológica, tiempos pareados y ficha técnica
Agrega el panel de tasa de confirmación histopatológica (cacu_confirmacion_citologia): tasas por resultado citológico de alto grado con su intervalo de Wilson a la izquierda, dona del grado de biopsia a la derecha y tabla de contingencia; la vista base es «LIEAG o más» y las pacientes sin biopsia aún no entran al denominador. Une en una sola figura los tiempos de toma a resultado (pedido por id, oculto en el catálogo) y de toma a diagnóstico. La pestaña Datos y definiciones muestra la ficha técnica y las reglas del kit en tablas; las notas de cada figura pasan a su Cómo leer, las tarjetas dejan solo valor, n y periodo, y el Cómo leer de EU7 muestra solo lo que publica el kit. Las transiciones animadas quedan fuera, como entrega aparte para el diseñador.

CSO5.5
2026-10-24 21:04:57 +00:00
edgar e6be341ad9 Redondeo único de porcentajes y etiqueta de la última citología sin resultado
- indicadores-format.ts: una regla para todo porcentaje mostrado. Una décima,
  medio hacia arriba; entre 0 y 0.1, la primera cifra significativa (0.04 %).
  De un conteo se calcula con enteros; de un valor publicado, sin sorpresas de
  coma flotante. La usan el resumen numérico (que mostraba el valor crudo,
  «0.6600660066 %»), los KPI, la dona, las barras y la tabla de EU7.
- Seguimiento: la última citología sin Bethesda dice «Insatisfactoria» si su
  calidad lo es y «Sin resultado al corte» si no; antes las dos decían
  «No disponible», que queda para cuando no hay citología.

CSO5.5
2026-10-24 18:17:54 +00:00
angel 85ec11ab0f Merge pull request 'feat(indicadores): ajustar indicadores CaCu y presentacion EU7' (#6) from feature/dona-barras-generales into dev
Reviewed-on: #6
2026-10-24 03:23:00 +00:00
Angel Capetillo Zavala db9ab0d1a7 feat(indicadores): ajustar indicadores CaCu y presentacion EU7
Actualiza los indicadores de oportunidad y clínicos de CaCu, incorpora el KPI no disponible, prioriza EU7, independiza dos figuras mediante Todos con reporte y añade el selector de prioridad no disponible en Seguimiento. Integra además los totales por escenario en las barras de EU7 y elimina el listado inferior redundante.
2026-10-23 21:18:43 -06:00
angel af70d6f378 Merge pull request 'feat(indicadores): interacción dona-barras, homologación visual y escenario clínico EU7' (#5) from feature/dona-barras-generales into dev
Reviewed-on: #5
2026-10-23 19:26:56 +00:00
Angel Capetillo Zavala 1940f4fa47 feat(isssteleon): add EU7 clinical scenario charts 2026-10-23 13:18:57 -06:00
alberto ec406d5d2d Merge pull request 'Reword "¿Cómo leer?" text for proportion and box charts' (#4) from fix/como-leer-textos into dev
Reviewed-on: #4
2026-10-23 18:27:14 +00:00
edgar 7b82427713 Reword "¿Cómo leer?" text for proportion and box charts
Replace "denominadores pequeños" with "tamaño de muestra pequeño" and drop the mention of Plotly from the box chart and fallback texts.
2026-10-23 18:26:26 +00:00
Angel Capetillo Zavala ec642df834 style(indicadores): homologar tarjetas y navegación de dominios
Homologa la presentación de figuras y tarjetas en TEA, CaCu y CaMa; recupera las leyendas superiores, permite la expansión independiente de Cómo leer y mueve la navegación de dominios a un selector compacto con resaltado institucional en la topbar. Preserva el comportamiento de Plotly y la interacción dona-barras.
2026-10-23 12:14:17 -06:00
Angel Capetillo Zavala 540506bde0 feat(indicadores): conectar donas jerárquicas con barras generales
Habilita el filtrado visual local de barras generales mediante selecciones jerárquicas C2, preservando datos originales, periodos, porcentajes y restauración de la distribución completa.
2026-10-23 10:32:40 -06:00
angel 14fd765122 Merge pull request 'Integra las mejoras del dashboard de indicadores para TEA, CaCu y CaMa.' (#3) from feature/dashboard-tabs-colores-donas into dev
Reviewed-on: #3
2026-10-23 07:30:35 +00:00
Angel Capetillo Zavala 9639423a32 feat(indicadores): completa metadatos y navegación multiperiodo 2026-10-23 01:18:24 -06:00
Angel Capetillo Zavala 1fe88dfb45 feat(indicadores): dashboard interactivo multidominio y seguimiento CaCu 2026-10-22 17:10:35 -06:00
edgar a30dbbb102 Merge pull request 'Feature/cama birads45' (#2) from feature/cama-birads45 into dev
Reviewed-on: #2
2026-10-20 07:04:58 +00:00
rodrigo 9cc67c0ef2 CaMa: sin la barra fija de BI-RADS 4 sin subcategoría
- Los catálogos de despliegue (cama.catalogos.birads y .birads_4_a_6) ya no
  traen B4: el hospital reporta la subcategoría (usuario, 2026-10-16) y la
  barra salía siempre en 0. Un 4 a secas sigue contando como sospecha y en
  BI-RADS 4 a 6, y si llega se reporta tal cual después de «Sin dato».
- CAMA_BIRADS 0.1.3, CAMA_BIRADS456_PACIENTE y _MASTOGRAFIA 0.1.1: misma
  consulta (misma huella), otras categorías publicadas.
- El fixture de H-003 pasa de B4 a B4A; pruebas e instantánea (solo agrega).

CSO5.5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 08:33:30 +00:00
rodrigo 1eda9eea29 CaMa: la tasa de confirmación histopatológica vuelve al catálogo
cama_confirmacion_birads45 deja de estar oculto (usuario, 2026-10-16): se ve
su tarjeta destacada con el filtro por omisión y su gráfica de tendencia
(fig_c1_puntos). Así WebApp no necesita un caso especial para un destacado
oculto del catálogo: se revierte ese mecanismo y las pruebas del colaborador
quedan como estaban.

CSO5.5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 07:48:21 +00:00
rodrigo 2cf3a5a40d Destacados: la tasa de confirmación de CaMa con su indicador oculto, y pacientes evaluadas
- cama_confirmacion_birads45 está `oculto` en su TOML a propósito (no sale en
  el catálogo ni tiene gráfica), pero su tarjeta destacada se quedaba en «Sin
  reportes disponibles» con el filtro por omisión: la disponibilidad y la
  tarjeta solo miraban el catálogo. Una definición marcada `hiddenInCatalog`
  pide sus periodos y datos por su id, que WebApi sigue sirviendo; no aparece
  en los indicadores gráficos. Las demás tarjetas no cambian.
- Primera tarjeta: «Pacientes evaluadas» (cacu_eu7) y «Pacientes evaluadas con
  BI-RADS 4, 5 y 6», que suma las categorías de cama_birads_456_paciente.
- Pruebas: indicadores-kpi-ocultos.spec.ts (con el catálogo real de CaMa),
  indicadores-kpi-cama-real.spec.ts (respuestas reales de WebApi sobre una
  base montada por dev-data: 31 pacientes, 66.7 % y la mediana del C3r). Las
  suites de catálogo y fijación aíslan sus peticiones de las tarjetas
  (kpiQueriesProvider), como las demás.

CSO5.5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 07:39:08 +00:00
rodrigo 30946823c4 CaMa: título «Tasa de confirmación histopatológica», como en CaCu
Título de cama_confirmacion_birads45 (usuario, 2026-10-16), en el TOML y en
la tarjeta de indicadores destacados. Solo cambia el texto.

CSO5.5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 07:16:51 +00:00
rodrigo d946228319 Destacados: títulos de los TOML y Tiempo de tamizaje a diagnóstico
- Los títulos de las tarjetas de indicadores destacados son ahora los
  `title` de los TOML del kit (M23, M24, M25, cacu_eu7, cacu_eu13,
  cama_birads, cama_confirmacion_birads45), copiados a mano: solución
  provisional hasta que las tarjetas lean el `titulo` que ya manda la API.
- La tercera tarjeta de CaCu y CaMa pasa de los días de la toma al resultado
  (cacu_eu_tiempo_reporte, cama_eu38a) a los días de la toma al diagnóstico
  (cacu_dias_toma_diagnostico, cama_dias_toma_diagnostico), «Tiempo de
  tamizaje a diagnóstico», con su horizonte provisional de 180 días.

CSO5.5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 07:09:36 +00:00
alberto 8cb3c97b80 Merge pull request 'Feature/arreglos viernes alberto' (#1) from feature/arreglos-viernes-alberto into dev
Reviewed-on: #1
2026-10-16 02:13:52 +00:00
edgar 1fc23bd0bd TEA: indicadores destacados (M23–M25), ocultar indicadores y renombrar a pacientes 2026-10-15 22:23:39 +00:00
Angel Capetillo Zavala 11337679dc feat(indicadores): mejorar presentación y legibilidad de figuras multidominio 2026-10-15 13:45:59 -06:00
Angel Capetillo Zavala 4685a91a7c feat(ui): mejorar presentacion y disponibilidad inicial de KPI 2026-10-14 13:00:54 -06:00
Angel Capetillo Zavala 69afcc7fdb feat(ui): mejorar periodos KPI y presentacion del dashboard 2026-10-14 11:46:17 -06:00
Angel Capetillo Zavala 9fcc65d84f feat(ui): incorporar selector de figuras KPI y fijacion de indicadores 2026-10-13 22:34:57 -06:00
Angel Capetillo Zavala c4faa7d9f6 feat(ui): incorporar filtros globales por dominio UX-06E.D.2 2026-10-13 19:45:48 -06:00
Angel Capetillo Zavala 98d0614d80 feat(ui): habilitar apertura automatica UX-06E.D.1.1 2026-10-13 16:34:28 -06:00
Angel Capetillo Zavala 35e1bc33d3 feat(ui): integrar grid y KPI preliminares UX-06E.D.1 2026-10-13 16:01:48 -06:00
Angel Capetillo Zavala f96fe97ed6 feat(ui): incorporar ayuda contextual UX-06E.B1 2026-10-13 15:21:48 -06:00
Angel Capetillo Zavala fe9442237b feat(ui): refinar buscador y navegacion UX-06E.A 2026-10-13 14:43:52 -06:00
Angel Capetillo Zavala 61cdf5b72e chore(tests): retirar scripts temporales UX-06 2026-10-13 13:42:10 -06:00
Angel Capetillo Zavala 37c4eacf84 feat(ui): completar presentacion de figuras UX-06D 2026-10-13 13:41:45 -06:00
Angel Capetillo Zavala 41be0c343f feat(ui): redisenar catalogo y filtros UX-06C 2026-10-13 12:34:03 -06:00
Angel Capetillo Zavala ecf2778f1a feat(ui): incorporar base institucional UX-06B 2026-10-13 11:38:17 -06:00
Angel Capetillo Zavala 9c012e9bb4 feat(indicadores): agregar busqueda priorizada UX-05C 2026-10-13 10:42:34 -06:00
Angel Capetillo Zavala 91832cc6ff feat(indicadores): implementar catalogo expandible UX-05B 2026-10-13 10:14:27 -06:00
Angel Capetillo Zavala ea91b31b17 feat(indicadores): implementar filtros hibridos y memoria UX-04 2026-10-13 00:29:46 -06:00
Angel Capetillo Zavala ae5e4c5db5 refactor(indicadores): extraer componente de figura UX-03 2026-10-12 23:33:40 -06:00
Angel Capetillo Zavala b1c4b78f32 feat(indicadores): habilitar dashboards Angular TEA CaCu y CaMa 2026-10-12 16:39:37 -06:00
Angel Capetillo Zavala a66205b725 feat(indicadores): agregar prototipo de dashboard TEA
Implementa el prototipo del dashboard de indicadores TEA.

- Integra catálogo y figuras mediante WebApi.
- Incorpora visualizaciones interactivas con Plotly.js.
- Agrega controles de indicadores, figuras, periodos y temas.
- Implementa estados de carga, errores y diseño responsive.
- Incluye explicaciones para los contratos C1, C2 y C3r.
- Incorpora pruebas unitarias y de integración de componentes.

Prototipo para investigación con datos sintéticos.
2026-10-12 10:43:00 -06:00
242 changed files with 16128 additions and 1392 deletions
+2 -5
View File
@@ -1,10 +1,7 @@
# Production image: build the Angular app, serve the static bundle with
# nginx, and reverse-proxy the API paths to the `webapi` compose service —
# the same routing `proxy.conf.json` gives `ng serve` in development, so the
# app's relative `/imports`, `/data`, ... calls work unchanged.
# Production image: the Angular build served by nginx, which proxies the API paths to `webapi`.
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json* ./
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx ng build --configuration production
+10 -53
View File
@@ -1,59 +1,16 @@
# WebApp
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 22.1.8.
## Development server
To start a local development server, run:
Interfaz de ISSSTELEON en Angular y Angular Material: conexión e importación de
datos (`/conectar`), bitácora de cargas (`/bitacora`), gobernanza y tablero de
indicadores (`/indicadores`).
```bash
ng serve
npm ci
npx ng serve # http://localhost:4200
npx ng test --watch=false # pruebas unitarias (Vitest)
npx ng build # compilación de producción en dist/WebApp
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
+8
View File
@@ -31,6 +31,14 @@
}
],
"styles": [
"node_modules/@fontsource/roboto/300.css",
"node_modules/@fontsource/roboto/400.css",
"node_modules/@fontsource/roboto/500.css",
"node_modules/@fontsource/rajdhani/600.css",
"node_modules/@fontsource/rajdhani/700.css",
"node_modules/@fontsource/roboto-mono/400.css",
"node_modules/@fontsource/roboto-mono/600.css",
"node_modules/material-icons/iconfont/filled.css",
"src/styles.scss"
]
},
+5 -1
View File
@@ -8,7 +8,11 @@ server {
# the ~33% base64 overhead.
client_max_body_size 270m;
location ~ ^/(api|imports|data|cacu|cama|tea|governance|health)(/|$) {
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {
proxy_pass http://webapi:5000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+283 -2
View File
@@ -16,9 +16,15 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"@fontsource/rajdhani": "^5.3.0",
"@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",
@@ -1417,6 +1423,33 @@
}
}
},
"node_modules/@fontsource/rajdhani": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/rajdhani/-/rajdhani-5.3.0.tgz",
"integrity": "sha512-oBJgSIibWJvVBKseme1JczqPLoDHN97LHti4uh0LjfcJqQoVmnQQlRKIpEjTJV559rmVQ6qbVZZwKwk2wkBTtw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/roboto": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.3.0.tgz",
"integrity": "sha512-BapRJOWYP+LZ21zp+wBQjfpPYKRoxc4LspJ/RLuI+HSMBD5u/X4O+ESDrSvEqDSy0rAl7GwBJ+09mdc16cVQ1Q==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/roboto-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/roboto-mono/-/roboto-mono-5.3.0.tgz",
"integrity": "sha512-yhwplHMHW9dCk+1pZuERfcJe+K3rosGVZEoK0XktkxRSqQ9qsipSwwiuW2/8Qmtp9lzu3Ixa/ie4BMH3i8CkZQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@harperfast/extended-iterable": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.3.tgz",
@@ -2670,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",
@@ -3666,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",
@@ -3980,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",
@@ -4070,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",
@@ -4326,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",
@@ -4529,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",
@@ -4890,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": {
@@ -4955,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",
@@ -4987,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",
@@ -5831,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",
@@ -5933,6 +6081,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/material-icons": {
"version": "1.13.14",
"resolved": "https://registry.npmjs.org/material-icons/-/material-icons-1.13.14.tgz",
"integrity": "sha512-kZOfc7xCC0rAT8Q3DQixYAeT+tBqZnxkseQtp2bxBxz7q5pMAC+wmit7vJn1g/l7wRU+HEPq23gER4iPjGs5Cg==",
"license": "Apache-2.0"
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -6336,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",
@@ -6439,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",
@@ -6488,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",
@@ -6718,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",
@@ -6816,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",
@@ -7150,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",
@@ -7313,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",
@@ -8033,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",
@@ -8050,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",
+7 -1
View File
@@ -19,9 +19,15 @@
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"@fontsource/rajdhani": "^5.3.0",
"@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",
+2 -1
View File
@@ -6,5 +6,6 @@
"/cacu": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
"/cama": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
"/tea": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
"/governance": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }
"/governance": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
"/reportes": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }
}
+90
View File
@@ -0,0 +1,90 @@
// Covers the shell's header: on an indicators page it carries the platform title and the domain selector; on
// the institutional routes it keeps the breadcrumb. The pages are stubs: only the header and the router matter.
import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { App } from './app';
import { routes } from './app.routes';
import { DOMINIOS } from './features/indicadores/indicadores.models';
@Component({ template: 'página', selector: 'app-stub' })
class Stub {}
describe('Encabezado del marco', () => {
const rutas = [
{ path: '', component: Stub },
{ path: 'conectar', component: Stub, data: { workspace: true, breadcrumb: 'Conectar datos' } },
{ path: 'gobernanza', component: Stub, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' } },
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, component: Stub, data: { workspace: true, breadcrumb: 'Indicadores', dominio } })),
];
let fixture: ReturnType<typeof TestBed.createComponent<App>>, router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({ imports: [App], providers: [provideRouter(rutas), provideHttpClient(), provideHttpClientTesting()] }).compileComponents();
fixture = TestBed.createComponent(App); router = TestBed.inject(Router);
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); document.querySelectorAll('.cdk-overlay-container').forEach(e => e.replaceChildren()); });
const root = () => fixture.nativeElement as HTMLElement;
async function ir(url: string) { await router.navigateByUrl(url); await fixture.whenStable(); fixture.detectChanges(); }
const selector = () => root().querySelector('.domain-selector') as HTMLButtonElement | null;
async function abrirMenu() {
selector()!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
return [...document.querySelectorAll('.mat-mdc-menu-panel a[mat-menu-item]')] as HTMLAnchorElement[];
}
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
// Fails if the selector would point at a route the application does not have.
const paths = routes.map(r => r.path);
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
});
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
await ir('/indicadores/' + dominio);
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
expect(root().querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
// The breadcrumb is replaced, not duplicated beside the selector.
expect(root().querySelector('.site-header__nav')).toBeNull();
expect(root().querySelector('.app-shell--indicadores')).not.toBeNull();
});
it('el selector tiene nombre accesible con el dominio actual y anuncia un menú', async () => {
await ir('/indicadores/cama');
expect(selector()!.getAttribute('aria-label')).toBe('Dominio actual: Cáncer de mama. Cambiar dominio');
expect(selector()!.getAttribute('aria-haspopup')).toBe('menu');
expect(selector()!.tagName).toBe('BUTTON');
expect(selector()!.tabIndex).toBeGreaterThanOrEqual(0);
});
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
await ir('/indicadores/cama');
const items = await abrirMenu();
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
});
it('elegir otro dominio navega por el enrutador, actualiza el selector y deja una entrada en el historial', async () => {
await ir('/indicadores/cama');
const items = await abrirMenu();
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
expect(router.url).toBe('/indicadores/cacu');
expect(selector()!.textContent).toContain('CaCu');
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
const ubicacion = TestBed.inject(Location);
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
expect(ubicacion.path()).toBe('/indicadores/cama');
});
it.each(['/', '/conectar', '/gobernanza'])('en %s conserva el encabezado institucional sin selector', async url => {
// Fails if the indicators header leaks into the institutional routes.
await ir(url);
expect(selector()).toBeNull();
expect(root().querySelector('.platform-title')).toBeNull();
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
});
it('una ruta parecida que no es de indicadores no activa el selector', async () => {
await router.navigateByUrl('/'); fixture.detectChanges();
expect(selector()).toBeNull();
});
});
+16 -6
View File
@@ -1,15 +1,25 @@
<div class="app-shell" [class.app-shell--workspace]="workspace()">
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
<header class="site-header">
<div class="site-header__content">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
@defer (on immediate) {
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
} @placeholder {
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
}
</nav>
} @else {
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
}
</nav>
}
</div>
</header>
+6
View File
@@ -20,6 +20,12 @@ export const routes: Routes = [
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
},
{
path: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
+23
View File
@@ -103,3 +103,26 @@
width: 155px;
}
}
.platform-title {
color: var(--color-text);
font-family: var(--issste-font-heading);
font-size: 1.25rem;
font-weight: 500;
line-height: 1.15;
margin-inline-start: var(--issste-space-4);
margin-inline-end: auto;
overflow-wrap: anywhere;
}
.domain-selector--espera {
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
}
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
@media (max-width: 599px) {
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
.app-shell--indicadores .brand { margin-inline-end: auto; }
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
}
+12 -1
View File
@@ -2,9 +2,11 @@ import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
import { DomainSelector } from './domain-selector';
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
@Component({
imports: [RouterLink, RouterOutlet],
imports: [RouterLink, RouterOutlet, DomainSelector],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
@@ -28,4 +30,13 @@ export class App {
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
protected readonly title = 'Plataforma de Indicadores';
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
private readonly url = toSignal(this.router.events.pipe(
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
/** On an indicators page the header names its domain and switches to the others. */
protected readonly activeDomain = computed(() =>
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
}
+4 -1
View File
@@ -136,7 +136,7 @@ export interface ImportSourcePayload extends SourceLocator {
defaults?: Record<string, unknown>;
}
// -- documents -----------------------------------------------------------------
// Clinical documents
export type OcrMode = 'auto' | 'always' | 'never';
@@ -223,6 +223,9 @@ export interface CommitSourceResult {
export interface BatchResult {
ok: boolean;
results: CommitSourceResult[];
/** Id of this attempt in the aggregate import log (`/reportes/importaciones`). */
audit_id?: string;
indicadores_en_recalculo?: boolean;
}
export interface DataPage {
+10 -8
View File
@@ -1,10 +1,12 @@
/** Base64 of a File's bytes, for JSON endpoints that carry a file. */
export async function fileToBase64(file: Blob): Promise<string> {
const bytes = new Uint8Array(await file.arrayBuffer());
const chunk = 0x8000;
let binary = '';
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
}
return btoa(binary);
export function fileToBase64(file: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const dataUrl = reader.result as string;
resolve(dataUrl.slice(dataUrl.indexOf(',') + 1));
};
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
@@ -8,7 +8,7 @@
@if (store.connections().length === 0) {
<div class="pane__empty">
<app-file-dropzone [accept]="store.acceptedExtensions()" [multiple]="true" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
<app-file-dropzone [accept]="store.acceptedExtensions()" [keepSelection]="false" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
<button mat-stroked-button type="button" class="pane__db-button" (click)="addConnection.emit()">
<mat-icon aria-hidden="true">storage</mat-icon>Conectar una base de datos
</button>
@@ -69,7 +69,7 @@
}
}
</p>
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" [multiple]="true" (filesChange)="files.set($event)"></app-file-dropzone>
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" (filesChange)="files.set($event)"></app-file-dropzone>
}
@case ('database') {
@@ -83,10 +83,8 @@ export class ConnectorGalleryDialog {
this.categories.filter((c) => c.id === 'all' || this.entries().some((entry) => entry.category === c.id)),
);
// -- files --
readonly files = signal<File[]>([]);
// -- database --
readonly serverForm = this.formBuilder.nonNullable.group({
host: ['', Validators.required],
port: [null as number | null],
@@ -101,8 +101,6 @@ export class DocumentReviewDialog {
});
}
// -- settings ------------------------------------------------------------
updateSettings(patch: Partial<DocumentSettings>): void {
this.settings.update((settings) => ({ ...settings, ...patch }));
}
@@ -128,8 +126,6 @@ export class DocumentReviewDialog {
});
}
// -- records and values ------------------------------------------------------
select(index: number): void {
this.selectedIndex.set(index);
this.page.set(null);
@@ -171,8 +167,6 @@ export class DocumentReviewDialog {
return record.conflicts.find((conflict) => conflict.field === field) ?? null;
}
// -- pages and images ----------------------------------------------------------
thumbnailKey(image: DocumentImage): string {
return `${image.document}|${image.page_number}|${image.bbox.join(',')}`;
}
@@ -199,8 +193,6 @@ export class DocumentReviewDialog {
});
}
// -- close -------------------------------------------------------------------------
apply(): void {
this.table.configure(this.settings(), { [this.target.key]: this.overrides() });
this.dialogRef.close(true);
@@ -2,7 +2,7 @@
<mat-icon class="dropzone__icon" aria-hidden="true">cloud_upload</mat-icon>
<p class="dropzone__title">Arrastra tus archivos aquí</p>
<p class="dropzone__formats">{{ formatsLabel }}</p>
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple()" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
<button class="upload-action upload-action--outlined select-files-button" mat-stroked-button type="button" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>
<span>Seleccionar archivos</span>
@@ -2,8 +2,10 @@ import { TestBed } from '@angular/core/testing';
import { FileDropzone } from './file-dropzone';
describe('FileDropzone', () => {
function createFixture() {
function createFixture(keepSelection = true) {
const fixture = TestBed.createComponent(FileDropzone);
fixture.componentRef.setInput('accept', ['xlsx', 'csv', 'json', 'pdf']);
fixture.componentRef.setInput('keepSelection', keepSelection);
fixture.detectChanges();
return fixture;
}
@@ -81,7 +83,27 @@ describe('FileDropzone', () => {
expect(emitted.at(-1)).toEqual([]);
});
it('honors a custom accept input, keeping pdf available by default', () => {
it('without keepSelection emits only each new batch and lists nothing', () => {
const fixture = createFixture(false);
const compiled = fixture.nativeElement as HTMLElement;
const component = fixture.componentInstance;
const emitted: File[][] = [];
component.filesChange.subscribe((files) => emitted.push(files));
const drop = (files: File[]) =>
component.onDrop({ preventDefault: () => undefined, dataTransfer: { files } } as unknown as DragEvent);
const first = new File(['a'], 'uno.csv');
const second = new File(['b'], 'dos.csv');
drop([first]);
drop([second]);
drop([new File(['x'], 'malo.docx')]);
fixture.detectChanges();
expect(emitted).toEqual([[first], [second]]);
expect(compiled.querySelectorAll('.file-row')).toHaveLength(0);
});
it('honors a custom accept input', () => {
const fixture = createFixture();
expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(true);
@@ -1,8 +1,12 @@
import { Component, EventEmitter, Input, Output, signal } from '@angular/core';
import { Component, input, output, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
/** Drag-and-drop and file-picker area that collects a validated list of files. */
/**
* Drag-and-drop and file-picker area that validates files by extension and size.
* With `keepSelection` it keeps and emits the whole selected list; without it,
* it emits only each batch of newly accepted files and keeps nothing.
*/
@Component({
imports: [MatButtonModule, MatIconModule],
selector: 'app-file-dropzone',
@@ -10,9 +14,10 @@ import { MatIconModule } from '@angular/material/icon';
templateUrl: './file-dropzone.html',
})
export class FileDropzone {
@Input() accept: string[] = ['xlsx', 'csv', 'json', 'pdf'];
@Input() multiple = true;
@Output() readonly filesChange = new EventEmitter<File[]>();
readonly accept = input.required<string[]>();
readonly multiple = input(true);
readonly keepSelection = input(true);
readonly filesChange = output<File[]>();
readonly files = signal<File[]>([]);
readonly fileMessages = signal<string[]>([]);
@@ -21,15 +26,15 @@ export class FileDropzone {
private dragDepth = 0;
get allowedExtensions(): Set<string> {
return new Set(this.accept.map((extension) => extension.toLowerCase()));
return new Set(this.accept().map((extension) => extension.toLowerCase()));
}
get acceptAttribute(): string {
return this.accept.map((extension) => `.${extension}`).join(',');
return this.accept().map((extension) => `.${extension}`).join(',');
}
get formatsLabel(): string {
return this.accept.map((extension) => extension.toUpperCase()).join(' · ');
return this.accept().map((extension) => extension.toUpperCase()).join(' · ');
}
onFileSelection(event: Event): void {
@@ -88,7 +93,8 @@ export class FileDropzone {
private addFiles(incomingFiles: File[]): void {
const messages: string[] = [];
const accepted = this.multiple ? [...this.files()] : [];
const kept = this.keepSelection() && this.multiple() ? [...this.files()] : [];
const accepted = [...kept];
for (const file of incomingFiles) {
const extension = this.extensionOf(file.name);
@@ -104,16 +110,20 @@ export class FileDropzone {
messages.push(`${file.name} ya se encuentra seleccionado.`);
continue;
}
if (!this.multiple) {
if (!this.multiple()) {
accepted.length = 0;
}
accepted.push(file);
if (!this.multiple) break;
if (!this.multiple()) break;
}
this.files.set(accepted);
this.fileMessages.set(messages);
this.filesChange.emit(accepted);
if (this.keepSelection()) {
this.files.set(accepted);
this.filesChange.emit(accepted);
} else if (accepted.length > kept.length) {
this.filesChange.emit(accepted.slice(kept.length));
}
}
private extensionOf(fileName: string): string {
@@ -20,6 +20,9 @@
{{ o.merged | number }} combinadas con registros de otras fuentes@if (o.warnings) {, {{ o.warnings | number }} valor(es) en desacuerdo}.
}
</p>
@if (o.created + o.updated > 0) {
<p class="lead">Los indicadores se recalcularán automáticamente. El avance y el resumen de esta carga pueden consultarse en la Bitácora de cargas.</p>
}
}
<table mat-table [dataSource]="flows()" class="flows">
@@ -49,7 +52,7 @@
<ng-container matColumnDef="outcome">
<th mat-header-cell *matHeaderCellDef>Resultado</th>
<td mat-cell *matCellDef="let flow">
@if (resultOf(flow); as result) {
@if (flow.result(); as result) {
+{{ result.created }} · ↻{{ result.updated }} · ✕{{ result.rejected }}@if (result.merged) { · ⧉{{ result.merged }} }
} @else {
—
@@ -37,12 +37,7 @@ export class LoadDialog implements OnInit {
/** With merging, rows incomplete on their own may be completed by another source. */
readonly canLoad = computed(() => this.totals().valid > 0 || (this.store.mergeDuplicates() && this.totals().rows > 0));
/**
* The flows the next batch would write. Reactive to the merge checkbox
* while nothing has loaded yet, so ticking it reveals the flow it
* completes; frozen the moment a batch starts, so the results table
* keeps listing exactly what was sent.
*/
/** The flows the next batch writes; frozen once it starts so the results match what was sent. */
private readonly _frozenFlows = signal<ImportFlow[] | null>(null);
readonly flows = computed(() => this._frozenFlows() ?? this.store.submittableFlows());
readonly skipped = computed(() => this.store.flows().filter((flow) => !this.flows().includes(flow) && !flow.canSubmit));
@@ -85,7 +80,7 @@ export class LoadDialog implements OnInit {
this.store.setOnConflict(strategy);
}
/** Toggling may bring an until-now-skipped flow into `flows()`; preview its rows too. */
/** Merging can add flows to the batch; validate them so their rows show up in the preview. */
toggleMerge(merge: boolean): void {
this.store.setMergeDuplicates(merge);
Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow)));
@@ -99,8 +94,4 @@ export class LoadDialog implements OnInit {
explore(): void {
this.dialogRef.close('explore');
}
resultOf(flow: ImportFlow) {
return flow.result();
}
}
@@ -6,8 +6,9 @@ import { FileConnection } from './file-source';
import { PdfConnection } from './pdf-source';
/** Turns the files chosen for one source kind into workspace connections. */
export type ConnectionFactory = (files: File[]) => DataConnection[];
type ConnectionFactory = (files: File[]) => DataConnection[];
// Adding a file source on the client is one `DataConnection` subclass and one entry here.
const FACTORIES = new Map<SourceType, ConnectionFactory>([
['csv', (files) => files.map((file) => new FileConnection(file, 'csv'))],
['excel', (files) => files.map((file) => new FileConnection(file, 'excel'))],
@@ -18,11 +19,6 @@ const FACTORIES = new Map<SourceType, ConnectionFactory>([
['document', (files) => [new DocumentConnection(files)]],
]);
/** Adding a file source on the client is one `DataConnection` subclass and one call here. */
export function registerConnectionFactory(kind: SourceType, factory: ConnectionFactory): void {
FACTORIES.set(kind, factory);
}
export function connectionsFor(kind: SourceType, files: File[]): DataConnection[] {
const factory = FACTORIES.get(kind);
return factory && files.length ? factory(files) : [];
+2 -8
View File
@@ -134,12 +134,7 @@ export class ImportFlow {
return !['loading', 'error', 'incomplete'].includes(this.status());
}
/**
* Belongs in the next load: complete and not already written. A loaded
* flow stays out of later batches (re-sending it would duplicate rows in
* tables without a natural key) until it's edited, since any edit clears
* its result.
*/
/** Complete and not yet written; editing a loaded flow clears its result and makes it pending again. */
get pendingLoad(): boolean {
return this.canSubmit && this.status() !== 'loaded';
}
@@ -162,7 +157,7 @@ export class ImportFlow {
);
}
// -- mapping edits (every one invalidates the last validation) -----------
// Every mapping edit invalidates the last validation.
map(source: string, field: string): void {
this.mapping.assign(source, field);
@@ -210,7 +205,6 @@ export class ImportFlow {
return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== ''));
}
// -- backend round trips ---------------------------------------------------
async toPayload(): Promise<ImportSourcePayload> {
const locator = await this.table.locator(this.target.key);
-1
View File
@@ -52,7 +52,6 @@ const SQL_DIALECT_LABELS: Record<string, string> = {
mariadb: 'MariaDB',
postgresql: 'PostgreSQL',
mssql: 'SQL Server',
oracle: 'Oracle',
sqlite: 'SQLite',
};
@@ -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' },
];
@@ -75,12 +75,7 @@ export class ConnectWorkspaceStore {
/** A batch writes to one domain's database, so the domain can only change while there are no flows. */
readonly domainLocked = computed(() => this._flows().length > 0);
/**
* Flows with a known target and a natural key, not still loading/erroring
* and not already written — candidates to combine by `mergeDuplicates`,
* complete or not (a source missing a required field may still supply
* others a sibling source lacks).
*/
/** Unwritten flows into a keyed target: what `mergeDuplicates` may combine, complete or not. */
private readonly mergeCandidateFlows = computed(() =>
this._flows().filter((flow) => !!flow.target.conflict_fields && !['loading', 'error', 'loaded'].includes(flow.status())),
);
@@ -97,13 +92,7 @@ export class ConnectWorkspaceStore {
return new Set([...counts].filter(([, count]) => count > 1).map(([key]) => key));
});
/**
* Flows the next batch will write. Normally just the complete ones; with
* `mergeDuplicates` on, a flow missing a required field joins them too
* when another flow targets the same keyed entity — the gap may be
* exactly what that other source supplies, so the batch combines them
* before validating instead of dropping the incomplete one silently.
*/
/** Flows the next batch writes: the complete ones, plus incomplete ones another flow may complete when merging. */
readonly submittableFlows = computed(() => {
const complete = this._flows().filter((flow) => flow.pendingLoad);
if (!this._mergeDuplicates()) return complete;
+10
View File
@@ -0,0 +1,10 @@
:host { display: contents; }
.domain-selector {
flex: 0 0 auto;
background-color: var(--issste-accent);
color: var(--issste-text);
font-weight: 700;
white-space: nowrap;
}
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
+28
View File
@@ -0,0 +1,28 @@
import { Component, input } from '@angular/core';
import { RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { Dominio } from './features/indicadores/indicadores.models';
/** The header's domain menu. Loaded deferred: Material's menu and overlay are not needed by the institutional routes. */
@Component({
selector: 'app-domain-selector',
imports: [RouterLink, MatButtonModule, MatMenuModule],
template: `
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
[attr.aria-label]="'Dominio actual: ' + labels()[actual()] + '. Cambiar dominio'">
{{ labels()[actual()] }} <span aria-hidden="true">▾</span>
</button>
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
@for (option of otros(); track option) {
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ labels()[option] }}</a>
}
</mat-menu>
`,
styleUrl: './domain-selector.scss',
})
export class DomainSelector {
readonly actual = input.required<Dominio>();
readonly otros = input.required<readonly Dominio[]>();
readonly labels = input.required<Record<Dominio, string>>();
}
@@ -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' })
@@ -39,12 +39,18 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
expect(root.textContent).toContain('Ventana consultada:');
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
expect(root.textContent).toContain('Insatisfactoria');
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/);
expect(root.querySelector('tbody tr td:last-child')?.textContent).toBe('No disponible');
expect(root.querySelector('tbody tr td:nth-child(8)')?.textContent).toBe('No disponible');
expect(root.querySelector('thead')?.textContent).not.toContain('Acciones');
expect(root.querySelectorAll('tbody button.patient-link')).toHaveLength(10);
expect(root.querySelector('tbody button.patient-link')?.getAttribute('aria-label')).toContain(fixture.componentInstance.data?.items[0].id_seudonimo);
expect(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15');
expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull();
});
@@ -86,7 +92,8 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
});
it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
it('tea conserva su estado pendiente sin consultas de pacientes', () => {
const dominio = 'tea';
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
@@ -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();
}
@@ -0,0 +1,56 @@
[
{
"id": "cama_dias_resultado_diagnostico",
"titulo": "Tiempo de resultado a diagnóstico",
"version": "0.1.0",
"contrato": "C3r",
"unidad": "examen",
"sentido": "decrease",
"tipos_periodo": [
"semestre",
"mes"
],
"figuras": [
"fig_c3r_caja"
],
"estratos": [],
"filtros": []
},
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"sentido": null,
"tipos_periodo": [
"semestre",
"mes"
],
"figuras": [
"fig_c2_barras",
"fig_c2_donas"
],
"estratos": [
"birads"
],
"filtros": []
},
{
"id": "cama_tasa_deteccion_histopatologica",
"titulo": "Detección histopatológica",
"version": "0.1.0",
"contrato": "C1",
"unidad": "examen",
"sentido": null,
"tipos_periodo": [
"semestre",
"mes"
],
"figuras": [
"fig_c1_puntos"
],
"estratos": [],
"filtros": []
}
]
@@ -0,0 +1,63 @@
{
"id": "cama_dias_resultado_diagnostico",
"titulo": "Tiempo de resultado a diagnóstico",
"version": "0.1.0",
"contrato": "C3r",
"unidad": "examen",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Días de resultado a diagnóstico"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [
"Sin nota hasta el corte no hay observación. Convención provisional."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 71,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2026-11-12",
"generado_en": "2026-11-12T17:00:26.219496+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "5e4badce17afe0141e8296c9edd88ff1ce50a21c8c278d1aad5327069830d251",
"parametros": {
"sql": {
"_catalogo": [],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2026-11-12",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"n": null,
"mediana": null,
"q1": null,
"q3": null,
"n_sin_evento": 0,
"n_excluido": 0,
"suprimido": 1,
"unidad": "dias"
}
],
"totales_estrato": []
}
@@ -0,0 +1,63 @@
{
"id": "cama_dias_resultado_diagnostico",
"titulo": "Tiempo de resultado a diagnóstico",
"version": "0.1.0",
"contrato": "C3r",
"unidad": "examen",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Días de resultado a diagnóstico"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [
"Sin nota hasta el corte no hay observación. Convención provisional."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 71,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2026-11-12",
"generado_en": "2026-11-12T17:00:38.264922+00:00",
"kit_version": "0.8.0",
"toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7",
"parametros_sha": "f26ecdc2fcef0aa015f8997b7c1aa2053678cb86ca9cff9b1524efaf000971ad",
"parametros": {
"sql": {
"_catalogo": [],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2026-11-12",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 1
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"n": 4,
"mediana": 6.5,
"q1": 2.25,
"q3": 12.5,
"n_sin_evento": 0,
"n_excluido": 1,
"suprimido": 0,
"unidad": "dias"
}
],
"totales_estrato": []
}
@@ -0,0 +1,477 @@
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": "birads",
"valores_estrato": [
"BIRADS_4",
"BIRADS_4A",
"BIRADS_4B",
"BIRADS_4C",
"BIRADS_5",
"BIRADS_6"
],
"etiquetas_estrato": {
"BIRADS_4": "BI-RADS 4 sin subtipo",
"BIRADS_4A": "BI-RADS 4A",
"BIRADS_4B": "BI-RADS 4B",
"BIRADS_4C": "BI-RADS 4C",
"BIRADS_5": "BI-RADS 5",
"BIRADS_6": "BI-RADS 6"
},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"BENIGNO": {
"etiqueta": "Benigno",
"color": "#9DBFE3",
"grupo": "NO_MALIGNO",
"gravedad": 1
},
"RIESGO_B3": {
"etiqueta": "Lesión de riesgo (B3)",
"color": "#2F6DB3",
"grupo": "NO_MALIGNO",
"gravedad": 2
},
"IN_SITU": {
"etiqueta": "Carcinoma in situ",
"color": "#D9822B",
"grupo": "MALIGNO",
"gravedad": 3
},
"INVASOR": {
"etiqueta": "Carcinoma invasor",
"color": "#B5482E",
"grupo": "MALIGNO",
"gravedad": 4
},
"SIN_BIOPSIA": {
"etiqueta": "Sin biopsia reportada",
"color": "#C9CDD2",
"grupo": null,
"gravedad": null
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_MALIGNO": "No maligno",
"MALIGNO": "Maligno",
"SIN_DATO": "Sin dato"
},
"notas": [
"Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 141,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2025-12-31",
"generado_en": "2026-11-12T16:33:37.621606+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
"parametros": {
"sql": {
"_catalogo": [
"BENIGNO",
"RIESGO_B3",
"IN_SITU",
"INVASOR"
],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2025-12-31",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "BENIGNO",
"n": 2,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "RIESGO_B3",
"n": 0,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "INVASOR",
"n": 2,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
}
],
"totales_estrato": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"n": 7,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"n": 6,
"suprimido": 0
}
]
}
@@ -0,0 +1,150 @@
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"BENIGNO": {
"etiqueta": "Benigno",
"color": "#9DBFE3",
"grupo": "NO_MALIGNO",
"gravedad": 1
},
"RIESGO_B3": {
"etiqueta": "Lesión de riesgo (B3)",
"color": "#2F6DB3",
"grupo": "NO_MALIGNO",
"gravedad": 2
},
"IN_SITU": {
"etiqueta": "Carcinoma in situ",
"color": "#D9822B",
"grupo": "MALIGNO",
"gravedad": 3
},
"INVASOR": {
"etiqueta": "Carcinoma invasor",
"color": "#B5482E",
"grupo": "MALIGNO",
"gravedad": 4
},
"SIN_BIOPSIA": {
"etiqueta": "Sin biopsia reportada",
"color": "#C9CDD2",
"grupo": null,
"gravedad": null
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_MALIGNO": "No maligno",
"MALIGNO": "Maligno",
"SIN_DATO": "Sin dato"
},
"notas": [
"Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 141,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2025-12-31",
"generado_en": "2026-11-12T16:33:37.621606+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
"parametros": {
"sql": {
"_catalogo": [
"BENIGNO",
"RIESGO_B3",
"IN_SITU",
"INVASOR"
],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2025-12-31",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "BENIGNO",
"n": 7,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "RIESGO_B3",
"n": 5,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "IN_SITU",
"n": 6,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "INVASOR",
"n": 7,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_BIOPSIA",
"n": 6,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_DATO",
"n": 6,
"orden": 5,
"suprimido": 0
}
],
"totales_estrato": []
}
@@ -0,0 +1,235 @@
{
"campo_ventana": "mastografia_fecha",
"columnas": [
{
"clave": "id_seudonimo",
"etiqueta": "Identificador seudónimo"
},
{
"clave": "grupo_edad",
"etiqueta": "Grupo de edad"
},
{
"clave": "estatus",
"etiqueta": "Estatus de seguimiento"
},
{
"clave": "birads",
"detalles": [
{
"clave": "mastografia_fecha",
"etiqueta": "Fecha"
}
],
"etiqueta": "Última mastografía"
},
{
"clave": "biopsia",
"detalles": [
{
"clave": "biopsia_fecha",
"etiqueta": "Fecha de biopsia"
}
],
"etiqueta": "Resultado histopatológico"
},
{
"clave": "dias_mastografia_diagnostico",
"etiqueta": "Días de mastografía a diagnóstico"
},
{
"clave": "prioridad",
"etiqueta": "Prioridad"
}
],
"corte": "2026-10-20",
"filtros": {
"birads": null,
"estatus": null,
"grupo_edad": null,
"prioridad": null
},
"filtros_disponibles": [
{
"clave": "estatus",
"etiqueta": "Estatus de seguimiento",
"opciones": [
{
"codigo": "PENDIENTE_BIOPSIA",
"etiqueta": "Pendiente de biopsia"
},
{
"codigo": "BIOPSIA_SIN_RESULTADO",
"etiqueta": "Biopsia sin resultado"
},
{
"codigo": "CANCER_CONFIRMADO",
"etiqueta": "Cáncer confirmado"
},
{
"codigo": "BENIGNO",
"etiqueta": "Benigno, regresa a tamizaje"
},
{
"codigo": "INFO_INSUFICIENTE",
"etiqueta": "Información insuficiente"
}
]
},
{
"clave": "birads",
"etiqueta": "Categoría BI-RADS",
"opciones": [
{
"codigo": "BIRADS_4A",
"etiqueta": "BI-RADS 4A"
},
{
"codigo": "BIRADS_4B",
"etiqueta": "BI-RADS 4B"
},
{
"codigo": "BIRADS_4C",
"etiqueta": "BI-RADS 4C"
},
{
"codigo": "BIRADS_5",
"etiqueta": "BI-RADS 5"
},
{
"codigo": "BIRADS_6",
"etiqueta": "BI-RADS 6"
}
]
},
{
"clave": "grupo_edad",
"etiqueta": "Grupo de edad",
"opciones": [
{
"codigo": "40-49",
"etiqueta": "40-49"
},
{
"codigo": "50-59",
"etiqueta": "50-59"
},
{
"codigo": "60-69",
"etiqueta": "60-69"
},
{
"codigo": "70+",
"etiqueta": "70+"
}
]
},
{
"clave": "prioridad",
"etiqueta": "Prioridad",
"opciones": [
{
"codigo": "ALTA",
"etiqueta": "Alta"
},
{
"codigo": "MEDIA",
"etiqueta": "Media"
},
{
"codigo": "BAJA",
"etiqueta": "Baja"
}
]
}
],
"items": [
{
"biopsia": null,
"biopsia_fecha": null,
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"dias_mastografia_diagnostico": null,
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"id_seudonimo": "M-0001",
"mastografia_fecha": "2026-10-15",
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"biopsia": null,
"biopsia_fecha": "2026-10-18",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"dias_mastografia_diagnostico": null,
"estatus": "Biopsia sin resultado",
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
"grupo_edad": "40-49",
"grupo_edad_codigo": "40-49",
"id_seudonimo": "M-0002",
"mastografia_fecha": "2026-10-15",
"prioridad": "Media",
"prioridad_codigo": "MEDIA"
},
{
"biopsia": "Benigno",
"biopsia_fecha": "2026-09-10",
"birads": "BI-RADS 4B",
"birads_codigo": "BIRADS_4B",
"dias_mastografia_diagnostico": 16,
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"id_seudonimo": "M-0003",
"mastografia_fecha": "2026-09-01",
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-08-22",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"dias_mastografia_diagnostico": 20,
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"grupo_edad": "70+",
"grupo_edad_codigo": "70+",
"id_seudonimo": "M-0004",
"mastografia_fecha": "2026-08-15",
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"biopsia": null,
"biopsia_fecha": null,
"birads": "BI-RADS 6",
"birads_codigo": "BIRADS_6",
"dias_mastografia_diagnostico": null,
"estatus": "Información insuficiente",
"estatus_codigo": "INFO_INSUFICIENTE",
"grupo_edad": "40-49",
"grupo_edad_codigo": "40-49",
"id_seudonimo": "M-0005",
"mastografia_fecha": "2026-07-21",
"prioridad": "Media",
"prioridad_codigo": "MEDIA"
}
],
"paginacion": {
"page": 1,
"page_size": 50,
"total_items": 5,
"total_pages": 1
},
"simulado": true,
"ventana": {
"desde": "2026-07-21",
"hasta": "2026-10-20",
"meses": 3
}
}
@@ -0,0 +1,159 @@
{
"campo_ventana": "mastografia_fecha",
"columnas": [
{
"clave": "id_seudonimo",
"etiqueta": "Identificador seudónimo"
},
{
"clave": "grupo_edad",
"etiqueta": "Grupo de edad"
},
{
"clave": "estatus",
"etiqueta": "Estatus de seguimiento"
},
{
"clave": "birads",
"detalles": [
{
"clave": "mastografia_fecha",
"etiqueta": "Fecha"
}
],
"etiqueta": "Última mastografía"
},
{
"clave": "biopsia",
"detalles": [
{
"clave": "biopsia_fecha",
"etiqueta": "Fecha de biopsia"
}
],
"etiqueta": "Resultado histopatológico"
},
{
"clave": "dias_mastografia_diagnostico",
"etiqueta": "Días de mastografía a diagnóstico"
},
{
"clave": "prioridad",
"etiqueta": "Prioridad"
}
],
"corte": "2026-10-20",
"filtros": {
"birads": null,
"estatus": null,
"grupo_edad": null,
"prioridad": "ALTA"
},
"filtros_disponibles": [
{
"clave": "estatus",
"etiqueta": "Estatus de seguimiento",
"opciones": [
{
"codigo": "PENDIENTE_BIOPSIA",
"etiqueta": "Pendiente de biopsia"
},
{
"codigo": "BIOPSIA_SIN_RESULTADO",
"etiqueta": "Biopsia sin resultado"
},
{
"codigo": "CANCER_CONFIRMADO",
"etiqueta": "Cáncer confirmado"
},
{
"codigo": "BENIGNO",
"etiqueta": "Benigno, regresa a tamizaje"
},
{
"codigo": "INFO_INSUFICIENTE",
"etiqueta": "Información insuficiente"
}
]
},
{
"clave": "birads",
"etiqueta": "Categoría BI-RADS",
"opciones": [
{
"codigo": "BIRADS_4A",
"etiqueta": "BI-RADS 4A"
},
{
"codigo": "BIRADS_4B",
"etiqueta": "BI-RADS 4B"
},
{
"codigo": "BIRADS_4C",
"etiqueta": "BI-RADS 4C"
},
{
"codigo": "BIRADS_5",
"etiqueta": "BI-RADS 5"
},
{
"codigo": "BIRADS_6",
"etiqueta": "BI-RADS 6"
}
]
},
{
"clave": "grupo_edad",
"etiqueta": "Grupo de edad",
"opciones": [
{
"codigo": "40-49",
"etiqueta": "40-49"
},
{
"codigo": "50-59",
"etiqueta": "50-59"
},
{
"codigo": "60-69",
"etiqueta": "60-69"
},
{
"codigo": "70+",
"etiqueta": "70+"
}
]
},
{
"clave": "prioridad",
"etiqueta": "Prioridad",
"opciones": [
{
"codigo": "ALTA",
"etiqueta": "Alta"
},
{
"codigo": "MEDIA",
"etiqueta": "Media"
},
{
"codigo": "BAJA",
"etiqueta": "Baja"
}
]
}
],
"items": [],
"paginacion": {
"page": 4,
"page_size": 1,
"total_items": 3,
"total_pages": 3
},
"simulado": true,
"ventana": {
"desde": "2025-10-21",
"hasta": "2026-10-20",
"meses": 12
}
}
@@ -0,0 +1,565 @@
{
"simulado": true,
"corte": "2026-10-20",
"ventana": {
"meses": 3,
"desde": "2026-07-21",
"hasta": "2026-10-20"
},
"campo_ventana": "mastografia_fecha",
"filtros": {
"estatus": null,
"birads": null,
"grupo_edad": null,
"prioridad": null
},
"filtros_disponibles": [
{
"clave": "estatus",
"etiqueta": "Estatus de seguimiento",
"opciones": [
{
"codigo": "PENDIENTE_BIOPSIA",
"etiqueta": "Pendiente de biopsia"
},
{
"codigo": "BIOPSIA_SIN_RESULTADO",
"etiqueta": "Biopsia sin resultado"
},
{
"codigo": "CANCER_CONFIRMADO",
"etiqueta": "Cáncer confirmado"
},
{
"codigo": "BENIGNO",
"etiqueta": "Benigno, regresa a tamizaje"
},
{
"codigo": "INFO_INSUFICIENTE",
"etiqueta": "Información insuficiente"
}
]
},
{
"clave": "birads",
"etiqueta": "Categoría BI-RADS",
"opciones": [
{
"codigo": "BIRADS_4A",
"etiqueta": "BI-RADS 4A"
},
{
"codigo": "BIRADS_4B",
"etiqueta": "BI-RADS 4B"
},
{
"codigo": "BIRADS_4C",
"etiqueta": "BI-RADS 4C"
},
{
"codigo": "BIRADS_5",
"etiqueta": "BI-RADS 5"
},
{
"codigo": "BIRADS_6",
"etiqueta": "BI-RADS 6"
}
]
},
{
"clave": "grupo_edad",
"etiqueta": "Grupo de edad",
"opciones": [
{
"codigo": "40-49",
"etiqueta": "40-49"
},
{
"codigo": "50-59",
"etiqueta": "50-59"
},
{
"codigo": "60-69",
"etiqueta": "60-69"
},
{
"codigo": "70+",
"etiqueta": "70+"
}
]
},
{
"clave": "prioridad",
"etiqueta": "Prioridad",
"opciones": [
{
"codigo": "ALTA",
"etiqueta": "Alta"
},
{
"codigo": "MEDIA",
"etiqueta": "Media"
},
{
"codigo": "BAJA",
"etiqueta": "Baja"
}
]
}
],
"columnas": [
{
"clave": "id_seudonimo",
"etiqueta": "Identificador seudónimo"
},
{
"clave": "grupo_edad",
"etiqueta": "Grupo de edad"
},
{
"clave": "estatus",
"etiqueta": "Estatus de seguimiento"
},
{
"clave": "birads",
"etiqueta": "Última mastografía",
"detalles": [
{
"clave": "mastografia_fecha",
"etiqueta": "Fecha"
}
]
},
{
"clave": "biopsia",
"etiqueta": "Resultado histopatológico",
"detalles": [
{
"clave": "biopsia_fecha",
"etiqueta": "Fecha de biopsia"
}
]
},
{
"clave": "dias_mastografia_diagnostico",
"etiqueta": "Días de mastografía a diagnóstico"
},
{
"clave": "prioridad",
"etiqueta": "Prioridad"
}
],
"paginacion": {
"page": 1,
"page_size": 50,
"total_items": 27,
"total_pages": 1
},
"items": [
{
"id_seudonimo": "M-0081",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"mastografia_fecha": "2026-07-25",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0020",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Información insuficiente",
"estatus_codigo": "INFO_INSUFICIENTE",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-07-31",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0051",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-08-01",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0022",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"birads": "BI-RADS 6",
"birads_codigo": "BIRADS_6",
"mastografia_fecha": "2026-08-03",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0029",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Biopsia sin resultado",
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-08-13",
"biopsia": null,
"biopsia_fecha": "2026-09-11",
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0019",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-08-21",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0064",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Información insuficiente",
"estatus_codigo": "INFO_INSUFICIENTE",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-08-22",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0048",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"estatus": "Biopsia sin resultado",
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-09-01",
"biopsia": null,
"biopsia_fecha": "2026-10-07",
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0059",
"grupo_edad": "40-49",
"grupo_edad_codigo": "40-49",
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-09-05",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0050",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"estatus": "Información insuficiente",
"estatus_codigo": "INFO_INSUFICIENTE",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-09-06",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0084",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Biopsia sin resultado",
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-09-08",
"biopsia": null,
"biopsia_fecha": "2026-09-18",
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0054",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"estatus": "Pendiente de biopsia",
"estatus_codigo": "PENDIENTE_BIOPSIA",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-10-04",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Alta",
"prioridad_codigo": "ALTA"
},
{
"id_seudonimo": "M-0035",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Biopsia sin resultado",
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
"birads": "BI-RADS 4B",
"birads_codigo": "BIRADS_4B",
"mastografia_fecha": "2026-08-21",
"biopsia": null,
"biopsia_fecha": "2026-08-31",
"dias_mastografia_diagnostico": null,
"prioridad": "Media",
"prioridad_codigo": "MEDIA"
},
{
"id_seudonimo": "M-0052",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Información insuficiente",
"estatus_codigo": "INFO_INSUFICIENTE",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"mastografia_fecha": "2026-10-01",
"biopsia": null,
"biopsia_fecha": null,
"dias_mastografia_diagnostico": null,
"prioridad": "Media",
"prioridad_codigo": "MEDIA"
},
{
"id_seudonimo": "M-0033",
"grupo_edad": "40-49",
"grupo_edad_codigo": "40-49",
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-07-25",
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-09-03",
"dias_mastografia_diagnostico": 15,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0040",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"mastografia_fecha": "2026-07-25",
"biopsia": "Benigno",
"biopsia_fecha": "2026-08-16",
"dias_mastografia_diagnostico": 71,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0011",
"grupo_edad": "40-49",
"grupo_edad_codigo": "40-49",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4B",
"birads_codigo": "BIRADS_4B",
"mastografia_fecha": "2026-08-08",
"biopsia": "Benigno",
"biopsia_fecha": "2026-08-16",
"dias_mastografia_diagnostico": 46,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0047",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-08-28",
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-09-28",
"dias_mastografia_diagnostico": 36,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0038",
"grupo_edad": "60-69",
"grupo_edad_codigo": "60-69",
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"mastografia_fecha": "2026-08-29",
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-10-08",
"dias_mastografia_diagnostico": 42,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0072",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"mastografia_fecha": "2026-09-03",
"biopsia": "Benigno",
"biopsia_fecha": "2026-09-26",
"dias_mastografia_diagnostico": 49,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0021",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-09-07",
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-09-27",
"dias_mastografia_diagnostico": 56,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0039",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4C",
"birads_codigo": "BIRADS_4C",
"mastografia_fecha": "2026-09-08",
"biopsia": "Benigno",
"biopsia_fecha": "2026-09-17",
"dias_mastografia_diagnostico": 27,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0083",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"birads": "BI-RADS 5",
"birads_codigo": "BIRADS_5",
"mastografia_fecha": "2026-09-20",
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-09-27",
"dias_mastografia_diagnostico": 25,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0062",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4A",
"birads_codigo": "BIRADS_4A",
"mastografia_fecha": "2026-09-26",
"biopsia": "Benigno",
"biopsia_fecha": "2026-10-14",
"dias_mastografia_diagnostico": 19,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0032",
"grupo_edad": "40-49",
"grupo_edad_codigo": "40-49",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4B",
"birads_codigo": "BIRADS_4B",
"mastografia_fecha": "2026-10-07",
"biopsia": "Benigno",
"biopsia_fecha": "2026-10-20",
"dias_mastografia_diagnostico": 61,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0077",
"grupo_edad": "50-59",
"grupo_edad_codigo": "50-59",
"estatus": "Benigno, regresa a tamizaje",
"estatus_codigo": "BENIGNO",
"birads": "BI-RADS 4B",
"birads_codigo": "BIRADS_4B",
"mastografia_fecha": "2026-10-14",
"biopsia": "Lesión de riesgo (B3)",
"biopsia_fecha": "2026-10-20",
"dias_mastografia_diagnostico": 60,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
},
{
"id_seudonimo": "M-0027",
"grupo_edad": "70+",
"grupo_edad_codigo": "70+",
"estatus": "Cáncer confirmado",
"estatus_codigo": "CANCER_CONFIRMADO",
"birads": "BI-RADS 4B",
"birads_codigo": "BIRADS_4B",
"mastografia_fecha": "2026-10-16",
"biopsia": "Carcinoma invasor",
"biopsia_fecha": "2026-10-20",
"dias_mastografia_diagnostico": 36,
"prioridad": "Baja",
"prioridad_codigo": "BAJA"
}
]
}
@@ -0,0 +1,59 @@
{
"id": "cama_tasa_deteccion_histopatologica",
"titulo": "Detección histopatológica",
"version": "0.1.0",
"contrato": "C1",
"unidad": "examen",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [
"Detección histopatológica"
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 127,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2026-11-12",
"generado_en": "2026-11-12T17:00:31.282549+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "d909bc4a153b244533acde1f26ce8c4cfaaedf0d277239dd9b1ce9e9f65b23a9",
"parametros": {
"sql": {
"fecha_corte": "2026-11-12",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "total",
"estrato": null,
"numerador": null,
"denominador": null,
"valor": null,
"ic_bajo": null,
"ic_alto": null,
"suprimido": 1,
"n_sin_evento": 0,
"n_excluido": 0
}
],
"totales_estrato": []
}
@@ -0,0 +1,59 @@
{
"id": "cama_tasa_deteccion_histopatologica",
"titulo": "Detección histopatológica",
"version": "0.1.0",
"contrato": "C1",
"unidad": "examen",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [
"Detección histopatológica"
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 127,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2026-11-12",
"generado_en": "2026-11-12T17:00:42.857591+00:00",
"kit_version": "0.8.0",
"toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7",
"parametros_sha": "7202a2779ae47c29a7659dd6fdfb77e8895d4d778a772ff13cc2ce93c5a6e871",
"parametros": {
"sql": {
"fecha_corte": "2026-11-12",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 1
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "total",
"estrato": null,
"numerador": 0,
"denominador": 1,
"valor": 0.0,
"ic_bajo": 0.0,
"ic_alto": 79.3450688208,
"suprimido": 0,
"n_sin_evento": 1,
"n_excluido": 0
}
],
"totales_estrato": []
}
@@ -17,31 +17,57 @@ import { filterCompatibility } from './indicadores-memory';
import { DonutSelection } from './indicadores-donut-drilldown';
import { IndicadoresService } from './indicadores.service';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama';
import { parTiempos } from './indicadores-tiempos-pareados';
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
import { parConteos } from './indicadores-conteos-pareados';
@Component({
selector: 'app-indicador-catalog-card',
host: { '[class.dual-card]': 'isDual || isEu7' },
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario],
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
template: `
<mat-card>
<header>
<div class="card-identity">
<h2 [id]="titleId">{{ indicador.titulo }}</h2>
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</div>
</header>
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ' · ' + indicador.titulo"
(click)="pinChanged.emit()">
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button>
@if (!sobrio) {
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
(click)="pinChanged.emit()">
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button>
}
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
<p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p>
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
@if (isEu7) {
<div #visibilityRegion class="eu7-region">
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (isConfirmacion) {
<div #visibilityRegion class="confirmacion-region">
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (isHistopatologia) {
<div #visibilityRegion class="confirmacion-region">
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (tiempos; as par) {
<div #visibilityRegion class="tiempos-region">
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (conteos; as par) {
<div #visibilityRegion class="conteos-region">
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (selectedFigure) {
@if (!pair.length || otherFigures.length) {
@if (!sobrio && (!pair.length || otherFigures.length)) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Representación gráfica</mat-label>
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
@@ -91,7 +117,7 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
}
.card-identity { min-width: 0; }
h2, p { overflow-wrap: anywhere; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
min-width: 48px; min-height: 48px; color: var(--issste-text); }
.pin-toggle mat-icon { flex-shrink: 0; }
@@ -119,8 +145,17 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
});
}
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
get sobrio() { return this.dominio === 'cama'; }
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
// Connected time pairs replace the diagnosis card with one coordinated box plot.
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
// Exams and patients of the same finding, drawn together on the exams' card.
get conteos() { return parConteos(this.dominio, this.indicador.id); }
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
@@ -0,0 +1,77 @@
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de la confirmación histopatológica">
<button type="button" aria-label="Periodo anterior de la confirmación" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
<button type="button" aria-label="Periodo siguiente de la confirmación" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
<div class="keys" role="group" aria-label="Grados del anillo exterior">
@for (c of m.grados; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
</div>
</div>
<div class="figures">
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
@if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + m.periodo + ', ' + selectionLabel" />
}
<ul class="rate-states">
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
</ul>
</section>
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de contingencia de citología y biopsia" tabindex="0">
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
<tbody>@for (fila of m.filas; track fila.id) {
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
}</tbody>
</table>
</div>
</details>
}
}
</section>
@@ -0,0 +1,37 @@
:host { display: block; min-width: 0; }
.confirmacion { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
.applied-summary, .note { color: var(--issste-text-secondary); }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.selection-status { font-weight: 600; }
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
button:disabled { opacity: .5; cursor: default; }
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
h3 { font-size: 1rem; line-height: 1.5; }
app-plotly-chart { --plot-height: 440px; }
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
.periods span { text-align: center; }
.periods button { min-width: 44px; font-size: 1.5rem; }
summary { cursor: pointer; padding-block: .75rem; }
.table-scroll { overflow: auto; max-height: 28rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
.reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide + .reading-guide { margin-top: 1rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
.reading-guide li + li { margin-top: .25rem; }
app-plotly-chart { --plot-height: 360px; }
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
.rate-states:empty { display: none; }
/* Rates on the left, donut on the right (the reverse of EU7). */
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } }
@@ -0,0 +1,140 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
Celda, tasas } from './indicadores-confirmacion-citologia';
// Figures of the kit whose "Cómo leer" describes this coordinated view.
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
@Component({
selector: 'app-indicador-confirmacion-citologia',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-confirmacion-citologia.html',
styleUrl: './indicador-confirmacion-citologia.scss',
})
export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
selection?: SeleccionConfirmacion;
periods: string[] = [];
periodIndex = 0;
model?: ModeloConfirmacion;
donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure;
helpOpen = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
private pages: ModeloConfirmacion[] = [];
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
readonly estadoTasa = estadoTasa;
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
get readingGuide() {
const details = this.metadata?.figuras_detalle ?? [];
return FIGURAS.flatMap(([figura, nombre]) => {
const detail = details.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
this.clear();
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
}
retry() { if (this.visible) this.load(); }
private clear() {
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
this.donutFigure = undefined; this.ratesFigure = undefined;
}
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return;
}
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
{ estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({
next: datos => {
if (key !== this.key) return;
try {
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
// The most recent period first, as the prototype; navigation goes back.
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.clear();
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof ConfirmacionIncompatible ? error.message : httpMessage(error);
this.status.set(error instanceof ConfirmacionIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
this.changeDetector.markForCheck();
}
private activatePeriod() {
this.model = this.pages[this.periodIndex];
this.selection = this.model ? seleccionBase(this.model) : undefined;
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
}
changePeriod(step: number) {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.activatePeriod();
}
select(trace: string, index = 0) {
if (!this.model || !this.selection || this.status() !== 'ready') return;
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
}
plotClicked(event: unknown) {
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
}
private draw() {
if (!this.model || !this.selection) return;
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -0,0 +1,57 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
<h3>Dona por categoría</h3>
@if (donutGuide; as guide) {
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
</section>
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
</section>
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
@case ('empty') { <p role="status">No hay periodos publicados por los dos conteos.</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' && model; as m) {
@if (pages.length > 1) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ m.periodo }}, {{ periodIndex + 1 }} de {{ pages.length }}</span>
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === pages.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
<div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
@if (total) {
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section>
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
</section>
</div>
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
</table>
</div>
</details>
}
</section>
@@ -0,0 +1,22 @@
:host { display: block; min-width: 0; }
.conteos { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
.applied-summary, .note { color: var(--issste-text-secondary); }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
.periods button:disabled { opacity: .5; cursor: default; }
// The two figures share the card in equal halves; one above the other on a narrow card.
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
app-plotly-chart { --plot-height: 400px; }
summary { cursor: pointer; padding-block: .75rem; }
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.table-scroll { overflow: auto; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@@ -0,0 +1,119 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { TitleCasePipe } from '@angular/common';
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
@Component({
selector: 'app-indicador-conteos-pareados',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe],
templateUrl: './indicador-conteos-pareados.html',
styleUrl: './indicador-conteos-pareados.scss',
})
export class IndicadorConteosPareados implements OnChanges, OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) par!: ParConteos;
// The card's indicator (the exams); its partner (the patients) has no card and is requested by id.
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
periodIndex = 0;
pages: ModeloConteos[] = [];
donutFigure?: PlotlyFigure;
barsFigure?: PlotlyFigure;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
// On a narrow screen the donut's long label gives way to a legend under it.
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
helpOpen = false;
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
// description of its own bars does not apply to them and is not used.
get donutGuide() {
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
}
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
}
retry() { if (this.visible) this.load(); }
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.';
this.status.set('incompatible'); return;
}
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version),
this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods),
]).pipe(timeout({ first: 40000 })).subscribe({
next: ([examenes, pacientes]) => {
if (key !== this.key) return;
try {
this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo);
// The most recent period first; navigation goes back.
this.periodIndex = Math.max(0, this.pages.length - 1);
this.draw(); this.status.set(this.model ? 'ready' : 'empty');
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.clear();
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof ConteosIncompatibles ? error.message : httpMessage(error);
this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
this.changeDetector.markForCheck();
}
changePeriod(step: number) {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.draw();
}
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
}
@@ -3,29 +3,14 @@
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<p>El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.</p>
<p>Las barras usan el total con resultado válido de cada escenario, excluyendo «Sin dato». Al seleccionar un grupo o categoría se conserva ese denominador.</p>
<p>El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.</p>
<p>Selecciona un grupo para expandirlo y una categoría para resaltarla. Repite el clic para liberar la selección. El centro o el botón Volver regresa de categoría a grupo y después a TOTAL. También puedes usar Tab y Enter o Espacio en la leyenda.</p>
<p>Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.</p>
@if (metadata; as info) {
@if (info.descripcion) { <p>{{ info.descripcion }}</p> }
@if (info.ficha; as ficha) {
@if (ficha.pregunta) { <p>{{ ficha.pregunta }}</p> }
@if (ficha.definicion) { <p>{{ ficha.definicion }}</p> }
@if (ficha.unidad) { <p>Unidad: {{ ficha.unidad }}</p> }
@if (ficha.nota) { <p>{{ ficha.nota }}</p> }
}
<details><summary>Metadatos publicados de las figuras originales</summary>
<p>Estas descripciones corresponden a las figuras publicadas originales. En esta vista coordinada, «Sin dato» queda fuera de la dona y las barras son porcentajes por escenario.</p>
@for (detail of info.figuras_detalle; track detail.figura) {
@if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') {
<p>{{ detail.descripcion }}</p>
@for (line of detail.como_leer; track $index) { <p>{{ line }}</p> }
}
}
@for (reference of info.referencias; track $index) { <p>{{ reference.etiqueta }} {{ reference.ref }}</p> }
</details>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
</div>
}
@@ -39,12 +24,12 @@
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de dona y barras EU7">
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ periods[periodIndex] }} · {{ periodIndex + 1 }} / {{ periods.length }}</span>
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }} · Selección: {{ selectionLabel }}</p>
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
@@ -61,28 +46,28 @@
</div>
</div>
<div class="figures">
<section class="figure"><h3>Distribución de resultados · {{ m.periodo }}</h3>
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
@if (m.total !== null && m.total > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'EU7 · Dona de dos anillos · ' + m.periodo + ' · ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado válido para la dona.' }}</p> }
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
<p>{{ sinDatoNote }}</p>
</section>
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico · {{ m.periodo }}</h3>
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
@if (m.escenarios.length && barsFigure) {
<app-plotly-chart [figure]="barsFigure" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7 · Barras por escenario clínico · ' + m.periodo + ' · ' + selectionLabel" />
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
}
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados y celdas suprimidas</summary>
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
<table><caption>Datos generales · {{ m.periodo }}</caption>
<table><caption>Datos generales, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
</table>
<table><caption>Escenarios clínicos · {{ m.periodo }} · Porcentajes sin «Sin dato»</caption>
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
</table>
@@ -27,3 +27,7 @@ table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
.reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide + .reading-guide { margin-top: 1rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
.reading-guide li + li { margin-top: .25rem; }
@@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub {
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>();
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>();
plotClick = output<unknown>();
}
describe('EU7 integración Angular y caché compartida', () => {
@@ -46,6 +46,7 @@ describe('EU7 integración Angular y caché compartida', () => {
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.model!.total).toBe(946);
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
@@ -70,10 +71,13 @@ describe('EU7 integración Angular y caché compartida', () => {
}
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
});
@@ -136,6 +140,36 @@ describe('EU7 integración Angular y caché compartida', () => {
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
});
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
toggle.click(); f.detectChanges();
expect(requested).toHaveBeenCalledTimes(1);
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes');
f.componentRef.setInput('metadata', {
descripcion: 'Descripción del indicador',
ficha: { pregunta: '¿Pregunta?', definicion: 'Definición', unidad: 'pacientes', nota: 'Nota de ficha' },
referencias: [{ tipo: 'cita', etiqueta: 'Referencia', ref: null }],
figuras_detalle: [
{ figura: 'fig_c2_barras', descripcion: 'Barras por escenario.', como_leer: ['Lee las barras así.', ' '] },
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona así.'] },
{ figura: 'fig_c2_apiladas', descripcion: 'Otra figura', como_leer: ['No va.'] },
],
}); f.detectChanges();
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[];
expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']);
expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']);
expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.');
expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']);
for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior'])
expect(help.textContent).not.toContain(absent);
expect(help.querySelector('details')).toBeNull();
f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges();
expect(help.textContent).toContain('no publica instrucciones de lectura');
http.expectNone(() => true);
});
it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const card = TestBed.createComponent(IndicadorCatalogCard);
@@ -8,10 +8,13 @@ import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './in
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
@Component({
selector: 'app-indicador-eu7-escenario',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
@@ -49,8 +52,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
if (m.vacio) return 'No hay registros publicados en este periodo.';
const n = m.sinDato.n;
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: m.total === null ? `Fuera de la dona: ${n} pacientes sin resultado válido. Total con resultado no disponible.`
: `Fuera de la dona: ${n} de ${m.total + n} pacientes sin resultado válido en el periodo.`;
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
}
get generalCells() {
const m = this.model;
@@ -63,8 +66,18 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })),
{ escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]);
}
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
get readingGuide() {
const details = this.metadata?.figuras_detalle ?? [];
return EU7_FIGURES.flatMap(([figura, nombre]) => {
const detail = details.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
percentText(value: number | null) { return value === null ? 'No disponible' : value.toFixed(1) + ' %'; }
percentText(value: number | null) { return percentText(value); }
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
@@ -1,8 +1,8 @@
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
@if (selected) {
<section class="interpretation" [class.expanded]="methodologyExpanded()">
<button mat-stroked-button type="button" class="methodology-toggle"
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ' · ' + dominio + ' · ' + figuraId"
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
[attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
(click)="toggleMethodology()">
<mat-icon aria-hidden="true">help_outline</mat-icon>
@@ -13,6 +13,12 @@
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
</ul>
<p class="period-note">{{ periodInterpretation }}</p>
@if (state.status === 'ready' && state.footnotes?.length) {
<h3 class="footnotes-title">Notas de la figura</h3>
<section class="methodological-footnotes" aria-label="Notas de la figura">
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
</section>
}
</div>
</section>
}
@@ -88,15 +94,11 @@
}
</div>
<div class="plot-slot" [hidden]="state.status !== 'ready'">
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
</div>
}
<div class="figure-footer" [hidden]="state.status !== 'ready'">
@if (state.footnotes?.length) {
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
</section>
}
@if (cutoffDate; as cutoff) { <p class="figure-cutoff">Fecha de corte: {{ cutoff }}</p> }
</div>
<div class="figure-labels" [hidden]="state.status !== 'ready'">
@if (state.categoryLabels?.length) {
@@ -44,8 +44,11 @@
.notes { padding: 1rem; overflow-wrap: anywhere; }
.notes h2 { font-size: 1rem; }
.notes p { line-height: 1.5; }
.footnotes-title { margin: var(--issste-space-4) 0 var(--issste-space-2); font-size: .9375rem; font-family: var(--issste-font-heading); }
.figure-cutoff { margin: 0; padding: .5rem 1rem .75rem; font-size: .8125rem; color: var(--issste-text-secondary); }
.dark .figure-cutoff { color: var(--mat-sys-outline); }
.methodological-footnotes {
padding: .75rem 1rem 1rem;
padding: 0;
min-width: 0;
max-width: 100%;
box-sizing: border-box;
@@ -145,25 +145,33 @@ describe('IndicadorFigureCard', () => {
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1);
});
it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => {
it.each(['tea', 'cacu', 'cama'])('presenta notas %s como texto seguro dentro de «Cómo leer» y deja visible la fecha de corte', dominio => {
fixture.componentRef.setInput('dominio', dominio);
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
const notes = ['Fuente: A & B\nSegunda línea', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
const notes = ['Nota de la ficha\nFuente: A & B · Fecha de corte: 2025-08-01\nLeyenda', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement;
expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura');
expect(section.getAttribute('aria-label')).toBe('Notas de la figura');
expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
expect(section.querySelector('img, script, a')).toBeNull();
expect(section.parentElement?.previousElementSibling?.querySelector('app-plotly-chart')).toBeTruthy();
expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull();
expect(section.parentElement?.parentElement?.querySelector('.figure-labels .category-labels')).toBeTruthy();
const detail = section.closest('.methodology-detail') as HTMLElement;
expect(detail).not.toBeNull(); expect(detail.hidden).toBe(true);
expect(section.previousElementSibling?.textContent).toBe('Notas de la figura');
// Interpretation lines come first; the notes are paragraphs, never list items.
expect(detail.querySelector('ul')!.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(section.querySelector('li')).toBeNull();
expect(section.closest('.plot-viewport, app-plotly-chart, details, .figure-footer')).toBeNull();
expect(fixture.nativeElement.querySelector('.figure-footer').textContent.trim()).toBe('Fecha de corte: 2025-08-01');
expect(fixture.nativeElement.querySelector('.figure-labels .category-labels')).toBeTruthy();
for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
state({ status });
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
}
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] });
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva');
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
});
it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => {
const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} };
@@ -284,9 +292,9 @@ describe('IndicadorFigureCard', () => {
state({ status: 'loading' });
expect(firstHost.closest('[hidden]')).toBeTruthy();
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
state({ status: 'incompatible', message: 'Granularidad no publicada' });
state({ status: 'incompatible', message: 'Intervalo de tiempo no publicado' });
expect(firstHost.closest('[hidden]')).toBeTruthy();
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Granularidad no publicada');
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Intervalo de tiempo no publicado');
ready({ data: [{ y: [50] }], layout: {} }); await settle();
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
expect(firstHost.closest('[hidden]')).toBeNull();
@@ -458,7 +466,7 @@ describe('IndicadorFigureCard', () => {
button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
}
expect(button.textContent).toContain('Cómo leer');
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba · ' + dominio + ' · fig_c1_puntos');
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba, ' + dominio + ', fig_c1_puntos');
expect(button.getAttribute('aria-expanded')).toBe('false');
expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true);
const warnings = detail.querySelector('ul')!;
@@ -10,7 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
import { CategoryLabel } from './indicadores-axis-labels';
import { figureIdentity, identityElementId } from './indicadores-identities';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { contractInterpretation, figureMetadataInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
// The panel owns requests; the card receives the original and its presentation copy.
@@ -143,23 +143,23 @@ export class IndicadorFigureCard implements OnChanges {
: this.figuraId.startsWith('fig_c2') ? 'C2'
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
}
private get complementaryLineCount(): number {
return this.contract === 'C1' ? 1
: this.contract === 'C2' ? (this.dominio === 'tea' ? 2 : 1) : 0;
}
get methodologyDetail(): readonly string[] {
return this.interpretation.slice(0, this.complementaryLineCount);
}
get visibleInterpretation(): readonly string[] {
return this.interpretation.slice(this.complementaryLineCount);
}
readonly hasNoVisibleValues = hasNoVisibleValues;
readonly figureTitle = figureTitle;
readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION;
get interpretation(): readonly string[] {
return figureMetadataInterpretation(this.metadata, this.figuraId)
?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie'));
return figureInterpretation(this.metadata, this.figuraId, this.contract, this.dominio,
this.state.figure?.data.some(trace => trace['type'] === 'pie'));
}
// The figure's notes live in "Cómo leer"; the cut-off date stays under the plot
// because it is the only temporal reference of the data on the card.
get cutoffDate(): string | undefined {
if (this.state.status !== 'ready') return undefined;
for (const note of this.state.footnotes ?? []) {
const match = /Fecha de corte: (\d{4}-\d{2}-\d{2})/.exec(note);
if (match) return match[1];
}
return undefined;
}
}
@@ -182,7 +182,7 @@ describe('IndicadorFigurePanel', () => {
expect(heading.id).toBe(id); expect(id).not.toBe('');
expect(section.getAttribute('aria-labelledby')).toBe(id);
expect(section.firstElementChild).toBe(heading);
expect(heading.textContent).toBe('tea · i1 · Uno · f1');
expect(heading.textContent).toBe('tea, i1, Uno, f1');
expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false);
const style = getComputedStyle(heading);
expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden');
@@ -23,7 +23,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
imports: [IndicadorFigureCard, MatTooltipModule],
template: `
<section class="figure-panel" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
<header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
@@ -56,7 +56,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (result().status === 'ready' && donutPages.length > 1) {
<nav class="donut-periods" aria-label="Periodos de la dona">
<button type="button" aria-label="Periodo anterior de la dona" [disabled]="donutPeriodIndex <= 0" (click)="changeDonutPeriod(-1)">‹</button>
<span role="status" aria-live="polite">{{ activeDonutPeriod }} · {{ donutPeriodIndex + 1 }} / {{ donutPages.length }}</span>
<span role="status" aria-live="polite">{{ activeDonutPeriod }}, {{ donutPeriodIndex + 1 }} de {{ donutPages.length }}</span>
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
</nav>
}
@@ -67,7 +67,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (dimension && result().status === 'ready') {
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados y celdas suprimidas</summary>
<details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
</tbody></table></div>
@@ -0,0 +1,78 @@
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
}
}
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
<button type="button" aria-label="Periodo siguiente de la histopatología" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
</div>
</div>
<div class="figures">
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
@if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
}
<ul class="rate-states">
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
</ul>
</section>
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
<tbody>@for (fila of m.filas; track fila.id) {
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (c of m.categorias; track c.id) { <td>{{ cellText(fila.celdas[c.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }<td>{{ cellText(fila.total) }}</td></tr>
}</tbody>
</table>
</div>
</details>
}
}
</section>
@@ -0,0 +1,149 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { Celda } from './indicadores-confirmacion-citologia';
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
// Figures of the kit whose "Cómo leer" describes this coordinated view.
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
/**
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
*/
@Component({
selector: 'app-indicador-histopatologia-cama',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-histopatologia-cama.html',
styleUrl: './indicador-confirmacion-citologia.scss',
})
export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
selection?: SeleccionHistopatologia;
periods: string[] = [];
periodIndex = 0;
model?: ModeloHistopatologia;
donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure;
helpOpen = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
private pages: ModeloHistopatologia[] = [];
// The rates figure has a phone-width variant; it is redrawn when the window crosses that width.
private readonly estrecho = typeof matchMedia === 'function' ? matchMedia('(max-width: 600px)') : undefined;
private readonly alCambiarAncho = () => this.draw();
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
readonly estadoTasa = estadoTasa;
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
get readingGuide() {
const details = this.metadata?.figuras_detalle ?? [];
return FIGURAS.flatMap(([figura, nombre]) => {
const detail = details.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
this.clear();
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
}
retry() { if (this.visible) this.load(); }
private clear() {
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
this.donutFigure = undefined; this.ratesFigure = undefined;
}
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return;
}
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
{ estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
next: datos => {
if (key !== this.key) return;
try {
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
// The most recent period first; navigation goes back.
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.clear();
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error);
this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
this.changeDetector.markForCheck();
}
private activatePeriod() {
this.model = this.pages[this.periodIndex];
this.selection = this.model ? seleccionBase(this.model) : undefined;
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
}
changePeriod(step: number) {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.activatePeriod();
}
select(trace: string, index = 0) {
if (!this.model || !this.selection || this.status() !== 'ready') return;
this.selection = clicHistopatologia(this.model, this.selection, trace, index); this.draw();
}
plotClicked(event: unknown) {
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
}
private draw() {
if (!this.model || !this.selection) return;
this.donutFigure = donaHistopatologia(this.model, this.selection, this.tema);
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
}
@@ -0,0 +1,48 @@
import { Component, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
/**
* CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator
* (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number.
*/
@Component({
selector: 'app-indicador-histopatologia-pendiente',
host: { class: 'dual-card' },
imports: [MatButtonModule, MatCardModule],
template: `
<mat-card>
<h2>Resultado histopatológico por categoría BI-RADS</h2>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
@if (ayuda()) {
<div class="methodology">
<p>Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.</p>
</div>
}
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
<div class="figures">
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
</div>
</mat-card>
`,
styles: `
:host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; }
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.estado { color: var(--issste-text-secondary); }
.methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.methodology p { margin: 0; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); }
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
`,
})
export class IndicadorHistopatologiaPendiente {
readonly ayuda = signal(false);
}
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
}
@if (temporalReference) { <p>{{ temporalReference }}</p> }
<p class="kpi-state" role="status">{{ state }}</p>
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</mat-card>
`,
@@ -22,12 +22,17 @@ import { MatCardModule } from '@angular/material/card';
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); box-shadow: none; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
h3, p { overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; }
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.value { font: var(--mat-sys-headline-medium); }
.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; }
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; }
// CaMa's cards are as tall as their grid row.
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
`,
})
export class IndicadorKpiCard {
@@ -38,6 +43,8 @@ export class IndicadorKpiCard {
@Input() loading = false;
@Input() notes: string[] = [];
@Input() state = 'Pendiente de definición';
// A card that shows its value needs no "Disponible" line.
@Input() quietWhenAvailable = false;
@Input() additionalInfo?: string;
get informationLine(): string | undefined {
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
@@ -33,13 +33,13 @@ describe('KPI búsqueda inicial del último dato visible', () => {
categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} },
filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] };
}
it('consulta secuencialmente por granularidad, detiene al visible y explica supresión posterior', () => {
it('consulta secuencialmente por intervalo de tiempo, detiene al visible y explica supresión posterior', () => {
const latest = request(periods[0]); http.expectNone(() => true);
expect(fixture.componentInstance.result().loading).toBe(true);
latest.flush(data(periods[0], 'suppressed'));
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
expect(fixture.componentInstance.result().value).toBe(5);
expect(fixture.nativeElement.textContent).toContain('Último dato visible · 2025-S1');
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1');
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
http.expectNone(() => true);
});
@@ -48,7 +48,7 @@ describe('KPI búsqueda inicial del último dato visible', () => {
const second = request(periods[1]); http.expectNone(() => true);
second.flush(data(periods[1], 'suppressed'));
request(periods[2]).flush(data(periods[2]));
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible · 2024-S2');
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2024-S2');
expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño');
});
it('agotado el inventario conserva el estado del último reporte', () => {
@@ -5,7 +5,7 @@ import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { KPI_BY_DOMAIN } from './indicadores-kpi';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorDatos, Dominio } from './indicadores.models';
import { IndicadoresMemory } from './indicadores-memory';
@@ -13,11 +13,14 @@ describe('KPI integración con autoridad global', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let http: HttpTestingController;
beforeEach(() => {
// KPI scope only: graphic cards stay outside the viewport, so coordinated views
// (such as the CaCu paired times) do not add their own /datos requests.
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
function load(domain: Dominio, missing = false, periods = ['2025-S1'], initial = domain === 'tea') {
// Ordinary consumer tests begin after initialization; dedicated P0 suites
// exercise the real shared search for all three domains.
@@ -27,8 +30,19 @@ describe('KPI integración con autoridad global', () => {
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
fixture.detectChanges();
}
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
function requests() { return http.match(r => r.url.endsWith('/datos')); }
// Regression assertions below target the original KPI contracts. The added lab
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
// Satisfy its independent request with an explicit empty response, never diagnosis data.
function originalRequests() {
const requests = http.match(r => r.url.endsWith('/datos'));
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
const period = r.request.params.get('periodos')!;
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
}
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
}
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
function requests() { return originalRequests(); }
function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos {
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
@@ -89,7 +103,7 @@ describe('KPI integración con autoridad global', () => {
});
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.slice(1).map(d => d.id));
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2);
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(4);
const req = requests(); expect(req).toHaveLength(1); req.forEach((r,i) => r.flush(response(i+1)));
});
it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
@@ -104,8 +118,8 @@ describe('KPI integración con autoridad global', () => {
expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
if (count) {
expect(grid!.children).toHaveLength(count + 1);
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 1));
expect(grid!.children).toHaveLength(count + 3);
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 3));
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
http.expectNone(() => true);
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
@@ -142,7 +156,7 @@ describe('KPI integración con autoridad global', () => {
if (scenario === 'nulo') data.filas[0]['mediana'] = null;
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges();
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3);
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(5);
expect(panels()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables');
expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true);
});
@@ -154,22 +168,25 @@ describe('KPI integración con autoridad global', () => {
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
http.expectNone(r => r.url.endsWith('/datos'));
});
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
for (const domain of ['cacu', 'cama'] as const) {
load(domain);
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
req.forEach((r, i) => r.flush(response(i, domain)));
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
fixture.detectChanges();
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
expect(cards).toHaveLength(3);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', '7', undefined] : ['5', '40.0', '7']);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', 'días (mediana)', undefined] : ['pacientes', '%', 'días (mediana)']);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'),
expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`),
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
]));
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
}
});
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
@@ -19,11 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="result().notes ?? []" />
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
@if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`,
styles: ':host { display: block; min-width: 0; }',
styles: `
:host { display: block; min-width: 0; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
`,
})
export class IndicadorKpiPanel implements OnChanges {
@Input({ required: true }) dominio!: Dominio;
@@ -40,7 +44,7 @@ export class IndicadorKpiPanel implements OnChanges {
readonly usedPeriod = signal<string | undefined>(undefined);
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
get temporalReference() {
if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod();
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
}
retry() { this.requests.next(); }
@@ -49,6 +53,9 @@ export class IndicadorKpiPanel implements OnChanges {
const applied = this.applied, definition = this.definition, domain = this.dominio;
this.usedPeriod.set(undefined);
if (!applied) return of({ state: 'Esperando filtro aplicado' });
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) {
return of({ state: 'Selección no consolidable', info: 'Elige un único periodo aplicado para consultar esta mediana.' });
}
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
@@ -2,13 +2,13 @@
section + section { margin-top: var(--issste-space-4); }
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; }
.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
.ficha-fields { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 3fr); gap: var(--issste-space-2) var(--issste-space-4); max-width: 75ch; margin: 0; }
.ficha-fields > div { display: contents; }
dt { color: var(--issste-text-secondary); font-weight: 600; }
dd { margin: 0; }
ul { padding-inline-start: 1.5rem; }
li + li { margin-top: var(--issste-space-2); }
.table-scroll { max-width: 100%; overflow-x: auto; }
table { border-collapse: collapse; width: 100%; max-width: 75rem; }
th, td { text-align: left; vertical-align: top; padding: var(--issste-space-2); border-bottom: 1px solid var(--issste-border); }
thead th, tbody th { color: var(--issste-text-secondary); font-weight: 600; }
.ficha-table th { width: 10rem; }
@media (max-width: 36rem) {
.ficha-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); }
dd { margin-bottom: var(--issste-space-2); }
.ficha-table th { width: 6rem; }
}
@@ -21,7 +21,7 @@ describe('Metadatos metodológicos opcionales', () => {
expect(text).toContain('Guía <img src=x onerror=alert(1)>');
expect(fixture.nativeElement.querySelector('img')).toBeNull();
expect(text).toContain('Segunda línea');
expect(text).not.toContain('Ficha metodológica');
expect(text).not.toContain('Ficha técnica');
expect(text).not.toContain('Título del catálogo');
expect(text).not.toContain('no está disponible');
http.verify(); fixture.destroy();
@@ -32,11 +32,29 @@ describe('Metadatos metodológicos opcionales', () => {
descripcion: 'Información general.',
ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' },
});
for (const content of ['Descripción', 'Información general.', 'Ficha metodológica', 'Código', 'IND-01', 'Para', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
for (const content of ['Descripción', 'Información general.', 'Ficha técnica', 'Código', 'IND-01', 'Para quién', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
expect(text).not.toContain('no está disponible');
http.verify(); fixture.destroy();
});
it('presenta la ficha en una tabla y no muestra las reglas (parametros) aunque vengan', () => {
const { fixture, http, text } = render({
ficha: { codigo: 'EU-T', definicion: 'Días de la toma al diagnóstico.' },
parametros: [{ clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario.' }],
});
const ficha = fixture.nativeElement.querySelector('table.ficha-table') as HTMLTableElement;
expect([...ficha.querySelectorAll('th[scope=row]')].map(th => th.textContent)).toEqual(['Código', 'Definición']);
expect(fixture.nativeElement.querySelectorAll('table')).toHaveLength(1);
for (const absent of ['Reglas', 'cacu.horizontes', 'Provisional', 'Arbitrario']) expect(text).not.toContain(absent);
http.verify(); fixture.destroy();
});
it('con solo parametros anuncia que no hay información ampliada', () => {
const { fixture, http, text } = render({ parametros: [{ clave: 'comun.umbral_supresion', valor: 5, estado: 'provisional' }] });
expect(text).toContain('no está disponible'); expect(text).not.toContain('comun.umbral_supresion');
http.verify(); fixture.destroy();
});
it('muestra sólo los campos utilizables de una ficha parcial', () => {
const { fixture, http, text } = render({ ficha: { codigo: 'IND-02', para: ' ', unidad: null, definicion: 'Definición breve', nota: '' } });
expect(text).toContain('Código'); expect(text).toContain('IND-02');
@@ -56,7 +74,7 @@ describe('Metadatos metodológicos opcionales', () => {
it('muestra estado vacío con descripción y ficha ausentes o nulas', () => {
const { fixture, http, text } = render({ descripcion: null, ficha: null, referencias: null, poblaciones: null });
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
expect(text).not.toContain('Ficha metodológica'); expect(text).not.toContain('Descripción');
expect(text).not.toContain('Ficha técnica'); expect(text).not.toContain('Descripción');
http.verify(); fixture.destroy();
});
@@ -68,7 +86,7 @@ describe('Metadatos metodológicos opcionales', () => {
categorias: { NORMAL: { etiqueta: 'Normal' } },
});
expect(text).toContain('Descripción publicada.');
expect(text).toContain('Guía publicada <em>edición 2</em> · Indicador 7');
expect(text).toContain('Guía publicada <em>edición 2</em>, Indicador 7');
expect(text).toContain('Pacientes con estudio publicado.');
expect(fixture.nativeElement.querySelector('em')).toBeNull();
expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/);
@@ -17,16 +17,20 @@ import { IndicadoresService } from './indicadores.service';
}
@if (fichaFields.length) {
<section aria-labelledby="metadata-ficha-title">
<h4 id="metadata-ficha-title">Ficha metodológica</h4>
<dl class="ficha-fields">@for (field of fichaFields; track field.key) {
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div>
}</dl>
<h4 id="metadata-ficha-title">Ficha técnica</h4>
<div class="table-scroll">
<table class="ficha-table">
<tbody>@for (field of fichaFields; track field.key) {
<tr><th scope="row">{{ field.label }}</th><td class="metadata-copy">{{ field.value }}</td></tr>
}</tbody>
</table>
</div>
</section>
}
@if (references.length) {
<section aria-labelledby="metadata-references-title">
<h4 id="metadata-references-title">Referencias</h4>
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) { · {{ ref.ref }} }</li> }</ul>
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) {, {{ ref.ref }} }</li> }</ul>
</section>
}
@if (populations.length) {
@@ -47,7 +51,7 @@ export class IndicadorMetadata implements OnChanges {
loading = false;
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly fichaLabels = [
['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'],
['codigo', 'Código'], ['para', 'Para quién'], ['unidad', 'Unidad'],
['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
] as const;
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
@@ -1,9 +1,59 @@
@if (compact) {
<section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields compact">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
@if (availability) {
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
}
</mat-select>
</mat-form-field>
<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>
@if (availability) {
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
@else if (availability.status === 'error') {
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
}
@if (!availability) {
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
<div class="fields period-builder">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>{{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-label>
<mat-select [(ngModel)]="unit">
@for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { <mat-option [value]="value">{{ value }}</mat-option> }
</mat-select>
</mat-form-field>
<button type="button" mat-stroked-button (click)="add()">Agregar periodo</button>
</div>
<div class="remove" aria-label="Eliminar periodos agregados">
@for (period of entry.added; track period) {
<button type="button" mat-button (click)="remove(period)" [attr.aria-label]="'Eliminar periodo ' + period">Eliminar {{ period }}</button>
}
</div>
}
@if (error) { <p class="error" role="alert">{{ error }}</p> }
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
</section>
} @else {
<section aria-label="Editor de filtros generales del proyecto">
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
@if (!types.includes(state.tipo)) { <p role="status">La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.</p> }
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
<div class="fields">
@if (types.length > 1 || !types.includes(state.tipo)) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Granularidad</mat-label>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
</mat-select>
@@ -24,7 +74,7 @@
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
@if (availability) {
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }} — disponibilidad no confirmada</mat-option> }
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
}
</mat-select>
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
@@ -36,7 +86,7 @@
@else if (availability.status === 'error') {
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
} @else if (!options.length) { <p role="status">Sin reportes disponibles para esta granularidad.</p> }
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
}
@if (!availability && entry.draft.mode !== 'todos') {
@@ -64,3 +114,4 @@
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
</section>
}
@@ -1,4 +1,12 @@
@use '@angular/material' as mat;
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
// CaMa's compact row: tighter fields and buttons, one line of text under it.
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
:host(.compacto) .apply-button { min-height: 40px; }
:host(.compacto) .period-builder button { min-height: 40px; }
section { min-width: 0; }
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
@@ -13,6 +21,9 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
.remove button { min-height: 44px; }
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
.fields.compact { align-items: center; }
.fields.compact mat-form-field { flex: 0 1 14rem; }
.fields.compact .apply-button { margin-top: 0; }
@media (max-width: 550px) {
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
.period-builder button { margin-top: 0; }
@@ -18,6 +18,13 @@ describe('UX-04 control asistido', () => {
control = fixture.componentInstance;
});
afterEach(() => fixture.destroy());
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
control.year = '2025'; control.unit = 'S1'; control.add();
control.unit = 'S2'; control.add();
expect(control.selectedPeriods).toEqual(['2025-S2']);
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
});
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
await fixture.whenStable(); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
@@ -11,6 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
@Component({
selector: 'app-indicador-period-filters',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
host: { '[class.compacto]': 'compact' },
templateUrl: './indicador-period-filters.html',
styleUrl: './indicador-period-filters.scss',
})
@@ -19,6 +20,8 @@ export class IndicadorPeriodFilters implements OnChanges {
@Input({ required: true }) types!: TipoPeriodo[];
@Input() availability?: PeriodAvailability;
@Input() initialPresentation = false;
// One period at a time, with the interval and Aplicar on one row.
@Input() compact = false;
@Output() retryAvailability = new EventEmitter<void>();
@Output() edited = new EventEmitter<void>();
@Output() apply = new EventEmitter<void>();
@@ -56,7 +59,7 @@ export class IndicadorPeriodFilters implements OnChanges {
this.edited.emit();
}
select(values: string[]) {
const unique = [...new Set(values)];
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
this.edited.emit();
@@ -0,0 +1,41 @@
<section class="tiempos" aria-label="Días desde la toma: resultado y diagnóstico">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
@for (guide of readingGuide; track guide.clave) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
}
<p class="caveat">{{ caveat }}</p>
@if (metadataPending) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando tiempos de resultado y diagnóstico" /><p role="status">Cargando los mismos periodos para los dos tiempos…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (model; as m) {
<h3 class="figure-title">Días desde la toma: resultado y diagnóstico</h3>
@if (status() === 'empty') { <p role="status">No hay cajas publicadas para estos periodos.</p> }
@else if (figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Tiempos por periodo, ' + par.etiquetas.reporte + ' y ' + par.etiquetas.diagnostico" />
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de tiempos por periodo" tabindex="0">
<table><caption>Q1, mediana y Q3 en días por periodo</caption>
<thead><tr><th scope="col">Periodo</th>@for (clave of claves; track clave) { <th scope="col">{{ par.etiquetas[clave] }}</th> }</tr></thead>
<tbody>@for (periodo of m.periodos; track periodo) {
<tr><th scope="row">{{ periodo }}</th>@for (clave of claves; track clave) { <td>{{ cajaTexto(m.cajas[clave][periodo]) }}</td> }</tr>
}</tbody>
</table>
</div>
</details>
}
</section>
@@ -0,0 +1,17 @@
:host { display: block; min-width: 0; }
.tiempos { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
.applied-summary, .note { color: var(--issste-text-secondary); }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide + .reading-guide, .caveat { margin-top: 1rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
.reading-guide li + li { margin-top: .25rem; }
h3 { font-size: 1rem; line-height: 1.5; }
app-plotly-chart { --plot-height: 440px; }
summary { cursor: pointer; padding-block: .75rem; }
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.table-scroll { overflow: auto; max-height: 28rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@@ -0,0 +1,131 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, combineLatest, of, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { IndicadoresService } from './indicadores.service';
import { httpMessage } from './indicadores-http';
import { cajaTexto, CLAVES, Clave, FIGURA_C3R, figuraTiempos, hayCajas, ModeloTiempos, modeloTiempos, ParTiempos,
TiemposIncompatibles } from './indicadores-tiempos-pareados';
@Component({
selector: 'app-indicador-tiempos-pareados',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-tiempos-pareados.html',
styleUrl: './indicador-tiempos-pareados.scss',
})
export class IndicadorTiemposPareados implements OnChanges, OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) par!: ParTiempos;
// The card's indicator (diagnosis). Its partner (lab result) is hidden from the
// catalog and requested directly by id, for data and metadata.
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
readonly claves = CLAVES;
readonly cajaTexto = cajaTexto;
message = '';
model?: ModeloTiempos;
figure?: PlotlyFigure;
helpOpen = false;
partnerMetadata?: IndicadorMetadatos;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly service = inject(IndicadoresService);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private metadataSubscription?: Subscription;
private key = '';
private loaded = false;
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
// TODO: mover al kit (como_leer de la vista coordinada de tiempos).
get caveat() {
return `Las dos cajas no cuentan exactamente a las mismas ${this.par.estudios}: cada indicador tiene su propio horizonte `
+ 'y la segunda solo incluye las que llegaron a diagnóstico. La diferencia entre las medianas no es el tiempo del tramo intermedio.';
}
/** "Cómo leer": only what the kit publishes for each C3r figure, plus the caveat above. */
get readingGuide() {
const fuentes: Record<Clave, IndicadorMetadatos | undefined> = { reporte: this.partnerMetadata, diagnostico: this.metadata };
return CLAVES.flatMap(clave => {
const detail = fuentes[clave]?.figuras_detalle?.find(item => item.figura === FIGURA_C3R);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? [{ clave, nombre: this.par.etiquetas[clave], descripcion, como_leer }] : [];
});
}
get metadataPending() { return !this.metadata || !this.partnerMetadata; }
toggleHelp() {
this.helpOpen = !this.helpOpen;
if (!this.helpOpen) return;
if (!this.metadata) this.metadataRequested.emit();
if (!this.partnerMetadata) {
this.metadataSubscription?.unsubscribe();
this.metadataSubscription = this.service.metadatos(this.dominio, this.par.reporte).pipe(catchError(() => of(undefined)))
.subscribe(value => { this.partnerMetadata = value; this.changeDetector.markForCheck(); });
}
}
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
this.par.reporte, this.par.diagnostico, this.indicador.contrato, this.indicador.tipos_periodo]);
if (changes['dominio'] || changes['par']) { this.partnerMetadata = undefined; this.metadataSubscription?.unsubscribe(); }
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
this.model = undefined; this.figure = undefined;
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
}
retry() { if (this.visible) this.load(); }
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.model = undefined; this.figure = undefined;
if (this.indicador.id !== this.par.diagnostico || this.indicador.contrato !== 'C3r') {
this.message = 'El catálogo no publica el indicador de tiempo necesario para esta vista.';
this.status.set('incompatible'); return;
}
// The partner shares the diagnosis periodicity; its response is validated by id, contract and period.
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (!compatibility.compatible) { this.message = compatibility.reason; this.status.set('incompatible'); return; }
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.par.reporte, this.applied.tipo, periods),
this.snapshots.datos(this.dominio, this.par.diagnostico, this.applied.tipo, periods, this.indicador.version),
]).pipe(timeout({ first: 40000 })).subscribe({
next: ([reporte, diagnostico]) => {
if (key !== this.key) return;
try {
this.model = modeloTiempos(this.par, { reporte, diagnostico }, this.applied.tipo, periods);
this.draw();
this.status.set(hayCajas(this.model) ? 'ready' : 'empty');
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.model = undefined; this.figure = undefined;
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof TiemposIncompatibles ? error.message : httpMessage(error);
this.status.set(error instanceof TiemposIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
this.changeDetector.markForCheck();
}
private draw() {
if (!this.model) return;
this.figure = figuraTiempos(this.model, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
}
@@ -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;
}
}

Some files were not shown because too many files have changed in this diff Show More