Compare commits

...

100 Commits

Author SHA1 Message Date
rockdrigo 59ce79d1a2 feat(cama): the detection-rate card without its Wilson interval line
How: the card shows the rate, its period and its one-line description, like
the other C1 cards. The `intervalo` option of KpiDefinition, the interval in
KpiResult and the card's line drawing are removed, since no card uses them.

Implications: the published ic_bajo/ic_alto are no longer read by any card;
the interval is still shown where it belongs, in the rate's Histórico chart
(the band) and in the BI-RADS confirmation rates.
2026-11-09 20:15:12 -06:00
rockdrigo e13e727de3 fix(cama): the confirmation donut expands and steps back like CaCu's
How: without buttons the view uses CaCu's interactive donut rules. The selection
may have no group (the total, where the view opens). clicDona: a group narrows to
it (again: back to the total), a result is chosen inside its group (again: back
to the group), the centre steps back result -> group -> total. donaExpandible
gives the other group's slices zero, so the chosen group's results fill the
outer ring, fades a chosen result's siblings, and writes the count and the
choice in the centre ("Con biopsia" at the total). At the total the rates count
the base group, so they read as the detection rate.

Implications: only views with `botones: false` (cáncer de mama) change; CaCu's
confirmation keeps clicConfirmacion and donaConfirmacion. The previous commit's
centre label on donaConfirmacion is removed, as no view uses it now.
2026-11-09 20:11:05 -06:00
rockdrigo 67cde017fa feat(cama): the confirmation donut is the control, without label buttons
How: VistaConfirmacion gains `botones`. Without them (cáncer de mama), the
donut works like CaCu's interactive one: a click on the inner ring chooses a
group, on the outer ring a result, on the centre goes back to the base; the
centre names the choice under its count; the donut and the rates animate
between choices; a one-line hint says how. The buttons stay in the page for the
keyboard, visually hidden until one of them has the focus. CaCu keeps
`botones: true` and is unchanged.

Implications: on cáncer de mama the choice is made on the chart; a keyboard user
tabs into the hidden buttons, which then show. A view whose centre would
overflow with long labels needs shorter category names in the catalog.
2026-11-09 20:05:23 -06:00
rockdrigo 8c3e41527c feat(cama): the four BI-RADS charts as two, mammograms and patients on one card
How: PARES_CONTEOS pairs two C2 counts of the same finding, one per exam and one
per patient, with the map from exam category to patient category (BI-RADS 4A,
4B and 4C are a patient's BI-RADS 4). The exams' card
(cama_birads_456_mastografia) draws IndicadorConteosPareados: a donut of the
mammograms by category with their total in the centre, and grouped bars with
each patient BI-RADS next to its mammograms and "≈ n por paciente" at the end of
each pair. Both counts come from the same period request; a suppressed cell
leaves its sum, ratio and the donut undrawn instead of using zero. The patients'
indicator has no card of its own in Resumen (esSocioConteos); it still feeds its
opportunity card and Histórico.

Implications: the view depends on the exams' and patients' category ids
(B4A..B6, BIRADS_4..BIRADS_6) matching grupoDe; a renamed category makes the view
reject the answer as incompatible. The real API already publishes both
indicators with these ids.
2026-11-09 19:56:36 -06:00
rockdrigo 3aba7fe329 feat(cama): histopathological confirmation drawn like CaCu's, by BI-RADS category
How: CaCu's confirmation view (rates per row with their horizontal Wilson
interval, and a donut of biopsy results whose buttons choose what the rates
count) takes a VistaConfirmacion: indicator id, stratum, fixed rows (most severe
on top), the grade whose group is the base view, the grade read as a false
positive, and its words. CONFIRMACION_CACU reproduces the previous behaviour
exactly; CONFIRMACION_CAMA reads cama_histopatologia_birads by BI-RADS 6, 5,
4C, 4B and 4A, with "Maligno" (the group of INVASOR) as the base, so the base
rate is the cancer detection rate, and "Benigno" alone reads as false positives.
The catalog card chooses the view with vistaConfirmacion(dominio, indicador).

Implications: the backend must publish cama_histopatologia_birads stratified by
`birads`, with exactly two groups of results (plus SIN_DATO/SIN_BIOPSIA kept
apart), as cacu_confirmacion_citologia is. The EU7-style view stays available
through the catalog's `escenario` field but no CaMa indicator uses it now.
2026-11-09 19:52:53 -06:00
rockdrigo 739bf9613c fix(indicadores): opportunity cards fill the height of their grid row
How: the grid rows were already equal (grid-auto-rows: 1fr), but the card kept
its content height inside the stretched panel: mat-card's height: 100% had no
definite parent height to resolve against. The KPI panel and the KPI card host
are now flex columns, and the card and mat-card grow (flex: 1 1 auto) to fill
them, so every card is as tall as its row.

Implications: applies to every domain's cards. A panel showing "Reintentar
consulta" keeps the button under its card, and the card takes the remaining
height.
2026-11-09 19:30:25 -06:00
rockdrigo 987bce0d93 style(cama): the four opportunity cards in one row, all of one size
How: cáncer de mama's card grid no longer auto-fits 18rem columns (which could
leave three cards and one below); it has two equal columns from 600px of
dashboard width and four from 1100px. With grid-auto-rows: 1fr every card is
as tall as the tallest one (the detection rate with its interval line).

Implications: CaCu keeps its auto-fit grid for its five cards. On a narrow
dashboard the cards stack in one column, still of one height per row.
2026-11-09 19:15:45 -06:00
rockdrigo eaaffa9ebe Revert "feat(indicadores): Resumen as a story of questions, for the domains that have one"
How: reverts e5ff342 entirely: indicadores-relato.ts and its spec are removed,
Resumen goes back to the opportunity cards followed by the clinical charts for
every domain, and the specs read cáncer de mama's cards in KPI order again.

Implications: no domain has a questions layout; RELATO_BY_DOMAIN is gone, so
nothing outside the KPI list and the catalog orders Resumen. The search
threshold and the equal card heights stay.
2026-11-09 19:14:30 -06:00
rockdrigo 088d9d4550 style(indicadores): opportunity cards of one height in the default layout
How: the opportunity card grid gets grid-auto-rows: 1fr, so every row is as
tall as its tallest card and all cards share that height (they already share
the column width).

Implications: CaCu and TEA cards no longer differ in height when one has a
longer line; a card with much more text makes every row taller. Domains with a
story size their cards in the story layout instead.
2026-11-09 19:09:36 -06:00
rockdrigo e5ff3427c7 feat(indicadores): Resumen as a story of questions, for the domains that have one
How: indicadores-relato.ts holds, per domain, the questions Resumen answers in
order, each with the opportunity cards and charts that answer it, a one-line
reading and, optionally, a button to the tab that continues it. Cáncer de mama
follows the patient's route: 1 ¿Cuántas pacientes tienen un hallazgo
sospechoso? (patients and mammograms with BI-RADS 4-6), 2 ¿Qué tan pronto llega
el diagnóstico? (the two time cards, then Histórico), 3 ¿Cuántos cánceres
confirma la biopsia, y en qué categorías? (detection rate and the BI-RADS
histopathology view), 4 ¿Quiénes siguen pendientes? (to Seguimiento). Each
answer leads to the next question. Indicators no question claims go to «Otros
indicadores». All opportunity cards have one size (17rem by at least 12.5rem):
beside charts they stack in a column, alone they sit in a row; charts take
equal halves and an interactive card the full width. Domains without a story
keep the opportunity and clinical sections.

Implications: the story is WebApp configuration, keyed by indicator ids; when
the catalog or KPI ids change, RELATO_BY_DOMAIN must follow (or come from the
API's metadata later, as a `pregunta` field per indicator). Cards render in
question order, so specs that read cáncer de mama's cards in DOM order expect
patients, times, then detection rate. The charts' search and the TEA print
report stay with the default layout.
2026-11-09 19:09:36 -06:00
rockdrigo 0bf1f82366 feat(indicadores): "Buscar indicadores" only from five indicators
How: searchVisible compares the indicators shown in Resumen with MIN_BUSQUEDA
(5) instead of 2. Below it every card is in view and the selector and its
"Mostrando n de m" line are not rendered.

Implications: cáncer de mama (three charts in Resumen) loses the selector; CaCu
(five) and TEA keep it. Pinning still works without it. If a domain grows past
the threshold the selector comes back with no other change.
2026-11-09 19:05:02 -06:00
rockdrigo edd6e4b640 style(indicadores): cards with a value don't say "Disponible"
How: the KPI card renders its state line only when the state is not
"Disponible"; a card with a value shows the value, unit, period and its one-line
description. Every other state ("Dato oculto por tamaño", "Selección no
consolidable", "Indicador no disponible"...) still shows, as a status message.

Implications: applies to every domain's cards. kpiResult still returns
"Disponible", so TEA's summary paragraph and any logic reading the state are
unchanged; only the card's text changes.
2026-11-09 18:49:45 -06:00
rockdrigo 3674a43587 feat(cama): four opportunity cards
How: KPI_BY_DOMAIN.cama keeps Pacientes evaluadas con BI-RADS 4, 5 y 6, Tasa de
detección histopatológica (with its Wilson interval), Tiempo de tamizaje a
resultado and Tiempo de resultado a diagnóstico. Tasa de confirmación and
Tiempo de tamizaje a diagnóstico (the sum of the two halves) are no longer
cards; both stay in Histórico.

Implications: the initial-period anchor is unchanged (the patients card). The
integration specs pin the first three cards (C2, C1, C3r); the real-data spec
builds a definition for the two answers that are no longer cards, so the C1 and
C3r rules keep being checked on real WebApi data.
2026-11-09 18:48:28 -06:00
rockdrigo 27bd4d4a65 style: institutional look, square corners and sober headings
How: --issste-radius is 4px instead of Material's medium corner (12px), and
the Material shape tokens are overridden after mat.theme (corner-full 4px, so
buttons stop being pills; medium and large 4px; extra-large 6px). The
indicators feature's 999px pills (legend buttons, EEG badges) use the shared
radius. Headings use Roboto at weight 500 instead of Rajdhani at 700, a step
smaller: page title 1.75rem, section titles 1.25rem, card titles 1.125rem,
KPI titles 1rem and KPI values 1.75rem; the header title is 1.25rem.

Implications: the corner tokens are global, so Conectar and Gobernanza (dialogs,
panels, buttons) also get square corners; their own 999px chips are unchanged.
Circles drawn with 50% (dots, swatches) stay round. Rajdhani is no longer used
anywhere, so it can be dropped from the font assets. No behaviour changes.
2026-11-09 18:26:52 -06:00
rockdrigo cbae29bc24 feat(cama): "cáncer de mama" instead of CaMa, and CaCu's brief wording
How: the parametrized domain names (domainLabels and domainTitles of the page,
domainNames of Datos y definiciones, and the header menu) say "cáncer de mama" /
"Cáncer de mama". Every non-TEA domain now uses CaCu's wording: "Indicadores de
oportunidad" and "Indicadores clínicos" as section titles, and cards that show
only their own line (the kit notes stay in the figure footers). The C2 card line
comes from a per-domain C2_INFO; CaMa's says what it counts in one sentence.

Implications: any text built from domainLabels changes with it (titles, aria
labels, "Seguimiento de cáncer de mama"); the route and API keep the `cama` id.
The header names CaMa in full while TEA and CaCu keep their short labels. The
Conectar workspace still lists "CaMa"; it has its own label table.
2026-11-09 18:24:55 -06:00
rockdrigo 35b329e235 style(indicadores): general filters as one compact row, like the Seguimiento form
How: the period editor puts Intervalo de análisis, Periodo seleccionado,
Aplicar and the "Hay cambios sin aplicar" notice on one row, with Material
density -4 (mat.theme((density: -4)) scoped to the component), and folds the
applied filter and the availability hint into one small line under it. The
"Selección en edición" and "Sin cambios pendientes" lines are gone: the
selectors already show the draft, and the notice only appears when there is
something pending. The section has less padding, a smaller title and a
one-line description per domain.

Implications: purely presentational; the filter state, the apply rules and the
requests don't change, and every spec passes unchanged. The density applies
only inside the period editor, so other form fields keep the global density.
2026-11-09 18:23:00 -06:00
rockdrigo 7f303d1160 feat(cama): opportunity cards for both halves of the screening time and the detection rate with its Wilson interval
How: KPI_BY_DOMAIN.cama gains cama_tasa_deteccion_histopatologica (C1),
cama_eu38a (screening to result) and cama_dias_resultado_diagnostico (result to
diagnosis), titled like CaCu's time cards. A KpiDefinition can ask for
`intervalo`: kpiResult then passes the row's published ic_bajo/ic_alto, and the
card draws them as a horizontal line on a 0-100 % scale with the value marked
and the bounds written out. Bounds that are missing or don't contain the value
are not drawn. CaMa uses CaCu's auto-fit card grid.

Implications: the backend must publish these three indicators (the ids are the
contract; cama_eu38a already exists in the kit) and, for the detection rate, the
Wilson bounds in ic_bajo/ic_alto, as every C1 already does; the WebApp never
computes an interval. Six CaMa cards request their data in two batches. The
period-integration specs stay pinned to the first three CaMa cards; the panel
spec covers all six.
2026-11-09 18:19:33 -06:00
rockdrigo e2b307abf5 feat(shell): domain menu in the header, as in the deployed dev version
How: on /indicadores/<domain> routes the App header shows the platform title
and a mat-menu button named after the current domain, listing the other two
(the same markup and styles as the deployed WebApp's app.html). Other routes
(Conectar, Gobernanza) keep the "Análisis de información" breadcrumb. The
indicators page drops its own TEA/CaCu/CaMa links, so there is one switcher.

Implications: domain switching now depends on the App shell; a page embedded
elsewhere has no way to change domain by itself. Specs that asserted the
in-page links now assert their absence, and app.spec covers the menu.
2026-11-09 18:10:58 -06:00
rockdrigo 39974b8533 feat(cama): TEA tabs, follow-up list from announced columns and histopathology donut by BI-RADS category 2026-11-09 17:55:34 -06:00
edgar 53edec8692 feat(tea): periodos personalizados en Histórico
«Personalizado…» en «Periodos a mostrar» abre un diálogo con los periodos del
intervalo elegido, por año. Las figuras muestran solo los elegidos, sin volver
a consultar, y cada intervalo recuerda su propia selección.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:21:18 -06:00
edgar a1ea31039e feat(tea): abrir las alteraciones del EEG con un mapa visible
Al desplegar un paciente se abre su primera alteración, o la primera métrica
si no tiene alteraciones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:46:26 -06:00
edgar ef631e2c0b feat(tea): cambios de la reunión del 5 de noviembre
Resumen
- Estado del caso (completo, en proceso, fuera del protocolo) al cierre del
  periodo, en una figura y en el párrafo, separado de diagnóstico confirmado.
- Tiempos por paso: M-CHAT a ADOS-2, ADOS-2 a diagnóstico y total.
- Un solo formato: barras. M24 son barras apiladas por grupo de edad.
- «Descargar reporte» abre la impresión con el periodo y los indicadores
  seleccionados.

Histórico
- Porcentaje de casos en proceso, tiempos por paso en la misma escala y
  calidad de los EEG (indicador solo de esta pestaña, con `vistas`).
- Ejes con unidades y fechas como «mar 2025».

Seguimiento
- Columna y filtro de estado del caso, con lo que falta.
- Filtro por tipo de alteración y resumen de EEG que sigue los filtros.
- Módulo de ADOS-2 junto al puntaje.
- Tarjetas de alteraciones: al elegir una se apartan y aparece su mapa, sin
  caja, con leyenda de colores. Referencia por grupo de edad.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:38:53 -06:00
edgar 27dc7a0166 feat(tea): calidad del EEG con criterios de PREP y calificación general
- La calificación general es una palabra (Bueno, Aceptable o Malo), como en
  Automagic, y es la peor de sus criterios.
- Los criterios son lo que busca PREP, con números: canales afectados de 19 y
  ruido de línea en dB.
- Se quitan impedancia, artefactos, canales rechazados, segmentos útiles y el
  puntaje de 100.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 12:46:01 -06:00
edgar e6353f9f4c test(tea): nuevas alteraciones del EEG en el resumen del paciente
Ritmo posterior, husos de sueño N2 y N3, picos paroxísticos y gradiente
anteroposterior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:55:07 -06:00
edgar 3bb9c2121d feat(tea): botones y rótulos en la dona C2 de un solo anillo
Sin grupos de categorías (M23), la dona de TEA se dibuja como la de M21: un
anillo con rótulos, el total al centro y un botón por categoría.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:56:54 -06:00
edgar 737c6f9f14 feat(tea): redactar el resumen según los pacientes de M23
M23 ya no cuenta los diagnósticos descartados: el párrafo dice ahora «evaluados
por psicología [...] diagnóstico confirmado o en proceso».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:48:19 -06:00
edgar 8e543cbcc6 feat(tea): filtros de edad, M-CHAT y ADOS-2 en Seguimiento
- Filtros por grupo de edad, rango de riesgo M-CHAT-R/F y nivel de CSS ADOS-2.
  Se envían a la API como grupo_edad, mchat_min/max y css_min/max.
- Se quita «Ordenar por prioridad», también de CaCu, donde estaba deshabilitado.
- El grupo de edad menor pasa a 16-23 meses, igual que en los indicadores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:06:37 -06:00
edgar ea7aad5067 test(tea): husos del sueño por etapa N2 y N3 en el resumen del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:56:25 -06:00
edgar 09b52e6b0a feat(tea): pestaña Histórico, colores por edad en EEG y acordeón en Seguimiento
- Evolución pasa a llamarse Histórico y añade «Periodos a mostrar»: los
  últimos 5, 10, 15... meses o semestres, según el intervalo elegido.
- M21 y M22 usan un color por grupo de edad, sin verde ni rojo, también en
  sus líneas de Histórico.
- Se quita el selector «Representación gráfica».
- Todas las filas de Seguimiento de TEA se despliegan en su lugar; se quita
  la ventana propia de los pacientes impares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:41:05 -06:00
edgar 078db53ae4 feat(tea): pestaña Evolución y paleta con el verde de ISSSTELEON
- Pestaña Evolución (solo TEA), entre Resumen y Seguimiento: una figura por
  indicador con todos los periodos publicados, mensual o semestral. Barras
  apiladas para C2, línea con intervalo de confianza para C1 y mediana con
  cuartiles para C3r. Los periodos suprimidos se sombrean, no se dibujan
  como cero.
- Paleta: verde #A8C243 y rojo ladrillo #B8433A, comprobados para
  daltonismo. Las líneas usan un verde más oscuro sobre fondo claro.
- «Sin EEG» conserva su color en M21 y M22.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:09:02 -06:00
edgar 957f4cd024 feat(tea): botones para resaltar grupos y categorías en las figuras
- Leyenda con botones, como la distribución de resultados citológicos de
  cáncer cervicouterino: el grupo o la categoría elegida conserva su color,
  el resto se atenúa, «Volver» retrocede y un clic en la figura equivale al
  botón (indicadores-highlight.ts).
- M21, M22 y M24 con botones por grupo de edad; el centro de las donas
  muestra la selección.
- En TEA, la dona C2 de un periodo (M23) se dibuja con ambos anillos y
  botones, y sus barras también los tienen.
2026-11-03 21:22:51 +00:00
edgar 1ce8d98663 feat(tea): ficha de paciente en tres columnas y dona de M21 solo con EEG
- La ficha propia del paciente reparte los paneles en tres columnas
  (dos o una en pantallas más estrechas), con los puntajes por reactivo
  abiertos y un mapa más grande.
- La dona de M21 muestra solo a los pacientes con EEG por grupo de edad;
  el centro conserva el porcentaje total con EEG.
2026-11-03 20:28:14 +00:00
edgar 1771cb7ec6 feat(tea): ficha propia para la mitad de los pacientes de Seguimiento
Los pacientes con número impar abren su propia ventana, como la ficha de
cáncer cervicouterino (con «Regresar» y un resumen arriba); los pares
conservan el resumen desplegable en la fila. El encabezado de la ficha ya
nombra el dominio en lugar de decir siempre cáncer cervicouterino.
2026-11-03 19:58:30 +00:00
edgar b74f188b15 feat(tea): dona por grupo de edad para M21 y barras por grupo de edad para M22
- M21 (fig_c1_dona_edad): solo el anillo por grupo de edad, con el porcentaje
  total con EEG al centro.
- M22 (fig_c1_barras_edad): una barra por grupo de edad con el porcentaje de
  pacientes sin EEG.
- M24 conserva la dona de dos anillos.
2026-11-03 19:45:32 +00:00
edgar 5196f20e47 feat(tea): dona de dos anillos por grupo de edad para M21, M22 y M24
Figura fig_c1_donas para indicadores C1 de un semestre: el anillo interior
divide la población entre con y sin el evento, y el exterior cada parte por
grupo de edad, con el mismo dibujo que la distribución de resultados
citológicos de cáncer cervicouterino. Se construye con los datos
estratificados por grupo de edad.
2026-11-03 19:22:54 +00:00
edgar 5d4cd6f654 feat(indicadores): enlace «Ir» en el selector y seguimiento de TEA más compacto
- Se quita el botón flotante de navegación por indicadores.
- Cada opción de «Buscar indicadores» tiene un enlace «Ir» que lleva a su
  tarjeta (y la muestra si estaba oculta por la selección).
- Resumen del paciente en Seguimiento más compacto; «Puntajes por reactivo»
  plegado por defecto, con un triángulo para desplegarlo.
2026-11-03 19:22:54 +00:00
edgar a05717f92d feat(tea): intervalo de análisis, resumen más preciso y alteraciones del EEG
- Filtro general: «Intervalo de análisis» (Semestral/Mensual) en lugar de
  «Modalidad»; al cambiar de intervalo se elige el periodo más reciente.
- Resumen de TEA: evaluaciones con o sin diagnóstico y diagnóstico positivo
  de TEA explícito.
- Seguimiento: panel «Alteraciones del EEG» (exponente aperiódico, husos del
  sueño, entropía multiescala) con posibles efectos asociados. Datos de
  ejemplo, pendientes de validación médica.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:07:22 +00:00
edgar 123232592f feat(indicadores): un solo periodo y selector de indicadores gráficos
- El filtro general admite un único periodo (Elegir periodo); agregar otro lo reemplaza.
- Buscar indicadores pasa a ser una lista desplegable con casillas; solo los
  indicadores marcados se muestran en Indicadores gráficos, con Mostrar todos.
2026-10-30 23:24:38 +00:00
edgar 2cbb994667 feat(tea): seguimiento con resumen por paciente y resumen por periodo
- Pestaña Seguimiento de TEA: tabla de pacientes con filtro de alteraciones EEG
  y fila desplegable con ADOS-2 por reactivo, calidad del EEG y mapa topográfico
  (GET /tea/seguimiento/<id>).
- Indicadores destacados: M21 y M22 (pacientes con TEA con y sin EEG).
- Con un solo periodo elegido, TEA muestra un párrafo de resumen en lugar de
  las tarjetas.
2026-10-30 23:24:38 +00: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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/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
162 changed files with 8847 additions and 1289 deletions
+8
View File
@@ -31,6 +31,14 @@
} }
], ],
"styles": [ "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" "src/styles.scss"
] ]
}, },
+1 -1
View File
@@ -8,7 +8,7 @@ server {
# the ~33% base64 overhead. # the ~33% base64 overhead.
client_max_body_size 270m; client_max_body_size 270m;
location ~ ^/(api|imports|data|cacu|cama|tea|governance|health)(/|$) { location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {
proxy_pass http://webapi:5000; proxy_pass http://webapi:5000;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+37
View File
@@ -16,6 +16,10 @@
"@angular/material": "^22.1.7", "@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0", "@angular/platform-browser": "^22.1.0",
"@angular/router": "^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",
"plotly.js-cartesian-dist-min": "4.1.2", "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"tslib": "^2.3.0" "tslib": "^2.3.0"
@@ -1417,6 +1421,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": { "node_modules/@harperfast/extended-iterable": {
"version": "1.0.3", "version": "1.0.3",
"resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.3.tgz", "resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.3.tgz",
@@ -5933,6 +5964,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5" "@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": { "node_modules/math-intrinsics": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+4
View File
@@ -19,6 +19,10 @@
"@angular/material": "^22.1.7", "@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0", "@angular/platform-browser": "^22.1.0",
"@angular/router": "^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",
"plotly.js-cartesian-dist-min": "4.1.2", "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"tslib": "^2.3.0" "tslib": "^2.3.0"
+2 -1
View File
@@ -6,5 +6,6 @@
"/cacu": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }, "/cacu": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
"/cama": { "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 }, "/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 }
} }
+13
View File
@@ -4,12 +4,25 @@
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio"> <a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" /> <img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a> </a>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
[attr.aria-label]="'Dominio actual: ' + domainLabels[domain] + '. Cambiar dominio'">
{{ domainLabels[domain] }} <span aria-hidden="true">▾</span>
</button>
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
@for (option of otherDomains(); track option) {
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ domainLabels[option] }}</a>
}
</mat-menu>
} @else {
<nav class="site-header__nav" aria-label="Secciones"> <nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a> <a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) { @if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span> <span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
} }
</nav> </nav>
}
</div> </div>
</header> </header>
+6
View File
@@ -20,6 +20,12 @@ export const routes: Routes = [
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage), loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' }, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
}, },
{
path: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportesPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({ ...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`, path: `indicadores/${dominio}`,
+25
View File
@@ -29,6 +29,31 @@
width: clamp(180px, 16vw, 200px); width: clamp(180px, 16vw, 200px);
} }
.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 {
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; }
@media (max-width: 599px) {
.platform-title { font-size: 1.125rem; min-width: 0; }
}
.site-header__nav { .site-header__nav {
align-items: center; align-items: center;
display: flex; display: flex;
+11
View File
@@ -30,6 +30,17 @@ describe('App', () => {
expect(page.querySelector('.site-footer')).not.toBeNull(); expect(page.querySelector('.site-footer')).not.toBeNull();
}); });
it('an indicators page shows the platform title and a menu named after its domain', async () => {
// Fails if the header stops naming the domain or offers the current one among the others.
const page = await render('/indicadores/cama');
expect(page.querySelector('.platform-title')?.textContent).toContain('Plataforma de Indicadores');
expect(page.querySelector('.domain-selector')?.textContent).toContain('Cáncer de mama');
(page.querySelector('.domain-selector') as HTMLButtonElement).click();
const options = Array.from(document.querySelectorAll('.mat-mdc-menu-panel a')).map(a => a.textContent?.trim());
expect(options).toEqual(['TEA', 'CaCu']);
expect(page.querySelector('.site-header__crumb')).toBeNull();
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => { it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar'); const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull(); expect(page.querySelector('app-connect-page')).not.toBeNull();
+13 -1
View File
@@ -1,10 +1,13 @@
import { Component, computed, inject } from '@angular/core'; import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop'; import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router'; import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { filter, map } from 'rxjs'; import { filter, map } from 'rxjs';
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
@Component({ @Component({
imports: [RouterLink, RouterOutlet], imports: [RouterLink, RouterOutlet, MatButtonModule, MatMenuModule],
selector: 'app-root', selector: 'app-root',
styleUrl: './app.scss', styleUrl: './app.scss',
templateUrl: './app.html', templateUrl: './app.html',
@@ -13,6 +16,15 @@ export class App {
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
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()));
private readonly leafRouteData = toSignal( private readonly leafRouteData = toSignal(
this.router.events.pipe( this.router.events.pipe(
filter((event) => event instanceof NavigationEnd), filter((event) => event instanceof NavigationEnd),
+3
View File
@@ -223,6 +223,9 @@ export interface CommitSourceResult {
export interface BatchResult { export interface BatchResult {
ok: boolean; ok: boolean;
results: CommitSourceResult[]; results: CommitSourceResult[];
/** Id of this attempt in the aggregate import log (`/reportes/importaciones`). */
audit_id?: string;
indicadores_en_recalculo?: boolean;
} }
export interface DataPage { export interface DataPage {
@@ -20,6 +20,9 @@
{{ o.merged | number }} combinadas con registros de otras fuentes@if (o.warnings) {, {{ o.warnings | number }} valor(es) en desacuerdo}. {{ o.merged | number }} combinadas con registros de otras fuentes@if (o.warnings) {, {{ o.warnings | number }} valor(es) en desacuerdo}.
} }
</p> </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"> <table mat-table [dataSource]="flows()" class="flows">
@@ -1,4 +1,6 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; } export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number;
// Filters a list announces in `filtros_disponibles`, by key.
filtros?: Record<string, string>; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; } export interface SeguimientoStatus { codigo: string; etiqueta: string; }
export interface SeguimientoPaciente { export interface SeguimientoPaciente {
id_seudonimo: string; id_seudonimo: string;
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
afterEach(()=>{ fixture.destroy(); http.verify(); }); afterEach(()=>{ fixture.destroy(); http.verify(); });
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); } function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); } function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => { it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
respond(); respond();
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement; expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad'); expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo); const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order); expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
fixture.componentInstance.apply(); fixture.componentInstance.apply();
@@ -39,12 +38,18 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(root.textContent).not.toContain('Las reglas de selección son provisionales'); expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
expect(root.textContent).toContain('Ventana consultada:'); 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('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.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 input[name="corte"]')).not.toBeNull();
expect(root.querySelector('form select[name="meses"]')).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.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/); 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[5])).toBe('2026-08-15');
expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull(); expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull();
}); });
@@ -86,13 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow(); 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(); open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
}); });
it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
});
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => { it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
const service=TestBed.inject(CacuSeguimientoService); const service=TestBed.inject(CacuSeguimientoService);
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow(); for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';
import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigurePanel } from './indicador-figure-panel';
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] }); fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
} }
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
@@ -47,13 +45,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(fixture.componentInstance.indicador.contrato).toBe(contrato); expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => { it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges(); fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
]);
http.expectNone(() => true); http.expectNone(() => true);
open(); request('fig_c1_grupos').flush({ data: [], layout: {} }); open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
for (const [id, label] of [ for (const [id, label] of [
@@ -62,7 +56,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
['fig_c2_donas', 'Donas'], ['fig_c2_donas', 'Donas'],
['fig_c9_futura', 'Representación 5'], ['fig_c9_futura', 'Representación 5'],
]) { ]) {
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges(); fixture.componentInstance.selectFigure(id); fixture.detectChanges();
const pending = request(id); const pending = request(id);
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id); expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
expect(pending.request.params.get('tema')).toBe('claro'); expect(pending.request.params.get('tema')).toBe('claro');
@@ -74,9 +68,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
} }
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => { it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
}); });
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => { it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2', fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
@@ -98,9 +92,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true); expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
}); });
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => { it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
open(); const first = request('f'); expect(select().disabled).toBe(false); open(); const first = request('f'); expect(panels()).toHaveLength(1);
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1); fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1); const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
expect(next.request.params.get('periodos')).toBe('2025-S1'); expect(next.request.params.get('periodos')).toBe('2025-S1');
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true); fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
import { catchError, of, Subscription } from 'rxjs'; import { catchError, of, Subscription } from 'rxjs';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models'; import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
@@ -17,20 +15,27 @@ import { filterCompatibility } from './indicadores-memory';
import { DonutSelection } from './indicadores-donut-drilldown'; import { DonutSelection } from './indicadores-donut-drilldown';
import { IndicadoresService } from './indicadores.service'; import { IndicadoresService } from './indicadores.service';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { vistaConfirmacion } from './indicadores-confirmacion-citologia';
import { parTiempos } from './indicadores-tiempos-pareados';
import { parConteos } from './indicadores-conteos-pareados';
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
@Component({ @Component({
selector: 'app-indicador-catalog-card', selector: 'app-indicador-catalog-card',
host: { '[class.dual-card]': 'isDual || isEu7' }, host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos || !!conteos' },
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario], imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados],
template: ` template: `
<mat-card> <mat-card>
<header> <header>
<div class="card-identity"> <div class="card-identity">
<h2 [id]="titleId">{{ indicador.titulo }}</h2> <h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</div> </div>
</header> </header>
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned" <button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ' · ' + indicador.titulo" [attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
(click)="pinChanged.emit()"> (click)="pinChanged.emit()">
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }} <mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button> </button>
@@ -40,17 +45,19 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
<div #visibilityRegion class="eu7-region"> <div #visibilityRegion class="eu7-region">
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" /> <app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div> </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 (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 (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 (selectedFigure) { } @else if (selectedFigure) {
@if (!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"
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
</mat-select>
</mat-form-field>
}
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual"> <div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@for (figure of displayFigures; track panelIdentity(figure)) { @for (figure of displayFigures; track panelIdentity(figure)) {
<div class="representation-panel"> <div class="representation-panel">
@@ -91,7 +98,7 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
} }
.card-identity { min-width: 0; } .card-identity { min-width: 0; }
h2, p { overflow-wrap: anywhere; } 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; .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); } min-width: 48px; min-height: 48px; color: var(--issste-text); }
.pin-toggle mat-icon { flex-shrink: 0; } .pin-toggle mat-icon { flex-shrink: 0; }
@@ -120,8 +127,12 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
}); });
} }
get pair() { return dualFigures(this.indicador); } get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isEu7() { return !!vistaEscenario(this.dominio, this.indicador); }
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } get isConfirmacion() { return !!vistaConfirmacion(this.dominio, this.indicador); }
// 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 isDual() { return this.pair.includes(this.selectedFigure ?? ''); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
private updateNumeric() { private updateNumeric() {
@@ -0,0 +1,81 @@
<section class="confirmacion" [attr.aria-label]="'Confirmación histopatológica, ' + vista.textos.filas.toLowerCase()">
<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" [attr.aria-label]="'Cargando ' + indicador.titulo" /><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">{{ vista.textos.vacio }}</p> }
@else {
@if (!vista.botones) {
<p class="hint">Haz clic en un anillo de la dona para elegir un grupo o un resultado; el centro regresa un paso, hasta el total.</p>
}
<!-- Without visible buttons they stay for the keyboard, shown while one has the focus. -->
<div class="legend" [class.solo-teclado]="!vista.botones" 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>{{ vista.textos.filas }}, {{ m.periodo }}</h3>
@if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, tasas ' + vista.textos.filas.toLowerCase() + ', ' + 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" [animated]="!vista.botones" [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 ' + vista.textos.sujetos + ' 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" [attr.aria-label]="'Tabla de contingencia, ' + indicador.titulo" tabindex="0">
<table><caption>Tabla de contingencia de {{ vista.textos.sujetos }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">{{ vista.textos.encabezado }}</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,41 @@
: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; }
.hint { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.legend.solo-teclado:not(:focus-within) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
// The donut is the control: its slices and centre answer to the pointer.
.donut app-plotly-chart { cursor: pointer; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); 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,143 @@
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, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas,
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
Celda, Tasa, tasas, vistaConfirmacion } from './indicadores-confirmacion-citologia';
@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.vista.botones ? this.model.base : undefined); }
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
// CaCu's words when the catalog doesn't name this indicator, so the messages still read.
get vista() { return vistaConfirmacion(this.dominio, this.indicador) ?? CONFIRMACION_CACU; }
estadoTasa(t: Tasa) { return estadoTasa(t, this.vista.textos.sujetos); }
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 ?? [];
// Figures of the kit whose "Cómo leer" describes this coordinated view.
const figuras = [['fig_c2_donas', 'Dona de resultados de biopsia'], ['fig_c2_barras', 'Tasas ' + this.vista.textos.filas.toLowerCase()]] as const;
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: this.vista.estrato })
+ 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);
const vista = vistaConfirmacion(this.dominio, this.indicador);
if (!vista || 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: vista.estrato }).pipe(timeout({ first: 40000 })).subscribe({
next: datos => {
if (key !== this.key) return;
try {
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods, vista);
this.pages = this.periods.map(p => modeloConfirmacion(datos, p, vista));
// 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];
// With buttons the view opens on the base group; without, on the total, as CaCu's interactive donut.
this.selection = this.model ? (this.vista.botones ? 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 = (this.vista.botones ? clicConfirmacion : clicDona)(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 = (this.vista.botones ? donaConfirmacion : donaExpandible)(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,53 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<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" [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 ' + par.unidades.pacientes.slice(0, -1) + ', ' + m.periodo" />
</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" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría</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>{{ texto(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,117 @@
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 { describePeriods, 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;
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
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'); }
helpOpen = false;
// "Cómo leer": what the kit publishes for the exams' two figures.
get readingGuide() {
const figuras = [['fig_c2_donas', 'Dona por categoría'], ['fig_c2_barras', 'Pacientes y ' + this.par.unidades.examenes]] as const;
return figuras.flatMap(([figura, nombre]) => {
const detail = this.metadata?.figuras_detalle?.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) + 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.barsFigure = barrasConteos(m, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -1,54 +1,39 @@
<section class="eu7" aria-label="Resultados citológicos por escenario clínico"> <section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p> <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> <button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) { @if (helpOpen) {
<div class="methodology"> <div class="methodology">
<p>El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.</p> @if (metadata) {
<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> @for (guide of readingGuide; track guide.figura) {
<p>El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.</p> <section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<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> <h3>{{ guide.nombre }}</h3>
<p>Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.</p> @if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (metadata; as info) { @if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
@if (info.descripcion) { <p>{{ info.descripcion }}</p> } </section>
@if (info.ficha; as ficha) { } @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
@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>
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> } } @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
</div> </div>
} }
@switch (status()) { @switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> } @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 resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> } @case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> } @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> } @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 (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) { @if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de dona y barras EU7"> <nav class="periods" [attr.aria-label]="'Periodos de dona y barras, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button> <button type="button" aria-label="Periodo anterior" [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> <button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav> </nav>
} }
@if (model; as m) { @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> } @if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
@else { @else {
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7"> <div class="legend" role="group" [attr.aria-label]="'Explorar grupos y categorías, ' + indicador.titulo">
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button> <button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior"> <div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) { @for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button> <button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
@@ -61,29 +46,29 @@
</div> </div>
</div> </div>
<div class="figures"> <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) { @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)" /> <app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="indicador.titulo + ', 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> } } @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> <p>{{ sinDatoNote }}</p>
</section> </section>
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico · {{ m.periodo }}</h3> <section class="figure"><h3>{{ selectionLabel }} por {{ etiquetaEstrato }}, {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p> <p>Porcentaje del total válido de cada {{ etiquetaEstrato }}; excluye «{{ m.sinDatoEtiqueta }}».</p>
@if (m.escenarios.length && barsFigure) { @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]="indicador.titulo + ', barras por ' + etiquetaEstrato + ', ' + m.periodo + ', ' + selectionLabel" />
} }
</section> </section>
</div> </div>
} }
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> } @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"> <div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" 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> <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> <tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
</table> </table>
<table><caption>Escenarios clínicos · {{ m.periodo }} · Porcentajes sin «Sin dato»</caption> <table><caption>Por {{ etiquetaEstrato }}, {{ m.periodo }}, porcentajes sin «{{ m.sinDatoEtiqueta }}»</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> <thead><tr><th scope="col">{{ etiquetaEstrato.charAt(0).toUpperCase() + etiquetaEstrato.slice(1) }}</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> <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> </table>
</div> </div>
@@ -8,7 +8,7 @@ p, h3, summary { overflow-wrap: anywhere; }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; } .keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; } .legend > button { justify-self: start; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border); 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; } border-radius: var(--issste-radius); 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; } .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[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:disabled { opacity: .5; cursor: default; }
@@ -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); } th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; } caption { text-align: start; font-weight: 600; }
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } } @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: '' }) @Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { 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>(); plotClick = output<unknown>();
} }
describe('EU7 integración Angular y caché compartida', () => { 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(); 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'); f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.model!.total).toBe(946); 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; const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1); expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682'); 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(); 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); 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(); 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.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.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined(); 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')[0].textContent).toContain('2025-S2');
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true); expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
}); });
@@ -122,7 +126,7 @@ describe('EU7 integración Angular y caché compartida', () => {
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido'); f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
expect(f.nativeElement.textContent).not.toContain('987654'); expect(f.nativeElement.textContent).not.toContain('987654');
expect(f.nativeElement.querySelector('table caption')).not.toBeNull(); expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0); expect(f.nativeElement.querySelector('[aria-label="Tabla de valores, Distribución de resultados citológicos"]').tabIndex).toBe(0);
}); });
it('catálogo sin capacidad temporal o clínica no inicia GET', () => { it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges(); f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
@@ -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.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true); 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', () => { it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
f.componentRef.setInput('visible', false); f.detectChanges(); f.componentRef.setInput('visible', false); f.detectChanges();
const card = TestBed.createComponent(IndicadorCatalogCard); const card = TestBed.createComponent(IndicadorCatalogCard);
@@ -4,13 +4,14 @@ import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http'; import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified'; import { stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, import { barras, Celda, clic, dona, esEu7, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; periodosCompatibles, Seleccion, seleccionEtiqueta, vistaEscenario } from './indicadores-eu7-escenario';
@Component({ @Component({
selector: 'app-indicador-eu7-escenario', selector: 'app-indicador-eu7-escenario',
@@ -41,6 +42,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private key = ''; private key = '';
private loaded = false; private loaded = false;
private pages: Modelo[] = []; private pages: Modelo[] = [];
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; } get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
get sinDatoNote() { get sinDatoNote() {
@@ -48,9 +51,11 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
if (!m) return ''; if (!m) return '';
if (m.vacio) return 'No hay registros publicados en este periodo.'; if (m.vacio) return 'No hay registros publicados en este periodo.';
const n = m.sinDato.n; const n = m.sinDato.n;
if (this.vista && !esEu7(this.vista)) return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: `Fuera de la dona: ${n} pacientes con «${m.sinDatoEtiqueta}»${m.total === null ? '' : ` de ${m.total + n}`}.`;
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.` 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.` : 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 sin resultado válido en el periodo.`; : `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() { get generalCells() {
const m = this.model; const m = this.model;
@@ -63,8 +68,19 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })), 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 }]); { 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 ?? [];
const figuras = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por ' + this.etiquetaEstrato]] as const;
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 }] : [];
});
}
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } 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(); } toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
@@ -86,10 +102,11 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
this.loaded = true; this.model = undefined; this.pages = []; this.periods = []; this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2' const vista = this.vista;
if (!vista || this.indicador.contrato !== 'C2'
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras') || !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) { || !stratifiedCapabilities(this.indicador).includes(vista.estrato) || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.'; this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return; this.status.set('incompatible'); return;
} }
const key = this.key; const key = this.key;
@@ -97,13 +114,13 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
this.status.set('loading'); this.status.set('loading');
this.subscription = combineLatest([ this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version), this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }), this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: vista.estrato }),
]).pipe(timeout({ first: 40000 })).subscribe({ ]).pipe(timeout({ first: 40000 })).subscribe({
next: ([general, escenarios]) => { next: ([general, escenarios]) => {
if (key !== this.key) return; if (key !== this.key) return;
try { try {
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods); this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
this.pages = this.periods.map(p => modelo(general, escenarios, p)); this.pages = this.periods.map(p => modelo(general, escenarios, p, vista.estrato));
this.periodIndex = 0; this.activatePeriod(); this.periodIndex = 0; this.activatePeriod();
} catch (error) { this.failure(error); } } catch (error) { this.failure(error); }
}, },
@@ -138,7 +155,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private draw() { private draw() {
if (!this.model) return; if (!this.model) return;
this.donutFigure = dona(this.model, this.selection, this.tema); this.donutFigure = dona(this.model, this.selection, this.tema);
this.barsFigure = barras(this.model, this.selection, this.tema); this.barsFigure = barras(this.model, this.selection, this.tema, `% de pacientes de cada ${this.etiquetaEstrato}`);
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
} }
ngOnDestroy() { this.subscription?.unsubscribe(); } ngOnDestroy() { this.subscription?.unsubscribe(); }
@@ -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) { @if (selected) {
<section class="interpretation" [class.expanded]="methodologyExpanded()"> <section class="interpretation" [class.expanded]="methodologyExpanded()">
<button mat-stroked-button type="button" class="methodology-toggle" <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" [attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
(click)="toggleMethodology()"> (click)="toggleMethodology()">
<mat-icon aria-hidden="true">help_outline</mat-icon> <mat-icon aria-hidden="true">help_outline</mat-icon>
@@ -13,6 +13,12 @@
@for (line of interpretation; track $index) { <li>{{ line }}</li> } @for (line of interpretation; track $index) { <li>{{ line }}</li> }
</ul> </ul>
<p class="period-note">{{ periodInterpretation }}</p> <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> </div>
</section> </section>
} }
@@ -77,7 +83,23 @@
</div> </div>
</div> </div>
} }
@if (state.status === 'ready' && state.donutLegend?.length) { @if (state.status === 'ready' && state.highlight; as h) {
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
@for (row of highlightRows(h); track row.group?.id ?? '') {
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
@if (row.group; as g) {
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
}
@for (c of row.items; track c.id) {
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
}
</div>
}
</div>
} @else if (state.status === 'ready' && state.donutLegend?.length) {
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona"> <div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
@for (entry of state.donutLegend; track entry.label) { @for (entry of state.donutLegend; track entry.label) {
<span class="donut-static-legend__item" role="listitem"> <span class="donut-static-legend__item" role="listitem">
@@ -88,15 +110,11 @@
} }
</div> </div>
<div class="plot-slot" [hidden]="state.status !== 'ready'"> <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 || state.highlight ? '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>
} }
<div class="figure-footer" [hidden]="state.status !== 'ready'"> <div class="figure-footer" [hidden]="state.status !== 'ready'">
@if (state.footnotes?.length) { @if (cutoffDate; as cutoff) { <p class="figure-cutoff">Fecha de corte: {{ cutoff }}</p> }
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
</section>
}
</div> </div>
<div class="figure-labels" [hidden]="state.status !== 'ready'"> <div class="figure-labels" [hidden]="state.status !== 'ready'">
@if (state.categoryLabels?.length) { @if (state.categoryLabels?.length) {
@@ -44,8 +44,11 @@
.notes { padding: 1rem; overflow-wrap: anywhere; } .notes { padding: 1rem; overflow-wrap: anywhere; }
.notes h2 { font-size: 1rem; } .notes h2 { font-size: 1rem; }
.notes p { line-height: 1.5; } .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 { .methodological-footnotes {
padding: .75rem 1rem 1rem; padding: 0;
min-width: 0; min-width: 0;
max-width: 100%; max-width: 100%;
box-sizing: border-box; box-sizing: border-box;
@@ -110,3 +113,16 @@
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; } .donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
} }
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
.dark .highlight-legend { color: #eef1f7; }
.highlight-status { margin: 0; font-weight: 600; }
.highlight-back { justify-self: start; }
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); font: inherit; cursor: pointer; }
.highlight-legend button:disabled { opacity: .45; cursor: default; }
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.highlight-legend .legend-swatch { border-radius: 50%; }
.highlight-legend .highlight-group { font-weight: 600; }
@@ -145,25 +145,33 @@ describe('IndicadorFigureCard', () => {
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined(); fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1); 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); fixture.componentRef.setInput('dominio', dominio);
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; 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, state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] }); minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement; 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.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
expect(section.querySelector('img, script, a')).toBeNull(); expect(section.querySelector('img, script, a')).toBeNull();
expect(section.parentElement?.previousElementSibling?.querySelector('app-plotly-chart')).toBeTruthy(); const detail = section.closest('.methodology-detail') as HTMLElement;
expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull(); expect(detail).not.toBeNull(); expect(detail.hidden).toBe(true);
expect(section.parentElement?.parentElement?.querySelector('.figure-labels .category-labels')).toBeTruthy(); 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) { for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
state({ status }); state({ status });
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
} }
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] }); state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] });
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('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 () => { 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: {} }; const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} };
@@ -284,9 +292,9 @@ describe('IndicadorFigureCard', () => {
state({ status: 'loading' }); state({ status: 'loading' });
expect(firstHost.closest('[hidden]')).toBeTruthy(); expect(firstHost.closest('[hidden]')).toBeTruthy();
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); 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(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(); ready({ data: [{ y: [50] }], layout: {} }); await settle();
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost); expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
expect(firstHost.closest('[hidden]')).toBeNull(); expect(firstHost.closest('[hidden]')).toBeNull();
@@ -458,7 +466,7 @@ describe('IndicadorFigureCard', () => {
button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
} }
expect(button.textContent).toContain('Cómo leer'); 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-expanded')).toBe('false');
expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true);
const warnings = detail.querySelector('ul')!; const warnings = detail.querySelector('ul')!;
@@ -10,8 +10,9 @@ import { figureDisplayName } from './indicadores-figure-labels';
import { CategoryLabel } from './indicadores-axis-labels'; import { CategoryLabel } from './indicadores-axis-labels';
import { figureIdentity, identityElementId } from './indicadores-identities'; import { figureIdentity, identityElementId } from './indicadores-identities';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; 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'; import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
// The panel owns requests; the card receives the original and its presentation copy. // The panel owns requests; the card receives the original and its presentation copy.
export interface FigureState { export interface FigureState {
@@ -22,6 +23,10 @@ export interface FigureState {
categoryLabels?: readonly CategoryLabel[]; categoryLabels?: readonly CategoryLabel[];
minimumPlotWidth?: number; minimumPlotWidth?: number;
donutLegend?: readonly DonutLegendEntry[]; donutLegend?: readonly DonutLegendEntry[];
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
ownLayout?: boolean;
// Legend buttons that highlight one part of the figure (CaCu style).
highlight?: FigureHighlight;
plotWidth?: number; plotWidth?: number;
plotHeight?: number; plotHeight?: number;
message?: string; message?: string;
@@ -64,7 +69,7 @@ export class IndicadorFigureCard implements OnChanges {
} }
@Input({ required: true }) set state(value: FigureState) { @Input({ required: true }) set state(value: FigureState) {
if (value.status !== 'ready' || value.figure !== this.currentState?.figure if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; } || JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
this.currentState = value; this.currentState = value;
if (value.status === 'ready') { if (value.status === 'ready') {
this.updateDonut(); this.updateDonut();
@@ -87,7 +92,8 @@ export class IndicadorFigureCard implements OnChanges {
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure; ? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
this.chartFigure = source && hierarchy this.chartFigure = source && hierarchy
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth) ? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
: source && this.state.donutLegend ? donutSimpleView(source) : source; : source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
} }
expandParent(parent: string) { expandParent(parent: string) {
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent) if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
@@ -109,9 +115,28 @@ export class IndicadorFigureCard implements OnChanges {
target?.focus(); target?.focus();
} }
} }
highlightSelection: HighlightSelection = {};
readonly highlightRows = highlightRows;
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
highlight(kind: 'group' | 'item', id: string) {
if (!this.state.highlight) return;
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
this.updateDonut();
}
highlightBack() {
const sel = this.highlightSelection;
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
this.updateDonut();
}
plotClicked(event: unknown) { plotClicked(event: unknown) {
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return; if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
const point = event.points[0]; const point = event.points[0];
if (this.state.highlight) {
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
if (hit) this.highlight(hit.kind, hit.id);
return;
}
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label); if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label); else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
} }
@@ -143,23 +168,23 @@ export class IndicadorFigureCard implements OnChanges {
: this.figuraId.startsWith('fig_c2') ? 'C2' : this.figuraId.startsWith('fig_c2') ? 'C2'
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato; : 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 hasNoVisibleValues = hasNoVisibleValues;
readonly figureTitle = figureTitle; readonly figureTitle = figureTitle;
readonly figureDisplayName = figureDisplayName; readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION; readonly periodInterpretation = PERIOD_INTERPRETATION;
get interpretation(): readonly string[] { get interpretation(): readonly string[] {
return figureMetadataInterpretation(this.metadata, this.figuraId) return figureInterpretation(this.metadata, this.figuraId, this.contract, this.dominio,
?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie')); 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(heading.id).toBe(id); expect(id).not.toBe('');
expect(section.getAttribute('aria-labelledby')).toBe(id); expect(section.getAttribute('aria-labelledby')).toBe(id);
expect(section.firstElementChild).toBe(heading); 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); expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false);
const style = getComputedStyle(heading); const style = getComputedStyle(heading);
expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden'); expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden');
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
expect(JSON.stringify(page.result().figure)).toBe(original); expect(JSON.stringify(page.result().figure)).toBe(original);
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
}); });
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => { it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
load(); figure().flush({ data: [], layout: {} }); load(); figure().flush({ data: [], layout: {} });
const control = filters(); const control = filters();
control.changeMode('manual'); control.select([]);
expect(control.canApply).toBe(false); expect(control.canApply).toBe(false);
apply(); apply();
http.expectNone(req => req.url.includes('/figuras/')); http.expectNone(req => req.url.includes('/figuras/'));
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
expect(state?.applied?.selection.mode).toBe('todos'); expect(state?.applied?.selection.mode).toBe('todos');
apply(); apply();
const manual = figure(); const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(manual.request.params.get('periodos')).toBe('2025-S2');
control.select([]); control.select([]);
expect(manual.cancelled).toBe(false); expect(manual.cancelled).toBe(false);
expect(control.canApply).toBe(false); expect(control.canApply).toBe(false);
apply(); apply();
http.expectNone(req => req.url.includes('/figuras/')); http.expectNone(req => req.url.includes('/figuras/'));
control.changeMode('todos'); manual.flush({ data: [], layout: {} });
apply();
expect(manual.cancelled).toBe(true);
const all = figure();
expect(all.request.params.has('periodos')).toBe(false);
all.flush({ data: [], layout: {} });
}); });
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => { it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 }; load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
}); });
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => { it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} }); load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
const control = filters(); control.changeMode('manual'); const control = filters(); control.select([]);
control.year = '2025'; control.unit = 'S1'; control.add(); control.year = '2025'; control.unit = 'S1'; control.add();
fixture.detectChanges(); fixture.detectChanges();
expect(page.result().figure?.data[0]['y']).toEqual([0, null]); expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte'); expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
http.expectNone(r => r.url.includes('/figuras/')); http.expectNone(r => r.url.includes('/figuras/'));
}); });
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => { it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} }); load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; const control = filters(); control.select([]); control.year = '2025';
for (const period of periodos) { control.unit = period.slice(-2); control.add(); } for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
apply(); apply();
const req = figure(); const req = figure();
@@ -320,7 +315,6 @@ describe('IndicadorFigurePanel', () => {
expect(page.result().figure).toBeUndefined(); expect(page.result().figure).toBeUndefined();
expect(page.result().message).toContain('esta selección'); expect(page.result().message).toContain('esta selección');
expect(page.result().message).not.toContain('2025'); expect(page.result().message).not.toContain('2025');
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
expect(control.selectedPeriods).toEqual(periodos); expect(control.selectedPeriods).toEqual(periodos);
control.select([]); control.select([]);
page.requestFigure(); page.requestFigure();
@@ -333,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
}); });
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => { it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
load(); figure().flush({ data: [], layout: {} }); load(); figure().flush({ data: [], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
apply(); figure().flush({ data: [{ y: [20] }], layout: {} }); apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
control.unit = 'S2'; control.add(); control.unit = 'S2'; control.add();
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
@@ -344,17 +338,17 @@ describe('IndicadorFigurePanel', () => {
page.requestFigure(); page.requestFigure();
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1'); const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
retry.flush({ data: [], layout: {} }); retry.flush({ data: [], layout: {} });
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
}); });
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => { it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
load(); figure().flush({ data: [], layout: {} }); load(); figure().flush({ data: [], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
apply(); const old = figure(); apply(); const old = figure();
control.unit = 'S2'; control.add(); control.unit = 'S2'; control.add();
expect(old.cancelled).toBe(false); expect(old.cancelled).toBe(false);
apply(); const current = figure(); apply(); const current = figure();
expect(old.cancelled).toBe(true); expect(old.cancelled).toBe(true);
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(current.request.params.get('periodos')).toBe('2025-S2');
current.flush({ data: [{ y: [12] }], layout: {} }); current.flush({ data: [{ y: [12] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['y']).toEqual([12]); expect(page.result().figure?.data[0]['y']).toEqual([12]);
@@ -362,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => { it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} }); load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
fixture.detectChanges(); fixture.detectChanges();
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState); const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance; const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
@@ -13,6 +13,8 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown'; import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
import { IndicadoresSnapshots } from './indicadores-snapshots'; import { IndicadoresSnapshots } from './indicadores-snapshots';
import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection'; import { c2GeneralSelection } from './indicadores-c2-general-selection';
@@ -23,7 +25,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
imports: [IndicadorFigureCard, MatTooltipModule], imports: [IndicadorFigureCard, MatTooltipModule],
template: ` template: `
<section class="figure-panel" [attr.aria-labelledby]="titleId"> <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"> <header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p> <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')) { @if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
@@ -56,7 +58,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (result().status === 'ready' && donutPages.length > 1) { @if (result().status === 'ready' && donutPages.length > 1) {
<nav class="donut-periods" aria-label="Periodos de la dona"> <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> <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> <button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
</nav> </nav>
} }
@@ -67,7 +69,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (dimension && result().status === 'ready') { @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 (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> } @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> <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> } @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> </tbody></table></div>
@@ -102,7 +104,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; } .distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
.distribution-dimensions { margin-top: .75rem; } .distribution-dimensions { margin-top: .75rem; }
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem; .distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); color: var(--issste-text);
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; } font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; } .distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; } .distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
@@ -245,6 +247,17 @@ export class IndicadorFigurePanel implements OnChanges {
const state = this.presentStratified(data); this.stratifiedData = data; return state; const state = this.presentStratified(data); this.stratifiedData = data; return state;
})); }));
} }
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
const adapted = c1DonutFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
}));
}
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) { if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
// Both panels, KPI and numeric table share the exact same transport key. // Both panels, KPI and numeric table share the exact same transport key.
// Do not catch /datos errors here: a backend failure is a real error state. // Do not catch /datos errors here: a backend failure is a real error state.
@@ -265,6 +278,13 @@ export class IndicadorFigurePanel implements OnChanges {
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data); return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
} }
const adapted = c2Figure(data, selection); const adapted = c2Figure(data, selection);
if (adapted.status === 'supported' && selection.dominio === 'tea') {
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
if (selection.figura === 'fig_c2_donas') {
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
}
return adapted.status === 'supported' return adapted.status === 'supported'
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const, ? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage }) footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
@@ -13,20 +13,21 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p> <p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
} }
@if (temporalReference) { <p>{{ temporalReference }}</p> } @if (temporalReference) { <p>{{ temporalReference }}</p> }
<p class="kpi-state" role="status">{{ state }}</p> <!-- A card with its value says nothing more about its state; any other state is the message. -->
@if (state !== 'Disponible') { <p class="kpi-state" role="status">{{ state }}</p> }
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> } @if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</mat-card> </mat-card>
`, `,
styles: ` styles: `
:host { display: block; min-width: 0; } :host { display: flex; flex-direction: column; min-width: 0; }
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6); mat-card { box-sizing: border-box; flex: 1 1 auto; padding: var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); box-shadow: none; } 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; } h3, p { overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; } p { margin: var(--issste-space-3) 0 0; }
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } .kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.value { font: var(--mat-sys-headline-medium); } .value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; } .value span { margin-inline-start: .3em; }
`, `,
}) })
@@ -33,13 +33,13 @@ describe('KPI búsqueda inicial del último dato visible', () => {
categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} }, categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} },
filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] }; 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); const latest = request(periods[0]); http.expectNone(() => true);
expect(fixture.componentInstance.result().loading).toBe(true); expect(fixture.componentInstance.result().loading).toBe(true);
latest.flush(data(periods[0], 'suppressed')); latest.flush(data(periods[0], 'suppressed'));
request(periods[1]).flush(data(periods[1])); fixture.detectChanges(); request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
expect(fixture.componentInstance.result().value).toBe(5); 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.'); expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
http.expectNone(() => true); http.expectNone(() => true);
}); });
@@ -48,7 +48,7 @@ describe('KPI búsqueda inicial del último dato visible', () => {
const second = request(periods[1]); http.expectNone(() => true); const second = request(periods[1]); http.expectNone(() => true);
second.flush(data(periods[1], 'suppressed')); second.flush(data(periods[1], 'suppressed'));
request(periods[2]).flush(data(periods[2])); 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'); expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño');
}); });
it('agotado el inventario conserva el estado del último reporte', () => { 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 { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page'; import { IndicadoresPage } from './indicadores-page';
import { IndicadorKpiPanel } from './indicador-kpi-panel'; 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 { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorDatos, Dominio } from './indicadores.models'; import { IndicadorDatos, Dominio } from './indicadores.models';
import { IndicadoresMemory } from './indicadores-memory'; import { IndicadoresMemory } from './indicadores-memory';
@@ -13,26 +13,57 @@ describe('KPI integración con autoridad global', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>; let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let http: HttpTestingController; let http: HttpTestingController;
beforeEach(() => { 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()] }); TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); 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') { function load(domain: Dominio, missing = false, periods = ['2025-S1'], initial = domain === 'tea') {
// Ordinary consumer tests begin after initialization; dedicated P0 suites // Ordinary consumer tests begin after initialization; dedicated P0 suites
// exercise the real shared search for all three domains. // exercise the real shared search for all three domains.
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain); if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }))); http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
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 })) }); flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
fixture.detectChanges(); fixture.detectChanges();
} }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); } // Availability runs four requests at a time; flushing one batch starts the next.
function requests() { return http.match(r => r.url.endsWith('/datos')); } function flushPeriodos(periodos: () => unknown[]) {
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
}
// 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 { 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: [ 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 }] }; { 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 }] };
} }
// Answers every card by its URL until none is waiting: a domain with more cards than the concurrent
// requests gets them in batches.
function flushAll(domain: Dominio, extra: Partial<IndicadorDatos> = {}) {
for (let reqs = requests(); reqs.length; reqs = requests()) {
// A flushed answer can cancel its siblings (a new anchor period); those are not answered.
for (const r of reqs.filter(r => !r.cancelled)) {
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.includes('/' + d.id + '/'));
r.flush({ ...response(index, domain, r.request.params.get('periodos') ?? '2025-S1'), ...extra });
}
fixture.detectChanges();
}
}
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') { function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] }; const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
fixture.componentInstance.applyFilters(); fixture.detectChanges(); fixture.componentInstance.applyFilters(); fixture.detectChanges();
@@ -42,7 +73,7 @@ describe('KPI integración con autoridad global', () => {
expect(panels().map(p => p.definition.id)).toEqual([]); expect(panels().map(p => p.definition.id)).toEqual([]);
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
}); });
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => { it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]); fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
load('tea'); const initial = requests(); load('tea'); const initial = requests();
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']); expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
@@ -50,8 +81,10 @@ describe('KPI integración con autoridad global', () => {
const req = requests(); const req = requests();
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos')); expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges(); req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]); expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.'); expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
expect(panels()[3].result().info).toBe('2 de 5 pacientes con TEA positivo tienen un EEG ligado.');
expect(panels()[4].result().info).toBe('2 de 5 pacientes con TEA positivo no tienen ningún EEG ligado.');
}); });
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => { it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true); load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
@@ -66,7 +99,7 @@ describe('KPI integración con autoridad global', () => {
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => { it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i))); load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true); editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0); fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
expect(panels().map(p => p.result().value)).toEqual([5, 7]); expect(panels().map(p => p.result().value)).toEqual([5, 7]);
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
@@ -83,13 +116,14 @@ describe('KPI integración con autoridad global', () => {
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => { it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true); load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] }; fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama'))); load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); expect(requests().every(r => r.request.url.startsWith('/cama/'))).toBe(true); flushAll('cama');
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); // CaMa's last cards start after its first batch and are cancelled by the change of domain.
load('cacu'); const restored = requests().filter(r => !r.cancelled); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i))); expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
}); });
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => { 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)); 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))); 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 => { it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
@@ -104,8 +138,8 @@ describe('KPI integración con autoridad global', () => {
expect(page.filters).toBe(state); expect(state).toEqual(snapshot); expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null; const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
if (count) { if (count) {
expect(grid!.children).toHaveLength(count + 1); expect(grid!.children).toHaveLength(count + 3);
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 1)); expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 3));
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); } else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
http.expectNone(() => true); http.expectNone(() => true);
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges(); page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
@@ -142,7 +176,7 @@ describe('KPI integración con autoridad global', () => {
if (scenario === 'nulo') data.filas[0]['mediana'] = null; if (scenario === 'nulo') data.filas[0]['mediana'] = null;
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; } if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges(); 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().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); expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true);
}); });
@@ -150,26 +184,27 @@ describe('KPI integración con autoridad global', () => {
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu'); TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] }))); http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges(); flushPeriodos(() => []); fixture.detectChanges();
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true); expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
http.expectNone(r => r.url.endsWith('/datos')); 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) { for (const domain of ['cacu', 'cama'] as const) {
load(domain); load(domain);
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length); flushAll(domain, { notas: ['Nota del pie de la figura.'] });
req.forEach((r, i) => r.flush(response(i, domain)));
fixture.detectChanges();
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')]; const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
expect(cards).toHaveLength(3); expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
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')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7', '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('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined]
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']); : ['pacientes', '%', 'días (mediana)', 'días (mediana)']);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'), 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'); expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line; the kit notes are the figure footer.
expect(fixture.nativeElement.textContent).not.toContain('Nota del pie de la figura.');
} }
}); });
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => { it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
@@ -189,7 +224,7 @@ describe('KPI integración con autoridad global', () => {
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => { it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
for (const domain of ['cacu', 'cama'] as const) { for (const domain of ['cacu', 'cama'] as const) {
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges(); load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges(); flushAll(domain);
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false); expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
} }
load('cacu', false, ['2025-S1'], true); load('cacu', false, ['2025-S1'], true);
@@ -201,7 +236,7 @@ describe('KPI integración con autoridad global', () => {
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data); const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
const old = requests(); expect(old).toHaveLength(1); const old = requests(); expect(old).toHaveLength(1);
load('cama'); expect(old.every(r => r.cancelled)).toBe(true); load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
requests().forEach((r, i) => r.flush(response(i, 'cama'))); flushAll('cama');
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1); load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
resumed[0].flush(response(0)); fixture.detectChanges(); resumed[0].flush(response(0)); fixture.detectChanges();
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); }); requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
@@ -19,11 +19,12 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule], imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit" template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference" [state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="result().notes ?? []" /> [loading]="result().loading ?? false" [notes]="dominio !== 'tea' ? [] : result().notes ?? []" />
@if (result().state === 'Error de consulta') { @if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button> <button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`, }`,
styles: ':host { display: block; min-width: 0; }', // The card fills the panel, so cards in one grid row are as tall as the row.
styles: ':host { display: flex; flex-direction: column; min-width: 0; } app-indicador-kpi-card { flex: 1 1 auto; }',
}) })
export class IndicadorKpiPanel implements OnChanges { export class IndicadorKpiPanel implements OnChanges {
@Input({ required: true }) dominio!: Dominio; @Input({ required: true }) dominio!: Dominio;
@@ -40,7 +41,7 @@ export class IndicadorKpiPanel implements OnChanges {
readonly usedPeriod = signal<string | undefined>(undefined); readonly usedPeriod = signal<string | undefined>(undefined);
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' }); readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
get temporalReference() { 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'); return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
} }
retry() { this.requests.next(); } retry() { this.requests.next(); }
@@ -49,6 +50,9 @@ export class IndicadorKpiPanel implements OnChanges {
const applied = this.applied, definition = this.definition, domain = this.dominio; const applied = this.applied, definition = this.definition, domain = this.dominio;
this.usedPeriod.set(undefined); this.usedPeriod.set(undefined);
if (!applied) return of({ state: 'Esperando filtro aplicado' }); 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' }); if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]); const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' }); 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); } section + section { margin-top: var(--issste-space-4); }
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; } 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; } .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; } ul { padding-inline-start: 1.5rem; }
li + li { margin-top: var(--issste-space-2); } 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) { @media (max-width: 36rem) {
.ficha-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); } .ficha-table th { width: 6rem; }
dd { margin-bottom: var(--issste-space-2); }
} }
@@ -21,7 +21,7 @@ describe('Metadatos metodológicos opcionales', () => {
expect(text).toContain('Guía <img src=x onerror=alert(1)>'); expect(text).toContain('Guía <img src=x onerror=alert(1)>');
expect(fixture.nativeElement.querySelector('img')).toBeNull(); expect(fixture.nativeElement.querySelector('img')).toBeNull();
expect(text).toContain('Segunda línea'); 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('Título del catálogo');
expect(text).not.toContain('no está disponible'); expect(text).not.toContain('no está disponible');
http.verify(); fixture.destroy(); http.verify(); fixture.destroy();
@@ -32,11 +32,29 @@ describe('Metadatos metodológicos opcionales', () => {
descripcion: 'Información general.', 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.' }, 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'); expect(text).not.toContain('no está disponible');
http.verify(); fixture.destroy(); 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', () => { 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: '' } }); 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'); 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', () => { 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 }); 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).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(); http.verify(); fixture.destroy();
}); });
@@ -68,7 +86,7 @@ describe('Metadatos metodológicos opcionales', () => {
categorias: { NORMAL: { etiqueta: 'Normal' } }, categorias: { NORMAL: { etiqueta: 'Normal' } },
}); });
expect(text).toContain('Descripción publicada.'); 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(text).toContain('Pacientes con estudio publicado.');
expect(fixture.nativeElement.querySelector('em')).toBeNull(); expect(fixture.nativeElement.querySelector('em')).toBeNull();
expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/); expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/);
@@ -17,16 +17,20 @@ import { IndicadoresService } from './indicadores.service';
} }
@if (fichaFields.length) { @if (fichaFields.length) {
<section aria-labelledby="metadata-ficha-title"> <section aria-labelledby="metadata-ficha-title">
<h4 id="metadata-ficha-title">Ficha metodológica</h4> <h4 id="metadata-ficha-title">Ficha técnica</h4>
<dl class="ficha-fields">@for (field of fichaFields; track field.key) { <div class="table-scroll">
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div> <table class="ficha-table">
}</dl> <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> </section>
} }
@if (references.length) { @if (references.length) {
<section aria-labelledby="metadata-references-title"> <section aria-labelledby="metadata-references-title">
<h4 id="metadata-references-title">Referencias</h4> <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> </section>
} }
@if (populations.length) { @if (populations.length) {
@@ -47,7 +51,7 @@ export class IndicadorMetadata implements OnChanges {
loading = false; loading = false;
private readonly changeDetector = inject(ChangeDetectorRef); private readonly changeDetector = inject(ChangeDetectorRef);
private readonly fichaLabels = [ 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'], ['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
] as const; ] as const;
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; } hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
@@ -1,45 +1,33 @@
<section aria-label="Editor de filtros generales del proyecto"> <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">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</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> }
<div class="fields"> <div class="fields">
@if (types.length > 1 || !types.includes(state.tipo)) { <mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Granularidad</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)"> <mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> } @for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
} <mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
@if (state.tipo === 'semestre' && state.tipo === types[0]) { <mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label> <mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
<mat-option value="todos">Todos con reporte</mat-option>
<mat-option value="manual">Elegir periodos</mat-option>
</mat-select>
</mat-form-field>
}
@if (entry.draft.mode !== 'todos') {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
<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> } @for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
@if (availability) { @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-select>
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
</mat-form-field> </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> </div>
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
@if (availability) { @if (availability) {
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> } @if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
@else if (availability.status === 'error') { @else if (availability.status === 'error') {
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p> <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> <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 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 (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') { @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> <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"> <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>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
@@ -57,10 +45,5 @@
</div> </div>
} }
@if (error) { <p class="error" role="alert">{{ error }}</p> } @if (error) { <p class="error" role="alert">{{ error }}</p> }
<p class="draft-summary">Selección en edición: {{ summary }}</p> @if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
<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> </section>
@@ -1,19 +1,19 @@
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } @use '@angular/material' as mat;
// One compact row, like the Seguimiento form: the two selectors, Aplicar and the pending notice.
:host { display: block; min-width: 0; @include mat.theme((density: -4)); }
section { min-width: 0; } section { min-width: 0; }
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); } .fields { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); }
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; } mat-form-field { flex: 0 1 14rem; min-width: 0; }
.period-builder mat-form-field { flex: 0 1 10rem; } .period-builder mat-form-field { flex: 0 1 9rem; }
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; } .period-builder button { min-height: 40px; }
p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; } p { overflow-wrap: anywhere; line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; } .select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.4; }
.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } .filter-help, .applied-summary { color: var(--issste-text-secondary); }
.draft-summary { font-weight: 500; } .pending { color: var(--issste-text); font: var(--mat-sys-body-small); border-left: 3px solid var(--issste-accent); padding-left: var(--issste-space-2); }
.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); }
.error { color: var(--mat-sys-error); } .error { color: var(--mat-sys-error); }
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); } .remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
.remove button { min-height: 44px; } .apply-button { min-height: 40px; }
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
@media (max-width: 550px) { @media (max-width: 550px) {
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; } mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; }
.period-builder button { margin-top: 0; }
} }
@@ -18,18 +18,19 @@ describe('UX-04 control asistido', () => {
control = fixture.componentInstance; control = fixture.componentInstance;
}); });
afterEach(() => fixture.destroy()); afterEach(() => fixture.destroy());
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => { function periodSelect() {
await fixture.whenStable(); fixture.detectChanges(); return fixture.debugElement.queryAll(By.css('mat-form-field'))
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte'); .find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
}
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
fixture.componentRef.setInput('state', { fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: { ...control.state, editors: { ...control.state.editors, semestre: {
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
} }, } },
}); });
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>); const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2'); expect(values.map(e => e.textContent)).toContain('2025-S2');
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
fixture.componentRef.setInput('state', { fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: { ...control.state, editors: { ...control.state.editors, semestre: {
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' }, added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
@@ -43,10 +44,11 @@ describe('UX-04 control asistido', () => {
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => { it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever. // Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
fixture.changeDetectorRef.detach(); fixture.changeDetectorRef.detach();
control.changeMode('manual'); control.select([]);
fixture.detectChanges(); fixture.detectChanges();
await Promise.resolve(); await Promise.resolve();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; const select = periodSelect();
expect(select.componentInstance.multiple).toBe(false);
const model = select.injector.get(NgModel); const model = select.injector.get(NgModel);
const writes = vi.spyOn(model.control, 'setValue'); const writes = vi.spyOn(model.control, 'setValue');
const edits = vi.spyOn(control.edited, 'emit'); const edits = vi.spyOn(control.edited, 'emit');
@@ -54,16 +56,16 @@ describe('UX-04 control asistido', () => {
fixture.detectChanges(); fixture.detectChanges();
await Promise.resolve(); await Promise.resolve();
} }
expect(model.control.value).toEqual([]); expect(model.control.value).toBeNull();
expect(writes).not.toHaveBeenCalled(); expect(writes).not.toHaveBeenCalled();
expect(edits).not.toHaveBeenCalled(); expect(edits).not.toHaveBeenCalled();
expect(control.state.applied?.selection.mode).toBe('todos'); expect(control.state.applied?.selection.mode).toBe('todos');
}); });
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => { it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
control.changeTipo('mes'); control.changeTipo('mes');
control.year = '2025'; control.unit = '01'; control.add(); control.select([]); control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); await fixture.whenStable();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; const select = periodSelect();
const model = select.injector.get(NgModel); const model = select.injector.get(NgModel);
const writes = vi.spyOn(model.control, 'setValue'); const writes = vi.spyOn(model.control, 'setValue');
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
@@ -78,7 +80,7 @@ describe('UX-04 control asistido', () => {
expect(control.canApply).toBe(false); expect(control.canApply).toBe(false);
}); });
it('normaliza el año y rechaza agregar duplicados', () => { it('normaliza el año y rechaza agregar duplicados', () => {
control.changeMode('manual'); control.select([]);
control.year = '1'; control.unit = 'S1'; control.add(); control.year = '1'; control.unit = 'S1'; control.add();
expect(control.selectedPeriods).toEqual(['0001-S1']); expect(control.selectedPeriods).toEqual(['0001-S1']);
control.add(); control.add();
@@ -86,7 +88,7 @@ describe('UX-04 control asistido', () => {
expect(control.entry.added).toEqual(['0001-S1']); expect(control.entry.added).toEqual(['0001-S1']);
}); });
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => { it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
control.changeMode('manual'); control.year = year; control.unit = unit; control.add(); control.select([]); control.year = year; control.unit = unit; control.add();
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false); expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
}); });
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => { it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
@@ -94,21 +96,22 @@ describe('UX-04 control asistido', () => {
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false); expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
}); });
it('conserva borradores independientes sin convertir periodos', () => { it('conserva borradores independientes sin convertir periodos', () => {
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add(); control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']); control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']); control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } }); expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
}); });
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => { it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
control.unit = 'S2'; control.add(); control.unit = 'S2'; control.add();
control.select(['2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']); expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']); control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
fixture.detectChanges(); fixture.detectChanges();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; const select = periodSelect();
expect(select).toBeTruthy(); expect(select.componentInstance.multiple).toBe(false);
expect(select.nativeElement.querySelector('button')).toBeNull(); expect(select.nativeElement.querySelector('button')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2'); expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
fixture.nativeElement.querySelector('.remove button').click(); fixture.nativeElement.querySelector('.remove button').click();
@@ -119,7 +122,7 @@ describe('UX-04 control asistido', () => {
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => { it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
const edited = vi.spyOn(control.edited, 'emit'); const edited = vi.spyOn(control.edited, 'emit');
const apply = vi.spyOn(control.apply, 'emit'); const apply = vi.spyOn(control.apply, 'emit');
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled(); expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar'); expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
@@ -128,11 +131,25 @@ describe('UX-04 control asistido', () => {
fixture.nativeElement.querySelector('button[mat-flat-button]').click(); fixture.nativeElement.querySelector('button[mat-flat-button]').click();
expect(apply).toHaveBeenCalledTimes(1); expect(apply).toHaveBeenCalledTimes(1);
}); });
it('no ofrece Todos en meses cuando el primero es semestre', () => { it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
control.changeTipo('mes'); fixture.detectChanges(); const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses'); expect(labels).toContain('Intervalo de análisis');
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty'); expect(labels).not.toContain('Modalidad');
control.changeTipo('semestre'); control.changeTipo('mes'); const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
expect(control.entry.draft.mode).toBe('empty'); .find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
expect(options).toEqual(['Semestral', 'Mensual']);
select.componentInstance.close();
});
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
fixture.detectChanges();
control.changeTipo('mes');
expect(control.selectedPeriods).toEqual(['2025-12']);
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
// A period already chosen for that interval is kept.
expect(control.selectedPeriods).toEqual(['2025-11']);
}); });
}); });
@@ -29,7 +29,7 @@ export class IndicadorPeriodFilters implements OnChanges {
ngOnChanges() { this.year = this.unit = this.error = ''; } ngOnChanges() { this.year = this.unit = this.error = ''; }
get entry() { return this.state.editors[this.state.tipo]!; } get entry() { return this.state.editors[this.state.tipo]!; }
// NgModel schedules a microtask and markForCheck when its input reference changes. // NgModel schedules a microtask and markForCheck when its input reference changes.
// Keep the empty multiple-select value stable so an unchanged draft can settle. // Keep the empty selection stable so an unchanged draft can settle.
private readonly emptyPeriods: string[] = []; private readonly emptyPeriods: string[] = [];
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; } get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; } get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
@@ -42,21 +42,21 @@ export class IndicadorPeriodFilters implements OnChanges {
get hasPending() { return pending(this.state); } get hasPending() { return pending(this.state); }
get summary() { return describePeriods(this.state.tipo, this.entry.draft); } get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; } get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
// There is no "every period" choice in the editor: a new interval starts on its most recent
// period with a report (options are sorted newest first).
changeTipo(tipo: TipoPeriodo) { changeTipo(tipo: TipoPeriodo) {
if (!this.types.includes(tipo)) return; if (!this.types.includes(tipo)) return;
this.state.tipo = tipo; this.state.tipo = tipo;
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]); this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
this.year = this.unit = this.error = ''; this.year = this.unit = this.error = '';
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
this.edited.emit(); this.edited.emit();
} }
changeMode(mode: 'todos' | 'manual') { // Only one period can be chosen: cards and figures never combine periods.
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
this.error = '';
this.edited.emit();
}
select(values: string[]) { select(values: string[]) {
const unique = [...new Set(values)]; const unique = [...new Set(values)];
if (unique.length > 1) return;
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return; 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.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
this.edited.emit(); this.edited.emit();
@@ -70,13 +70,11 @@ export class IndicadorPeriodFilters implements OnChanges {
return; return;
} }
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; } if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
const selected = this.selectedPeriods;
this.entry.added.push(period); this.entry.added.push(period);
this.select([...selected, period]); this.select([period]);
} }
remove(period: string) { remove(period: string) {
this.entry.added = this.entry.added.filter(p => p !== period); this.entry.added = this.entry.added.filter(p => p !== period);
// Removing an unselected option must not change the Todos mode.
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period)); if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
else this.edited.emit(); else 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,109 @@
import { c1DonutCapability, c1DonutFigure, c1DonutLabels } from './indicadores-c1-donut';
import { FigureSelection, IndicadorDatos } from './indicadores.models';
const fila = (estrato: string, numerador: number, denominador: number, extra: object = {}) => ({
periodo: '2025-S2', grupo: 'TOTAL', estrato, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
});
const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]): IndicadorDatos => ({
id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unidad: 'paciente',
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'grupo_edad', valores_estrato: ['16-23', '24-29', '30-36'],
etiquetas_estrato: { '16-23': '16 a 23 meses', '24-29': '24 a 29 meses', '30-36': '30 a 36 meses' },
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
});
const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
describe('Dona de dos anillos para C1', () => {
it('solo aplica a C1 con las figuras por grupo de edad', () => {
expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true);
expect(c1DonutCapability('C1', 'fig_c1_dona_edad')).toBe(true);
expect(c1DonutCapability('C1', 'fig_c1_barras_edad')).toBe(true);
expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false);
expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false);
});
it('anillo interior con y sin el evento; exterior por grupo de edad, con el total al centro', () => {
const result = c1DonutFigure(datos(), selection);
expect(result.status).toBe('supported');
if (result.status !== 'supported') return;
const [center, inner, outer] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
expect(center.text[0]).toContain('<b>64</b>');
expect(inner.labels).toEqual(['Con EEG', 'Sin EEG']);
expect(inner.values).toEqual([46, 18]);
expect(inner.text).toEqual(['Con EEG<br>71.9 %', 'Sin EEG<br>28.1 %']);
expect(outer.labels).toEqual(['Con EEG · 16 a 23 meses', 'Con EEG · 24 a 29 meses', 'Con EEG · 30 a 36 meses',
'Sin EEG · 16 a 23 meses', 'Sin EEG · 24 a 29 meses', 'Sin EEG · 30 a 36 meses']);
expect(outer.values).toEqual([16, 13, 17, 8, 5, 5]);
// Inside the outer ring only the age group; slices under 5 % stay unlabeled.
expect(outer.text[0]).toMatch(/^16 a 23 meses<br>/);
expect(outer.text[4]).toMatch(/^24 a 29 meses<br>7.8/);
const small = c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 14), fila('30-36', 17, 40)]), selection);
if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe('');
expect(result.total).toBe(64);
expect(result.notes).toEqual(['Datos ficticios.']);
expect(result.highlight.groups.map(g => g.label)).toEqual(['Con EEG', 'Sin EEG']);
expect(result.highlight.items.map(i => i.short)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(result.highlight.groups[1].center).toBe('<b>18</b><br>Sin EEG');
expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' });
});
it('dona por grupo de edad: solo los pacientes con el evento, con el porcentaje total al centro', () => {
const result = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.figure.data).toHaveLength(1);
// Only the patients with EEG, by age group; each slice is its share of those 46 patients.
const [ring] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
expect(ring.labels).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(ring.values).toEqual([16, 13, 17]);
expect(ring.text[0]).toMatch(/^16 a 23 meses<br>34.8/);
expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>71.9 %</b>');
expect(result.highlight.groups).toEqual([]);
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
});
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
if (dona.status !== 'supported') throw new Error('sin figura');
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
expect(dona.highlight.items.map(i => i.color)).toEqual(colores);
const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
if (barras.status !== 'supported') throw new Error('sin figura');
expect((barras.figure.data[0] as { marker: { color: string[] } }).marker.color).toEqual(colores);
expect(barras.highlight.items.map(i => i.color)).toEqual(colores);
});
it('barras apiladas por grupo de edad: confirmados y en proceso, con un botón por estado', () => {
const result = c1DonutFigure({ ...datos(), id: 'M24_confirmacion_diagnostico' }, { ...selection, indicador: 'M24_confirmacion_diagnostico', figura: 'fig_c1_barras_apiladas_edad' });
if (result.status !== 'supported') throw new Error('sin figura');
expect(result.figure.layout['barmode']).toBe('stack');
expect(result.figure.data.map(t => [t['name'], t['y']])).toEqual([['Diagnóstico confirmado', [16, 13, 17]], ['En proceso', [8, 5, 5]]]);
expect(result.figure.data[1]['text']).toEqual(['8 (33.3 %)', '5 (27.8 %)', '5 (22.7 %)']);
expect(result.highlight.items.map(i => i.label)).toEqual(['Diagnóstico confirmado', 'En proceso']);
});
it('barras por grupo de edad: una barra por grupo con su porcentaje', () => {
const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' },
{ ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
if (result.status !== 'supported') throw new Error(result.reason);
const [bars] = result.figure.data as { type: string; x: string[]; y: number[]; text: string[] }[];
expect(bars.type).toBe('bar');
expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']);
expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG');
expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]);
});
it('usa etiquetas propias por indicador y neutrales para otros', () => {
expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Diagnóstico confirmado', 'En proceso']);
expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']);
expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']);
});
it('solo un semestre', () => {
expect(c1DonutFigure({ ...datos(), tipo_periodo: 'mes', periodos: ['2025-12'] }, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-12'] }))
.toEqual({ status: 'unsupported', reason: 'Esta figura solo está disponible para un semestre.' });
expect(c1DonutFigure({ ...datos(), periodos: ['2025-S1', '2025-S2'] }, { ...selection, periodos: ['2025-S1', '2025-S2'] }).status).toBe('unsupported');
expect(c1DonutFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
});
it('rechaza estratos incompletos, suprimidos o imposibles', () => {
expect(c1DonutFigure({ ...datos(), estrato: null }, selection).status).toBe('unsupported');
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18)]), selection).status).toBe('unsupported');
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', null as unknown as number, 22, { suprimido: 1 })]), selection).status).toBe('unsupported');
expect(c1DonutFigure(datos([fila('16-23', 30, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]), selection).status).toBe('unsupported');
});
});
@@ -0,0 +1,161 @@
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
import { percentNumber, shareText } from './indicadores-format';
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
// Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows:
// - fig_c1_donas: double donut drawn like CaCu's «Distribución de resultados citológicos»; the inner ring
// splits the denominator into patients with and without the event, the outer ring each of them by age group.
// - fig_c1_dona_edad: only the patients with the event, by age group, with the overall percentage in the centre.
// - fig_c1_barras_edad: one bar per age group with its percentage.
export const C1_DONUT = 'fig_c1_donas';
export const C1_RING = 'fig_c1_dona_edad';
export const C1_AGE_BARS = 'fig_c1_barras_edad';
export const C1_AGE_STACK = 'fig_c1_barras_apiladas_edad';
const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS, C1_AGE_STACK];
export const C1_DONUT_ESTRATO = 'grupo_edad';
// Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording.
const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
M21_diagnosticados_con_eeg: ['Con EEG', 'Sin EEG'],
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
};
// Green for the event, red for its complement; age groups get lighter shades.
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
// One colour per age group, the same in the donut (M21) and the bars (M22).
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
export type C1DonutResult = { status: 'unsupported'; reason: string }
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
export function c1DonutCapability(contract: string, representation: string): boolean {
return contract === 'C1' && C1_AGE_FIGURES.includes(representation);
}
export function c1DonutLabels(indicador: string): readonly [string, string] {
return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento'];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function shade(hex: string, step: number, steps: number): string {
const t = steps > 1 ? 0.65 * step / (steps - 1) : 0;
const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)).map(c => Math.round(c + (255 - c) * t));
return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase();
}
export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): C1DonutResult {
const unsupported = (reason: string): C1DonutResult => ({ status: 'unsupported', reason });
if (!c1DonutCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
if (selection.tipoPeriodo !== 'semestre' || data.tipo_periodo !== 'semestre') return unsupported('Esta figura solo está disponible para un semestre.');
if (data.periodos.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0])))
return unsupported('Se requiere un semestre único concordante');
const values = data['valores_estrato'], names = data['etiquetas_estrato'];
if (data['estrato'] !== C1_DONUT_ESTRATO || !Array.isArray(values) || !values.length || !values.every(v => typeof v === 'string')
|| new Set(values).size !== values.length || (names != null && !record(names))) return unsupported('Estratificación por grupo de edad no verificable');
const period = data.periodos[0];
const rows = values.map(v => data.filas.filter(r => r['periodo'] === period && r['estrato'] === v));
if (rows.some(r => r.length !== 1) || data.filas.length !== values.length) return unsupported('Partición por grupo de edad incompleta');
const strata = rows.map(([r], i) => ({ id: values[i] as string, label: typeof names?.[values[i]] === 'string' ? names[values[i]] as string : values[i] as string,
numerador: r['numerador'], denominador: r['denominador'], suprimido: r['suprimido'], grupo: r['grupo'] }));
if (strata.some(s => s.grupo !== 'TOTAL' || (s.suprimido !== 0 && s.suprimido !== false)
|| !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables');
const labels = c1DonutLabels(data.id);
const notes = Array.isArray(data.notas) ? [...data.notas] : [];
const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period };
const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0);
if (selection.figura === C1_AGE_STACK) {
const figure = ageStack(strata, labels, selection);
figure.layout = { ...figure.layout, title };
const highlight: FigureHighlight = { groups: [], traces: [0, 1], allLabel: 'Todos los pacientes',
items: labels.map((label, g) => ({ id: g ? 'SIN' : 'CON', label, color: RING_COLORS[g], points: strata.map((_, i) => ({ trace: g, index: i })) })) };
return { status: 'supported', figure, highlight, total, notes };
}
if (selection.figura === C1_AGE_BARS) {
const figure = ageBars(strata, labels[0], selection);
figure.layout = { ...figure.layout, title };
const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad',
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }] })) };
return { status: 'supported', figure, highlight, total, notes };
}
const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] }));
const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {};
grupos.forEach((g, gi) => strata.forEach((s, i) => {
const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number;
// Unique labels: Plotly merges pie slices that share one.
categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id });
celdas[id] = { n, estado: 'Publicado' };
}));
const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' },
escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' };
const figure = dona(modelo, {}, selection.tema);
if (figure.data.length === 3) {
const [, inner, outer] = figure.data as Record<string, unknown>[];
const hover = '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de ' + total + '<extra></extra>';
inner['hovertemplate'] = outer['hovertemplate'] = hover;
// Inside the outer ring the colour already tells the group: show only the age group and its share.
const outerValues = outer['values'] as number[];
outer['text'] = categorias.map((c, i) => outerValues[i] / total < .05 ? ''
: escape(strata[i % strata.length].label) + '<br>' + shareText(outerValues[i], total));
inner['text'] = grupos.map((g, i) => {
const n = (inner['values'] as number[])[i];
return n / total < .05 ? '' : escape(g.etiqueta) + '<br>' + percentNumber(100 * n / total) + ' %';
});
if (selection.figura === C1_RING) {
// Only the patients with the event, by age group, around the overall percentage of the event.
// Each slice is its age group's share of those patients.
const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0);
const values = strata.map(s => s.numerador as number);
figure.data = [{ ...outer, hole: .6, values, labels: strata.map(s => escape(s.label)),
marker: { ...(outer['marker'] as object), colors: strata.map((_, i) => ageColor(i)) },
text: values.map((n, i) => !numerador || n / numerador < .05 ? '' : escape(strata[i].label) + '<br>' + shareText(n, numerador)),
customdata: values.map(n => [n, numerador ? percentNumber(100 * n / numerador) : '0']),
hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '<extra></extra>' }];
figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
text: '<b>' + percentNumber(100 * numerador / total) + ' %</b>', font: { size: 26, color: c2Theme(selection.tema).text } }] };
const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0],
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }],
center: '<b>' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %</b><br>' + escape(s.label) })) };
return { status: 'supported', figure, highlight, total, notes };
}
}
figure.layout = { ...figure.layout, title };
// Next to its group's button, a category only needs its age group.
const highlight = donaHighlight(modelo, id => strata.find(s => id.endsWith(':' + s.id))?.label);
return { status: 'supported', figure, highlight, total, notes };
}
// "Con EEG" -> "con EEG", to follow «pacientes».
const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1);
// One stacked bar per age group: how many of its patients have the event and how many don't.
function ageStack(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], labels: readonly [string, string], selection: FigureSelection): PlotlyFigure {
const theme = c2Theme(selection.tema);
const x = strata.map(s => escape(s.label));
const conEvento = strata.map(s => s.numerador as number), sinEvento = strata.map(s => (s.denominador as number) - (s.numerador as number));
return { data: [conEvento, sinEvento].map((y, g) => ({ type: 'bar', name: escape(labels[g]), x, y, marker: { color: RING_COLORS[g], line: { color: theme.background, width: 1 } },
text: y.map((n, i) => (strata[i].denominador as number) ? n + ' (' + percentNumber(100 * n / (strata[i].denominador as number)) + ' %)' : ''),
textposition: 'inside', insidetextanchor: 'middle', hovertemplate: '%{x}<br>%{fullData.name}: %{y} pacientes<extra></extra>' })),
layout: { autosize: true, height: 400, barmode: 'stack', margin: { t: 24, l: 72, r: 24, b: 80 }, showlegend: true,
legend: { orientation: 'h', y: -0.28, itemclick: false, itemdoubleclick: false },
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero', gridcolor: theme.grid, zeroline: false } },
config: { displayModeBar: false } };
}
// One bar per age group: the share of its patients with the event.
function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure {
const theme = c2Theme(selection.tema);
const x = strata.map(s => escape(s.label));
const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null);
return { data: [{ type: 'bar', x, y, marker: { color: strata.map((_, i) => ageColor(i)), line: { color: theme.background, width: 1 } },
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
customdata: strata.map(s => [s.numerador, s.denominador]),
hovertemplate: '%{x}<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)<extra></extra>' }],
layout: { autosize: true, height: 400, margin: { t: 24, l: 72, r: 24, b: 64 }, showlegend: false,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
yaxis: { title: { text: '% de pacientes ' + escape(what(event)) }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
config: { displayModeBar: false } };
}
@@ -4,7 +4,6 @@ import { c2Fixture } from './indicadores-c2-adapter.testing';
import { FigureSelection } from './indicadores.models'; import { FigureSelection } from './indicadores.models';
import { donutFixture } from './indicadores-donut-drilldown.testing'; import { donutFixture } from './indicadores-donut-drilldown.testing';
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown'; import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
import { numericRows } from './indicadores-numeric-rows';
import { figurePresentation } from './indicadores.presentation'; import { figurePresentation } from './indicadores.presentation';
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
@@ -26,7 +25,7 @@ describe('C2: datos publicados a Plotly', () => {
const donut = supported(data), bars = supported(data, { ...selection, figura: 'fig_c2_barras' }); const donut = supported(data), bars = supported(data, { ...selection, figura: 'fig_c2_barras' });
expect(donut.figure.data).toHaveLength(1); expect(donut.hierarchy).toBeUndefined(); expect(donut.figure.data).toHaveLength(1); expect(donut.hierarchy).toBeUndefined();
expect(bars.figure.data[0]['x']).toEqual(donut.figure.data[0]['values']); expect(bars.figure.data[0]['y']).toEqual(donut.figure.data[0]['labels']); expect(bars.figure.data[0]['x']).toEqual(donut.figure.data[0]['values']); expect(bars.figure.data[0]['y']).toEqual(donut.figure.data[0]['labels']);
expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo · paciente' } }); expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo (paciente)' } });
}); });
it('el layout final de barras muestra ambos ejes y el hover no repite el periodo', () => { it('el layout final de barras muestra ambos ejes y el hover no repite el periodo', () => {
const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' }); const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' });
@@ -44,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final); const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
const legend = donutLegend(final), view = donutSimpleView(final); const legend = donutLegend(final), view = donutSimpleView(final);
expect(legend).toEqual([ expect(legend).toEqual([
{ label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' }, { label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
]); ]);
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } }); expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
@@ -109,7 +108,6 @@ describe('C2: datos publicados a Plotly', () => {
const data = c2Fixture(); data.filas.forEach(r => r['denominador'] = 10); data['denominador'] = 10; const data = c2Fixture(); data.filas.forEach(r => r['denominador'] = 10); data['denominador'] = 10;
const result = supported(data); expect(result.figure.layout['meta']).toMatchObject({ denominator: 10 }); const result = supported(data); expect(result.figure.layout['meta']).toMatchObject({ denominator: 10 });
expect(result.figure.data[0]['hovertemplate']).toContain('10 paciente publicados'); expect(result.figure.data[0]['hovertemplate']).toContain('10 paciente publicados');
expect(numericRows(data).map(r => r.value)).toEqual(result.model.categories.map(c => String(c.value)));
}); });
it('explorar, cambiar padre y restaurar parte del original y no modifica las barras', () => { it('explorar, cambiar padre y restaurar parte del original y no modifica las barras', () => {
const data = c2Fixture(), result = supported(data), original = structuredClone(result.figure); const data = c2Fixture(), result = supported(data), original = structuredClone(result.figure);
@@ -163,12 +161,12 @@ describe('paleta C2 institucional y semántica', () => {
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => { it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A'; const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
const figure = supported(data, { ...selection, tema }).figure; const figure = supported(data, { ...selection, tema }).figure;
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']); expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background); expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text }); expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2'); expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
expect(c2Color(undefined, 0)).toBe('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A'); expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E'); expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined(); expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
}); });
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => { it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
@@ -83,7 +83,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label); const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
const colors = categories.map((c, i) => c2Color(c.color, i)); const colors = categories.map((c, i) => c2Color(c.color, i));
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined; const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
const layout: Record<string, unknown> = { title: { text: model.title + ' · ' + period }, autosize: true, const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 }, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
margin: { l: 76, r: 28, t: 112, b: 62, pad: 4 }, margin: { l: 76, r: 28, t: 112, b: 62, pad: 4 },
legend: selection.figura === 'fig_c2_donas' legend: selection.figura === 'fig_c2_donas'
@@ -95,7 +95,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels, if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
marker: { color: colors, line: { color: theme.outline, width: 0.7 } }, marker: { color: colors, line: { color: theme.outline, width: 0.7 } },
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }]; hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
layout['xaxis'] = { title: { text: 'Conteo · ' + model.unit }, rangemode: 'tozero', showgrid: true, layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1, gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
ticks: 'outside', tickcolor: '#AEB7C2', automargin: true }; ticks: 'outside', tickcolor: '#AEB7C2', automargin: true };
layout['yaxis'] = { type: 'category', categoryorder: 'array', categoryarray: [...labels].reverse(), automargin: true, layout['yaxis'] = { type: 'category', categoryorder: 'array', categoryarray: [...labels].reverse(), automargin: true,
@@ -37,7 +37,7 @@ describe('barras generales conectadas con la selección compartida de la dona',
select({ parent: 'G2', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B', 'C']); select({ parent: 'G2', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B', 'C']);
select({ parent: 'G2', category: 'B', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B']); select({ parent: 'G2', category: 'B', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B']);
expect(panel().result().figure).toBe(original); expect(original).toEqual(before); expect(panel().result().figure).toBe(original); expect(original).toEqual(before);
expect(fixture.nativeElement.querySelector('.selection-status').getAttribute('aria-label')).toContain('G2 · B · 2025-S2'); expect(fixture.nativeElement.querySelector('.selection-status').getAttribute('aria-label')).toContain('G2, B, 2025-S2');
select({}); expect(displayed()).toEqual(all); expect(panel().generalSelectionContext).toBeUndefined(); select({}); expect(displayed()).toEqual(all); expect(panel().generalSelectionContext).toBeUndefined();
expect(panel().applied).toEqual(filter); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true); expect(panel().applied).toEqual(filter); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true);
}); });
@@ -19,10 +19,10 @@ describe('selección local segura de barras generales C2', () => {
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => { it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source }); const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, selection, local)!; const view = c2GeneralSelection(source, data, selection, local)!;
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } }); expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] }); expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' }); expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
expect(view.context).toContain('G2 · 2025-S2'); expect(view.context).toContain('G2, 2025-S2');
expect({ data, source }).toEqual(before); expect({ data, source }).toEqual(before);
(view.figure.data[0]['x'] as number[])[0] = 999; (view.figure.data[0]['x'] as number[])[0] = 999;
expect(source).toEqual(before.source); expect(source).toEqual(before.source);
@@ -117,7 +117,7 @@ describe('selección local segura de barras generales C2', () => {
expect(source).toEqual(before); expect(source).toEqual(before);
}); });
it.each([ it.each([
{ id: 'cacu_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' }, { id: 'c2_grados_biopsia_sintetico', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] }, categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
{ id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' }, { id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' },
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] }, categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
@@ -70,6 +70,6 @@ export function c2GeneralSelection(source: PlotlyFigure, data: IndicadorDatos,
if (record(figure.layout['yaxis']) && Array.isArray(figure.layout['yaxis']['categoryarray'])) { if (record(figure.layout['yaxis']) && Array.isArray(figure.layout['yaxis']['categoryarray'])) {
figure.layout['yaxis']['categoryarray'] = figure.layout['yaxis']['categoryarray'].filter(v => selected.some(c => c.label === v)); figure.layout['yaxis']['categoryarray'] = figure.layout['yaxis']['categoryarray'].filter(v => selected.some(c => c.label === v));
} }
return { figure, context: 'Vista local de la dona: ' + [local.parent, local.category, period].filter(Boolean).join(' · ') return { figure, context: 'Vista local de la dona: ' + [local.parent, local.category, period].filter(Boolean).join(', ')
+ '. Sólo se muestran las categorías seleccionadas de este periodo. Los conteos y porcentajes conservan el denominador de la distribución completa del periodo.' }; + '. Sólo se muestran las categorías seleccionadas de este periodo. Los conteos y porcentajes conservan el denominador de la distribución completa del periodo.' };
} }
@@ -3,10 +3,14 @@ import { Tema } from './indicadores.models';
// Matches src/styles.scss: interface tokens are the source of these candidates, // Matches src/styles.scss: interface tokens are the source of these candidates,
// not a certified brand guide. Published semantic colours always take priority. // not a certified brand guide. Published semantic colours always take priority.
export const C2_PALETTE = Object.freeze({ export const C2_PALETTE = Object.freeze({
series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']), // ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }), states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1' }), // line: the green for thin marks; the brand green itself is too light to read as a line on white.
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F' }), claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }),
}); });
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; } export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
export function c2Color(published: string | undefined, index: number): string { export function c2Color(published: string | undefined, index: number): string {
@@ -59,7 +59,18 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'}); http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'});
expect(fixture.componentInstance.result().status).toBe('error'); expect(fixture.componentInstance.result().status).toBe('error');
}); });
it('TEA: dona de un periodo con ambos anillos y botones para resaltar grupos y categorías', () => {
fixture.detectChanges(); dataRequest().flush(c2Fixture());
const result = fixture.componentInstance.result();
expect(result.status).toBe('ready');
expect(result.hierarchy).toBeUndefined();
expect(result.figure?.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
expect(result.highlight?.groups.length).toBeGreaterThan(0);
expect(result.highlight?.items.every(i => i.group)).toBe(true);
});
it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => { it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => {
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
fixture.componentRef.setInput('dominio', 'cama');
fixture.detectChanges(); const old = dataRequest(); fixture.detectChanges(); const old = dataRequest();
fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges(); fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges();
expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1'); expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1');
@@ -11,7 +11,6 @@ import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadoresMemory } from './indicadores-memory'; import { IndicadoresMemory } from './indicadores-memory';
import { IndicadoresSnapshots } from './indicadores-snapshots'; import { IndicadoresSnapshots } from './indicadores-snapshots';
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
import { Indicador, PlotlyFigure } from './indicadores.models'; import { Indicador, PlotlyFigure } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { figureApplied } from './indicadores-figure-selection'; import { figureApplied } from './indicadores-figure-selection';
@@ -23,7 +22,7 @@ const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'):
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1', figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
}); });
const catalog = [ const catalog = [
item('cacu_eu13', 'Tasa de confirmación histopatológica'), item('cacu_eu13', 'Tasa de detección histopatológica'),
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'), item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'),
item('ind1', 'Pacientes con citología anómala'), item('ind1', 'Pacientes con citología anómala'),
item('ordinary', 'Otra gráfica'), item('ordinary', 'Otra gráfica'),
@@ -79,33 +78,35 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } }; page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } };
page.applyFilters(); fixture.detectChanges(); page.applyFilters(); fixture.detectChanges();
} }
it('encabezados, tres tarjetas en orden y placeholder inerte sin periodo, unidad ni HTTP', () => { it('encabezados, cinco tarjetas en orden y placeholders inertes sin periodo, unidad ni HTTP', () => {
const root: HTMLElement = fixture.nativeElement; const root: HTMLElement = fixture.nativeElement;
expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad'); expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card')); const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([ expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
'Pacientes evaluadas', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de diagnóstico a tratamiento', 'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
]); ]);
expect(kpis[2].querySelectorAll('p')).toHaveLength(1); for (const kpi of kpis.slice(3)) {
expect(kpis[2].querySelector('p')?.textContent).toBe('Indicador no disponible'); expect(kpi.querySelectorAll('p')).toHaveLength(1);
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 3'); expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(2); }
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('confirmación histopatológica'); expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('detección histopatológica');
expect(card('cacu_eu13')).toBeDefined(); expect(card('cacu_eu13')).toBeDefined();
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => { it('EU7 primero sin alterar catálogo; selección y fijación prevalecen y conservan identidades y memoria', () => {
const original = page.catalog(), before = cards(); const original = page.catalog(), before = cards();
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id)); expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
expect(before[0].indicador.id).toBe('cacu_eu7'); expect(before[0].indicador.id).toBe('cacu_eu7');
page.togglePinned(original[0]); fixture.detectChanges(); page.togglePinned(original[0]); fixture.detectChanges();
expect(cards()[0]).toBe(card('cacu_eu13')); expect(cards()[0]).toBe(card('cacu_eu13'));
page.changeSearchQuery('anómala'); fixture.detectChanges(); page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('ind1'); expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
page.changeSearchQuery(''); fixture.detectChanges(); for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
page.showAllIndicators(); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('cacu_eu13'); expect(cards()[0].indicador.id).toBe('cacu_eu13');
for (const c of before) expect(card(c.indicador.id)).toBe(c);
expect(page.catalog()).toBe(original); expect(page.catalog()).toBe(original);
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true); expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
http.expectNone(() => true); http.expectNone(() => true);
@@ -167,13 +168,6 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
apply('mes', ['2026-01']); apply('mes', ['2026-01']);
http.expectNone(r => /\/(cacu_eu13|ind1)\/datos/.test(r.url)); http.expectNone(r => /\/(cacu_eu13|ind1)\/datos/.test(r.url));
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] })); http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
const summary = fixture.debugElement.query(By.directive(IndicadoresNumericSummary)).componentInstance as IndicadoresNumericSummary;
for (const id of ['cacu_eu13', 'ind1']) {
const selected = page.catalog().find(i => i.id === id)!;
const reading = summary.snapshots.reading('cacu', selected, summary.figureSelection(selected))!;
expect(summary.rows(reading.data!).map(row => row.period)).toEqual(periods);
expect(reading.data!.filas.map(row => row['denominador'])).toEqual([4, 10]);
}
}); });
it('reintento individual tras error usa Todos; una nueva versión de catálogo puede revalidar sin tocar otra selección', () => { it('reintento individual tras error usa Todos; una nueva versión de catálogo puede revalidar sin tocar otra selección', () => {
open('cacu_eu13', 'ind1'); open('cacu_eu13', 'ind1');
@@ -0,0 +1,287 @@
import { Component, input, 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 { By } from '@angular/platform-browser';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { GlobalApplied } from './indicadores-memory';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, CONFIRMACION_CAMA, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
periodosConfirmacion, rangoTasas, seleccionBase, seleccionEtiqueta, tasas, vistaConfirmacion, wilson } from './indicadores-confirmacion-citologia';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
// valores_estrato as texts. Counts per cytology: NORMAL, LIEBG, LIEAG, CIS, CARCINOMA,
// SIN_BIOPSIA (no biopsy yet), SIN_DATO (biopsy without grade), CIN2.
const CATEGORIAS = [...GRADOS, 'SIN_BIOPSIA', 'SIN_DATO', 'CIN2'];
const CONTEOS: Record<string, number[]> = {
'ASC-H': [16, 11, 9, 1, 1, 20, 2, 0], LIEAG: [6, 10, 31, 8, 2, 22, 2, 1], CIS: [0, 1, 4, 4, 3, 11, 2, 0],
};
function respuesta(periodos = ['2026-S2'], conteos = CONTEOS): IndicadorDatos {
const filas = periodos.flatMap(periodo => Object.entries(conteos).flatMap(([estrato, ns]) =>
CATEGORIAS.map((categoria, orden) => ({ periodo, grupo: 'TOTAL', estrato, categoria, n: ns[orden], orden, suprimido: 0 }))));
const color = ['#9DBFE3', '#E8C28E', '#D98E4A', '#B55A1F', '#7A2E0E'];
const estratos = Object.keys(conteos);
return {
id: 'cacu_confirmacion_citologia', contrato: 'C2', tipo_periodo: 'semestre', periodos, filas, version: '1',
estrato: 'citologia_alto_grado', valores_estrato: estratos,
etiquetas_estrato: Object.fromEntries(estratos.map(e => [e, e === 'CIS' ? 'Carcinoma in situ' : e])),
totales_estrato: periodos.flatMap(periodo => estratos.map(estrato => ({ periodo, grupo: 'TOTAL', estrato,
n: conteos[estrato].reduce((a, b) => a + b, 0), suprimido: 0 }))),
categorias: {
...Object.fromEntries(GRADOS.map((id, i) => [id, { etiqueta: id === 'CIS' ? 'Carcinoma in situ' : id, color: color[i],
grupo: i < 2 ? 'NO_ANORMAL' : 'ANORMAL', gravedad: i + 1 }])),
SIN_BIOPSIA: { etiqueta: 'Sin biopsia aún', color: '#C9CDD2', grupo: null, gravedad: null },
SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: 'SIN_DATO', gravedad: null },
CIN2: { etiqueta: 'CIN2', color: null, grupo: 'NO_ANORMAL', gravedad: null },
},
grupos_de_categoria: { NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Sin dato' },
};
}
describe('Confirmación histopatológica: modelo', () => {
it('denominador: mujeres con biopsia y grado; SIN_BIOPSIA y SIN_DATO van aparte; CIN2 cuenta en su grupo', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2');
expect(m.filas.map(f => f.id)).toEqual(['CIS', 'LIEAG', 'ASC-H']);
expect(m.filas.map(f => f.etiqueta)).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
expect(m.filas.map(f => f.den)).toEqual([12, 58, 38]);
expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]);
expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n])).toEqual([[11, 2], [22, 2], [20, 2]]);
expect(m.grados.map(g => g.id)).toEqual([...GRADOS, 'CIN2']);
expect(m.grados.find(g => g.id === 'CIN2')).toMatchObject({ grupo: 'NO_ANORMAL', color: '#8A9199' });
expect(m.grupos.find(g => g.id === 'NO_ANORMAL')!.grados).toEqual(['NORMAL', 'LIEBG', 'CIN2']);
expect(m.conBiopsia).toBe(108); expect(m.base).toBe('ANORMAL');
});
it('estratos ausentes de valores_estrato dicen «Sin mujeres con biopsia»; total suprimido suprime la fila', () => {
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
const m = modeloConfirmacion(d, '2026-S2');
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
expect(tasas(m, seleccionBase(m)).map(t => estadoTasa(t))).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
const s = modeloConfirmacion(d, '2026-S2');
expect([s.filas[1].den, s.filas[1].estado]).toEqual([null, 'Suprimido']);
expect(s.conBiopsia).toBeNull();
expect((figuraTasas(s, seleccionBase(s), 'claro').layout['annotations'] as { text: string }[])[1].text).toBe('Suprimido');
});
it('Wilson al 95 % con la fórmula del kit y extremos 0 y n', () => {
const [bajo, alto] = wilson(11, 12);
expect(bajo).toBeCloseTo(64.61, 1); expect(alto).toBeCloseTo(98.51, 1);
expect(wilson(0, 10)[0]).toBe(0); expect(wilson(10, 10)[1]).toBe(100);
});
it('vista base LIEAG o más; grupo, grado, segundo clic al grupo y centro a la base', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2');
const base = seleccionBase(m);
expect(tasas(m, base).map(t => [t.k, t.fila.den])).toEqual([[11, 12], [41, 58], [11, 38]]);
expect(lectura(m, base)).toBe('Verdaderos positivos (valor predictivo positivo)');
const menor = clicConfirmacion(m, base, 'grupos', m.grupos.findIndex(g => g.id === 'NO_ANORMAL'));
expect(menor).toEqual({ grupo: 'NO_ANORMAL' }); expect(lectura(m, menor)).toBe('Sin confirmación de alto grado');
const normal = clicConfirmacion(m, menor, 'categorias', 0);
expect(normal).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
expect(lectura(m, normal)).toBe('Falsos positivos: la biopsia no confirmó lesión');
expect(tasas(m, normal).map(t => t.k)).toEqual([0, 6, 16]);
expect(clicConfirmacion(m, normal, 'categorias', 0)).toEqual({ grupo: 'NO_ANORMAL' });
const cis = clicConfirmacion(m, normal, 'categorias', 3);
expect(lectura(m, cis)).toBe('Proporción con biopsia Carcinoma in situ');
expect(clicConfirmacion(m, cis, 'centro', 0)).toEqual(base);
});
it('figura de tasas: una traza siempre, etiquetas «xx.x %» y «k/n», eje acotado a múltiplos de 5', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
const f = figuraTasas(m, base, 'claro');
expect(f.data).toHaveLength(1); expect(f.data[0]['type']).toBe('scatter');
expect(f.data[0]['y']).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray).toEqual(['ASC-H', 'LIEAG', 'Carcinoma in situ']);
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text))
.toEqual(['<b>91.7 %</b><br>11/12', '<b>70.7 %</b><br>41/58', '<b>28.9 %</b><br>11/38']);
const range = (f.layout['xaxis'] as { range: number[] }).range;
expect(range).toEqual(rangoTasas(tasas(m, base)));
expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); expect(range[0]).toBeGreaterThanOrEqual(0); expect(range[1]).toBeLessThanOrEqual(100);
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Verdaderos positivos (valor predictivo positivo)');
const otra = figuraTasas(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'oscuro');
expect(otra.data).toHaveLength(1); expect(otra.layout['paper_bgcolor']).toBe('#081839');
});
it('fila suprimida o nula dice Suprimido o No disponible, nunca 0, y la dona no suma un total parcial', () => {
const d = respuesta();
Object.assign(d.filas.find(f => f['estrato'] === 'CIS' && f['categoria'] === 'LIEAG')!, { n: null, suprimido: 1 });
d.filas = d.filas.filter(f => !(f['estrato'] === 'ASC-H' && f['categoria'] === 'NORMAL'));
const m = modeloConfirmacion(d, '2026-S2'), base = seleccionBase(m);
expect(m.filas.map(f => [f.den, f.estado])).toEqual([[null, 'Suprimido'], [58, 'Publicado'], [null, 'No disponible']]);
const f = figuraTasas(m, base, 'claro');
expect(f.data[0]['x']).toEqual([null, 100 * 41 / 58, null]);
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(['Suprimido', '<b>70.7 %</b><br>41/58', 'No disponible']);
expect(JSON.stringify(f.layout['annotations'])).not.toContain('0/');
expect(m.conBiopsia).toBeNull(); expect(donaConfirmacion(m, base, 'claro').data).toHaveLength(0);
});
it('dona de dos anillos; la selección atenúa sin cambiar valores y el centro dice «k de N con biopsia»', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
const d = donaConfirmacion(m, base, 'claro');
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
expect(d.data[1]['values']).toEqual([45, 63]);
expect(d.data[2]['values']).toEqual([22, 22, 44, 13, 6, 1]);
expect(d.data[0]['text']).toEqual(['<b>63</b><br>de 108 con biopsia']);
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
});
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
expect(() => periodosConfirmacion({ ...respuesta(), estrato: 'estatus_seguimiento' }, 'semestre')).toThrow(ConfirmacionIncompatible);
expect(() => periodosConfirmacion(respuesta(), 'semestre', ['2026-S1'])).toThrow(ConfirmacionIncompatible);
const dup = respuesta(); dup.filas.push({ ...dup.filas[0] });
expect(() => modeloConfirmacion(dup, '2026-S2')).toThrow(ConfirmacionIncompatible);
});
});
describe('Confirmación histopatológica: componente', () => {
const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 };
let f: ReturnType<typeof TestBed.createComponent<IndicadorConfirmacionCitologia>>;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
f = TestBed.createComponent(IndicadorConfirmacionCitologia);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
});
afterEach(() => { f.destroy(); http.verify(); });
function flush(body: unknown = respuesta(['2026-S1', '2026-S2'])) {
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_confirmacion_citologia/datos');
expect(r.request.params.get('estrato')).toBe('citologia_alto_grado');
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
r.flush(body as Record<string, unknown>); f.detectChanges();
}
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.status()).toBe('ready');
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
normal.click(); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
expect(normal.getAttribute('aria-pressed')).toBe('true');
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].slice(-3).map(td => td.textContent))).toEqual([['12', '11', '2'], ['58', '22', '2'], ['38', '20', '2']]);
f.componentInstance.changePeriod(-1); f.detectChanges();
expect(f.componentInstance.model!.periodo).toBe('2026-S1'); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
});
it('error se anuncia y el reintento recupera; respuesta incompatible no dibuja', () => {
f.detectChanges();
http.expectOne(req => req.url.endsWith('/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
f.componentInstance.retry(); flush({ ...respuesta(['2026-S1', '2026-S2']), estrato: 'otro' });
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
});
it('filtro general incompatible no pide datos', () => {
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
});
it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
expect(requested).toHaveBeenCalledTimes(1);
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('pendientes');
f.componentRef.setInput('metadata', { descripcion: 'No va', ficha: { nota: 'Tampoco' }, figuras_detalle: [
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']);
for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
});
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const card = TestBed.createComponent(IndicadorCatalogCard);
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(1);
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['cama', 'cacu_confirmacion_citologia']] as const) {
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(0);
}
card.destroy(); http.expectNone(() => true);
});
});
// Cáncer de mama's configuration of the same view. Fixture: a one-period answer of cama_histopatologia_birads
// built below, with two BI-RADS categories published and biopsies without a result kept apart.
describe('Confirmación histopatológica de cáncer de mama', () => {
const categorias = {
BENIGNO: { etiqueta: 'Benigno', color: '#9DBFE3', grupo: 'NO_MALIGNO' }, RIESGO_B3: { etiqueta: 'Lesión de riesgo (B3)', color: '#2F6DB3', grupo: 'NO_MALIGNO' },
IN_SITU: { etiqueta: 'Carcinoma in situ', color: '#D9822B', grupo: 'MALIGNO' }, INVASOR: { etiqueta: 'Carcinoma invasor', color: '#B5482E', grupo: 'MALIGNO' },
SIN_DATO: { etiqueta: 'Sin resultado histopatológico', color: '#BDBDBD', grupo: 'SIN_DATO' },
};
const n: Record<string, Record<string, number>> = {
BIRADS_5: { BENIGNO: 3, RIESGO_B3: 0, IN_SITU: 11, INVASOR: 38, SIN_DATO: 3 },
BIRADS_4A: { BENIGNO: 91, RIESGO_B3: 15, IN_SITU: 1, INVASOR: 7, SIN_DATO: 9 },
};
const datos = () => ({ id: 'cama_histopatologia_birads', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'birads',
valores_estrato: Object.keys(n), categorias, grupos_de_categoria: { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' },
filas: Object.entries(n).flatMap(([estrato, c]) => Object.entries(c).map(([categoria, v]) =>
({ periodo: '2025-S2', grupo: 'TOTAL', estrato, categoria, n: v, suprimido: 0 }))) }) as IndicadorDatos;
it('la elige el dominio y el indicador', () => {
// Fails if the view stops being found for cáncer de mama, or leaks to another indicator.
expect(vistaConfirmacion('cama', { id: 'cama_histopatologia_birads' })).toBe(CONFIRMACION_CAMA);
expect(vistaConfirmacion('cama', { id: 'cacu_confirmacion_citologia' })).toBeUndefined();
});
it('filas BI-RADS de la más grave a la menor, base maligna y sin resultado aparte', () => {
// Fails if the rows don't follow the configuration, the base isn't malignancy or «Sin dato» enters the rate.
const m = modeloConfirmacion(datos(), '2025-S2', CONFIRMACION_CAMA), base = seleccionBase(m);
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_6', 'BIRADS_5', 'BIRADS_4C', 'BIRADS_4B', 'BIRADS_4A']);
expect(base).toEqual({ grupo: 'MALIGNO' });
expect(lectura(m, base)).toBe('Detección de cáncer (valor predictivo positivo)');
const t = tasas(m, base);
expect(t[1].k).toBe(49); expect(t[1].fila.den).toBe(52);
expect(t[4].k).toBe(8); expect(t[4].fila.den).toBe(114);
expect(estadoTasa(t[0], m.vista.textos.sujetos)).toBe('Sin pacientes con biopsia');
});
});
describe('Dona interactiva como la de CaCu (sin botones)', () => {
const vista = { ...CONFIRMACION_CAMA, id: 'cacu_confirmacion_citologia', estrato: 'citologia_alto_grado' as const, filas: CONFIRMACION_CACU.filas, base: 'LIEAG' };
const modelo = () => modeloConfirmacion(respuesta(), '2026-S2', vista);
it('total → grupo → resultado y el centro regresa un paso hasta el total', () => {
// Fails if the centre stops returning to the total, or a group click no longer narrows to it.
const m = modelo(), g = m.grupos.findIndex(x => x.id === m.base), c = m.grados.findIndex(x => x.grupo === m.base);
let s = clicDona(m, {}, 'grupos', g); expect(s).toEqual({ grupo: m.base });
s = clicDona(m, s, 'categorias', c); expect(s).toEqual({ grupo: m.base, categoria: m.grados[c].id });
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({ grupo: m.base });
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({});
expect(clicDona(m, { grupo: m.base }, 'grupos', g)).toEqual({});
const otra = m.grados.findIndex(x => x.grupo !== m.base);
expect(clicDona(m, { grupo: m.base }, 'categorias', otra)).toEqual({ grupo: m.base });
});
it('el grupo elegido llena los dos anillos y el total cuenta el grupo base en las tasas', () => {
// Fails if the other group's slices stay (no expansion), or the total stops reading as the base rate.
const m = modelo(), base = m.grupos.find(x => x.id === m.base)!;
const d = donaExpandible(m, { grupo: m.base }, 'claro');
const exterior = d.data[2]['values'] as number[];
m.grados.forEach((g, i) => expect(exterior[i] === 0).toBe(g.grupo !== m.base));
expect((d.data[1]['values'] as number[]).filter(v => v > 0)).toHaveLength(1);
expect(d.data[0]['text']).toEqual([`<b>${base.grados.reduce((s, c) => s + m.totales[c]!, 0)}</b><br>${base.etiqueta}`]);
expect(tasas(m, {}).map(t => t.k)).toEqual(tasas(m, seleccionBase(m)).map(t => t.k));
expect(lectura(m, {})).toBe(vista.textos.base);
});
});
@@ -0,0 +1,321 @@
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
// a C2 stratified by the last valid cytology of the period; the category is the grade
// of the biopsy it originated. Unknown or suppressed cells never become zero.
export const ID_CONFIRMACION = 'cacu_confirmacion_citologia';
export const ESTRATO_CITOLOGIA = 'citologia_alto_grado';
// Outside the denominator and the donut, reported apart in the table:
// SIN_BIOPSIA = no biopsy reported at the cut-off; SIN_DATO = biopsy reported without a grade.
export const APARTE = [
{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' },
{ id: 'SIN_DATO', etiqueta: 'Biopsia sin grado' },
] as const;
const APARTE_IDS: readonly string[] = APARTE.map(a => a.id);
// Grades outside the published catalog (CIN2, DESCONOCIDO…) arrive without a colour.
const COLOR_RESPALDO = '#8A9199';
// Fixed vertical axis, most severe cytology on top.
export const FILAS_CITOLOGIA = [
{ id: 'CIS', etiqueta: 'Carcinoma in situ' },
{ id: 'LIEAG', etiqueta: 'LIEAG' },
{ id: 'ASC-H', etiqueta: 'ASC-H' },
] as const;
export const Z95 = 1.959963984540054;
// One confirmation view: which indicator and stratum, its fixed rows (most severe on top), the grade whose group is
// the base view (the true positives), the grade read as a false positive, and the words the view uses.
export interface VistaConfirmacion {
id: string; estrato: DimensionEstrato; filas: readonly { id: string; etiqueta: string }[];
base: string; falsoPositivo: string;
// With buttons, the choice is made on them; without, on the donut (donaExpandible), whose centre names it.
botones: boolean;
textos: { base: string; falsoPositivo: string; sinConfirmacion: string; filas: string; encabezado: string; sujetos: string; vacio: string };
}
export const CONFIRMACION_CACU: VistaConfirmacion = {
id: ID_CONFIRMACION, estrato: ESTRATO_CITOLOGIA, filas: FILAS_CITOLOGIA, base: 'LIEAG', falsoPositivo: 'NORMAL', botones: true,
textos: { base: 'Verdaderos positivos (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia no confirmó lesión',
sinConfirmacion: 'Sin confirmación de alto grado', filas: 'Por resultado de la citología', encabezado: 'Citología', sujetos: 'mujeres',
vacio: 'No hay citologías de alto grado publicadas para este periodo.' },
};
// Cáncer de mama: the biopsies by the BI-RADS of the mammogram that led to them; the base is malignancy.
export const CONFIRMACION_CAMA: VistaConfirmacion = {
id: 'cama_histopatologia_birads', estrato: 'birads', base: 'INVASOR', falsoPositivo: 'BENIGNO', botones: false,
filas: [{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6' }, { id: 'BIRADS_5', etiqueta: 'BI-RADS 5' }, { id: 'BIRADS_4C', etiqueta: 'BI-RADS 4C' },
{ id: 'BIRADS_4B', etiqueta: 'BI-RADS 4B' }, { id: 'BIRADS_4A', etiqueta: 'BI-RADS 4A' }],
textos: { base: 'Detección de cáncer (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia resultó benigna',
sinConfirmacion: 'Sin malignidad', filas: 'Por categoría BI-RADS', encabezado: 'BI-RADS', sujetos: 'pacientes',
vacio: 'No hay biopsias publicadas para este periodo.' },
};
const VISTAS_CONFIRMACION: Readonly<Partial<Record<Dominio, VistaConfirmacion>>> = { cacu: CONFIRMACION_CACU, cama: CONFIRMACION_CAMA };
export function vistaConfirmacion(dominio: Dominio, indicador: Pick<Indicador, 'id'>): VistaConfirmacion | undefined {
const vista = VISTAS_CONFIRMACION[dominio];
return vista?.id === indicador.id ? vista : undefined;
}
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
export interface FilaCitologia {
id: string; etiqueta: string; celdas: Record<string, Celda>;
// SIN_BIOPSIA and SIN_DATO cells, when the response publishes those categories.
aparte: Record<string, Celda>;
// Women of the row with a biopsy: the denominator. Null when any of its cells is unknown.
den: number | null; estado: Celda['estado'];
}
export interface ModeloConfirmacion {
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; vista: VistaConfirmacion;
}
// Without a group, the total: every result is shown and the rates count the base group.
export interface SeleccionConfirmacion { grupo?: string; categoria?: string; }
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
export class ConfirmacionIncompatible extends Error {}
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0;
const fail = (message: string): never => { throw new ConfirmacionIncompatible(message); };
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const miles = (v: number) => v.toLocaleString('es-MX');
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
/** Wilson score interval at 95 %, in percent; same formula as the kit (oro/calculo.py:wilson). */
export function wilson(k: number, n: number): [number, number] {
const p = k / n, z2 = Z95 * Z95, base = 1 + z2 / n;
const centro = (p + z2 / (2 * n)) / base;
const mitad = Z95 * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / base;
return [100 * Math.max(0, Math.min(p, centro - mitad)), 100 * Math.min(1, Math.max(p, centro + mitad))];
}
function celda(fila?: Record<string, unknown>): Celda {
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
}
function suma(celdas: Celda[]): number | null {
return celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0);
}
function estado(celdas: Celda[]): Celda['estado'] {
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
}
function promedio(colores: string[]): string {
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
.toString(16).padStart(2, '0')).join('');
}
function rgba(hex: string, alfa: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
}
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
/** Validated periods of one stratified response, in request order or sorted. */
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[], vista = CONFIRMACION_CACU): string[] {
if (datos.id !== vista.id || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== vista.estrato
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|| datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) {
return fail('Los datos no corresponden a la confirmación histopatológica o al periodo aplicado.');
}
return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort();
}
/** One /datos payload -> the contingency table of a single period. */
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista = CONFIRMACION_CACU): ModeloConfirmacion {
periodosConfirmacion(datos, datos.tipo_periodo, undefined, vista);
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
const c = cats[a.id];
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
});
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
});
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
// Off-catalogue grades share the group but not its colour.
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
grados: propios.map(g => g.id) };
});
// The base view is the group of the view's base grade (CaCu: "LIEAG o más"): the true positives.
const base = grados.find(g => g.id === vista.base)?.grupo ?? fail(`El catálogo no publica el grado ${vista.base}.`);
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
const index = new Map<string, Record<string, unknown>>();
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
const c = row['categoria'], e = row['estrato'];
if (!esTotal(row['grupo']) || typeof e !== 'string' || typeof c !== 'string'
|| (!grados.some(g => g.id === c) && !aparte.some(a => a.id === c)) || ![0, 1].includes(row['suprimido'] as number)) {
return fail('Fila de confirmación inválida.');
}
const key = JSON.stringify([e, c]);
if (index.has(key)) return fail('Filas de confirmación duplicadas.');
index.set(key, row);
}
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined;
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos inválidos.');
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
if (!totales.every(registro)) fail('Totales por estrato inválidos.');
const filas = vista.filas.map(({ id, etiqueta }) => {
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
const cero = (): Celda => ({ n: 0, estado: 'Publicado' });
const celdas = Object.fromEntries(grados.map(g => [g.id, ausente ? cero() : celda(index.get(JSON.stringify([id, g.id])))]));
const otras = Object.fromEntries(aparte.map(a => [a.id, ausente ? cero() : celda(index.get(JSON.stringify([id, a.id])))]));
// A suppressed published total suppresses the row, whatever its cells say.
const suprimida = (totales as Record<string, unknown>[]).some(t => t['periodo'] === periodo && t['estrato'] === id && t['suprimido'] === 1);
const valores = Object.values(celdas);
return { id, etiqueta: rotulo, celdas, aparte: otras,
den: suprimida ? null : suma(valores), estado: suprimida ? 'Suprimido' as const : estado(valores) };
});
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
return { periodo, grados, grupos, base, filas, totales: porGrado,
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])], vista };
}
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === (sel.grupo ?? m.base))?.grados ?? [];
}
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'Todos los resultados';
}
/** CaCu's interactive donut: a group narrows to it, a result is chosen inside its group, the centre steps back
* (result -> its group -> the total), and choosing the chosen entry again also steps back. */
export function clicDona(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
if (traza === 'grupos') { const g = m.grupos[indice]?.id; return !g ? sel : sel.grupo === g && !sel.categoria ? {} : { grupo: g }; }
if (traza !== 'categorias') return sel;
const c = m.grados[indice];
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
}
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
if (traza === 'centro') return seleccionBase(m);
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
if (traza !== 'categorias') return sel;
const c = m.grados[indice];
if (!c) return sel;
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
}
/** The axis title says what the rate reads. */
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
if (!sel.categoria && (sel.grupo ?? m.base) === m.base) return m.vista.textos.base;
if (sel.categoria === m.vista.falsoPositivo) return m.vista.textos.falsoPositivo;
if (!sel.categoria) return m.vista.textos.sinConfirmacion;
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
}
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[] {
const cats = seleccionados(m, sel);
return m.filas.map(fila => {
if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null };
const k = cats.reduce((s, c) => s + fila.celdas[c].n!, 0);
const [bajo, alto] = wilson(k, fila.den);
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
});
}
export function estadoTasa(t: Tasa, sujetos = 'mujeres'): string {
return t.fila.den === 0 ? `Sin ${sujetos} con biopsia` : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
}
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
export function rangoTasas(valores: Tasa[]): [number, number] {
const visibles = valores.filter(t => t.bajo !== null && t.alto !== null);
if (!visibles.length) return [0, 100];
const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!));
return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)];
}
/** Rates on the left: one point and horizontal Wilson interval per cytology, one trace always. */
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
const p = c2Theme(tema);
const valores = tasas(m, sel);
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === (sel.grupo ?? m.base))!.color;
const y = valores.map(t => t.fila.etiqueta);
return { data: [{
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
marker: { size: 12, color }, cliponaxis: false,
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
customdata: valores.map(t => t.k === null ? [estadoTasa(t, m.vista.textos.sujetos), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
}], layout: {
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { l: 130, r: 96, t: 16, b: 64 },
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true },
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
font: { size: 12, color: p.text },
text: t.k === null ? estadoTasa(t, m.vista.textos.sujetos) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
}, config: { displayModeBar: false } };
}
/** Donut on the right: groups inside, grades outside; selection dims, values stay. */
export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
const p = c2Theme(tema), activos = new Set(seleccionados(m, sel)), total = m.conBiopsia;
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
const exterior = m.grados.map(g => m.totales[g.id]!);
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
/** Donut without buttons, drawn like CaCu's interactive one: the chosen group fills both rings (the other's
* slices are zero, so its results expand), a chosen result keeps its colour and its siblings fade, and the
* centre names the choice. The traces keep their names and counts, so a choice animates. */
export function donaExpandible(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
const p = c2Theme(tema), total = m.conBiopsia;
const nGrupo = (g: GrupoGrados) => g.grados.reduce((s, c) => s + m.totales[c]!, 0);
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(g) : 0);
const exterior = m.grados.map(g => !sel.grupo || sel.grupo === g.grupo ? m.totales[g.id]! : 0);
const centro = sel.categoria ? m.totales[sel.categoria]! : sel.grupo ? nGrupo(m.grupos.find(g => g.id === sel.grupo)!) : total;
const rotulos = (values: number[], labels: string[], pct: boolean) => {
const suma = values.reduce((s, n) => s + n, 0);
return values.map((v, i) => !suma || v / suma < .05 ? '' : escapar(labels[i]) + (pct ? '<br>' + shareText(v, suma) : ''));
};
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'text', textposition: 'inside',
insidetextorientation: 'horizontal' };
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`<b>${miles(centro)}</b><br>${escapar(sel.grupo || sel.categoria ? seleccionEtiqueta(m, sel) : 'Con biopsia')}`],
textfont: { size: 16, color: p.text }, marker: { colors: [p.background] },
hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Todos los resultados') + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.grados.map(g => escapar(g.etiqueta)), text: rotulos(exterior, m.grados.map(g => g.etiqueta), true),
textfont: { size: 11 }, customdata: custom(exterior),
marker: { colors: m.grados.map(g => rgba(g.color, sel.categoria && g.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 400, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
@@ -0,0 +1,45 @@
import { IndicadorDatos } from './indicadores.models';
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, PARES_CONTEOS, parConteos, razon, totalExamenes } from './indicadores-conteos-pareados';
// Covers the paired counts of cáncer de mama: mammograms by BI-RADS (donut) and each patient BI-RADS next to its
// mammograms (bars). Fixtures: two one-period answers built below, with the categories the API publishes.
const par = PARES_CONTEOS[0];
const filas = (n: Record<string, number | null>) => Object.entries(n).map(([categoria, v]) =>
({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: v, suprimido: v === null ? 1 : 0 }));
const examenes = (n: Record<string, number | null> = { B4A: 30, B4B: 18, B4C: 12, B5: 1016, B6: 972, SIN_DATO: 20 }) => ({
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
categorias: Object.fromEntries(Object.keys(n).map(k => [k, { etiqueta: k === 'SIN_DATO' ? 'Sin dato' : 'BI-RADS ' + k.slice(1), color: '#C26A2B' }])),
filas: filas(n) }) as unknown as IndicadorDatos;
const pacientes = () => ({ id: 'cama_birads_456_paciente', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
categorias: { BIRADS_4: { etiqueta: 'BI-RADS 4' }, BIRADS_5: { etiqueta: 'BI-RADS 5' }, BIRADS_6: { etiqueta: 'BI-RADS 6' } },
filas: filas({ BIRADS_4: 15, BIRADS_5: 254, BIRADS_6: 243 }) }) as unknown as IndicadorDatos;
describe('Conteos por mastografía y por paciente', () => {
it('la tarjeta de mastografías los dibuja y la de pacientes no tiene tarjeta propia', () => {
// Fails if the pair is found on the wrong card, or the patients still get a card of their own.
expect(parConteos('cama', 'cama_birads_456_mastografia')).toBe(par);
expect(parConteos('cama', 'cama_birads_456_paciente')).toBeUndefined();
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true);
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false);
});
it('suma 4A, 4B y 4C en el BI-RADS 4 de la paciente y deja «Sin dato» fuera de la dona', () => {
// Fails if subcategories don't add up to their patient category, or uncategorised exams enter the donut.
const [m] = modelosConteos(par, examenes(), pacientes(), 'semestre');
expect(m.filas.map(f => [f.id, f.pacientes, f.examenes])).toEqual([['BIRADS_4', 15, 60], ['BIRADS_5', 254, 1016], ['BIRADS_6', 243, 972]]);
expect(razon(m.filas[0])).toBe(4);
expect(totalExamenes(m)).toBe(2048); expect(m.sinDato).toBe(20);
expect(donaConteos(m, par, 'claro').data[0]['values']).toEqual([30, 18, 12, 1016, 972]);
expect(barrasConteos(m, par, 'claro').data.map(t => t['x'])).toEqual([[15, 254, 243], [60, 1016, 972]]);
});
it('una celda suprimida no se vuelve cero', () => {
// Fails if a suppressed exam count is drawn as zero or its category's sum and ratio are still computed.
const [m] = modelosConteos(par, examenes({ B4A: null, B4B: 18, B4C: 12, B5: 1016, B6: 972 }), pacientes(), 'semestre');
expect(totalExamenes(m)).toBeNull(); expect(m.filas[0].examenes).toBeNull(); expect(razon(m.filas[0])).toBeNull();
expect(donaConteos(m, par, 'claro').data).toEqual([]);
});
it('rechaza respuestas de otro indicador o intervalo', () => {
// Fails if the view accepts data that isn't the pair it draws.
expect(() => modelosConteos(par, pacientes(), pacientes(), 'semestre')).toThrow(ConteosIncompatibles);
expect(() => modelosConteos(par, examenes(), pacientes(), 'mes')).toThrow(ConteosIncompatibles);
});
});
@@ -0,0 +1,102 @@
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber } from './indicadores-format';
// Two C2 counts of the same finding, one per exam and one per patient: the exams' composition as a donut, and
// each patient category next to its exams, so the bars say how many exams each patient has.
export interface ParConteos {
dominio: Dominio;
examenes: string;
pacientes: string;
// Exam category -> patient category it adds to (BI-RADS 4A, 4B and 4C are a patient's BI-RADS 4).
grupoDe: Readonly<Record<string, string>>;
unidades: { examenes: string; pacientes: string; porPaciente: string };
}
export const PARES_CONTEOS: readonly ParConteos[] = [
{ dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente',
grupoDe: { B4A: 'BIRADS_4', B4B: 'BIRADS_4', B4C: 'BIRADS_4', B5: 'BIRADS_5', B6: 'BIRADS_6' },
unidades: { examenes: 'mastografías', pacientes: 'pacientes', porPaciente: 'por paciente' } },
];
// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own.
export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id);
export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) =>
PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes));
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
export interface ModeloConteos { periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[]; notas: string[]; }
export class ConteosIncompatibles extends Error {}
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const fail = (message: string): never => { throw new ConteosIncompatibles(message); };
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const miles = (v: number) => v.toLocaleString('es-MX');
// A suppressed or unpublished cell is unknown, never zero.
function cuenta(filas: Record<string, unknown>[], periodo: string, categoria: string): number | null {
const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria);
return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null;
}
const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce<number>((s, v) => s + v!, 0);
/** One model per period both responses publish, in chronological order. */
export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] {
for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) {
if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) {
fail('Los datos no corresponden a los conteos por mastografía y por paciente.');
}
}
const catExamenes = examenes['categorias'] as Record<string, unknown>, catPacientes = pacientes['categorias'] as Record<string, unknown>;
const etiqueta = (cat: Record<string, unknown>, id: string) => registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : id;
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : '#8A9199';
const ids = Object.keys(par.grupoDe).filter(id => Object.hasOwn(catExamenes, id));
const filasIds = [...new Set(Object.values(par.grupoDe))];
if (!ids.length || filasIds.some(id => !Object.hasOwn(catPacientes, id))) fail('Las categorías de mastografías y pacientes no coinciden.');
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
return periodos.map(periodo => {
const cats = ids.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) }));
return {
periodo, examenes: cats, sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
filas: filasIds.map(id => ({ id, etiqueta: etiqueta(catPacientes, id), pacientes: cuenta(filasP, periodo, id),
examenes: sumar(cats.filter(c => par.grupoDe[c.id] === id).map(c => c.n)) })),
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
};
});
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
export const razon = (f: FilaConteo) => f.pacientes && f.examenes !== null ? f.examenes / f.pacientes : null;
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const total = totalExamenes(m);
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
}
/** Per patient category: patients next to their exams, and how many exams each patient has. */
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
const traza = (clave: 'pacientes' | 'examenes', nombre: string, color: string) => ({
type: 'bar', orientation: 'h', name: nombre, y, x: m.filas.map(f => f[clave]), marker: { color },
text: m.filas.map(f => f[clave] === null ? 'Sin dato' : miles(f[clave]!)), textposition: 'outside', cliponaxis: false,
hovertemplate: `%{y}: %{x} ${nombre}<extra></extra>` });
const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0));
return { data: [traza('pacientes', par.unidades.pacientes, '#7A8794'), traza('examenes', par.unidades.examenes, '#C26A2B')],
layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 96, r: 150, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false },
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true },
annotations: m.filas.map((f, i) => {
const r = razon(f);
return { x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: y[i], yref: 'y', showarrow: false, align: 'left', font: { size: 12, color: p.text },
text: r === null ? 'Sin razón' : `<b>≈ ${r.toLocaleString('es-MX', { maximumFractionDigits: 1 })}</b> ${par.unidades.porPaciente}` };
}) }, config: { displayModeBar: false } };
}
@@ -1,7 +1,7 @@
<h2>Datos y definiciones · {{ domainNames[dominio] }}</h2> <h2>Datos y definiciones de {{ domainNames[dominio] }}</h2>
<section aria-labelledby="domain-info-title"> <section aria-labelledby="domain-info-title">
<h3 id="domain-info-title">Información del dominio</h3> <h3 id="domain-info-title">Información del dominio</h3>
<p>Dominio: {{ domainNames[dominio] }}.</p> @if (dominio === 'cacu') { <p>Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo espécimen fue insatisfactorio.</p> }
@if (!loading && !error && periodTypes.length) { @if (!loading && !error && periodTypes.length) {
<p>Periodicidad disponible: <p>Periodicidad disponible:
@for (tipo of periodTypes; track tipo; let last = $last) { {{ periodNames[tipo] }}{{ last ? '.' : ', ' }} } @for (tipo of periodTypes; track tipo; let last = $last) { {{ periodNames[tipo] }}{{ last ? '.' : ', ' }} }
@@ -29,10 +29,6 @@
@if (item.tipos_periodo.length) { @if (item.tipos_periodo.length) {
<ul>@for (tipo of item.tipos_periodo; track tipo) { <li>{{ periodNames[tipo] }}</li> }</ul> <ul>@for (tipo of item.tipos_periodo; track tipo) { <li>{{ periodNames[tipo] }}</li> }</ul>
} @else { <p>Pendiente de información.</p> } } @else { <p>Pendiente de información.</p> }
<h4>Cómo interpretar este indicador</h4>
@if (interpretation(item).length) {
<ul>@for (line of interpretation(item); track $index) { <li>{{ line }}</li> }</ul>
}
@if (opened.has(dominio + ':' + item.id)) { @if (opened.has(dominio + ':' + item.id)) {
<app-indicador-metadata [dominio]="dominio" [indicador]="item.id" /> <app-indicador-metadata [dominio]="dominio" [indicador]="item.id" />
} @else { } @else {
@@ -43,14 +39,3 @@
} }
} }
</section> </section>
<section aria-labelledby="definitions-methodology-title">
<h3 id="definitions-methodology-title">Interpretación y metodología</h3>
<p>Ten en cuenta estas limitaciones al consultar las gráficas.</p>
<ul>
<li>Un valor nulo significa que no hay un valor disponible; un cero es un valor observado. Los datos suprimidos tampoco representan un cero.</li>
<li>{{ periodInterpretation }}</li>
<li>Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.</li>
<li>Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por un tamaño de muestra pequeño.</li>
</ul>
<p>Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. Las notas de cada gráfica incluyen detalles adicionales para interpretar los datos mostrados.</p>
</section>
@@ -1,6 +1,6 @@
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere; :host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { font-size: 1.5rem; margin-top: 0; } h2 { font-size: 1.25rem; font-weight: 500; margin-top: 0; }
h3 { font-size: 1.25rem; } h3 { font-size: 1.25rem; }
h4 { font-size: 1rem; margin-bottom: .5rem; } h4 { font-size: 1rem; margin-bottom: .5rem; }
section + section { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); } section + section { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); }
@@ -2,7 +2,7 @@ import { Component, Input, output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { Dominio, Indicador, TipoPeriodo } from './indicadores.models'; import { Dominio, Indicador, TipoPeriodo } from './indicadores.models';
import { figureDisplayName } from './indicadores-figure-labels'; import { figureDisplayName } from './indicadores-figure-labels';
import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; import { PERIOD_INTERPRETATION } from './indicadores-methodology';
import { IndicadorMetadata } from './indicador-metadata'; import { IndicadorMetadata } from './indicador-metadata';
@Component({ @Component({
@@ -19,20 +19,9 @@ export class IndicadoresDefinitions {
@Input() loading = false; @Input() loading = false;
@Input() error = ''; @Input() error = '';
readonly retry = output<void>(); readonly retry = output<void>();
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' }; readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
readonly figureDisplayName = figureDisplayName; readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION; readonly periodInterpretation = PERIOD_INTERPRETATION;
get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; } get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; }
interpretation(item: Indicador) {
if (!item.contrato) return [];
const lines = contractInterpretation(item.contrato, this.dominio);
// Catalog metadata does not describe the traces. Keep the shared C2 guidance
// independent of bars/sectors; the actual figure retains its full explanation.
return lines.filter(line =>
!line.includes('Los valores nulos o suprimidos') &&
!line.includes('Los puntos suprimidos') &&
!line.includes('No hay una explicación específica disponible'),
).slice(item.contrato === 'C2' ? 1 : 0);
}
} }
@@ -113,7 +113,7 @@ describe('navegación multiperiodo en el panel común', () => {
expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false); expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false);
for (let i = 0; i < periods.length; i++) { for (let i = 0; i < periods.length; i++) {
expect(panel().activeDonutPeriod).toBe(periods[i]); expect(panel().activeDonutPeriod).toBe(periods[i]);
expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} / 3`); expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} de 3`);
expect(card().chartFigure?.data).toHaveLength(1); expect(card().chartFigure?.data).toHaveLength(1);
expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true); expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true);
if (i < 2) { buttons()[1].click(); fixture.detectChanges(); } if (i < 2) { buttons()[1].click(); fixture.detectChanges(); }
@@ -176,6 +176,8 @@ describe('navegación multiperiodo en el panel común', () => {
expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true); expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true);
}); });
it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => { it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => {
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
fixture.componentRef.setInput('dominio', 'cama');
apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges(); apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges();
expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy(); expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy();
apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true); apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true);
@@ -1,6 +1,7 @@
import fixture from './fixtures/eu7-c2-ejemplos.json'; import fixture from './fixtures/eu7-c2-ejemplos.json';
import { IndicadorDatos } from './indicadores.models'; import { IndicadorDatos } from './indicadores.models';
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario'; import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
import { percentNumber } from './indicadores-format';
function eu7Datos() { function eu7Datos() {
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos }); return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
@@ -41,10 +42,13 @@ describe('EU7 modelo de presentación del entregable', () => {
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1))) expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
.toEqual(['5.0', '24.3', '21.7', '7.8']); .toEqual(['5.0', '24.3', '21.7', '7.8']);
const category = barras(m, { categoria: 'LIEAG' }, 'claro'); const category = barras(m, { categoria: 'LIEAG' }, 'claro');
expect(category.data).toHaveLength(1); // Same traces in every selection (animation identity); unselected ones are zero-width.
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text)) expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
.toEqual(m.escenarios.map(s => `<b>${(100 * s.celdas['LIEAG'].n! / s.den!).toFixed(1)} %</b> (${s.celdas['LIEAG'].n}/${s.den})`)); .toEqual(m.escenarios.map(s => `<b>${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} %</b> (${s.celdas['LIEAG'].n}/${s.den})`));
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
}); });
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => { it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
@@ -73,7 +77,10 @@ describe('EU7 modelo de presentación del entregable', () => {
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 }); else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 }); else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro'); const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]); expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
expect(JSON.stringify(f)).not.toContain('123456'); expect(JSON.stringify(f)).not.toContain('123456');
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull(); expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
}); });
@@ -94,6 +101,7 @@ describe('EU7 modelo de presentación del entregable', () => {
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0); (data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]); const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true); expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })])); expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
}); });
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => { it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
@@ -101,4 +109,20 @@ describe('EU7 modelo de presentación del entregable', () => {
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]); const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
expect(m.celdas['NORMAL'].n).toBeNull(); expect(m.celdas['NORMAL'].n).toBeNull();
}); });
it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
const ids = m.categorias.map(c => c.id);
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
const f = barras(m, selection, 'claro');
expect(f.data.map(t => t['uid'])).toEqual(ids);
expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
f.data.forEach((t, i) => {
if (t['hoverinfo'] === 'skip') {
expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
} else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
});
dona(m, selection, 'claro');
}
expect(m).toEqual(snapshot); expect(data).toEqual(original);
});
}); });
@@ -1,10 +1,18 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette'; import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
// This boundary is intentionally specific to EU7. Unknown cells never become zero. // A C2 distribution with category groups, next to the same categories by one stratum. Unknown cells never become zero.
export const ESTRATO = 'estatus_seguimiento'; export const ESTRATO = 'estatus_seguimiento';
const SIN_DATO = 'SIN_DATO'; const SIN_DATO = 'SIN_DATO';
// CaCu's EU7 predates the catalog's `escenario` field.
const EU7: VistaEscenario = { estrato: ESTRATO, etiqueta: 'escenario clínico' };
export function vistaEscenario(dominio: Dominio, indicador: Indicador): VistaEscenario | undefined {
if (indicador.escenario) return indicador.escenario;
return dominio === 'cacu' && indicador.id === 'cacu_eu7' ? EU7 : undefined;
}
export const esEu7 = (vista: VistaEscenario) => vista === EU7;
export interface Seleccion { grupo?: string; categoria?: string; } export interface Seleccion { grupo?: string; categoria?: string; }
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; } export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
export interface Grupo { id: string; etiqueta: string; color: string; } export interface Grupo { id: string; etiqueta: string; color: string; }
@@ -63,7 +71,7 @@ function catalogo(data: IndicadorDatos): Categoria[] {
/** Validate the common temporal scope before exposing any period's figures. */ /** Validate the common temporal scope before exposing any period's figures. */
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
for (const d of [general, escenarios]) { for (const d of [general, escenarios]) {
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) if (d.id !== general.id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|| new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string' || new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string'
|| !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p)) || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) { || !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
@@ -79,10 +87,10 @@ export function periodosCompatibles(general: IndicadorDatos, escenarios: Indicad
} }
/** Two immutable /datos payloads -> one safe presentation model for a single period. */ /** Two immutable /datos payloads -> one safe presentation model for a single period. */
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo { export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string, estrato: DimensionEstrato = ESTRATO): Modelo {
periodosCompatibles(general, porEscenario, general.tipo_periodo); periodosCompatibles(general, porEscenario, general.tipo_periodo);
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato']; const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo) if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== estrato || !general.periodos.includes(periodo)
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length || !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string') || !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) { || [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
@@ -189,12 +197,12 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total; const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
const rotulos = (values: number[], labels: string[], pct: boolean) => { const rotulos = (values: number[], labels: string[], pct: boolean) => {
const total = values.reduce((s, n) => s + n, 0); const total = values.reduce((s, n) => s + n, 0);
return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `<br>${(100 * v / total).toFixed(0)} %` : '')); return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `<br>${shareText(v, total)}` : ''));
}; };
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text', const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' }; insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes · %{customdata[1]} % del total con resultado<extra></extra>' }; const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]); const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
return { data: [ return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text }, text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
@@ -211,28 +219,35 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
config: { displayModeBar: false } }; config: { displayModeBar: false } };
} }
/** Selection never changes the original denominator or renormalizes a subset. */ /** Selection never changes the original denominator or renormalizes a subset. */
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { export function barras(m: Modelo, sel: Seleccion, tema: Tema, eje = '% de pacientes del escenario con resultado'): PlotlyFigure {
const p = c2Theme(tema); const p = c2Theme(tema);
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id); const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
const y = m.escenarios.map(s => escapar(s.etiqueta)); const y = m.escenarios.map(s => escapar(s.etiqueta));
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0)); const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => { // Every category keeps its trace (same uid and count) so a selection animates;
const x = m.escenarios.map(s => porcentaje(s, c.id)); // an unselected category is a zero-width bar without text or hover, never data.
return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x, return { data: m.categorias.map(c => {
marker: { color: c.color, line: { color: p.background, width: 1 } }, const visible = visibles.includes(c.id);
text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', const x = m.escenarios.map(s => {
customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]), const value = porcentaje(s, c.id);
hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }; return value === null ? null : visible ? value : 0;
});
return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
...(visible ? { hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }
: { hoverinfo: 'skip' }) };
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false, margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true }, yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid, xaxis: { title: { text: eje }, ticksuffix: ' %', gridcolor: p.grid,
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112], range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] }, tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false, annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
: sel.grupo || sel.categoria ? `<b>${sumas[i]!.toFixed(1)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` : sel.grupo || sel.categoria ? `<b>${percentNumber(sumas[i]!)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
: miles(s.den) })), : miles(s.den) })),
}, config: { displayModeBar: false } }; }, config: { displayModeBar: false } };
} }
@@ -2,6 +2,10 @@
// Exact IDs remain the option values and HTTP identities; never infer a type // Exact IDs remain the option values and HTTP identities; never infer a type
// from a prefix. Unknown options keep a neutral label in publication order. // from a prefix. Unknown options keep a neutral label in publication order.
const FIGURE_LABELS: Readonly<Record<string, string>> = { const FIGURE_LABELS: Readonly<Record<string, string>> = {
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
fig_c1_barras_edad: 'Barras por grupo de edad',
fig_c1_dona_edad: 'Dona por grupo de edad',
fig_c1_donas: 'Dona de dos anillos',
fig_c1_grupos: 'Grupos', fig_c1_grupos: 'Grupos',
fig_c1_puntos: 'Puntos', fig_c1_puntos: 'Puntos',
fig_c2_apiladas: 'Barras apiladas', fig_c2_apiladas: 'Barras apiladas',
@@ -0,0 +1,24 @@
import { percentNumber, percentText, roundPercent, sharePercent, shareText } from './indicadores-format';
describe('regla de redondeo de porcentajes', () => {
it('una décima, medio hacia arriba, calculada con enteros', () => {
expect(sharePercent(2, 303)).toBe(0.7);
expect(sharePercent(1, 8)).toBe(12.5);
expect(sharePercent(1, 3)).toBe(33.3);
expect(sharePercent(2, 3)).toBe(66.7);
expect(shareText(0, 9)).toBe('0.0 %');
expect(shareText(5, 5)).toBe('100.0 %');
});
it('entre 0 y 0.1, la primera cifra significativa', () => {
expect(shareText(1, 2000)).toBe('0.05 %');
expect(shareText(1, 1600)).toBe('0.06 %');
expect(percentText(0.0432)).toBe('0.04 %');
});
it('un porcentaje publicado redondea igual, sin sorpresas de coma flotante', () => {
expect(roundPercent(0.6600660066)).toBe(0.7);
expect(roundPercent(12.25)).toBe(12.3);
expect(roundPercent(1.005 * 10)).toBe(10.1);
expect(percentNumber(100)).toBe('100.0');
expect(percentText(null)).toBe('No disponible');
});
});
@@ -0,0 +1,33 @@
// One rounding rule for every percentage shown: one decimal, half up; between 0 and 0.1
// the first significant digit (0.04 %, not 0.0 %). Integer counts round exactly, without
// binary floating-point surprises (1.005 → 1.0 with toFixed).
/** The percentage of `k` in `n`, rounded by the rule, computed from integers. */
export function sharePercent(k: number, n: number): number {
if (k > 0 && 1000 * k < n) return Number((100 * k / n).toPrecision(1));
return Math.floor((2000 * k + n) / (2 * n)) / 10;
}
/** A published percentage (0 to 100), rounded by the rule. */
export function roundPercent(value: number): number {
if (value > 0 && value < 0.1) return Number(value.toPrecision(1));
// Snap to 9 decimals first so 12.25 published as 12.2499999999 still rounds up.
return Math.floor(Math.round(value * 1e9) / 1e8 + 0.5) / 10;
}
/** Text of a rounded percentage: «12.3», «0.04», «100.0». */
export function percentNumber(value: number): string {
const rounded = roundPercent(value);
return rounded > 0 && rounded < 0.1 ? String(rounded) : rounded.toFixed(1);
}
/** «12.3 %» from a published percentage, or the fallback when there is none. */
export function percentText(value: number | null | undefined, fallback = 'No disponible'): string {
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
}
/** «12.3 %» from a count over its denominator. */
export function shareText(k: number, n: number): string {
const value = sharePercent(k, n);
return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
}
@@ -38,7 +38,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); }
function draft(tipo: TipoPeriodo, periods: string[]) { function draft(tipo: TipoPeriodo, periods: string[]) {
const control = editor(); control.changeTipo(tipo); control.changeMode('manual'); const control = editor(); control.changeTipo(tipo); control.select([]);
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); } for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
} }
function apply() { page.applyFilters(); fixture.detectChanges(); } function apply() { page.applyFilters(); fixture.detectChanges(); }
@@ -67,7 +67,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
}); });
it('edición y vacío no consultan ni cambian el resultado vigente', () => { it('edición y vacío no consultan ni cambian el resultado vigente', () => {
load(); open(); respond(); const result = panels()[0].result(); load(); open(); respond(); const result = panels()[0].result();
editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0); editor().select([]); apply(); expect(page.filters!.applied.revision).toBe(0);
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
draft('semestre', ['2025-S1']); fixture.detectChanges(); draft('semestre', ['2025-S1']); fixture.detectChanges();
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
@@ -82,9 +82,9 @@ describe('D.2 integración de autoridad global y consumidores', () => {
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => { it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond(); load(); open(); respond(); draft('semestre', ['2025-S2']); apply(); respond();
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied; const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
editor().select(['2025-S2', '2025-S1']); apply(); editor().select(['2025-S2']); apply();
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
}); });
@@ -114,7 +114,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined(); expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b'); http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('granularidad mes'); expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de análisis mensual');
expect((host as HTMLElement).parentElement!.hidden).toBe(true); expect((host as HTMLElement).parentElement!.hidden).toBe(true);
r.flush({ data: [], layout: {} }); r.flush({ data: [], layout: {} });
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses'); expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
@@ -145,7 +145,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges(); editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos'); expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load(); draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); expect(editor().selectedPeriods).toEqual(['2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
expect(cards()[0].visible).toBe(false); expect(cards()[0].visible).toBe(false);
http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
http.expectNone(() => true); http.expectNone(() => true);
@@ -0,0 +1,57 @@
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, toggleHighlight } from './indicadores-highlight';
import { PlotlyFigure } from './indicadores.models';
// A double donut like dona(): 0 centre, 1 groups, 2 categories.
const figure: PlotlyFigure = { data: [
{ type: 'pie', values: [1], text: ['<b>10</b><br>TOTAL'] },
{ type: 'pie', values: [6, 4], marker: { colors: ['rgba(10, 20, 30, 1)', '#FF0000'] } },
{ type: 'pie', values: [2, 4, 4], marker: { colors: ['#000000', '#111111', '#222222'] } },
], layout: {} };
const h: FigureHighlight = { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
groups: [{ id: 'A', label: 'Grupo A', color: '#000000', points: [{ trace: 1, index: 0 }, { trace: 2, index: 0 }, { trace: 2, index: 1 }], center: 'A' },
{ id: 'B', label: 'Grupo B', color: '#FF0000', points: [{ trace: 1, index: 1 }, { trace: 2, index: 2 }], center: 'B' }],
items: [{ id: 'a1', label: 'A · 1', short: '1', color: '#000000', group: 'A', points: [{ trace: 2, index: 0 }], center: 'a1' },
{ id: 'a2', label: 'A · 2', short: '2', color: '#111111', group: 'A', points: [{ trace: 2, index: 1 }] },
{ id: 'b1', label: 'B · 1', short: '1', color: '#222222', group: 'B', points: [{ trace: 2, index: 2 }] }] };
const colors = (f: PlotlyFigure, t: number) => (f.data[t]['marker'] as { colors: string[] }).colors;
describe('Botones que resaltan una parte de la figura', () => {
it('sin selección deja la figura intacta', () => {
expect(highlightFigure(figure, h, {})).toBe(figure);
expect(highlightLabel(h, {})).toBe('TOTAL');
});
it('un grupo conserva su parte de ambos anillos y atenúa el resto, también colores rgba', () => {
const f = highlightFigure(figure, h, { group: 'B' });
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 0.3)', '#FF0000']);
expect(colors(f, 2)).toEqual(['rgba(0, 0, 0, 0.3)', 'rgba(17, 17, 17, 0.3)', '#222222']);
expect(f.data[0]['text']).toEqual(['B']);
expect(colors(figure, 2)).toEqual(['#000000', '#111111', '#222222']);
});
it('una categoría conserva su grupo en el anillo interior', () => {
const f = highlightFigure(figure, h, { item: 'a1' });
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 1)', 'rgba(255, 0, 0, 0.3)']);
expect(colors(f, 2)).toEqual(['#000000', 'rgba(17, 17, 17, 0.3)', 'rgba(34, 34, 34, 0.3)']);
expect(f.data[0]['text']).toEqual(['a1']);
});
it('en barras atenúa con la opacidad de cada barra', () => {
const bars: PlotlyFigure = { data: [{ type: 'bar', x: ['a', 'b', 'c'], y: [1, 2, 3], marker: { color: '#000000' } }], layout: {} };
const hb: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todas', items: ['a', 'b', 'c'].map((id, i) => ({ id, label: id, color: '#000000', points: [{ trace: 0, index: i }] })) };
expect((highlightFigure(bars, hb, { item: 'b' }).data[0]['marker'] as { opacity: number[] }).opacity).toEqual([.3, 1, .3]);
});
it('alterna como CaCu: repetir vuelve un paso y un grupo limita las categorías', () => {
expect(toggleHighlight(h, {}, 'group', 'A')).toEqual({ group: 'A' });
expect(toggleHighlight(h, { group: 'A' }, 'group', 'A')).toEqual({});
expect(toggleHighlight(h, { group: 'A' }, 'item', 'a2')).toEqual({ group: 'A', item: 'a2' });
expect(toggleHighlight(h, { group: 'A', item: 'a2' }, 'item', 'a2')).toEqual({ group: 'A' });
expect(toggleHighlight(h, { group: 'A' }, 'item', 'b1')).toEqual({ group: 'A' });
expect(toggleHighlight(h, {}, 'item', 'b1')).toEqual({ item: 'b1' });
});
it('un clic en el anillo exterior es la categoría; en el interior, el grupo', () => {
expect(highlightAt(h, { trace: 2, index: 1 })).toEqual({ kind: 'item', id: 'a2' });
expect(highlightAt(h, { trace: 1, index: 1 })).toEqual({ kind: 'group', id: 'B' });
expect(highlightAt(h, { trace: 0, index: 0 })).toBeUndefined();
});
it('agrupa los botones en filas: cada grupo seguido de sus categorías', () => {
expect(highlightRows(h).map(r => [r.group?.id, r.items.map(i => i.id)])).toEqual([['A', ['a1', 'a2']], ['B', ['b1']]]);
});
});
@@ -0,0 +1,117 @@
import { Modelo } from './indicadores-eu7-escenario';
import { PlotlyFigure } from './indicadores.models';
// Legend buttons that highlight one part of a figure, like CaCu's «Distribución de resultados
// citológicos»: the chosen group or category keeps its colour and everything else fades.
export interface HighlightPoint { trace: number; index: number; }
export interface HighlightEntry {
id: string; label: string; color: string;
// Shorter label for the button when it sits next to its group's button.
short?: string;
// Only for categories: the group they belong to (its button narrows the categories on offer).
group?: string;
points: readonly HighlightPoint[];
// Text for the centre of a donut while this entry is chosen.
center?: string;
}
export interface FigureHighlight {
groups: readonly HighlightEntry[];
items: readonly HighlightEntry[];
// Traces whose points fade when they are not part of the choice.
traces: readonly number[];
// Where a donut shows its centre text: a pie trace's single text, or a layout annotation.
center?: { trace: number } | { annotation: number };
// Name of the whole, for the status line.
allLabel: string;
}
export interface HighlightSelection { group?: string; item?: string; }
const FADED = .3;
// Accepts #RRGGBB and rgb()/rgba() (dona() already writes its colours as rgba).
function rgba(color: string, alpha: number): string {
const hex = /^#([0-9a-f]{6})$/i.exec(color);
if (hex) {
const [r, g, b] = [0, 2, 4].map(i => parseInt(hex[1].slice(i, i + 2), 16));
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
const rgb = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(color);
return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
}
export function highlightEntry(h: FigureHighlight, sel: HighlightSelection): HighlightEntry | undefined {
return sel.item ? h.items.find(e => e.id === sel.item) : sel.group ? h.groups.find(e => e.id === sel.group) : undefined;
}
export function highlightLabel(h: FigureHighlight, sel: HighlightSelection): string {
return highlightEntry(h, sel)?.label ?? h.allLabel;
}
// Same state machine as CaCu: choosing the chosen entry again goes back one step.
export function toggleHighlight(h: FigureHighlight, sel: HighlightSelection, kind: 'group' | 'item', id: string): HighlightSelection {
if (kind === 'group') return !h.groups.some(g => g.id === id) || sel.group === id ? {} : { group: id };
const item = h.items.find(e => e.id === id);
if (!item || (sel.group && item.group !== sel.group)) return sel;
return sel.item === id ? (sel.group ? { group: sel.group } : {}) : { ...(sel.group ? { group: sel.group } : {}), item: id };
}
// The entry a click on the figure means: a category first, otherwise a group.
export function highlightAt(h: FigureHighlight, point: HighlightPoint): { kind: 'group' | 'item'; id: string } | undefined {
const hit = (e: HighlightEntry) => e.points.some(p => p.trace === point.trace && p.index === point.index);
// A group also covers its categories' slices, so an outer slice hits both: the category wins.
const item = h.items.find(hit);
if (item) return { kind: 'item', id: item.id };
const group = h.groups.find(hit);
return group ? { kind: 'group', id: group.id } : undefined;
}
export function highlightFigure(figure: PlotlyFigure, h: FigureHighlight, sel: HighlightSelection): PlotlyFigure {
const entry = highlightEntry(h, sel);
if (!entry) return figure;
const keep = new Set(entry.points.map(p => p.trace + ':' + p.index));
// A chosen category also keeps its group's slice of the inner ring (not its sibling categories).
const group = entry.group ? h.groups.find(g => g.id === entry.group) : undefined;
const own = new Set(entry.points.map(p => p.trace));
group?.points.filter(p => !own.has(p.trace)).forEach(p => keep.add(p.trace + ':' + p.index));
const data = figure.data.map((trace, t) => {
if (!h.traces.includes(t)) return trace;
const marker = (trace['marker'] ?? {}) as Record<string, unknown>;
if (trace['type'] === 'pie') {
const colors = (marker['colors'] as unknown[] | undefined) ?? [];
return { ...trace, marker: { ...marker, colors: colors.map((c, i) => typeof c === 'string' && !keep.has(t + ':' + i) ? rgba(c, FADED) : c) } };
}
const count = Array.isArray(trace['x']) ? (trace['x'] as unknown[]).length : Array.isArray(trace['y']) ? (trace['y'] as unknown[]).length : 0;
return { ...trace, marker: { ...marker, opacity: Array.from({ length: count }, (_, i) => keep.has(t + ':' + i) ? 1 : FADED) } };
});
let layout = figure.layout;
if (entry.center !== undefined && h.center) {
if ('trace' in h.center) {
const t = h.center.trace;
data[t] = { ...data[t], text: [entry.center] };
} else {
const annotations = [...((layout['annotations'] as Record<string, unknown>[] | undefined) ?? [])];
if (annotations[h.center.annotation]) annotations[h.center.annotation] = { ...annotations[h.center.annotation], text: entry.center };
layout = { ...layout, annotations };
}
}
return { ...figure, data, layout };
}
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Buttons for a figure drawn by dona() (traces: 0 centre, 1 groups, 2 categories). A group also
// covers its categories' slices; the centre shows the count of the choice. `short` gives each
// category's button label next to its group (by default, its full label).
export function donaHighlight(m: Modelo, short: (id: string) => string | undefined = () => undefined): FigureHighlight {
const centre = (n: number, label: string) => '<b>' + n.toLocaleString('es-MX') + '</b><br>' + escape(label);
return { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
groups: m.grupos.map((g, gi) => {
const children = m.categorias.map((c, i) => ({ c, i })).filter(({ c }) => c.grupo === g.id);
return { id: g.id, label: g.etiqueta, color: g.color,
points: [{ trace: 1, index: gi }, ...children.map(({ i }) => ({ trace: 2, index: i }))],
center: centre(children.reduce((n, { c }) => n + (m.celdas[c.id].n ?? 0), 0), g.etiqueta) };
}),
items: m.categorias.map((c, i) => ({ id: c.id, label: c.etiqueta, short: short(c.id), color: c.color, group: c.grupo,
points: [{ trace: 2, index: i }], center: centre(m.celdas[c.id].n ?? 0, c.etiqueta) })) };
}
// Rows of buttons: each group followed by its categories; categories without a group share one row.
export function highlightRows(h: FigureHighlight): { group?: HighlightEntry; items: HighlightEntry[] }[] {
const rows = h.groups.map(group => ({ group, items: h.items.filter(i => i.group === group.id) }));
const loose = h.items.filter(i => !i.group || !h.groups.some(g => g.id === i.group));
return loose.length ? [...rows, { items: loose }] : rows;
}
@@ -0,0 +1,172 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
import { sortedPeriods } from './indicadores-periodos';
export interface HistoricoFigura {
figure: PlotlyFigure;
comoLeer: string;
suprimidos: string[];
sinDato: string[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'];
// «mar 2024» and «2024 S1»: a bare 2024-03 was read as a mix of months and years.
export function etiquetaPeriodo(periodo: string): string {
const [anio, resto] = periodo.split('-');
return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`;
}
export interface HistoricoOpciones {
// Same vertical scale across small charts, so their heights compare.
yMax?: number;
pequena?: boolean;
}
function validar(data: IndicadorDatos) {
for (const row of data.filas) {
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
}
return cronologico(data.periodos);
}
function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string, pequena = false) {
const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo);
const cada = pequena && periodos.length > 12 ? 6 : 3;
return {
autosize: true, height: pequena ? 340 : 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false },
// A label for every month does not fit: one per quarter is still readable with the full period on hover.
xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0,
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % cada === 0) },
yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false },
// Shaded, because an empty space alone reads as zero. Text below the figure says the same.
shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 },
x0: periodos.indexOf(periodo) - .5, x1: periodos.indexOf(periodo) + .5, fillcolor: C2_PALETTE.states.suppressed, opacity: .18 })),
};
}
// One polygon per run of consecutive values: a band must not bridge a gap in the line.
function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string) {
const x: (string | null)[] = [], y: (number | null)[] = [];
let run: number[] = [];
const cerrar = () => {
if (run.length) {
if (x.length) { x.push(null); y.push(null); }
x.push(...run.map(i => periodos[i]), ...[...run].reverse().map(i => periodos[i]));
y.push(...run.map(i => alto[i]), ...[...run].reverse().map(i => bajo[i]));
}
run = [];
};
periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); });
cerrar();
return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor: color + '40', line: { width: 0 }, hoverinfo: 'skip' };
}
// Separate rows from what is missing or suppressed; a period is judged by its only row.
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
const filas = new Map(data.filas.map(row => [row['periodo'] as string, row]));
if (filas.size !== data.filas.length) throw new Error('Filas ambiguas');
const suprimidos: string[] = [], sinDato: string[] = [];
const validas = periodos.map(periodo => {
const row = filas.get(periodo);
if (row?.['suprimido'] === 1) { suprimidos.push(periodo); return null; }
if (!row || !valor(row)) { sinDato.push(periodo); return null; }
return row;
});
return { validas, suprimidos, sinDato };
}
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
function porcentaje(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']));
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line;
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 },
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
suprimidos, sinDato,
};
}
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): HistoricoFigura {
const periodos = validar(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']));
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} pacientes` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => {
const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena);
return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout;
})() },
comoLeer: 'La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de los pacientes.',
suprimidos, sinDato,
};
}
// What each count means, for the indicators that don't count patients in the period.
const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
};
function conteo(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {};
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
for (const row of data.filas) {
const id = row['categoria'], key = JSON.stringify([id, row['periodo']]);
if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de histórico inválida');
celdas.set(key, row);
categorias.set(id, row['orden']);
}
const orden = [...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id);
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
return {
figure: { data: orden.map((id, i) => {
const meta = record(catalogo[id]) ? catalogo[id] : {};
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
return { type: 'bar', name: escape(typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? 'Pacientes'), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
comoLeer: CONTEOS[data.id]?.comoLeer ?? 'Cada barra es el total de pacientes del periodo, y sus partes muestran cuántos hay en cada categoría.',
suprimidos, sinDato,
};
}
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
// and medians do not, so those two are never stacked.
export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura {
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined;
if (!figura) throw new Error('Representación no soportada');
return { ...figura, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
}
// The share of cases still in process, from the case-status counts. Cases out of the protocol aren't in the base.
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data);
const n = (periodo: string, categoria: string) => {
const valor = data.filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria)?.['n'];
return numero(valor) ? valor : null;
};
const puntos = periodos.map(periodo => {
const proceso = n(periodo, 'EN_PROCESO'), completo = n(periodo, 'COMPLETO');
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
});
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
return {
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} casos` : ''),
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'De los casos completos o en proceso al cierre de cada periodo, el porcentaje que seguía en proceso. Los que quedaron fuera del protocolo no cuentan.',
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
};
}
@@ -0,0 +1,58 @@
import { Component, computed, inject, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { etiquetaPeriodo } from './indicadores-historico-figures';
import { TipoPeriodo } from './indicadores.models';
export interface PeriodosDialogoDatos { tipo: TipoPeriodo; periodos: readonly string[]; elegidos: readonly string[]; }
// The periods of the chosen analysis interval, by year. Closes with the chosen ones, oldest first, or with nothing if cancelled.
@Component({
selector: 'app-indicadores-historico-periodos',
imports: [MatButtonModule, MatCheckboxModule, MatDialogModule],
template: `
<h2 mat-dialog-title>Elegir {{ datos.tipo === 'mes' ? 'meses' : 'semestres' }}</h2>
<mat-dialog-content>
<div class="acciones">
<button type="button" mat-button (click)="elegidos.set(todos)">Elegir todos</button>
<button type="button" mat-button (click)="elegidos.set([])">Quitar todos</button>
</div>
@for (grupo of anios; track grupo.anio) {
<fieldset>
<legend>{{ grupo.anio }}</legend>
@for (periodo of grupo.periodos; track periodo) {
<mat-checkbox [checked]="elegidos().includes(periodo)" (change)="alternar(periodo)">{{ etiqueta(periodo) }}</mat-checkbox>
}
</fieldset>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<span class="cuenta" role="status">{{ cuenta() }}</span>
<button type="button" mat-button mat-dialog-close>Cancelar</button>
<button type="button" mat-flat-button [disabled]="!elegidos().length" (click)="aplicar()">Aplicar</button>
</mat-dialog-actions>
`,
styles: `
.acciones { display: flex; gap: .5rem; margin-bottom: .5rem; }
fieldset { display: grid; grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); gap: 0 .5rem; margin: 0 0 .75rem; padding: .25rem .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
legend { padding-inline: .25rem; font-weight: 600; }
.cuenta { margin-inline-end: auto; padding-inline-start: .75rem; font: var(--mat-sys-body-medium); }
`,
})
export class IndicadoresHistoricoPeriodos {
readonly datos = inject<PeriodosDialogoDatos>(MAT_DIALOG_DATA);
private readonly dialogo = inject<MatDialogRef<IndicadoresHistoricoPeriodos, string[]>>(MatDialogRef);
readonly etiqueta = etiquetaPeriodo;
readonly todos = [...this.datos.periodos];
readonly elegidos = signal<readonly string[]>(this.datos.elegidos);
readonly anios = [...new Set(this.todos.map(p => p.slice(0, 4)))].map(anio => ({ anio, periodos: this.todos.filter(p => p.startsWith(anio)) }));
readonly cuenta = computed(() => {
const n = this.elegidos().length, mes = this.datos.tipo === 'mes';
return n === 1 ? (mes ? '1 mes elegido' : '1 semestre elegido') : `${n} ${mes ? 'meses elegidos' : 'semestres elegidos'}`;
});
alternar(periodo: string) {
this.elegidos.update(actual => actual.includes(periodo) ? actual.filter(p => p !== periodo) : [...actual, periodo]);
}
aplicar() { this.dialogo.close(this.todos.filter(p => this.elegidos().includes(p))); }
}
@@ -0,0 +1,235 @@
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Subject } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
import { IndicadoresHistorico } from './indicadores-historico';
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
import { Indicador, IndicadorDatos } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const traza = (d: IndicadorDatos, i: number) => historicoFigura(d, 'claro').figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
const base = { id: 'i', tipo_periodo: 'mes' as const, periodos: ['2024-03', '2024-01', '2024-02'] };
const c1 = (periodo: string, valor: number | null, suprimido = 0) => ({ periodo, suprimido, valor, numerador: valor, denominador: valor === null ? null : 100,
ic_bajo: valor === null ? null : valor - 5, ic_alto: valor === null ? null : valor + 5 });
const c2 = (periodo: string, categoria: string, n: number | null, orden: number, suprimido = 0) => ({ periodo, categoria, n, orden, suprimido });
describe('Figuras de histórico', () => {
it('C2 apila conteos en orden cronológico, por categoría y con el color publicado', () => {
const data: IndicadorDatos = { ...base, contrato: 'C2', categorias: { B: { etiqueta: 'Bé <b>', color: '#112233' } }, filas: base.periodos.flatMap(p => [c2(p, 'B', 2, 1), c2(p, 'A', 1, 0)]) };
const { figure, suprimidos, sinDato } = historicoFigura(data, 'claro');
expect(figure.layout['barmode']).toBe('stack');
expect(figure.data.map(t => t['name'])).toEqual(['A', 'Bé &lt;b&gt;']);
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024', 'mar 2024']);
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Mes y año');
expect((figure.data[1]['marker'] as { color: string }).color).toBe('#112233');
expect(suprimidos).toEqual([]); expect(sinDato).toEqual([]);
});
it('C2 no dibuja como cero una celda suprimida y sombrea su periodo', () => {
const data: IndicadorDatos = { ...base, contrato: 'C2', filas: [c2('2024-01', 'A', 5, 0), c2('2024-02', 'A', null, 0, 1), c2('2024-03', 'A', 0, 0)] };
const { figure, suprimidos } = historicoFigura(data, 'claro');
expect(figure.data[0]['y']).toEqual([5, null, 0]);
expect(suprimidos).toEqual(['feb 2024']);
expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]);
});
it('C1 es una línea que no cruza huecos y su banda tampoco', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] };
const { suprimidos, figure } = historicoFigura(data, 'claro');
expect(traza(data, 1).y).toEqual([40, null, 60]);
expect(traza(data, 0).x).toEqual(['ene 2024', 'ene 2024', null, 'mar 2024', 'mar 2024']);
expect(traza(data, 0).y).toEqual([45, 35, null, 65, 55]);
expect(suprimidos).toEqual(['feb 2024']);
expect(figure.layout['barmode']).toBeUndefined();
expect((figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 100]);
});
it('C3r muestra la mediana con la banda entre cuartiles y distingue sin dato de suprimido', () => {
const data: IndicadorDatos = { ...base, periodos: ['2024-01', '2024-02'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
const { sinDato, suprimidos } = historicoFigura(data, 'claro');
expect(traza(data, 1).y).toEqual([20, null]);
expect(traza(data, 0).y).toEqual([30, 10]);
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
});
it('las líneas usan el verde legible en cada tema', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color;
expect(color('claro')).toBe('#6A8000'); expect(color('oscuro')).toBe('#A8C243');
});
it('escribe los periodos con mes y año', () => {
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
});
it('el porcentaje en proceso se calcula sobre completos y en proceso, sin los que quedaron fuera', () => {
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
fila('2024-01', 'COMPLETO', 10), fila('2024-01', 'EN_PROCESO', 30), fila('2024-01', 'FUERA_PROTOCOLO', 99),
fila('2024-02', 'COMPLETO', 30), fila('2024-02', 'EN_PROCESO', 10), fila('2024-02', 'FUERA_PROTOCOLO', 99)] }, 'claro');
expect(figure.data[0]['y']).toEqual([75, 25]);
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
});
it('una escala compartida fija el máximo de las medianas', () => {
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
});
it('M21 y M22 no usan verde en sus líneas', () => {
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
});
it('rechaza contratos sin representación y filas ambiguas', () => {
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
expect(() => historicoFigura({ ...base, contrato: 'C1', filas: [c1('2024-01', 1), c1('2024-01', 2)] }, 'claro')).toThrow('ambiguas');
});
});
describe('Pestaña Histórico', () => {
let http: HttpTestingController;
let fixture: ComponentFixture<IndicadoresHistorico>;
const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
const periodos = { id: 'm1', version: '1', periodos: [
{ periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
{ periodo: '2024-02', tipo: 'mes', report_id: 2, periodo_inicio: '2024-02-01', periodo_fin: '2024-03-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
{ periodo: '2024-S1', tipo: 'semestre', report_id: 3, periodo_inicio: '2024-01-01', periodo_fin: '2024-07-01', fecha_corte: '2024-08-01', generado_en: '2024-08-01T00:00:00+00:00' },
] };
const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
const datosUrl = '/tea/indicadores/m1/datos';
const render = () => { TestBed.tick(); fixture.detectChanges(); };
const datos_ = (tipo: string, ps: string[]) => datos(tipo, ps);
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
fixture = TestBed.createComponent(IndicadoresHistorico);
fixture.componentRef.setInput('dominio', 'tea');
fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro');
render();
});
afterEach(() => http.verify());
const abrir = () => {
fixture.componentRef.setInput('active', true); render();
http.expectOne('/tea/indicadores/m1/periodos').flush(periodos);
};
it('no consulta hasta abrir la pestaña y entonces pide todos los periodos de una vez', () => {
http.expectNone(() => true);
abrir();
const request = http.expectOne(r => r.url === datosUrl);
expect(request.request.params.get('periodos')!.split(',').sort()).toEqual(['2024-01', '2024-02']);
request.flush(datos('mes', ['2024-01', '2024-02'])); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a feb 2024 (2 meses)');
});
it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => {
abrir();
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
fixture.componentInstance.elegido.set('semestre'); render();
const semestre = http.expectOne(r => r.url === datosUrl);
expect(semestre.request.params.get('periodos')).toBe('2024-S1');
semestre.flush(datos('semestre', ['2024-S1'])); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)');
fixture.componentInstance.elegido.set('mes'); render();
fixture.componentRef.setInput('tema', 'oscuro'); render();
http.expectNone(() => true);
});
it('el selector ofrece pasos de cinco en la unidad elegida y recorta a los periodos más recientes sin consultar', () => {
const c = fixture.componentInstance;
const meses = Array.from({ length: 12 }, (_, i) => '2024-' + String(i + 1).padStart(2, '0'));
const semestres = ['2020-S1', '2020-S2', '2021-S1', '2021-S2', '2022-S1', '2022-S2'];
fixture.componentRef.setInput('active', true); render();
http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render();
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)', 'Personalizado…']);
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)');
c.elegirVentana(5); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)');
http.expectNone(() => true);
c.elegido.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render();
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']);
c.elegido.set('mes'); render();
expect(c.ventana()).toBe(5);
http.expectNone(() => true);
});
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
for (const { id } of items) {
const c2 = id.startsWith('M28');
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
filas: c2 ? [{ periodo: '2024-01', categoria: 'COMPLETO', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'EN_PROCESO', n: 1, orden: 1, suprimido: 0 }]
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
}
render();
const paneles = fixture.componentInstance.paneles();
expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']);
const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
});
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
const c = fixture.componentInstance;
const cerrar = new Subject<string[] | undefined>();
const abrir = vi.spyOn(TestBed.inject(MatDialog), 'open').mockReturnValue({ afterClosed: () => cerrar } as never);
abrir_();
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado…');
c.elegirVentana(-1);
const datos = abrir.mock.calls[0][1]!.data as PeriodosDialogoDatos;
expect(datos).toEqual({ tipo: 'mes', periodos: ['2024-01', '2024-02'], elegidos: ['2024-01', '2024-02'] });
// Cancelling changes nothing.
cerrar.next(undefined); render();
expect(c.ventana()).toBe(0);
c.elegirVentana(-1);
cerrar.next(['2024-02']); render();
expect(c.ventana()).toBe(-1);
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)');
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)');
// The other granularity keeps its own choice.
c.elegido.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render();
c.elegido.set('mes'); render();
expect(c.ventana()).toBe(-1);
http.expectNone(() => true);
});
it('avisa del error sin perder la pestaña y reintenta', () => {
abrir();
http.expectOne(r => r.url === datosUrl).flush({}, { status: 500, statusText: 'Error' }); render();
expect(fixture.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
fixture.nativeElement.querySelector('[role="alert"] button').click(); render();
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeNull();
expect(fixture.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
});
it('un indicador sin reportes del intervalo lo dice sin consultar sus datos', () => {
fixture.componentRef.setInput('active', true); render();
http.expectOne('/tea/indicadores/m1/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
http.expectNone(r => r.url === datosUrl);
expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados');
});
});
describe('Diálogo de periodos de Histórico', () => {
it('el diálogo agrupa por año, no aplica sin periodos y devuelve los elegidos en orden', () => {
const cierre = vi.fn();
TestBed.configureTestingModule({ providers: [{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'mes', periodos: ['2023-12', '2024-01', '2024-02'], elegidos: ['2024-02'] } }, { provide: MatDialogRef, useValue: { close: cierre } }] });
const dialogo = TestBed.createComponent(IndicadoresHistoricoPeriodos);
dialogo.detectChanges();
const root: HTMLElement = dialogo.nativeElement;
expect(Array.from(root.querySelectorAll('legend')).map(l => l.textContent)).toEqual(['2023', '2024']);
expect(root.textContent).toContain('dic 2023');
expect(root.querySelector('.cuenta')!.textContent).toBe('1 mes elegido');
const aplicar = Array.from(root.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Aplicar')!;
dialogo.componentInstance.elegidos.set([]); dialogo.detectChanges();
expect(aplicar.disabled).toBe(true);
dialogo.componentInstance.alternar('2024-01'); dialogo.componentInstance.alternar('2023-12'); dialogo.detectChanges();
aplicar.click();
expect(cierre).toHaveBeenCalledWith(['2023-12', '2024-01']);
});
});
@@ -0,0 +1,245 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatDialog } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
import { httpMessage } from './indicadores-http';
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { item: Pick<Indicador, 'id' | 'titulo' | 'contrato'>; rango?: string } & (
{ estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
const CASOS = 'M28_casos_por_estado';
const PERSONALIZADO = -1;
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
const listos = pasos.every(p => p?.estado === 'listo');
return paneles.flatMap((panel): Panel[] => {
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
}
if (listos && TIEMPOS.includes(panel.item.id)) return [];
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de casos en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
}
return [panel];
});
}
// Evolution of each indicator: the granularity and how many of the latest periods to show.
// Nothing is requested until the tab is first opened, and each granularity is requested once.
@Component({
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
<div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
</div>
<div class="paneles">
@for (panel of paneles(); track panel.item.id) {
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
<h2>{{ panel.item.titulo }}</h2>
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
@switch (panel.estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
@case ('error') {
<div role="alert"><p>{{ panel.mensaje }}</p>
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
}
@case ('listo') {
@if (panel.pasos; as pasos) {
<div class="pasos">
@for (paso of pasos; track paso.titulo) {
<section><h3>{{ paso.titulo }}</h3>
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
</section>
}
</div>
} @else {
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
}
<p class="nota">{{ panel.figura.comoLeer }}</p>
@if (panel.figura.suprimidos.length) {
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
}
}
</article>
}
</div>
`,
styles: `
:host { display: block; min-width: 0; }
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 1304px) { .paneles { 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 { 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; }
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
app-plotly-chart { margin-top: var(--issste-space-3); }
.panel.ancho { grid-column: 1 / -1; }
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
h3 { margin: 0; font: var(--mat-sys-title-small); }
mat-form-field { min-width: 18rem; }
`,
})
export class IndicadoresHistorico {
readonly dominio = input.required<Dominio>();
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.catalog().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
readonly tipo = computed<TipoPeriodo>(() => {
const elegido = this.elegido(), tipos = this.tipos();
return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes';
});
// How many of the latest periods to show, per granularity; 0 shows them all.
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
readonly PERSONALIZADO = PERSONALIZADO;
// The periods the user picked in the dialog, per granularity.
private readonly personalizados = signal<Partial<Record<TipoPeriodo, readonly string[]>>>({});
private readonly dialogo = inject(MatDialog);
private readonly selector = viewChild<MatSelect>('selector');
// Every period published for the granularity by any indicator.
private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {})
.flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : [])));
// The periods on screen, out of those an indicator publishes.
private recortar(periodos: readonly string[]) {
const orden = cronologico(periodos), ventana = this.ventana();
if (ventana !== PERSONALIZADO) return orden.slice(-ventana);
const elegidos = this.personalizados()[this.tipo()] ?? [];
return orden.filter(p => elegidos.includes(p));
}
private readonly service = inject(IndicadoresService);
private readonly periodos = inject(IndicadoresPeriodos);
private readonly cargas = signal<Partial<Record<TipoPeriodo, Record<string, Carga>>>>({});
private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>();
private solicitada?: string;
private catalogoCargado?: readonly Indicador[];
// Steps of five, up to what the indicator with the most periods has published.
readonly opciones = computed(() => {
const tipo = this.tipo();
const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0));
const opciones = [];
for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` });
const elegidos = this.personalizados()[tipo]?.length;
return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' },
...(total ? [{ valor: PERSONALIZADO, etiqueta: elegidos && this.ventana() === PERSONALIZADO ? `Personalizado (${elegidos} ${unidad(tipo, elegidos)})` : 'Personalizado…' }] : [])];
});
readonly paneles = computed<Panel[]>(() => {
const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema();
// Top of the shared scale: the highest third quartile of the steps, in the periods on screen.
const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => {
const carga = cargas?.[id];
if (carga?.estado !== 'listo') return [];
const visibles = this.recortar(carga.datos.periodos);
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
})) * 1.05;
const base: (Panel & { datos?: IndicadorDatos })[] = this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(item => {
const carga = cargas?.[item.id];
if (!carga) return { item, estado: 'cargando' };
if (carga.estado !== 'listo') return { item, ...carga };
const periodos = this.recortar(carga.datos.periodos);
if (!periodos.length) return { item, estado: 'vacio' };
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
try {
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
} catch (error) {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
});
return agrupar(base, tema);
});
constructor() {
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => {
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
});
effect(() => {
const tipo = this.tipo(), items = this.catalog();
if (!this.active() || !items.length) return;
untracked(() => {
if (this.catalogoCargado !== items) { this.catalogoCargado = items; this.cargas.set({}); this.solicitada = undefined; }
if (this.cargas()[tipo] || this.solicitada === tipo) return;
this.solicitada = tipo;
this.solicitudes.next({ tipo, items });
});
});
}
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
return this.periodos.periodos(this.dominio(), item.id).pipe(
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
switchMap((periodos): Observable<Carga> => periodos.length
? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos })))
: of({ estado: 'vacio' })),
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
}
elegirVentana(valor: number) {
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
}
abrirPersonalizado() {
const tipo = this.tipo(), periodos = this.disponibles();
// Starts from what's on screen, so the user only adjusts it.
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : periodos.slice(-this.ventana());
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
.afterClosed().subscribe(resultado => {
if (resultado?.length) {
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
}
// Cancelled, the selector goes back to what's on screen.
this.selector()?.writeValue(this.ventana());
});
}
reintentar() {
const tipo = this.tipo();
this.solicitada = tipo;
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
this.solicitudes.next({ tipo, items: this.catalog() });
}
}
@@ -10,19 +10,23 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorPeriodFilters } from './indicador-period-filters';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { pending } from './indicadores-memory'; import { pending } from './indicadores-memory';
import { Indicador } from './indicadores.models'; import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {} class ChartStub {}
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
// rules (indicador-kpi-panel.spec.ts covers all four).
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => { describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage; let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage;
const periods = ['2026-S2', '2026-S1', '2025-S2']; const periods = ['2026-S2', '2026-S1', '2025-S2'];
const definitions = KPI_BY_DOMAIN[domain]; const definitions = KPIS[domain];
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu'; const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })), const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }]; // Two figures, so every domain keeps an ordinary card whose representation can change.
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f', 'g'] }];
beforeEach(() => { beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
@@ -32,9 +36,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
http = TestBed.inject(HttpTestingController); http = TestBed.inject(HttpTestingController);
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
const inventory = http.match(r => r.url.endsWith('/periodos')); // The anchor shares the catalog inventory request; availability runs four at a time.
expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request. expect(flushPeriodos(() => [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })))).toBe(items.length);
inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
fixture.detectChanges(); fixture.detectChanges();
}); });
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
@@ -44,15 +47,37 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0, periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] }; valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
} }
function flushPeriodos(periodos: () => unknown[]) {
let flushed = 0;
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos'))) {
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() })); flushed += pending.length;
}
return flushed;
}
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); } function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } // 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(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
// The shared request queue runs four at a time: flushing a batch starts the next.
function flushPanels(period: string, expected = definitions.length - 1) { function flushPanels(period: string, expected = definitions.length - 1) {
const requests = http.match(r => r.url.endsWith('/datos')); let flushed = 0;
expect(requests).toHaveLength(expected); for (let requests = originalRequests(); requests.length; requests = originalRequests()) {
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); }); const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
flushed += requests.length;
}
expect(flushed).toBe(expected);
fixture.detectChanges(); fixture.detectChanges();
} }
function choose() { function choose() {
@@ -67,7 +92,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const ongoing = request(periods[0]); const ongoing = request(periods[0]);
for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) {
page.changeSection(section); fixture.detectChanges(); page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.initialPeriodState()).toBe('loading'); expect(page.initialPeriodState()).toBe('loading');
expect(ongoing.cancelled).toBe(false); expect(ongoing.cancelled).toBe(false);
http.expectNone(() => true); http.expectNone(() => true);
@@ -87,7 +112,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
editor().select([periods[2]]); fixture.detectChanges(); editor().select([periods[2]]); fixture.detectChanges();
for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
page.changeSection(section); fixture.detectChanges(); page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(editor().selectedPeriods).toEqual([periods[2]]);
expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g'); expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g');
@@ -108,27 +133,32 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => { it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => {
choose(); http.expectNone(r => r.url.includes('/figuras/')); choose(); http.expectNone(r => r.url.includes('/figuras/'));
cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); }); cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); });
// EU7 now owns a coordinated C2 view. This temporal fixture publishes only // EU7 and the CaCu paired times own coordinated views. This temporal fixture publishes
// placeholder f/g figures, so that card must stop as incompatible, without GET. // only placeholder f/g figures, so EU7 stops as incompatible without GET; the paired times
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true); // ask /datos for the same shared period, including the partner hidden from the catalog.
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length);
const tiempos = http.match(r => r.url.endsWith('/datos'));
// P0-C.1 cached the same lab payload; the paired figure reuses it.
expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(false);
for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); }
http.expectNone(() => true);
}); });
it('KPI secundarios sin datos no retroceden a otro periodo', () => { it('KPI secundarios sin datos no retroceden a otro periodo', () => {
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(definitions.length - 1); const requests = originalRequests(); expect(requests).toHaveLength(definitions.length - 1);
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); }); requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true); fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
}); });
it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => { it('aplicación manual posterior prevalece sin repetir la búsqueda', () => {
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true); choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] }); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
}); });
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => { it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
choose(); const applied = page.filters!.applied; choose(); const applied = page.filters!.applied;
page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true); page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true);
const card = cards().find(card => !card.isEu7)!; const card = cards().find(card => !card.isEu7 && !card.tiempos)!;
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1); card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1); card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true); expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
@@ -185,7 +215,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
expect(page.kpiIndicator(definitions[0].id)).toBeUndefined(); expect(page.kpiIndicator(definitions[0].id)).toBeUndefined();
expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges(); editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges();
http.match(r => r.url.endsWith('/datos')).forEach(r => { originalRequests().forEach(r => {
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0])); expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0]));
}); fixture.detectChanges(); }); fixture.detectChanges();
@@ -197,19 +227,19 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const catalogs = new Map<string, typeof items>([[domain, items]]); const catalogs = new Map<string, typeof items>([[domain, items]]);
for (const target of ['tea', 'cacu', 'cama'] as const) { for (const target of ['tea', 'cacu', 'cama'] as const) {
if (target === domain) continue; if (target === domain) continue;
const definitions = KPI_BY_DOMAIN[target]; const definitions = KPIS[target];
const period = own.size === 1 ? '2024-S2' : '2025-S1'; const period = own.size === 1 ? '2024-S2' : '2025-S1';
own.set(target, period); own.set(target, period);
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] })); const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
catalogs.set(target, catalog); catalogs.set(target, catalog);
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges(); page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges();
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] })); flushPeriodos(() => [{ periodo: period, tipo: 'semestre' }]);
const payload = (index: number) => { const payload = (index: number) => {
const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato; const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato;
value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value; value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value;
}; };
http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges(); http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges();
http.match(r => r.url.endsWith('/datos')).forEach(r => { originalRequests().forEach(r => {
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index)); const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index));
}); fixture.detectChanges(); }); fixture.detectChanges();
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] }); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] });
@@ -48,7 +48,8 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
if (domain === 'cama') { if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente'); expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6'); expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico']); expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_tasa_deteccion_histopatologica',
'cama_eu38a', 'cama_dias_resultado_diagnostico']);
} else expect(anchor.id).toBe('cacu_eu7'); } else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0])); const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
expect(run.selected()?.periodo).toBe(periods[0]); expect(run.selected()?.periodo).toBe(periods[0]);
@@ -74,7 +75,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
const run = start(); http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush('', { status: 404, statusText: 'Missing' }); const run = start(); http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush('', { status: 404, statusText: 'Missing' });
expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true); expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true);
}); });
it.each(['semestre', 'mes'] as const)('busca únicamente la granularidad activa %s, sin mezclar tipos ni usar un mes más reciente', tipo => { it.each(['semestre', 'mes'] as const)('busca únicamente el intervalo de tiempo activo %s, sin mezclar tipos ni usar un mes más reciente', tipo => {
const run = start(tipo); inventory(['2026-12', '2025-10', '2026-S1', '2025-S2']); const run = start(tipo); inventory(['2026-12', '2025-10', '2026-S1', '2025-S2']);
const expected = tipo === 'mes' ? '2026-12' : '2026-S1'; request(expected).flush(data(expected)); const expected = tipo === 'mes' ? '2026-12' : '2026-S1'; request(expected).flush(data(expected));
expect(run.selected()).toEqual({ periodo: expected, tipo }); http.expectNone(() => true); expect(run.selected()).toEqual({ periodo: expected, tipo }); http.expectNone(() => true);
@@ -129,7 +129,15 @@ const DATOS_2025_S2: Record<string, IndicadorDatos> = {
describe('KPI de CaMa con respuestas reales de WebApi', () => { describe('KPI de CaMa con respuestas reales de WebApi', () => {
const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 }; const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 };
const result = (index: number) => kpiResult(DATOS_2025_S2[KPI_BY_DOMAIN.cama[index].id], KPI_BY_DOMAIN.cama[index], 'cama', applied); // The card of each real answer; confirmación and tamizaje a diagnóstico are no longer cards, so theirs is
// built from the answer, to keep checking the C1 and C3r rules on real data.
const ids = Object.keys(DATOS_2025_S2);
const result = (index: number) => {
const data = DATOS_2025_S2[ids[index]];
const definition = KPI_BY_DOMAIN.cama.find(d => d.id === ids[index])
?? { id: data.id, title: data.id, contrato: data.contrato as 'C1' | 'C3r', unit: '' };
return kpiResult(data, definition, 'cama', applied);
};
it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => { it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => {
expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 })); expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 }));
@@ -140,6 +148,6 @@ describe('KPI de CaMa con respuestas reales de WebApi', () => {
}); });
it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => { it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => {
expect(result(2).state).toBe('Disponible'); expect(result(2).state).toBe('Disponible');
expect(result(2).info).toContain('El horizonte de 180 días es provisional.'); expect(result(2).info).toMatch(/^[\d.,]+ mastografías; Q1 a Q3: [\d.]+ a [\d.]+ días\.$/);
}); });
}); });
@@ -0,0 +1,138 @@
import { TestBed } from '@angular/core/testing';
import { Component, input } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter, ActivatedRoute } from '@angular/router';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos } from './indicadores.models';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { IndicadoresPage } from './indicadores-page';
import { PARES_TIEMPOS } from './indicadores-tiempos-pareados';
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
// Synthetic contract examples only; no value in these tests is a deployed clinical result.
const payload = (period = '2025-S1', extra: Record<string, unknown> = {}): IndicadorDatos => ({
id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period],
filas: [{ periodo: period, grupo: 'TOTAL', estrato: null, n: 20, q1: 7, mediana: 12, q3: 20, unidad: 'dias', suprimido: 0, ...extra }],
});
describe('P0-C.1: contrato de toma a resultado', () => {
const read = (data: IndicadorDatos) => kpiResult(data, CACU_RESULTADO_KPI, 'cacu', applied);
it('usa el ID del laboratorio del par, nunca la mediana de diagnóstico', () => {
expect(CACU_RESULTADO_KPI.id).toBe(PARES_TIEMPOS.find(p => p.dominio === 'cacu')!.reporte);
expect(read(payload())).toMatchObject({ state: 'Disponible', value: 12 });
expect(CACU_RESULTADO_KPI.unit).toBe('días (mediana)');
const diagnosis = { ...payload('2025-S1', { mediana: 52, q3: 90 }), id: KPI_BY_DOMAIN.cacu[1].id };
expect(read(diagnosis).state).toBe('Error de contrato');
expect(kpiResult(diagnosis, KPI_BY_DOMAIN.cacu[1], 'cacu', applied).value).toBe(52);
});
it.each([{ mediana: null }, { n: 0 }, { n: null }, { q1: null }, { unidad: 'meses' }, { q1: 15 }])('no inventa valor ante %j', extra => {
expect(read(payload('2025-S1', extra))).toEqual({ state: 'Sin valor disponible' });
});
it('cero publicado es válido, supresión nunca expone cuantiles ni conteo', () => {
expect(read(payload('2025-S1', { mediana: 0, q1: 0 })).value).toBe(0);
expect(read(payload('2025-S1', { suprimido: 1 }))).toEqual({ state: 'Dato oculto por tamaño' });
expect(read(payload('2025-S1', { suprimido: null })).value).toBeUndefined();
});
it('distingue vacío, periodo equivocado y selección no consolidable sin mezclar grupos o tipos', () => {
expect(read({ ...payload(), filas: [], periodos: [] }).state).toBe('Sin filas utilizables');
expect(read(payload('2025-S2')).state).toBe('Selección no consolidable');
expect(read(payload('2025-01')).state).toBe('Error de contrato');
expect(read({ ...payload(), filas: [...payload().filas, ...payload().filas] }).state).toBe('Selección no consolidable');
expect(read(payload('2025-S1', { estrato: 'grupo_edad' })).state).toBe('Selección no consolidable');
expect(kpiResult(payload(), CACU_RESULTADO_KPI, 'cacu', { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable');
});
});
describe('P0-C.1: transporte y periodo aplicado', () => {
let f: ReturnType<typeof TestBed.createComponent<IndicadorKpiPanel>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
f = TestBed.createComponent(IndicadorKpiPanel);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('definition', CACU_RESULTADO_KPI);
f.componentRef.setInput('applied', applied); f.detectChanges();
});
afterEach(() => { f.destroy(); http.verify(); });
const request = () => http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
it('reutiliza la consulta idéntica en vuelo y completada de la gráfica mediante snapshots', () => {
let received: IndicadorDatos | undefined;
const snapshots = TestBed.inject(IndicadoresSnapshots);
snapshots.datos('cacu', CACU_RESULTADO_KPI.id, 'semestre', ['2025-S1']).subscribe(data => received = data);
const r = request(); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(payload());
expect(received?.filas[0]['mediana']).toBe(12); expect(f.componentInstance.result().value).toBe(12);
f.componentRef.setInput('applied', { ...applied, revision: 2 }); f.detectChanges();
expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
});
it.each(['empty', '404', 'suppressed', 'error'] as const)('%s no dispara búsqueda de otro periodo', scenario => {
const r = request();
if (scenario === '404' || scenario === 'error') r.flush('private', { status: scenario === '404' ? 404 : 503, statusText: 'Unavailable' });
else r.flush(scenario === 'empty' ? { ...payload(), filas: [], periodos: [] } : payload('2025-S1', { suprimido: 1 }));
f.detectChanges();
expect(f.componentInstance.result().state).toBe({ empty: 'Sin filas utilizables', '404': 'Sin datos del periodo', suppressed: 'Dato oculto por tamaño', error: 'Error de consulta' }[scenario]);
expect(f.componentInstance.result().value).toBeUndefined(); expect(f.componentInstance.temporalReference).toBe('2025-S1');
expect(f.nativeElement.textContent).not.toContain('private'); http.expectNone(() => true);
});
it('la gráfica pareada comparte la petición en vuelo y conserva ambas series originales', () => {
const chart = TestBed.createComponent(IndicadorTiemposPareados);
try {
chart.componentRef.setInput('dominio', 'cacu'); chart.componentRef.setInput('tema', 'claro');
chart.componentRef.setInput('par', PARES_TIEMPOS.find(p => p.dominio === 'cacu')!);
chart.componentRef.setInput('indicador', { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', tipos_periodo: ['semestre'], figuras: ['fig_c3r_caja'] });
chart.componentRef.setInput('applied', applied); chart.detectChanges();
const lab = request(); expect(lab.request.params.get('periodos')).toBe('2025-S1');
lab.flush(payload());
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
chart.detectChanges();
expect(chart.componentInstance.figure!.data.map(series => series['name'])).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
expect(chart.componentInstance.figure!.data.map(series => series['median'])).toEqual([[12], [52]]);
expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
} finally { chart.destroy(); }
});
it('Todos y varios periodos no consultan; un mes consulta únicamente ese mes', () => {
const old = request();
for (const selection of [{ mode: 'todos' as const }, { mode: 'explicit' as const, periodos: ['2025-S1', '2025-S2'] as [string, ...string[]] }]) {
f.componentRef.setInput('applied', { ...applied, selection, revision: 2 }); f.detectChanges();
expect(f.componentInstance.result().state).toBe('Selección no consolidable'); http.expectNone(() => true);
}
expect(old.cancelled).toBe(true);
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 3 }); f.detectChanges();
const r = request(); expect(r.request.params.get('periodos')).toBe('2025-02'); r.flush(payload('2025-02'));
expect(f.componentInstance.result().value).toBe(12);
});
});
describe('P0-C.1: cinco tarjetas de oportunidad', () => {
it('conserva los originales, agrega laboratorio y deja ambos tratamientos inertes', () => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]),
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }] });
const f = TestBed.createComponent(IndicadoresPage), http = TestBed.inject(HttpTestingController);
try {
// The established lab partner is absent from this visible catalog, as in the paired figure.
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
http.expectOne(r => r.url.includes('/cacu_eu7/datos')).flush({ id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 20, suprimido: 0 }] });
f.detectChanges();
http.expectOne(r => r.url.includes('/cacu_eu_tiempo_reporte/datos')).flush(payload());
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
f.detectChanges();
const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
for (const card of cards.slice(3)) {
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
}
http.expectNone(() => true);
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
});
});
@@ -5,7 +5,9 @@ const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit'
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 }; const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 };
// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI. // Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI.
const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0], const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0],
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] }; { id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]],
// One card of each contract, in the C2, C1, C3r order the tests index by.
cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos { function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas }; const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
} }
@@ -21,10 +23,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6'); expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0'); expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
}); });
it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => { it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => {
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]); const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días'); expect(result.value).toBe(0);
if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional'); expect(result.info).toContain(domain === 'cacu' ? 'primer cuartil: 0 días; tercer cuartil: 7 días' : '0 a 7 días');
expect(result.info).not.toContain('provisional');
}); });
it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => { it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => {
expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' }); expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' });
@@ -54,12 +57,16 @@ it('categorías incompletas nunca producen un total parcial', () => {
expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined(); expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined();
}); });
it('TEA usa sus tres indicadores destacados y su grupo C1 es TOTAL', () => { it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([ expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([
['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r']]); ['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r'],
['M21_diagnosticados_con_eeg', 'C1'], ['M22_diagnosticados_sin_eeg', 'C1']]);
const eeg = data('tea', 3, [{ ...total, grupo: 'TOTAL', valor: 62.3, numerador: 71, denominador: 114 }]);
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con TEA positivo tienen un EEG ligado.');
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]); const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0', expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' }); info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state) expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
.toBe('Selección no consolidable'); .toBe('Selección no consolidable');
}); });
@@ -1,16 +1,35 @@
import { Dominio, IndicadorDatos } from './indicadores.models'; import { Dominio, IndicadorDatos } from './indicadores.models';
import { GlobalApplied } from './indicadores-memory'; import { GlobalApplied } from './indicadores-memory';
import { percentNumber } from './indicadores-format';
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } export interface KpiDefinition {
id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean;
// C1 only: replaces the domain's explanatory line when the numerator is not the domain's usual one.
c1Info?: (numerador: number, denominador: number) => string;
}
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
};
// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML // Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories // in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
// (patients), not the distribution. If a TOML title changes, change it here too, until the // (patients), not the distribution. If a TOML title changes, change it here too, until the
// cards read the `titulo` that the API already sends. // cards read the `titulo` that the API already sends.
// What only TEA's summary paragraph needs: case status and the time of each screening step.
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
{ id: 'M28_casos_por_estado', title: 'Casos iniciados', contrato: 'C2', unit: 'casos' },
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
];
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = { export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
tea: [ tea: [
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
{ id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' }, { id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' },
{ id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' }, { id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'M21_diagnosticados_con_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo tienen un EEG ligado.` },
{ id: 'M22_diagnosticados_sin_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo no tienen ningún EEG ligado.` },
], ],
cacu: [ cacu: [
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, { id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
@@ -18,8 +37,10 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
], ],
cama: [ cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
{ id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, { id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
{ id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.` },
{ id: 'cama_eu38a', title: 'Tiempo de tamizaje a resultado', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
], ],
}; };
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
@@ -29,12 +50,17 @@ const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => strin
cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`, cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`,
cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`, cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`,
}; };
const C2_INFO: Record<Dominio, string> = {
tea: 'Conteo de pacientes únicos en el periodo.',
cacu: 'Pacientes con citología tomada en el periodo.',
cama: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
};
const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = { const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = {
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`, tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
}; };
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; } export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; }
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0; const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' }; const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
@@ -42,6 +68,7 @@ const unscoped = { state: 'Selección no consolidable', info: 'Elige un único p
// C2 definitions count each patient once per period, in disjoint categories of TOTAL. // C2 definitions count each patient once per period, in disjoint categories of TOTAL.
// C1/C3r publish a single total row. Never combine totals, strata, or periods. // C1/C3r publish a single total row. Never combine totals, strata, or periods.
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult { export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) return unscoped;
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) { if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' }; return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
} }
@@ -68,12 +95,12 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
if (!rows.every(row => count(row['n']))) return empty; if (!rows.every(row => count(row['n']))) return empty;
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0); const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
if (!count(value)) return empty; if (!count(value)) return empty;
return { state: 'Disponible', value, info: 'Conteo de pacientes únicos en el periodo.' }; return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: C2_INFO[domain] };
} }
if (definition.contrato === 'C1') { if (definition.contrato === 'C1') {
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) }; return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(row['numerador'], row['denominador']) };
} }
if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
} }
@@ -68,7 +68,7 @@ describe('D.2 memoria global por dominio', () => {
it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => { it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => {
expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false); expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false);
}); });
it('adapter no transforma ni recorta y requiere primera granularidad para Todos', () => { it('adapter no transforma ni recorta y requiere el primer intervalo de tiempo para Todos', () => {
const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 }; const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 };
const snapshot = JSON.stringify(applied); const snapshot = JSON.stringify(applied);
expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true); expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true);
@@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason:
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility { export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' }; if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' }; if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite la granularidad ' + applied.tipo + ' del filtro general.' }; if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de análisis ' + (applied.tipo === 'mes' ? 'mensual' : 'semestral') + ' del filtro general.' };
const mode = applied.selection.mode; const mode = applied.selection.mode;
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos' if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
? 'Todos con reporte requiere semestre como primera granularidad publicada. Para meses elige periodos explícitos.' ? 'Todos con reporte requiere semestre como primer intervalo de análisis publicado. Para meses elige un periodo.'
: 'Los periodos del filtro general no son válidos para esta granularidad.' }; : 'Los periodos del filtro general no son válidos para este intervalo de análisis.' };
return { compatible: true }; return { compatible: true };
} }
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean { export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
@@ -1,7 +1,7 @@
import { Dominio, IndicadorMetadatos } from './indicadores.models'; import { Dominio, IndicadorMetadatos } from './indicadores.models';
// Existing WebApp explanations, shared by figures and the definitions section. // Editorial fallback for a figure whose metadata publishes no `como_leer`
// These are editorial guidance, not additional metadata supplied by WebApi. // (metadata not loaded yet, failed, or an older kit). Not WebApi metadata.
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = { const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
C1: [ C1: [
'El punto representa la proporción observada.', 'El punto representa la proporción observada.',
@@ -17,14 +17,15 @@ const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
}; };
export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.'; export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.';
export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined { // "Cómo leer" of a figure: the kit's `como_leer` when it publishes one, otherwise
const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId); // the generic guidance of the figure's contract.
if (!detail) return undefined; export function figureInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string,
const instructions = detail.como_leer ?? []; contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
return instructions.some(line => line.trim().length > 0) ? instructions : undefined; const instructions = metadata?.figuras_detalle?.find(item => item.figura === figureId)?.como_leer ?? [];
return instructions.some(line => line.trim().length > 0) ? instructions : contractInterpretation(contract, domain, pie);
} }
export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] { function contractInterpretation(contract: string | undefined, domain: Dominio, pie: boolean): readonly string[] {
if (contract === 'C2') return [ if (contract === 'C2') return [
pie pie
? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.' ? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.'
@@ -44,8 +44,8 @@ describe('UX-04 navegación Angular', () => {
const harness = await setup(); const harness = await setup();
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
load(domain, harness); harness.detectChanges(); load(domain, harness); harness.detectChanges();
// Our shell keeps the domain nav on the page itself, see indicadores-page.html. // Domain switching lives in the App header (app.spec.ts); the page must not add a second one.
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(3); expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(0);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => { it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
@@ -53,7 +53,7 @@ describe('UX-04 navegación Angular', () => {
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
load('tea', harness); harness.detectChanges(); load('tea', harness); harness.detectChanges();
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges(); (harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
control.year = '2025'; control.unit = 'S2'; control.add(); control.year = '2025'; control.unit = 'S2'; control.add();
@@ -62,7 +62,7 @@ describe('UX-04 navegación Angular', () => {
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
const req = load('tea', harness); const req = load('tea', harness);
expect(req.request.params.get('periodos')).toBe('2025-S1'); expect(req.request.params.get('periodos')).toBe('2025-S1');
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }); expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] });
expect(TestBed.inject(Router).url).toBe('/indicadores/tea'); expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
}); });
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => { it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
@@ -1,50 +0,0 @@
import { IndicadorDatos } from './indicadores.models';
export interface NumericRow { period: string; group: string; category: string; value: string; detail: string; state: string; }
const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);
function number(value: unknown, suffix = ''): string {
if (value === null) return 'Sin valor (nulo)';
return typeof value === 'number' && Number.isFinite(value) ? `${value}${suffix}` : 'No disponible';
}
function label(dictionary: unknown, key: unknown, fallback: string): string {
const entry = record(dictionary) && typeof key === 'string' ? dictionary[key] : undefined;
return typeof entry === 'string' ? entry : record(entry) && typeof entry['etiqueta'] === 'string' ? entry['etiqueta'] : fallback;
}
// Read published cells individually. No totals, reconstruction, statistical
// computation or conversion of missing/suppressed values into zero.
export function numericRows(data: IndicadorDatos): NumericRow[] {
return data.filas.map(row => {
const group = row['grupo'];
const groupName = group === 'TOTAL' || group === 'total' ? 'Total'
: label(data['grupos'], group, 'Grupo sin etiqueta publicada');
const stratum = row['estrato'];
const base = { period: typeof row['periodo'] === 'string' ? row['periodo'] : 'Periodo no disponible',
group: stratum == null ? groupName : `${groupName} · ${label(data['valores_estrato'], stratum, 'Estrato sin etiqueta publicada')}`,
category: label(data['categorias'], row['categoria'], row['categoria'] == null ? '—' : 'Categoría sin etiqueta publicada'),
value: 'No disponible', detail: '', state: 'Disponible' };
if (row['suprimido'] === 1 || row['suprimido'] === true) return { ...base, value: 'Dato suprimido', state: 'Dato suprimido' };
if (row['suprimido'] !== 0 && row['suprimido'] !== false) return { ...base, state: 'Estado de supresión no disponible' };
let primary: unknown;
if (data.contrato === 'C1') {
primary = row['valor'];
return { ...base, value: number(primary, ' %'), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible',
detail: `Intervalo publicado: ${number(row['ic_bajo'])} a ${number(row['ic_alto'])} %. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` };
}
if (data.contrato === 'C2') {
primary = row['n'];
const category = record(data['categorias']) ? data['categorias'][String(row['categoria'])] : undefined;
const parent = record(category) ? label(data['grupos_de_categoria'], category['grupo'], '') : '';
const unit = typeof row['unidad'] === 'string' ? row['unidad'] : typeof data['unidad'] === 'string' ? data['unidad'] : '';
return { ...base, category: [parent, base.category].filter(Boolean).join(' · '), value: number(primary),
state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible',
detail: [unit && `Unidad: ${unit}.`, Object.hasOwn(row, 'denominador') && `Denominador publicado: ${number(row['denominador'])}.`].filter(Boolean).join(' ') };
}
if (data.contrato === 'C3r') {
primary = row['mediana'];
const unit = row['unidad'] === 'dias' ? 'días' : typeof row['unidad'] === 'string' ? row['unidad'] : 'Unidad no disponible';
return { ...base, value: `Mediana: ${number(primary)} · ${unit}`, state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible',
detail: `Q1: ${number(row['q1'])}; Q3: ${number(row['q3'])}; n: ${number(row['n'])}.` };
}
return { ...base, state: 'Resumen no disponible para este indicador' };
});
}
@@ -1,222 +0,0 @@
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorFigureCard } from './indicador-figure-card';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { numericRows } from './indicadores-numeric-rows';
import { dualFigures } from './indicadores-dual-figures';
import { c2Fixture } from './indicadores-c2-adapter.testing';
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
const item: Indicador = { id: 'future_indicator', titulo: 'Distribución publicada', contrato: 'C2',
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre'], version: '2.0' };
// Representative MD-19 wire shapes: published C1 interval, C2 counts/category
// metadata and C3r quartiles. Only test data; never served as dashboard indicators.
function data(contract = 'C2'): IndicadorDatos {
return { id: item.id, contrato: contract, tipo_periodo: 'semestre', periodos: ['2025-S2'], version: '2.0',
categorias: { A: { etiqueta: 'Categoría publicada', grupo: 'g' } }, grupos_de_categoria: { g: 'Grupo de categorías' },
filas: [{ periodo: '2025-S2', grupo: 'TOTAL', categoria: 'A', suprimido: 0, n: 0,
valor: 0, numerador: 0, denominador: 20, ic_bajo: 0, ic_alto: 16.1, mediana: 4, q1: 2, q3: 7, unidad: 'dias' }] };
}
describe('MD-19 lecturas y celdas numéricas', () => {
it.each(['new_name', 'any_future_id'])('descubre doble representación de %s sin IDs de indicador', id => {
expect(dualFigures({ ...item, id })).toEqual(['fig_c2_donas', 'fig_c2_barras']);
expect(dualFigures({ ...item, id, contrato: 'C1' })).toEqual([]);
expect(dualFigures({ ...item, id, figuras: ['fig_c2_donas'] })).toEqual([]);
expect(dualFigures({ ...item, id, figuras: ['future_donut', 'future_bar'] })).toEqual([]);
});
it('C1 conserva cero, intervalo publicado y poblaciones sin recalcular Wilson', () => {
const row = numericRows(data('C1'))[0];
expect(row.value).toBe('0 %'); expect(row.state).toBe('Disponible');
expect(row.detail).toBe('Intervalo publicado: 0 a 16.1 %. Numerador: 0; denominador: 20.');
});
it('C2 conserva categorías, grupos y conteos; no suma poblaciones superpuestas', () => {
const sample = data(); sample['grupos'] = { other: 'Otra población' }; sample.filas.push({ ...sample.filas[0], grupo: 'other', n: 11 });
const rows = numericRows(sample);
expect(rows).toHaveLength(2); expect(rows.map(r => r.value)).toEqual(['0', '11']);
expect(rows[0].category).toBe('Grupo de categorías · Categoría publicada');
expect(rows[1].group).toBe('Otra población');
});
it('C3r sólo muestra mediana, Q1, Q3, n y unidad publicados', () => {
const row = numericRows(data('C3r'))[0];
expect(row.value).toBe('Mediana: 4 · días'); expect(row.detail).toBe('Q1: 2; Q3: 7; n: 0.');
expect(JSON.stringify(row)).not.toMatch(/bigote|extremo|min|max/);
});
it.each(['C1', 'C2', 'C3r'])('%s nunca revela valores de una fila suprimida ni reconstruye totales', contract => {
const sample = data(contract); sample.filas[0]['suprimido'] = 1;
const row = numericRows(sample)[0]; expect(row.value).toBe('Dato suprimido'); expect(row.detail).toBe('');
expect(row.state).toBe('Dato suprimido');
});
it('distingue null, ausencia, NaN, cero y supresión desconocida', () => {
const sample = data();
sample.filas = [null, undefined, NaN, 0].map(n => ({ periodo: '2025-S2', grupo: 'TOTAL', n, suprimido: 0 }));
expect(numericRows(sample).map(r => r.value)).toEqual(['Sin valor (nulo)', 'No disponible', 'No disponible', '0']);
delete sample.filas[0]['suprimido']; expect(numericRows(sample)[0].value).toBe('No disponible');
expect(numericRows(sample)[0].state).toContain('supresión no disponible');
});
});
describe('snapshots compartidos y resumen accesible', () => {
let http: HttpTestingController, snapshots: IndicadoresSnapshots;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots);
});
afterEach(() => http.verify());
const request = () => http.expectOne(r => r.url.endsWith('/datos'));
it('deduplica datos simultáneos de KPI, panel y tabla, y reutiliza payload terminado', () => {
const queries = TestBed.inject(IndicadoresKpiQueries);
const values: IndicadorDatos[] = [];
queries.datos('tea', item.id, applied.tipo, '2025-S2', item.version).subscribe(value => values.push(value));
snapshots.read('tea', item, applied).subscribe();
snapshots.datos('tea', item.id, applied.tipo, ['2025-S2'], item.version).subscribe(value => values.push(value));
request().flush(data()); expect(values).toHaveLength(2); expect(values[0]).toBe(values[1]);
snapshots.read('tea', item, { ...applied, revision: 2 }).subscribe(); http.expectNone(() => true);
expect(snapshots.numeric().get(snapshotKey('tea', item, { ...applied, revision: 2 }))?.status).toBe('ready');
});
it('incluye dominio, versión, tipo, selección y revisión en identidad', () => {
const keys = [snapshotKey('tea', item, applied), snapshotKey('cama', item, applied),
snapshotKey('tea', { ...item, version: '3.0' }, applied), snapshotKey('tea', item, { ...applied, revision: 2 }),
snapshotKey('tea', item, { ...applied, tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01'] } }),
snapshotKey('tea', item, { ...applied, selection: { mode: 'todos' } })];
expect(new Set(keys).size).toBe(keys.length);
});
it('registra la identidad de versión publicada aunque el catálogo no la exponga', () => {
const unversioned = { ...item, version: undefined };
snapshots.read('tea', unversioned, applied).subscribe(); request().flush(data());
const alias = snapshots.numeric().get(snapshotKey('tea', unversioned, applied));
expect(alias?.sourceKey).toBe(snapshotKey('tea', item, applied));
expect(snapshots.numeric().get(alias!.sourceKey!)).toBe(alias);
});
it('reutiliza en la tabla los detalles de datos consultados por un KPI, sin activar figuras', () => {
TestBed.inject(IndicadoresKpiQueries).datos('tea', item.id, 'semestre', '2025-S2', item.version).subscribe();
request().flush(data());
expect(snapshots.reading('tea', item, applied)?.data).toEqual(data()); http.expectNone(() => true);
});
it('cancelar una lectura compartida conserva al otro consumidor; cancelar todos aborta HTTP', () => {
const a = snapshots.read('tea', item, applied).subscribe(), b = snapshots.read('tea', item, applied).subscribe();
const pending = request(); a.unsubscribe(); expect(pending.cancelled).toBe(false);
b.unsubscribe(); expect(pending.cancelled).toBe(true);
snapshots.read('tea', item, applied).subscribe(); request().flush(data());
});
it.each([404, 503])('conserva error HTTP %s y permite reintento sin cachear el error', status => {
snapshots.read('tea', item, applied).subscribe(); request().flush({}, { status, statusText: 'Failure' });
expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error');
snapshots.read('tea', item, applied).subscribe(); request().flush(data());
expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready');
});
it.each(['period', 'contract', 'version', 'row'])('rechaza respuesta incompatible por %s', kind => {
snapshots.read('tea', item, applied).subscribe(); const sample = data();
if (kind === 'period') sample.periodos = ['2024-S1'];
if (kind === 'contract') sample.contrato = 'C1';
if (kind === 'version') sample['version'] = '1.0';
if (kind === 'row') sample.filas[0]['periodo'] = '2024-S1';
request().flush(sample); expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error');
});
it('tabla reutiliza exactamente KPI, cambia periodo/dominio sin mostrar valores anteriores y respeta catálogo retirado', () => {
const fixture = TestBed.createComponent(IndicadoresNumericSummary);
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied);
fixture.componentRef.setInput('kpis', [{ id: item.id, title: 'Destacado publicado', unit: '%', contrato: 'C1' }]);
snapshots.publishKpi('tea', item, applied, { value: '42.0', unit: '%', state: 'Disponible', period: '2025-S2', info: 'Nota publicada' });
fixture.detectChanges(); let element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('.kpi-reading')?.textContent?.replace(/\s+/g, ' ')).toContain('42.0 %');
expect(element.querySelector('.kpi-reading')?.textContent).toContain('2025-S2');
expect(element.querySelector('.kpi-reading')?.textContent).toContain('Nota publicada');
expect(element.querySelector('caption')).toBeTruthy(); expect(element.querySelectorAll('thead th[scope="col"]')).toHaveLength(5);
expect(element.querySelector('.table-scroll')?.getAttribute('tabindex')).toBe('0'); http.expectNone(() => true);
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } });
fixture.detectChanges(); expect(element.textContent).not.toContain('42.0'); expect(element.textContent).toContain('2026-S1');
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
expect(element.textContent).not.toContain('42.0');
fixture.componentRef.setInput('catalog', []); fixture.detectChanges(); expect(element.querySelectorAll('tbody tr')).toHaveLength(0);
fixture.destroy();
});
it('tabla distingue carga, error y vacío publicado sin volver a consultar', () => {
const fixture = TestBed.createComponent(IndicadoresNumericSummary);
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied);
snapshots.read('tea', item, applied).subscribe(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando…');
request().flush({}, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Error de consulta');
snapshots.read('tea', item, applied).subscribe(); request().flush({ ...data(), filas: [] }); fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Sin filas publicadas'); http.expectNone(() => true); fixture.destroy();
});
});
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
describe('card doble, jerarquía y carga numérica diferida', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorCatalogCard>>, http: HttpTestingController, snapshots: IndicadoresSnapshots;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots);
fixture = TestBed.createComponent(IndicadorCatalogCard);
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', item);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const panels = () => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(el => el.componentInstance as IndicadorFigurePanel);
function activate() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
const figure = (id: string) => http.expectOne(r => r.url.endsWith('/figuras/' + id));
it('dos paneles sin selector redundante, diferidos hasta activación y con mismo periodo aplicado', () => {
expect(panels()).toHaveLength(2); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); http.expectNone(() => true);
activate();
const pending = http.expectOne(r => r.url.endsWith('/datos'));
expect(pending.request.params.get('periodos')).toBe('2025-S2'); pending.flush({ ...c2Fixture(), id: item.id });
expect(panels().every(p => p.result().source === 'datos')).toBe(true);
expect(fixture.nativeElement.classList.contains('dual-card')).toBe(true);
expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']);
http.expectNone(() => true);
});
it('drill-down filtra la presentación de barras y restaurar recupera la distribución sin alterar JSON ni consultar', () => {
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges();
const bars = structuredClone(panels()[1].result().figure);
const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard);
const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result();
const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf<HTMLButtonElement>].find(button => button.textContent?.trim() === 'G2')!;
parentButton.click(); fixture.detectChanges(); expect(cards[0].activeParent).toBe('G2');
expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B', 'C']);
expect(panels()[1].result().figure).toBe(barState.figure); expect(panels()[1].result().figure).toEqual(bars);
cards[0].selectCategory('B'); fixture.detectChanges();
expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B']);
(fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges();
expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before);
expect(panels()[1].result().presentationFigure).toEqual(barState.presentationFigure); http.expectNone(() => true);
});
it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => {
snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true);
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges();
expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready');
snapshots.expanded.set(false); fixture.detectChanges(); snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true);
});
it('cambio de periodo cancela ambas figuras y números; fuera de vista difiere el siguiente aplicado', () => {
snapshots.expanded.set(true); activate(); const old = [http.expectOne(r => r.url.endsWith('/datos'))];
fixture.componentInstance.setVisible(false); fixture.detectChanges();
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges();
expect(old.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().status === 'deferred')).toBe(true);
http.expectNone(() => true);
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...data(), periodos: ['2026-S1'], filas: [] });
for (const id of ['fig_c2_donas', 'fig_c2_barras']) {
const pending = figure(id); expect(pending.request.params.get('periodos')).toBe('2026-S1'); pending.flush({ data: [], layout: {} });
}
});
it('conserva preferencias y opciones adicionales; desaparece representación retirada y hace fallback', () => {
const memory = TestBed.inject(IndicadoresMemory); memory.rememberFigure('tea', item.id, 'fig_c2_barras');
fixture.componentRef.setInput('indicador', { ...item, figuras: [...item.figuras, 'future_representation'] }); fixture.detectChanges();
expect(fixture.componentInstance.isDual).toBe(true); expect(memory.figure('tea', item.id)).toBe('fig_c2_barras');
fixture.componentInstance.selectFigure('future_representation'); fixture.detectChanges();
expect(fixture.componentInstance.displayFigures).toEqual(['future_representation']);
fixture.componentRef.setInput('indicador', { ...item, figuras: ['fig_c2_donas'] }); fixture.detectChanges();
expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas']); expect(fixture.nativeElement.querySelector('mat-select')).toBeTruthy(); http.expectNone(() => true);
});
});
@@ -1,88 +0,0 @@
import { Component, inject, Input, OnDestroy } from '@angular/core';
import { Dominio, Indicador } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { KpiDefinition } from './indicadores-kpi';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { numericRows } from './indicadores-numeric-rows';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
@Component({
selector: 'app-indicadores-numeric-summary',
template: `
<details (toggle)="toggle($event)">
<summary><h2>Resumen de indicadores</h2></summary>
<p>Valores publicados para {{ period }}. Los detalles se cargan al consultar las gráficas correspondientes. Cada fila conserva su periodo y población; no se suman grupos ni periodos.</p>
<div class="table-scroll" role="region" aria-label="Resultados numéricos de indicadores" tabindex="0">
<table>
<caption>Resultados de indicadores destacados y gráficas consultadas</caption>
<thead><tr><th scope="col">Indicador</th><th scope="col">Periodo</th><th scope="col">Grupo / categoría</th><th scope="col">Resultado</th><th scope="col">Estado y notas</th></tr></thead>
<tbody>
@for (definition of kpis; track definition.id) {
@let item = find(definition.id);
@if (item) {
@let kpi = snapshots.kpis().get(key(item));
<tr class="kpi-reading"><th scope="row">{{ definition.title }} <span class="kind">Destacado</span></th>
<td>{{ kpi?.period ?? period }}</td><td>—</td>
<td>{{ kpi?.value ?? 'No disponible' }} @if (kpi?.value !== undefined) { {{ kpi?.unit }} }</td>
<td>{{ kpi?.state ?? 'Pendiente de lectura' }} {{ kpi?.info }} {{ kpi?.notes?.join(' ') }}</td></tr>
}
}
@for (item of catalog; track item.id) {
@let reading = snapshots.reading(dominio, item, figureSelection(item));
@let compatible = compatibility(item);
@if (compatible.compatible && reading?.status === 'ready' && reading?.data; as data) {
@for (row of rows(data); track $index) {
<tr><th scope="row">{{ item.titulo }}</th><td>{{ row.period }}</td><td>{{ row.group }} · {{ row.category }}</td>
<td>{{ row.value }} <span class="detail">{{ row.detail }}</span></td><td>{{ row.state }} {{ data.notas?.join(' ') }}</td></tr>
} @empty {
<tr><th scope="row">{{ item.titulo }}</th><td>{{ figurePeriod(item) }}</td><td>—</td><td>Sin filas publicadas</td><td>{{ data.notas?.join(' ') }}</td></tr>
}
} @else {
<tr><th scope="row">{{ item.titulo }}</th><td>{{ figurePeriod(item) }}</td><td>—</td><td>No disponible</td>
<td>{{ !compatible.compatible ? compatible.reason : reading?.status === 'loading' ? 'Cargando…' : reading?.status === 'error' ? 'Error de consulta: ' + reading?.message : 'Pendiente: consulta la gráfica para cargar sus números.' }}
@if (reading?.status === 'error') { <button type="button" (click)="snapshots.retries.update(increment)" [attr.aria-label]="'Reintentar números de ' + item.titulo">Reintentar</button> }</td></tr>
}
}
</tbody>
</table>
</div>
</details>`,
styles: `
:host { display: block; min-width: 0; margin-top: var(--issste-space-6); }
details { border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); padding: 1rem; }
summary { cursor: pointer; min-height: 44px; align-content: center; }
h2 { display: inline; font-family: var(--issste-font-heading); font-size: 1.5rem; }
p, td, th { overflow-wrap: anywhere; }
p, .kind, .detail { color: var(--issste-text-secondary); }
.kind, .detail { display: block; font-weight: normal; }
.table-scroll { overflow-x: auto; max-height: 32rem; }
table { width: 100%; border-collapse: collapse; font-size: .9rem; }
caption { text-align: left; padding: .5rem; }
th, td { padding: .65rem; border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; min-width: 6rem; }
thead { background: var(--issste-surface); position: sticky; top: 0; }
button { min-height: 44px; font: inherit; color: var(--issste-text); background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -2px; }
@media (max-width: 550px) { details { padding: .5rem; } th, td { padding: .5rem; } }
`,
})
export class IndicadoresNumericSummary implements OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) catalog: readonly Indicador[] = [];
@Input({ required: true }) applied!: GlobalApplied;
@Input() kpis: readonly KpiDefinition[] = [];
readonly snapshots = inject(IndicadoresSnapshots);
readonly rows = numericRows;
readonly increment = (value: number) => value + 1;
get period() { return describePeriods(this.applied.tipo, this.applied.selection); }
key(item: Indicador) { return snapshotKey(this.dominio, item, this.applied); }
find(id: string) { return this.catalog.find(item => item.id === id); }
figureSelection(item: Indicador) { return figureApplied(this.dominio, item.id, this.applied); }
figurePeriod(item: Indicador) {
const selection = this.figureSelection(item);
return (independentFigurePeriods(this.dominio, item.id) ? 'Selección independiente: ' : '')
+ describePeriods(selection.tipo, selection.selection);
}
compatibility(item: Indicador) { return filterCompatibility(this.figureSelection(item), item.tipos_periodo); }
toggle(event: Event) { this.snapshots.expanded.set((event.target as HTMLDetailsElement).open); }
ngOnDestroy() { this.snapshots.expanded.set(false); }
}
@@ -1,17 +1,15 @@
<section class="dashboard" aria-labelledby="dashboard-title"> <section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
<header> <header>
<span class="domain">Dominio {{ domainLabels[dominio] }} · Investigación</span> @if (fichaPacienteAbierta()) {
<h1 id="dashboard-title">Dashboard de indicadores</h1> <h1 id="dashboard-title">Ficha del paciente</h1>
<p>Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.</p> <p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
</header> } @else {
<!-- Upstream moved domain switching into its own app shell's header (a <span class="domain">{{ domainTitles[dominio] }}, investigación</span>
dropdown in app.ts/app.html); our shell is shared with other workspace <h1 id="dashboard-title">Indicadores</h1>
sections (Conectar, Gobernanza) so it stays here instead, same as before. --> <p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
<nav aria-label="Dominios de indicadores" class="domain-nav">
@for (domain of dominios; track domain) {
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainLabels[domain] }}</a>
} }
</nav> </header>
@if (!fichaPacienteAbierta()) {
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)"> <div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
@for (section of sections; track section.id) { @for (section of sections; track section.id) {
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id" <button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
@@ -19,12 +17,13 @@
(click)="changeSection(section.id)">{{ section.label }}</button> (click)="changeSection(section.id)">{{ section.label }}</button>
} }
</div> </div>
}
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'"> <div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
@if (!catalogLoading() && filters; as state) { @if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio"> <section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2> <h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p> <p class="section-description">{{ dominio === 'tea' ? 'Se aplica a las figuras y los indicadores destacados.' : 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' }}</p>
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked" <app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()" (retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" /> (edited)="editFilters()" (apply)="applyFilters()" />
@@ -45,16 +44,20 @@
} @else if (initialPeriodState() === 'manual') { } @else if (initialPeriodState() === 'manual') {
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p> <p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
} }
@let kpis = availableKpis; @let kpis = opportunityKpis;
@if (kpis.length && !initialPeriodBlocked) { @if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio"> <section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2> @let resumen = teaResumenPeriodo;
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 1 : 0)"> <h2 id="kpi-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
@for (definition of kpis; track dominio + ':' + definition.id) { @for (definition of kpis; track dominio + ':' + definition.id) {
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)" <app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" /> [applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
} }
@if (dominio === 'cacu') { @if (dominio === 'cacu') {
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" /> <app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
} }
</div> </div>
@@ -63,9 +66,9 @@
<section class="graphic-section" aria-labelledby="graphic-section-title"> <section class="graphic-section" aria-labelledby="graphic-section-title">
<div class="catalog-heading"> <div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2> <h2 id="graphic-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
@if (!catalogLoading() && !catalogError() && catalog().length) { @if (!catalogLoading() && !catalogError() && catalog().length) {
<p class="catalog-count" role="status">{{ catalog().length }} indicadores publicados</p> <p class="catalog-count" role="status">{{ catalogOrder().length }} indicadores publicados</p>
} }
</div> </div>
@if (catalogLoading()) { @if (catalogLoading()) {
@@ -82,38 +85,49 @@
<div class="catalog-search"> <div class="catalog-search">
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Buscar indicadores</mat-label> <mat-label>Buscar indicadores</mat-label>
<input #searchInput matInput type="search" [ngModel]="searchQuery()" (ngModelChange)="changeSearchQuery($event)" <mat-select #indicatorSelect multiple panelClass="indicator-select-panel" [ngModel]="selectedIndicators()" (ngModelChange)="changeIndicatorSelection($event)" aria-describedby="catalog-search-result">
placeholder="Título o identificador" aria-describedby="catalog-search-help catalog-search-result" /> <mat-select-trigger><span class="select-value">{{ selectionSummary() }}</span></mat-select-trigger>
<button mat-icon-button matIconSuffix type="button" (click)="clearSearch()" [disabled]="!searchQuery()" @for (item of catalogOrder(); track item.id) {
aria-label="Limpiar búsqueda"><mat-icon aria-hidden="true">close</mat-icon></button> <mat-option [value]="item.id"><span class="option-row"><span class="option-title">{{ item.titulo }}</span>
<mat-hint id="catalog-search-help">Las coincidencias aparecen primero; todos los indicadores siguen visibles.</mat-hint> <a class="option-go" [href]="'#' + cardElementId(item)" (click)="goToIndicator(item.id, $event)"
[attr.aria-label]="'Ir a ' + item.titulo">Ir</a></span></mat-option>
}
</mat-select>
</mat-form-field> </mat-form-field>
<button mat-stroked-button type="button" (click)="showAllIndicators()" [disabled]="indicatorSelection() === null">Mostrar todos</button>
</div> </div>
<p id="catalog-search-result" class="search-result"> <p id="catalog-search-result" class="search-result" role="status">
@if (searchResults().active) { Mostrando {{ searchResults().items.length }} de {{ catalogOrder().length }} indicadores.
@if (searchResults().count) {
{{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles.
} @else {
No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero.
}
}
</p> </p>
} }
@if (!searchResults().items.length) {
<p class="state" role="status">No hay indicadores seleccionados. Elige al menos uno en «Buscar indicadores».</p>
}
@if (dominio === 'tea') {
<div class="reporte-acciones">
<button mat-stroked-button type="button" [disabled]="preparandoReporte()" (click)="descargarReporte()">{{ preparandoReporte() ? 'Preparando reporte…' : 'Descargar reporte' }}</button>
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
</div>
}
<div class="catalog-grid"> <div class="catalog-grid">
@for (item of searchResults().items; track cardIdentity(item)) { @for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)" <app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> [pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
} }
</div> </div>
} }
</section> </section>
@if (!initialPeriodBlocked && filters && !catalogLoading() && !catalogError() && catalog().length) {
<app-indicadores-numeric-summary [dominio]="dominio" [catalog]="catalog()" [applied]="filters.applied" [kpis]="availableKpis" />
}
</div> </div>
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-seguimiento" tabindex="0" [hidden]="activeSection() !== 'seguimiento'"> @if (conHistorico) {
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'" /> <section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
</section>
}
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
</section> </section>
<section id="panel-datos" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-datos" tabindex="0" [hidden]="activeSection() !== 'datos'"> <section id="panel-datos" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-datos" tabindex="0" [hidden]="activeSection() !== 'datos'">
@@ -4,66 +4,51 @@
// The workspace shell clips overflow, so the page scrolls itself. // The workspace shell clips overflow, so the page scrolls itself.
:host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); } :host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); }
.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; } .dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
h1 { font: var(--mat-sys-headline-large); font-family: var(--issste-font-heading); font-weight: 700; margin: .65rem 0; } h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); } .domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
// Kept here (not moved to our app shell, see the template comment above the
// nav) -- same rules as before upstream relocated its own copy into app.scss.
.domain-nav {
display: flex;
flex-wrap: wrap;
gap: var(--issste-space-2);
padding: var(--issste-space-2);
justify-content: center;
margin: var(--issste-space-4) 0;
border-radius: var(--issste-radius);
}
.domain-nav a {
flex: 0 1 6rem;
max-width: 10rem;
color: var(--issste-text);
border: 1px solid var(--issste-border);
background: var(--issste-surface);
min-height: 44px;
border-radius: var(--issste-radius);
}
.domain-nav a[aria-current='page'] {
background: var(--issste-accent);
font-weight: 700;
text-decoration: none;
}
@media (max-width: 550px) {
.domain-nav { gap: var(--issste-space-2); padding-inline: 0; }
}
.state { padding: 1.25rem; margin: 0; } .state { padding: 1.25rem; margin: 0; }
.section-title { font-family: var(--issste-font-heading); font-size: 1.5rem; line-height: 1.3; margin: 0; overflow-wrap: anywhere; } .section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; } .section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
.kpi-section, .graphic-section { min-width: 0; } .kpi-section, .graphic-section { min-width: 0; }
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); } .graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
// Every card of a row of cards is as tall as the tallest one.
.kpi-grid { grid-auto-rows: 1fr; }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
.catalog-grid { align-items: stretch; } .catalog-grid { align-items: stretch; }
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; } .catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); } .catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; } .catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.catalog-search { display: flex; justify-content: flex-end; margin-top: var(--issste-space-4); } .catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); }
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; } .catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
.catalog-search button { width: 48px; height: 48px; } .catalog-search button { min-height: 48px; }
.catalog-search button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; }
// Keep search semantics; Material supplies the single accessible clear control.
.catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right; .search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right;
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); } overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } } @container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 550px) { @media (max-width: 550px) {
h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); } h1 { font-size: 1.5rem; }
} }
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; } .global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
.global-filters .section-title { font-size: 1rem; }
.global-filters .section-description { margin: var(--issste-space-1) 0 var(--issste-space-2); font: var(--mat-sys-body-small); }
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } @container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
// Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids.
.kpi-section[data-domain='cacu'] .kpi-grid {
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
align-items: stretch;
}
// Cáncer de mama's four cards: one size, four in a row on wide screens and two by two below.
@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1); .section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border); border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
background: var(--issste-surface); padding: var(--issste-space-2) var(--issste-space-2) 0; background: var(--issste-surface); padding: var(--issste-space-2) var(--issste-space-2) 0;
@@ -6,6 +6,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page'; import { IndicadoresPage } from './indicadores-page';
import { IndicadoresTracking } from './indicadores-tracking';
import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigureCard } from './indicador-figure-card';
@@ -51,6 +52,22 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
.toEqual([]); .toEqual([]);
http.expectNone(r => r.url.endsWith('/datos')); http.expectNone(r => r.url.endsWith('/datos'));
}); });
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
load();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de TEA');
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
expect(page.activeSection()).toBe('resumen');
http.expectNone(() => true);
});
it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(page.catalogLoading()).toBe(true); expect(page.catalogLoading()).toBe(true);
@@ -74,9 +91,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true); expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true);
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>; const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']); expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
const summary = fixture.nativeElement.querySelector('app-indicadores-numeric-summary') as HTMLElement; // Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página.
expect(sections[1].compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull();
expect(summary.textContent).toContain('Resumen de indicadores');
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados');
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right'); expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
toggle(0); toggle(1); flushAll(); toggle(0); toggle(1); flushAll();
@@ -85,16 +101,23 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true); expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => { it('D.3.A muestra identidad y skeleton sin control de expansión ni HTTP', () => {
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
expect(host.querySelector('h2').textContent).toBe('Uno'); expect(host.querySelector('h2').textContent).toBe('Uno');
expect(host.querySelector('header button')).toBeNull(); expect(host.querySelector('header button')).toBeNull();
expect(host.querySelector('mat-select')).toBeTruthy(); expect(host.querySelector('mat-select')).toBeNull();
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
expect(host.textContent).not.toContain('Contrato C1'); expect(host.textContent).not.toContain('Contrato C1');
expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
load([item, { ...second, vistas: ['historico'] }]);
expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]);
expect(fixture.nativeElement.querySelector('.catalog-count').textContent).toContain('1 indicadores');
expect(page.catalog()).toHaveLength(2);
http.expectNone(r => r.url.endsWith('/figuras/f1'));
});
it('D.3.A conserva encabezado y contenido al salir del viewport', () => { it('D.3.A conserva encabezado y contenido al salir del viewport', () => {
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
const header = host.querySelector('header'); toggle(); flushAll(); const header = host.querySelector('header'); toggle(); flushAll();
@@ -113,13 +136,9 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('UX-06B mantiene una sola navegación entre dominios, sin duplicar botones', () => { it('UX-06B mantiene una sola navegación entre dominios, sin duplicar botones', () => {
// Our shell has no domain selector of its own (unlike upstream's App), // The App header owns the domain menu (app.spec.ts); fails if the page brings back its own links.
// so the page keeps exactly the one it always had -- not duplicated.
// (Needs a render pass first: unlike upstream's trivial "absent" check,
// confirming presence requires the template to have actually painted.)
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(1); expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(0);
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav a')).toHaveLength(3);
expect(cards()).toHaveLength(0); expect(cards()).toHaveLength(0);
// Constructing the page legitimately initializes its domain catalog. // Constructing the page legitimately initializes its domain catalog.
const catalogRequest = http.expectOne('/tea/indicadores'); const catalogRequest = http.expectOne('/tea/indicadores');
@@ -189,7 +208,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => { it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
load([item]); toggle(); flushAll(); const a = control(); load([item]); toggle(); flushAll(); const a = control();
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true); a.select([]); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
page.applyFilters(); fixture.detectChanges(); page.applyFilters(); fixture.detectChanges();
const appliedA = request('f1'); const appliedA = request('f1');
expect(appliedA.request.params.get('periodos')).toBe('2025-S1'); expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
@@ -197,14 +216,14 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
page.changeTema('oscuro'); fixture.detectChanges(); page.changeTema('oscuro'); fixture.detectChanges();
const themedA = request('f1'); const themedA = request('f1');
expect(themedA.request.params.get('periodos')).toBe('2025-S1'); expect(themedA.request.params.get('periodos')).toBe('2025-S1');
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S2']);
themedA.flush({ data: [], layout: {} }); themedA.flush({ data: [], layout: {} });
}); });
it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => { it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => {
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll(); load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
const filters = control(); const filters = control();
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied); const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
const result = panel.result(); const result = panel.result();
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
@@ -222,10 +241,10 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
} }
}); });
it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => { it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => {
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); load([item]); toggle(); flushAll(); const a = control(); a.select([]); a.year = '2025'; a.unit = 'S1'; a.add();
page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add(); page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add();
cards()[0].setVisible(false); fixture.detectChanges(); toggle(); cards()[0].setVisible(false); fixture.detectChanges(); toggle();
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S2']);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => { it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => {
@@ -245,7 +264,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama'); expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
}); });
it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => { it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => {
load(); toggle(); flushAll(); control().changeMode('manual'); load(); toggle(); flushAll(); control().select([]);
page.changeTema('oscuro'); fixture.detectChanges(); flushAll(); page.changeTema('oscuro'); fixture.detectChanges(); flushAll();
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll(); page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll();
toggle(); page.changeDominio('tea'); fixture.detectChanges(); load(); toggle(); page.changeDominio('tea'); fixture.detectChanges(); load();
@@ -299,7 +318,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
load(syntheticCatalogs.tea); load(syntheticCatalogs.tea);
const index = cards().findIndex(c => c.indicador.id === id); const index = cards().findIndex(c => c.indicador.id === id);
toggle(index); flushAll(); toggle(index); flushAll();
const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable(); const c = control(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
expect(c.canApply).toBe(false); http.expectNone(() => true); expect(c.canApply).toBe(false); http.expectNone(() => true);
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable(); c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
toggle(index); toggle(index); flushAll(); await fixture.whenStable(); toggle(index); toggle(index); flushAll(); await fixture.whenStable();
@@ -325,9 +344,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1')); const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1')); const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges(); a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf<HTMLElement>;
expect(panels()[0].titleId).not.toBe(panels()[1].titleId); expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1);
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]); expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
}); });
}); });
+163 -53
View File
@@ -1,48 +1,61 @@
import { DOCUMENT } from '@angular/common'; import { DOCUMENT } from '@angular/common';
import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } from '@angular/core'; import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, RouterLink } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select'; import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs'; import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models'; import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { esSocioConteos } from './indicadores-conteos-pareados';
import { IndicadoresService } from './indicadores.service'; import { IndicadoresService } from './indicadores.service';
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorCatalogCard } from './indicador-catalog-card';
import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, KPI_RESUMEN_TEA } from './indicadores-kpi';
import { TeaResumenPeriodo } from './tea-resumen-periodo';
import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorKpiCard } from './indicador-kpi-card'; import { IndicadorKpiCard } from './indicador-kpi-card';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
import { indicatorIdentity } from './indicadores-identities'; import { identityElementId, indicatorIdentity } from './indicadores-identities';
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
import { httpMessage } from './indicadores-http'; import { httpMessage } from './indicadores-http';
import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadoresTracking } from './indicadores-tracking'; import { IndicadoresTracking } from './indicadores-tracking';
import { IndicadoresNumericSummary } from './indicadores-numeric-summary'; import { IndicadoresHistorico } from './indicadores-historico';
type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
@Component({
selector: 'app-indicadores-page',
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
readonly sections: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' }, { id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' }, { id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' }, { id: 'datos', label: 'Datos y definiciones' },
]; ];
// Domains with enough periods for their history to say anything.
const CON_HISTORICO: readonly Dominio[] = ['tea', 'cama'];
const MIN_BUSQUEDA = 5;
const HISTORICO_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections() { return this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
get conHistorico() { return CON_HISTORICO.includes(this.dominio); }
readonly activeSection = signal<DashboardSection>('resumen'); readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
setFichaPacienteAbierta(open: boolean) {
this.fichaPacienteAbierta.set(open);
}
changeSection(section: DashboardSection) { changeSection(section: DashboardSection) {
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return; if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
this.activeSection.set(section); this.activeSection.set(section);
@@ -64,8 +77,9 @@ export class IndicadoresPage {
private readonly document = inject(DOCUMENT); private readonly document = inject(DOCUMENT);
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef); private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly injector = inject(Injector); private readonly injector = inject(Injector);
private readonly searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput'); private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly graphicCards = viewChildren(IndicadorCatalogCard); private readonly graphicCards = viewChildren(IndicadorCatalogCard);
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>(); private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
private renderedCards: readonly IndicadorCatalogCard[] = []; private renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver; private visibilityObserver?: IntersectionObserver;
@@ -151,7 +165,26 @@ export class IndicadoresPage {
this.visibilityObserver = observer; this.visibilityObserver = observer;
for (const region of this.observedRegions.keys()) observer.observe(region); for (const region of this.observedRegions.keys()) observer.observe(region);
} }
// Report: every selected chart has to be drawn, narrow enough for a page, before opening the print dialog.
readonly preparandoReporte = signal(false);
async descargarReporte() {
const browser = this.document.defaultView;
if (!browser || this.preparandoReporte()) return;
this.preparandoReporte.set(true);
for (const card of this.graphicCards()) card.setVisible(true);
this.changeDetector.markForCheck();
const espera = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const pendiente = () => this.element.nativeElement.querySelector('#panel-resumen mat-progress-bar, #panel-resumen .figure-skeleton');
await espera(100);
for (let i = 0; pendiente() && i < 150; i++) await espera(100);
// Charts resize to the page width on their next frames.
await espera(500);
const terminar = () => { this.preparandoReporte.set(false); this.changeDetector.markForCheck(); this.visibilityChanged(); };
browser.addEventListener('afterprint', terminar, { once: true });
browser.print();
}
private evaluateVisibility() { private evaluateVisibility() {
if (this.preparandoReporte()) return;
const browser = this.document.defaultView; const browser = this.document.defaultView;
if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return;
if (this.activeSection() !== 'resumen') return; if (this.activeSection() !== 'resumen') return;
@@ -168,14 +201,12 @@ export class IndicadoresPage {
} }
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
} }
clearSearch() { changeIndicatorSelection(ids: string[]) {
this.changeSearchQuery('');
this.searchInput()?.nativeElement.focus({ preventScroll: true });
}
changeSearchQuery(query: string) {
this.preserveCardFocus(); this.preserveCardFocus();
this.searchQuery.set(query); // Every indicator checked is the same as no filter, so later catalog additions also show.
this.indicatorSelection.set(ids.length === this.catalogOrder().length ? null : ids);
} }
showAllIndicators() { this.changeIndicatorSelection(this.catalogOrder().map(item => item.id)); }
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); } isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
togglePinned(item: Indicador) { togglePinned(item: Indicador) {
this.preserveCardFocus(); this.preserveCardFocus();
@@ -239,41 +270,69 @@ export class IndicadoresPage {
private readonly memory = inject(IndicadoresMemory); private readonly memory = inject(IndicadoresMemory);
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute, { optional: true }); private readonly route = inject(ActivatedRoute, { optional: true });
readonly dominios = DOMINIOS;
dominio: Dominio = 'tea'; dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
readonly kpisByDomain = KPI_BY_DOMAIN; // At the start of the header line.
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
// Short form for the domain-switcher buttons (our shell's own nav, see the
// template comment above it) -- `domainLabels`/`domainTitles` are prose-length.
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); } figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); } independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } kpiIndicator(id: string) {
const published = this.catalog().find(item => item.id === id);
if (published) return published;
// The lab partner is deliberately hidden from some catalogs, as in the paired figure.
// Reuse its established periodicity, without assigning the diagnosis version to lab data.
if (this.dominio === 'cacu' && id === CACU_RESULTADO_KPI.id) {
const diagnosis = this.catalog().find(item => item.id === 'cacu_dias_toma_diagnostico');
if (diagnosis) return { id, titulo: CACU_RESULTADO_KPI.title, contrato: diagnosis.contrato,
figuras: [], tipos_periodo: diagnosis.tipos_periodo };
}
return undefined;
}
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
get teaResumenPeriodo(): string | undefined {
const selection = this.filters?.applied.selection;
return this.dominio === 'tea' && selection?.mode === 'explicit' && selection.periodos.length === 1 ? selection.periodos[0] : undefined;
}
get opportunityKpis() {
const definitions = this.availableKpis;
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
// Keep the established KPI definitions and initial-period anchor intact.
const diagnosis = definitions.findIndex(item => item.id === 'cacu_dias_toma_diagnostico');
return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI,
...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)];
}
private readonly catalogRequests = new Subject<void>(); private readonly catalogRequests = new Subject<void>();
readonly catalog = signal<Indicador[]>([]); readonly catalog = signal<Indicador[]>([]);
readonly searchQuery = signal(''); // Ids of the indicators to render; null shows the whole catalog.
readonly searchVisible = computed(() => this.catalog().length >= 5); readonly indicatorSelection = signal<string[] | null>(null);
readonly searchResults = computed(() => { // With a few indicators every card is in view; the selector only pays off from MIN_BUSQUEDA on.
readonly searchVisible = computed(() => this.catalogOrder().length >= MIN_BUSQUEDA);
// Stable presentation priority; pins still take precedence in the grid.
readonly catalogOrder = computed(() => {
const catalog = this.catalog(); const catalog = this.catalog();
// Stable presentation priority; search matches and pins still take precedence. // The interactive views go first.
const items = this.dominio === 'cacu' // A paired partner is drawn on its pair's card, not on one of its own.
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] const ids = catalog.map(item => item.id);
: catalog; const resumen = catalog.filter(item => (!item.vistas || item.vistas.includes('resumen')) && !esSocioConteos(this.dominio, item.id, ids));
const query = this.normalizeSearch(this.searchQuery()); const primero = (item: Indicador) => !!vistaEscenario(this.dominio, item);
const prioritize = (group: Indicador[]) => [ return [...resumen.filter(primero), ...resumen.filter(item => !primero(item))];
...group.filter(item => this.isPinned(item)), });
...group.filter(item => !this.isPinned(item)), readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
]; readonly selectionSummary = computed(() => {
if (!query) return { items: prioritize(items), active: false, count: 0 }; const selected = this.selectedIndicators();
const matches: Indicador[] = []; if (this.indicatorSelection() === null) return 'Todos los indicadores';
const remaining: Indicador[] = []; if (selected.length === 1) return this.catalog().find(item => item.id === selected[0])?.titulo ?? selected[0];
for (const item of items) { return selected.length + ' indicadores';
const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query)); });
(matchesQuery ? matches : remaining).push(item); readonly searchResults = computed(() => {
} const selected = new Set(this.selectedIndicators());
return { items: [...prioritize(matches), ...prioritize(remaining)], active: true, count: matches.length }; const items = this.catalogOrder().filter(item => selected.has(item.id));
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
}); });
private normalizeSearch(value: string) {
return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim();
}
readonly catalogLoading = signal(true); readonly catalogLoading = signal(true);
readonly catalogError = signal(''); readonly catalogError = signal('');
tema: Tema = 'claro'; tema: Tema = 'claro';
@@ -302,14 +361,65 @@ export class IndicadoresPage {
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
} }
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); } cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
// «Ir» in the indicator selector: show the indicator if it was filtered out, then scroll to its card.
goToIndicator(id: string, event?: Event) {
// The link sits inside a mat-option: it must not toggle the option's selection.
event?.preventDefault(); event?.stopPropagation();
if (!this.catalog().some(item => item.id === id)) return;
const selection = this.indicatorSelection();
if (selection && !selection.includes(id)) this.indicatorSelection.set([...selection, id]);
const key = indicatorIdentity(this.dominio, id), select = this.indicatorSelect();
const scroll = () => afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
// Closing the panel returns focus to the selector, which would cancel a scroll started before it ends.
if (select?.panelOpen) { select.openedChange.pipe(first(open => !open)).subscribe(scroll); select.close(); }
else scroll();
}
private scrollToIndicator(key: string) {
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return;
const target = this.document.getElementById(identityElementId(key));
const grid = this.element.nativeElement.querySelector('.catalog-grid');
if (!target || !grid?.contains(target)) return;
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
target.querySelector('h2')?.focus({ preventScroll: true });
this.keepAligned(target, grid);
}
// Figures above the card load as the scroll passes them and grow taller than their placeholders,
// pushing the card down. For a short while, put it back in place whenever the grid resizes;
// any scrolling by the user ends this.
private stopAligning?: () => void;
private keepAligned(target: HTMLElement, grid: Element) {
this.stopAligning?.();
const browser = this.document.defaultView;
if (!browser || typeof ResizeObserver === 'undefined') return;
const host = this.element.nativeElement;
const userInput = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const;
const observer = new ResizeObserver(() => {
const offset = target.getBoundingClientRect().top - host.getBoundingClientRect().top - parseFloat(browser.getComputedStyle(target).scrollMarginTop || '0');
if (Math.abs(offset) > 2) target.scrollIntoView({ behavior: 'instant', block: 'start' });
});
const timer = setTimeout(() => this.stopAligning?.(), 2500);
const stop = () => {
observer.disconnect(); clearTimeout(timer);
for (const type of userInput) host.removeEventListener(type, stop);
if (this.stopAligning === stop) this.stopAligning = undefined;
};
this.stopAligning = stop;
observer.observe(grid);
for (const type of userInput) host.addEventListener(type, stop, { passive: true });
}
constructor() { constructor() {
afterEveryRender(() => this.syncVisibility()); afterEveryRender(() => {
this.syncVisibility();
});
const browser = this.document.defaultView; const browser = this.document.defaultView;
if (typeof IntersectionObserver !== 'undefined') { if (typeof IntersectionObserver !== 'undefined') {
browser?.addEventListener('scroll', this.viewportChanged, { passive: true }); browser?.addEventListener('scroll', this.viewportChanged, { passive: true });
browser?.addEventListener('resize', this.viewportChanged); browser?.addEventListener('resize', this.viewportChanged);
} }
this.destroyRef.onDestroy(() => { this.destroyRef.onDestroy(() => {
this.stopAligning?.();
this.filtersEdited(); this.filtersEdited();
this.visibilityDestroyed = true; this.visibilityDestroyed = true;
this.clearVisibility(); this.clearVisibility();
@@ -348,7 +458,7 @@ export class IndicadoresPage {
changeDominio(dominio: Dominio) { changeDominio(dominio: Dominio) {
if (!isDominio(dominio) || dominio === this.dominio) return; if (!isDominio(dominio) || dominio === this.dominio) return;
this.activeSection.set('resumen'); this.activeSection.set('resumen');
this.searchQuery.set(''); this.indicatorSelection.set(null);
this.filtersEdited(); this.filtersEdited();
this.filters = undefined; this.filters = undefined;
this.dominio = dominio; this.dominio = dominio;
@@ -6,9 +6,12 @@ import { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page'; import { IndicadoresPage } from './indicadores-page';
import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorPeriodFilters } from './indicador-period-filters';
import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { Dominio, IndicadorDatos } from './indicadores.models'; import { Dominio, IndicadorDatos } from './indicadores.models';
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
// rules (indicador-kpi-panel.spec.ts covers all four).
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
describe('P0.1 selección publicada y último periodo por KPI', () => { describe('P0.1 selección publicada y último periodo por KPI', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController; let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
beforeEach(() => { beforeEach(() => {
@@ -21,18 +24,29 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) }); const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) });
function catalog(domain: Dominio) { function catalog(domain: Dominio) {
fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }))); http.expectOne('/' + domain + '/indicadores').flush(KPIS[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
fixture.detectChanges(); fixture.detectChanges();
return http.match(r => r.url.endsWith('/periodos')); return http.match(r => r.url.endsWith('/periodos'));
} }
function load(domain: Dominio, periods: string[][]) { function load(domain: Dominio, periods: string[][]) {
catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i]))); catalog(domain).forEach((r, i) => r.flush(payload(KPIS[domain][i].id, periods[i])));
fixture.detectChanges(); fixture.detectChanges();
} }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } // 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(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos { function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
const d = KPI_BY_DOMAIN[domain][index]; const d = KPIS[domain][index];
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{ 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' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', periodo: period, grupo: d.contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0, n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0,
@@ -41,11 +55,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
function flushDatos(domain: Dominio, suppressed = false) { function flushDatos(domain: Dominio, suppressed = false) {
const resolved = []; const resolved = [];
for (;;) { for (;;) {
const requests = http.match(r => r.url.endsWith('/datos')); const requests = originalRequests();
if (!requests.length) return resolved; if (!requests.length) return resolved;
resolved.push(...requests); resolved.push(...requests);
requests.forEach(r => { requests.forEach(r => {
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); const index = KPIS[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed)); r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed));
}); });
fixture.detectChanges(); fixture.detectChanges();
@@ -53,11 +67,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
} }
it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => { it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => {
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]);
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos')); const anchor = http.expectOne(r => r.url.endsWith('/' + KPIS[domain][0].id + '/datos'));
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges(); const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
const requests = flushDatos(domain); const requests = flushDatos(domain);
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1')); expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPIS[domain].slice(1).map(() => '2026-S1'));
expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1')); expect(panels().map(p => p.temporalReference)).toEqual(KPIS[domain].map(() => '2026-S1'));
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]); expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]);
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] }); expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
expect(fixture.componentInstance.filters!.applied.revision).toBe(1); expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
@@ -65,7 +79,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
}); });
it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => { it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => {
load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2'])); load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2']));
const initial = http.match(r => r.url.endsWith('/datos')); const initial = originalRequests();
fixture.componentInstance.applyFilters(); fixture.detectChanges(); fixture.componentInstance.applyFilters(); fixture.detectChanges();
expect(initial.every(r => r.cancelled)).toBe(true); expect(initial.every(r => r.cancelled)).toBe(true);
const requests = flushDatos('cacu', true); const requests = flushDatos('cacu', true);
@@ -81,7 +95,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
expect(panels()[0].result().value).toBeUndefined(); expect(panels()[0].result().value).toBeUndefined();
}); });
it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => { it('selección mensual edita sin HTTP; un periodo consulta y no se pueden elegir varios', async () => {
load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu'); load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu');
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges(); const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']); expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
@@ -92,23 +106,22 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const single = flushDatos('cacu'); expect(single).toHaveLength(2); const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true); expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true); control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
expect(control.selectedPeriods).toEqual(['2025-10']);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); fixture.componentInstance.applyFilters(); fixture.detectChanges();
expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true); expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
http.expectNone(() => true);
control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges();
http.expectNone(() => true); http.expectNone(() => true);
await fixture.whenStable(); await fixture.whenStable();
}); });
it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => { it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => {
const requests = catalog('cacu'); const requests = catalog('cacu');
requests[0].flush('private', { status: 503, statusText: 'Unavailable' }); requests[0].flush('private', { status: 503, statusText: 'Unavailable' });
requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2']))); requests.slice(1).forEach((r, i) => r.flush(payload(KPIS.cacu[i + 1].id, ['2025-S2'])));
fixture.detectChanges(); flushDatos('cacu'); fixture.detectChanges(); flushDatos('cacu');
expect(fixture.componentInstance.initialPeriodState()).toBe('error'); expect(fixture.componentInstance.initialPeriodState()).toBe('error');
expect(panels()).toHaveLength(0); expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de CaCu'); expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de cáncer cervicouterino');
expect(fixture.nativeElement.textContent).not.toContain('private'); expect(fixture.nativeElement.textContent).not.toContain('private');
const control = editor(); control.changeMode('manual'); control.select(['2025-S2']); const control = editor(); control.select([]); control.select(['2025-S2']);
expect(control.canApply).toBe(false); expect(control.canApply).toBe(false);
fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges(); fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges();
const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos'); const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos');
@@ -120,7 +133,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const outgoing = catalog('cacu'); const incoming = catalog('cama'); const outgoing = catalog('cacu'); const incoming = catalog('cama');
expect(outgoing.every(r => r.cancelled)).toBe(true); expect(outgoing.every(r => r.cancelled)).toBe(true);
expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow(); expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow();
incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1']))); incoming.forEach((r, i) => r.flush(payload(KPIS.cama[i].id, ['2025-S1'])));
fixture.detectChanges(); const requests = flushDatos('cama'); fixture.detectChanges(); const requests = flushDatos('cama');
expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true); expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true);
expect(editor().options).toEqual(['2025-S1']); expect(editor().options).toEqual(['2025-S1']);
@@ -63,25 +63,22 @@ describe('UX-06E.D.3.B fijación temporal', () => {
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']); await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true); expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
}); });
it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => { it('la selección de indicadores conserva la prioridad de los fijados', async () => {
await pin('i3'); await pin('i4'); await pin('i3'); await pin('i4');
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle(); page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']); expect(ids()).toEqual(['i3', 'i4', 'i1']);
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true); await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']); expect(cards()).toHaveLength(3); http.expectNone(() => true);
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
}); });
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => { it('Mostrar todos restaura el catálogo con los fijados primero', async () => {
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle(); await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
expect(ids()[0]).toBe('i0'); expect(ids()).toEqual(['i0']);
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
}); });
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => { it('un fijado sin seleccionar no se muestra', async () => {
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle(); await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0); expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true);
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true);
}); });
it('memoria independiente por dominio y persistente al recrear la página', async () => { it('memoria independiente por dominio y persistente al recrear la página', async () => {
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id)); await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
@@ -42,8 +42,8 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2); expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
const hosts = charts.map(c => c.componentInstance.host.nativeElement); const hosts = charts.map(c => c.componentInstance.host.nativeElement);
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f'); expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, i, f');
expect(hosts[1].getAttribute('aria-label')).toBe('tea · j · g'); expect(hosts[1].getAttribute('aria-label')).toBe('tea, j, g');
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges(); fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges();
expect(runtime.purge).toHaveBeenCalledWith(hosts[0]); expect(runtime.purge).toHaveBeenCalledWith(hosts[0]);
@@ -4,15 +4,11 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { NgModel } from '@angular/forms';
import { MatSelect } from '@angular/material/select'; import { MatSelect } from '@angular/material/select';
import { IndicadoresPage } from './indicadores-page'; import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadoresMemory } from './indicadores-memory';
import { Indicador } from './indicadores.models'; import { Indicador } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
const items: Indicador[] = [ const items: Indicador[] = [
@@ -23,16 +19,15 @@ const items: Indicador[] = [
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, { id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
]; ];
describe('UX-05C búsqueda local y partición estable', () => { describe('Selección de indicadores gráficos', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>; let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage; let page: IndicadoresPage;
let http: HttpTestingController; let http: HttpTestingController;
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
const disconnect = vi.fn();
beforeEach(() => { beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; }); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
@@ -43,184 +38,89 @@ describe('UX-05C búsqueda local y partición estable', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
} }
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function ids() { return cards().map(c => c.indicador.id); }
function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); } function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); } function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
async function search(value: string) { function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle();
}
function respond() {
http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges();
}
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { it.each([0, 1, 4, 5, 6])('muestra el selector desde cinco indicadores: catálogo de %i', count => {
// Fails if the selector shows for a handful of cards, or stops showing for a long catalog.
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); expect(!!select()).toBe(count >= 5); expect(cards()).toHaveLength(count);
expect(cards().every(c => !c.visible)).toBe(true);
http.expectNone(() => true);
if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
});
it.each([
['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
[' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
[' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => {
load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards();
await search(query as string);
expect(cards().map(c => c.indicador.id)).toEqual(ids);
expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim());
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot);
for (const card of cards()) {
expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id));
expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false);
}
if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible');
if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe('');
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => { it('lista todo el catálogo, con todos seleccionados al inicio', () => {
load(); await settle(); load();
const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')); expect(select()!.multiple).toBe(true);
const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement; expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
const clear = field.querySelector('button')!; expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
expect(clear.hasAttribute('matIconSuffix')).toBe(true); expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy(); expect(result()).toBe('Mostrando 5 de 5 indicadores.');
expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1); expect(showAll().disabled).toBe(true);
expect(input().type).toBe('search'); http.expectNone(() => true);
for (const query of ['sexo', 'Indicador destacado', '']) { });
await search(query); it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis); load(); const before = cards(), original = page.catalog();
choose(['B02', 'E05']);
expect(ids()).toEqual(['B02', 'E05']);
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados'); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
expect(cards()).toHaveLength(5); choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
} expect(page.catalog()).toBe(original);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => { it('sin selección no muestra tarjetas y Mostrar todos restaura el catálogo', () => {
load(); await settle(); const field = input(); field.focus(); await search('sexo'); load(); choose([]);
expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo'); expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2); expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
expect(field.labels?.[0].textContent).toContain('Buscar indicadores'); expect(showAll().disabled).toBe(false);
for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy(); showAll().click(); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); clear.click(); fixture.detectChanges(); await settle();
expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field);
await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => { it('marcar todos equivale a no filtrar', () => {
load(); await settle(); load(); choose(['A01']); choose(items.map(i => i.id));
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement; expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true); });
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); it('los indicadores destacados no dependen de la selección', () => {
const icon = clear.querySelector('mat-icon')!; load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'));
expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true'); choose(['A01']);
expect(clear.textContent).not.toContain('Limpiar'); expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px'); });
await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0); it('«Ir» lleva a la tarjeta sin alternar la opción y muestra el indicador si estaba oculto', async () => {
// jsdom does not synthesize native keyboard activation. Verify that keys remain const scroll = vi.fn();
// available to the browser; Enter/Space activation is a Chrome acceptance check. Element.prototype.scrollIntoView = scroll;
for (const key of ['Enter', ' ']) { load(); choose(['A01']);
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); select()!.open(); fixture.detectChanges(); await fixture.whenStable();
clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go'))
} .find(a => a.closest('mat-option')!.textContent!.includes(items.find(i => i.id === id)!.titulo))!;
clear.focus(); clear.click(); fixture.detectChanges(); await settle(); expect(go('D04').getAttribute('aria-label')).toBe('Ir a Seguimiento');
expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true); // The scroll waits until the panel has finished closing.
const settle = (calls: number) => vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(calls); });
go('D04').click(); fixture.detectChanges(); await fixture.whenStable();
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
expect(select()!.panelOpen).toBe(false);
await settle(1);
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
// Already visible: the selection is untouched.
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
await settle(2);
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
});
it('no muestra el botón flotante de navegación por indicadores', () => {
load();
expect(fixture.nativeElement.querySelector('.graphic-navigation-trigger')).toBeNull();
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => { it('cambiar de dominio restablece la selección', () => {
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle(); load(); choose(['A01']);
const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull();
const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id));
page.applyFilters(); fixture.detectChanges(); respond(); await settle();
c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026';
fixture.detectChanges(); await settle();
const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result());
const titleIds = beforePanels.map(p => p.titleId);
expect(new Set(titleIds).size).toBe(beforePanels.length);
const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement);
const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple);
const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue'));
const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal');
const reacts = runtime.react.mock.calls.length;
const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[];
expect(helps).toHaveLength(5);
const helpIds = helps.map(button => button.getAttribute('aria-controls')!);
expect(new Set(helpIds).size).toBe(5);
for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true);
helps[0].click(); fixture.detectChanges();
http.expectOne(r => r.url.endsWith('/metadatos')).flush({});
fixture.detectChanges(); await settle();
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]);
for (const query of ['sexo', 'evaluacion', '']) {
if (query) await search(query);
else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); }
for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card);
for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel);
beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c));
beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c));
}
expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true);
for (const button of helps) expect(button.isConnected).toBe(true);
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
helps[0].click(); fixture.detectChanges(); await settle();
expect(document.getElementById(helpIds[0])?.hidden).toBe(true);
expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts);
expect(beforePanels.map(p => p.titleId)).toEqual(titleIds);
for (const id of titleIds) {
const heading = document.getElementById(id)!;
expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id);
}
beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); });
beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i]));
expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
for (const write of writes) expect(write).not.toHaveBeenCalled();
expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled();
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
http.expectNone(() => true);
});
it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => {
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges();
const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo');
b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle();
await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error');
expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true);
a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]);
const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} });
expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true);
});
it('reordenar el catálogo conserva foco en el selector global existente', async () => {
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
filters()[0].changeMode('manual'); fixture.detectChanges(); await settle();
const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf<HTMLElement>).at(-1)!;
field.focus(); expect(document.activeElement).toBe(field);
page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle();
expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true);
page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field);
http.expectNone(() => true);
});
it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => {
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add();
await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe('');
load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false);
page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe('');
expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]);
http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges();
const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} });
expect(filters()[0].selectedPeriods).toEqual(['2025-S1']);
await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond();
expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
}); });
}); });
@@ -31,45 +31,37 @@ describe('Secciones compartidas por dominio', () => {
}); });
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
it.each(DOMINIOS)('entrada directa en %s presenta tres pestañas y Resumen seleccionado', async domain => { it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
const harness = await RouterTestingHarness.create(); const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!; const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]')); const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']); expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' || domain === 'cama'
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(['true', 'false', 'false']); ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]); expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
// Upstream moved domain selection to its own App shell; ours keeps it on // The App header switches domains (see app.html); the page has no switcher of its own.
// the page itself (see indicadores-page.html), since our shell is shared expect(root.querySelector('nav.domain-nav')).toBeNull();
// with other workspace sections.
expect(root.querySelector('nav.domain-nav')).not.toBeNull();
for (const tab of tabs) { for (const tab of tabs) {
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!; const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
expect(panel.getAttribute('aria-labelledby')).toBe(tab.id); expect(panel.getAttribute('aria-labelledby')).toBe(tab.id);
expect(panel.hidden).toBe(tab.id !== 'tab-resumen'); expect(panel.hidden).toBe(tab.id !== 'tab-resumen');
} }
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance); const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
tabs[1].click(); harness.detectChanges(); tab('seguimiento').click(); harness.detectChanges();
if (domain === 'cacu') { http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges(); harness.detectChanges();
}
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!; const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false); expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain('El seguimiento aún no está disponible'); expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
if (domain === 'cacu') { // Every domain queries its list; until it is published there is no table, only the form.
expect(tracking.querySelector('tbody')).toBeNull(); expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull(); expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else { tab('datos').click(); harness.detectChanges();
expect(tracking.querySelectorAll('thead th')).toHaveLength(6);
expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1);
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
}
tabs[2].click(); harness.detectChanges();
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false); expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
tabs[0].click(); harness.detectChanges(); tab('resumen').click(); harness.detectChanges();
expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards); expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards);
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes. http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
}); });
@@ -91,15 +83,15 @@ describe('Secciones compartidas por dominio', () => {
const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges(); http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
const tabs = Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('[role="tab"]')); const tabs = Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1]); expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1, -1]);
const focus = tabs.map(tab => vi.spyOn(tab, 'focus')); const focus = tabs.map(tab => vi.spyOn(tab, 'focus'));
function key(index: number, key: string, target: number) { function key(index: number, key: string, target: number) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true); tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true);
expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen'); expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen');
} }
key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 2); key(1, 'Home', 0); key(0, 'End', 2); key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 3); key(1, 'Home', 0); key(0, 'End', 3);
tabs[2].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, 0]); tabs[3].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, -1, 0]);
http.expectNone(() => true); http.expectNone(() => true);
}); });
@@ -142,8 +134,7 @@ describe('Datos y definiciones reutiliza metadatos sin servicios', () => {
expect(root.textContent).not.toMatch(/WebApp|WebApi|C1|C2|C3r|Origen de la información/); expect(root.textContent).not.toMatch(/WebApp|WebApi|C1|C2|C3r|Origen de la información/);
expect(root.textContent).toContain('La información metodológica ampliada no está disponible'); expect(root.textContent).toContain('La información metodológica ampliada no está disponible');
expect(root.querySelectorAll('details[open]')).toHaveLength(0); expect(root.querySelectorAll('details[open]')).toHaveLength(0);
expect(root.textContent).toContain('Un valor nulo significa que no hay un valor disponible'); expect(root.textContent).not.toContain('Interpretación y metodología');
expect(root.textContent).toContain('Los datos suprimidos tampoco representan un cero');
fixture.destroy(); fixture.destroy();
}); });
}); });
@@ -6,7 +6,7 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] { export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
return item.contrato === 'C2' && Array.isArray(item.filtros) return item.contrato === 'C2' && Array.isArray(item.filtros)
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d ? (['grupo_edad', 'estatus_seguimiento', 'birads'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
} }
@@ -54,7 +54,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)), return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' }; hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: 'Distribución estratificada · ' + period }, barmode: 'group', autosize: true, }), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background, height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 }, font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
@@ -0,0 +1,28 @@
import { C2Distribution } from './indicadores-c2-adapter';
import { highlightFigure } from './indicadores-highlight';
import { teaC2Donut } from './indicadores-tea-c2';
const categoria = (id: string, label: string, value: number, color: string, parentId?: string) => ({ id, label, value, color, parentId });
const modelo = (extra: object = {}) => ({ period: '2025-S2', unit: 'paciente', title: 'T', total: 380, notes: [], nodes: [], parents: [],
categories: [categoria('CONFIRMADO', 'Diagnóstico confirmado', 338, '#A8C243'), categoria('EN_PROCESO', 'En proceso', 42, '#B8433A')], ...extra }) as unknown as C2Distribution;
describe('Dona C2 de TEA', () => {
it('sin grupos dibuja un anillo con rótulos, el total al centro y un botón por categoría', () => {
const { figure, highlight } = teaC2Donut(modelo(), 'claro', { text: 'T' })!;
expect(figure.data).toHaveLength(1);
expect(figure.data[0]).toMatchObject({ type: 'pie', values: [338, 42], labels: ['Diagnóstico confirmado', 'En proceso'] });
expect(figure.data[0]['text']).toEqual(['Diagnóstico confirmado<br>88.9 %', 'En proceso<br>11.1 %']);
expect((figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>380</b><br>TOTAL');
expect(highlight.groups).toEqual([]);
expect(highlight.items.map(i => [i.label, i.color])).toEqual([['Diagnóstico confirmado', '#A8C243'], ['En proceso', '#B8433A']]);
});
it('al elegir una categoría atenúa la otra y muestra su número al centro', () => {
const { figure, highlight } = teaC2Donut(modelo(), 'claro', { text: 'T' })!;
const elegida = highlightFigure(figure, highlight, { item: 'EN_PROCESO' });
expect((elegida.data[0]['marker'] as { colors: string[] }).colors).toEqual(['rgba(168, 194, 67, 0.3)', 'rgba(184,67,58,1)']);
expect((elegida.layout['annotations'] as { text: string }[])[0].text).toBe('<b>42</b><br>En proceso');
});
it('sin pacientes no dibuja nada', () => {
expect(teaC2Donut(modelo({ total: 0 }), 'claro', {})).toBeUndefined();
});
});

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