Compare commits

..

151 Commits

Author SHA1 Message Date
alberto 29d021b347 Merge pull request 'Gobernanza: results of one EDF and its ADOS-2 report without storing them; EEG sentence in the TEA summary' (#29) from feature/tea-eeg-analysis into dev 2026-11-23 12:28:00 -06:00
ulises 98e9b60e83 Gobernanza: view the results of one EDF and its ADOS-2 report without storing them, with Guardar como PDF 2026-11-23 12:26:19 -06:00
ulises 5061350dd8 TEA summary: the EEG sentence gives the number of studies not acceptable for an analysis 2026-11-23 12:26:19 -06:00
alberto eb887be447 Merge pull request 'Gobernanza: TEA · EEG tab with the whole baseline flow' (#28) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:35 -06:00
ulises 0b22b3c309 Gobernanza: TEA · EEG tab with cluster check, reference data, training, baselines, reports, promotion, run monitor, analysis and result 2026-11-23 09:31:38 -06:00
Roberto Treviño Cervantes 6ade415f63 Merge dev into the CaMa survival record change 2026-11-23 00:10:03 -06:00
angel 5791928976 Merge pull request 'CaMa: etiquetas, secciones y pies de figura (verificación contra dev y título de Análisis de riesgos)' (#27) from fix/cama-etiquetas-secciones-20261122 into dev
Reviewed-on: #27
2026-11-22 23:53:48 -06:00
angel f4d1829cd3 Merge branch 'dev' into fix/cama-etiquetas-secciones-20261122 2026-11-22 23:52:56 -06:00
Roberto Treviño Cervantes 069cc459a4 CaMa survival record: the adjusted Kaplan-Meier is optional 2026-11-22 23:46:57 -06:00
Angel Capetillo Zavala 881c613744 fix(cama): title the risk analysis panel Análisis de riesgos 2026-11-22 23:41:31 -06:00
Roberto Treviño Cervantes be46429627 Merge dev into the CaMa consolidation branch 2026-11-22 23:31:20 -06:00
edgar 25f584c864 Merge pull request 'CaCu patient record and indicators: risk by follow-up status, screening route reading note, history panels' (#26) from feature/cacu-ficha-riesgo-gobernanza into dev
Reviewed-on: #26
2026-11-22 23:26:15 -06:00
edgar 561a5dde36 Merge dev into the CaCu risk record branch
dev already names the history tab «Trazabilidad» for the three domains, so its version of those files stays. CaCu's
diagnosis-to-treatment time keeps one presentation, its card: it has no figure of its own next to the screening
route chart.
2026-11-22 23:17:21 -06:00
edgar bf89099ce8 Merge pull request 'fix(cacu): ajustar trazabilidad y figuras disponibles' (#24) from fix/cacu-etiquetas-secciones-20261122 into feature/cacu-ficha-riesgo-gobernanza
Reviewed-on: #24
2026-11-22 22:57:36 -06:00
Angel Capetillo Zavala ff1f6758ba fix(cacu): ajustar trazabilidad y figuras disponibles 2026-11-22 22:27:49 -06:00
alberto f38a2c6bb4 Merge pull request 'TEA indicators: Resumen and Trazabilidad tabs, round help, series chips, shared colours' (#23) from feature/tea-eeg-analysis into dev
Reviewed-on: #23
2026-11-22 22:13:11 -06:00
ulises 40c19a6a1f Merge the TEA labels and sections branch into the TEA indicators branch 2026-11-22 22:11:34 -06:00
ulises 329c0891ae TEA indicators: Resumen and Trazabilidad tabs, round help buttons, series chips, shared colours, summary box, three-per-row grid and three-significant-digit EEG values 2026-11-22 22:01:50 -06:00
ulises 34c6f2af3a TEA seguimiento: the ADOS-2 relation panel reads the association's rows 2026-11-22 21:43:11 -06:00
Roberto Treviño Cervantes 7ab2567dc9 CaMa survival: the patient's own scenario, a menu only when she is in several 2026-11-22 21:38:43 -06:00
edgar 14d6875d9b Screening route: the reading note, condensed, folds into «Cómo leer» 2026-11-22 19:48:41 -06:00
edgar f82ce8cc38 Patient record: probability columns by follow-up status
The risk table shows only what the patient's follow-up status follows, as the follow-up table does: a case, her
survival; before colposcopy, LIEAG+ and cancer; after colposcopy or treatment, LIEAG+. Without a status every
column stays.
2026-11-22 19:41:39 -06:00
edgar 61867ff973 Patient risk: survival is 1 at 0 years, at the index date 2026-11-22 18:40:34 -06:00
edgar 8bca0fbcdf CaCu indicators: «Progresión por grupo de riesgo» withdrawn from the clinical figures 2026-11-22 18:39:22 -06:00
Roberto Treviño Cervantes ec8542de9f Seguimiento in place of Análisis de riesgos 2026-11-22 18:10:48 -06:00
Roberto Treviño Cervantes 29c9e6853b CaMa recurrence: the patient's own scenarios, without a cohort menu 2026-11-22 18:04:57 -06:00
Angel Capetillo Zavala b1ff6cadb2 fix(cama): ajustar títulos y pies de trazabilidad 2026-11-22 17:21:15 -06:00
Angel Capetillo Zavala 26285a87fa fix(cacu): ajustar trazabilidad y figuras clínicas 2026-11-22 16:55:16 -06:00
edgar f058f1f476 Screening route chart: it follows the page's period filter, with no filter of its own
The chart takes the page's period type and shows the newest of the periods the filter applies that has published
boxes (the newest with data when the filter applies every period), so it moves with the other indicators. Its own
period selector is gone; the period shown is written over the chart.
2026-11-22 16:30:01 -06:00
edgar 7f1e43bdc5 CaCu indicators: no «Tiempo de tamizaje a diagnóstico» figures next to the screening route chart
The route chart draws every time from the sample to each event, the cytology's result and the diagnosis included, so
the separate time figures repeated it. They come back only when the chart isn't shown (the catalog lacks one of its
measures).
2026-11-22 16:26:55 -06:00
Roberto Treviño Cervantes 5bf6af8ecf Revert "CaMa patient card: the SEER model's survival by clinical scenario beside the production model's"
This reverts commit dd356efb6b.
2026-11-22 16:12:44 -06:00
Angel Capetillo Zavala 253290ed6a fix(tea): ajustar indicadores, trazabilidad y etiquetas de riesgo 2026-11-22 16:04:04 -06:00
edgar ec5b8fde6b CaCu treatment time cards: no provisional notice under the value 2026-11-22 15:54:54 -06:00
edgar 2a36397fac CaCu history: the CIN2+ risk-band panel draws its measure
`CACU-RIESGO-BANDA` is published, so its panel reads it like the others; it counts the patients of the confirmed risk
batches, and is empty until one is confirmed. No CaCu history panel stays reserved.
2026-11-22 15:39:42 -06:00
edgar eada50d2ff CaCu history: the diagnosis-to-treatment time panel draws its measure
`CACU-DIAS-DIAGNOSTICO-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones
instead of showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it.
2026-11-22 15:38:55 -06:00
edgar 396902541d CaCu history: the screening-to-treatment time panel draws its measure
`CACU-DIAS-TOMA-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones instead of
showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it, and the panel specs
count the active and reserved panels from their lists.
2026-11-22 15:38:12 -06:00
edgar 68b5e927e7 CaCu follow-up table: the latest biopsy, and the probabilities of the status filtered
A column with each patient's latest biopsy. The probability columns follow the follow-up status chosen, its
scenario's models: a case shows survival, pre-colposcopy LIEAG+ and cancer, post-colposcopy and post-treatment
LIEAG+, every patient none. A horizon selector, and an order by the most recent study or one of the columns shown,
which the API applies to the whole list.
2026-11-22 15:04:13 -06:00
edgar 990cab0e37 Patient risk: probabilities in percent, survival as such, covariates, and one row per model
The table says its probabilities are percentages (0 to 100 %) with their 95 % interval, and its covariates under it.
A model whose estimand asks for its complement (survival from a probability of dying) shows 1 − p with its interval
swapped. "Riesgo acumulado" reads "probabilidad". The models' details are a table of one row per model, without
the version or the batch state.
2026-11-22 15:04:13 -06:00
edgar 39e1e3e094 Merge pull request 'Patient risk record and governance: one column per outcome, the model's estimand, single risk-batch decisions' (#21) from feature/cacu-ficha-riesgo-gobernanza into dev
Reviewed-on: #21
2026-11-22 13:48:07 -06:00
edgar 4e08bb8c4b Risk batches: one decision at a time, so a double click doesn't send it twice
(cherry picked from commit 88c1eb33be)
2026-11-22 09:47:11 -06:00
edgar 686580af81 Patient risk: a column per outcome, the index visit's sentence, and the model's details folded
The record reads every RiskAssessment of the patient. CaCu's table always has the LIEAG+ and cancer columns, each
risk with its interval in parentheses; a column with no current model says "No disponible", and one whose model
didn't estimate her says so, with the reason under the table. Another outcome (a survival model's death) shows only
when she has its risk, with its own index date in its header. The models' details fold under the table, without the
interval's method; the collapsible curves draw one line per outcome with the index date on the x axis, under a
sentence that words the index cytology's results and each outcome's risk at the longest common horizon.

(cherry picked from commit 73b88de0ca)
2026-11-22 09:47:11 -06:00
edgar 60c71bfc3d Governance: a version lists only the routines its run recorded
Not every model has each of the five routines, and the registry doesn't require them; the dialog showed the missing
ones as failures. It now lists the recorded ones and says so when there are none.

(cherry picked from commit b5bff7e0c6)
2026-11-22 09:47:11 -06:00
edgar ad4edbe2a1 Patient risk: what the model's number is, and its curve with the interval
The record reads the RiskAssessment's `estimando` extension and shows the quantity, the outcome, the index date and
the interval's method, and names the table's columns with the quantity and the horizons' unit. Below the table, a
collapsible curve of the risk at each horizon, with its interval as a band (or as error bars when a horizon lacks
one); Plotly is loaded only when it's opened.

(cherry picked from commit 6039e6b741)
2026-11-22 09:47:11 -06:00
angel 1af0c21291 Merge pull request 'feat(indicadores): consolidar Histórico CaCu y ajustes TEA/CaCu/CaMa' (#20) from feature/197-integracion-historico-cacu into dev
Reviewed-on: #20
2026-11-22 09:34:04 -06:00
Roberto Treviño Cervantes dd356efb6b CaMa patient card: the SEER model's survival by clinical scenario beside the production model's 2026-11-22 09:22:15 -06:00
Roberto Treviño Cervantes 01271621b7 Merge feature/cama-survival into dev, keeping dev's CaMa patient card 2026-11-22 09:19:17 -06:00
ulises 4c181af291 CaMa patient card: the recurrence figure of the scenarios the patient meets, and a menu of both cohorts' scenarios
Shown only for patients after treatment, in the recurrence slot of "Pronóstico y recomendaciones". Includes the survival
figure this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:39 -06:00
Angel Capetillo Zavala b8bf57e235 feat(cacu): presentar KPI provisionales de tiempo a tratamiento
Adapta 245622b a las secciones de oportunidad del PR #20 y reutiliza el contrato C3r. Conserva la ruta y los paneles reservados del Histórico.
2026-11-22 05:53:59 -06:00
edgar 17cef51d90 Screening route: without a requested period, open on the newest one that has published boxes
A semester that has just begun has no events and the chart opened on it, empty, while earlier ones had data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit a15e37ed77)
2026-11-22 05:40:50 -06:00
edgar 7692952ec9 Risk record: the evaluation instant reads as a day and minute in UTC
The index date is a calendar day and the evaluation time was the raw ISO instant, so the two looked inconsistent. The
instant now shows as 'YYYY-MM-DD HH:MM UTC' (the full value stays in the <time> element's datetime).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit ea2664f324)
2026-11-22 05:40:22 -06:00
edgar feaed5ff0e Indicators: a typed page size is brought into 1 to the maximum, one maximum for both lists
An input's max only flags the field and still lets a larger number be typed. The follow-up table and the tracking
list now clamp the value when it changes and when the query is sent, and both read the single PAGE_SIZE_MAX instead
of a literal 200.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 1342b1712d)
2026-11-22 05:37:25 -06:00
Angel Capetillo Zavala 999bc4ecf5 fix(indicadores): distinguish EEG findings and populations 2026-11-22 04:03:33 -06:00
Angel Capetillo Zavala 6ed87ff3d8 Fix CaMa Histórico order expectation in the f4c spec 2026-11-22 03:28:05 -06:00
Angel Capetillo Zavala ff4ad2c964 Análisis de riesgos: TEA and CaCu headings and the EEG status label 2026-11-22 03:21:09 -06:00
Angel Capetillo Zavala b5f8e5bfc2 Histórico: TEA order and EEG normal/abnormal lines, CaMa titles, order and captions 2026-11-22 03:18:19 -06:00
Angel Capetillo Zavala f04478e600 CaMa Indicadores: five time figures under «Tiempo de tamizaje a diagnóstico», requested clinical titles, order and confirmation rate 2026-11-22 03:11:12 -06:00
Angel Capetillo Zavala 6a0c3c9e92 Histórico CaCu: remove the notice above the panels 2026-11-22 02:49:46 -06:00
Angel Capetillo Zavala e3c9849e29 Port TEA and CaCu section 1 adjustments onto the Histórico integration
TEA: Indicadores tab, opportunity summary with real contract values, ordered
opportunity and clinical figures, «No aceptable» label for the EEG quality.
CaCu: renamed lab-result KPI, six time figures under «Tiempo de tamizaje a
diagnóstico», clinical figures with the pending «Progresión por grupo de riesgo».
CaCu's colposcopy and biopsy times use the measures the screening route
publishes and leave them to the route chart while it is shown.
2026-11-22 02:20:31 -06:00
Angel Capetillo Zavala 10773edcc1 Histórico CaCu: remove the simulation-only gate so the tab and its queries behave the same in every build 2026-11-22 02:11:29 -06:00
Angel Capetillo Zavala 8b80e1d26c Checkpoint: Histórico CaCu integration by Codex, before consolidating the TEA/CaCu section 1 work 2026-11-22 02:09:35 -06:00
edgar 2a48c28245 Merge pull request 'CaCu indicators: screening route chart, proportion intervals and survival notebook chooser' (#19) from integration/cacu-indicadores into dev
Reviewed-on: #19
2026-11-22 01:01:26 -06:00
edgar e1a8127c22 feat(indicadores): add the screening route chart to CaCu
Horizontal bars of the days from the sample to each event of the route (cytology result, colposcopy, biopsy result and
diagnosis), cumulative with the Q1 to Q3 interval or step by step with each step starting where the previous one ends.
It reads the seven duration measures of the route and shows up in CaCu's page once the catalog publishes all of them;
the measures only it draws get no card of their own.
2026-11-22 00:23:36 -06:00
edgar 6de193f44e fix(indicadores): draw CaCu's proportions in the history
The WebApi names the group of a proportion `principal`; the page read it as `total` only for CaMa, so the EU13 and
IND1 trends of CaCu came out empty. The rename now applies to every domain.
2026-11-22 00:23:33 -06:00
edgar 0059427179 fix(indicadores): read a proportion's interval as percentages
The ic-bajo and ic-alto of a proportion's score travel as proportions; the rows hold percentages, like the value,
so the history trend draws its confidence band on the same axis.
2026-11-22 00:23:28 -06:00
edgar 8192f92be9 Governance: choose a notebook kept in the code or upload one
The "Correr un notebook" dialog offers "Del código" (the domain's templates from /governance/notebook-templates, each
with the scenarios it can run for) or "Subir archivo". Choosing a template fills its scenario; a scenario it doesn't
serve keeps "Correr" disabled. The request sends the template's id and no file. A domain without templates opens on
the upload, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-22 00:23:28 -06:00
roberto 1fef7812b4 Merge pull request 'CaMa recurrence figure: the y axis follows the months it draws' (#17) from fix/cama-recurrence-axis into dev
Reviewed-on: #17
2026-11-21 15:37:58 -06:00
angel 6465165e34 CaMa recurrence figure: the y axis follows the months it draws 2026-11-21 15:36:00 -06:00
angel a26df55214 Merge pull request 'CaMa patient record: survival and recurrence figures; governance trains any scenario' (#16) from feature/cama-roundtrip into dev
Reviewed-on: #16
2026-11-21 15:03:15 -06:00
rockdrigo 72e5f9bf93 CaMa record: the recurrence analysis only for patients after treatment 2026-11-21 14:57:30 -06:00
rockdrigo 08f1d812ac CaMa patient record as specified: recurrence and survival analyses with a scenario selector and their risk factors 2026-11-21 14:43:46 -06:00
rockdrigo ce207a72a5 Merge origin/dev 2026-11-21 13:50:16 -06:00
rockdrigo 5094880622 CaMa patient record: the recurrence figures of the scenarios she meets 2026-11-21 13:34:56 -06:00
Angel Capetillo Zavala 093ceffa36 feat(indicadores): rename the Seguimiento tab to Análisis de riesgos in CaCu, TEA and CaMa
The tab has the same name in every domain, and the texts that point to it
(patient lists opened from the analysis, the patient file error) use it.
2026-11-21 13:27:15 -06:00
Angel Capetillo Zavala 6a7c1d0cbd feat(home): drop the topbar section label, shorten the eyebrow and rename the indicators action
The topbar no longer shows «Análisis de información» next to the logo; the
breadcrumb stays on the workspace routes. The home eyebrow reads «ISSSTELEON»
and the «Indicadores» action is «Modelos predictivos de riesgo».
2026-11-21 13:27:14 -06:00
rockdrigo fb5a4ed5cc CaMa patient record: the pipeline's figure of each clinical scenario she belongs to, without a curve of her own 2026-11-21 13:14:06 -06:00
rockdrigo e8ce7a487b CaMa patient record: no subgroup panel, one legend entry for the patient 2026-11-21 13:03:19 -06:00
angel a3a552ad0e Merge pull request 'Integration/tea eeg analysis into dev' (#15) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: #15
2026-11-21 12:35:52 -06:00
Angel Capetillo Zavala fb54cfb188 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:41 -06:00
rockdrigo 7adceb86bf CaMa patient record: the pipeline's survival figure with her curve, computed live and comparable with her subgroup 2026-11-21 12:07:21 -06:00
alberto 4e9b25bd8f feat(tea): read the age-norm curve, the age at the EEG and the ADOS-2 relation from the WebApi's FHIR answer 2026-11-21 11:17:59 -06:00
rockdrigo a7b5f4c50b CaMa patient survival figure: the legend claims an interval only when one is drawn 2026-11-21 10:53:41 -06:00
rockdrigo 4d159ae0d0 CaMa survival figure in the patient's risk evaluation instead of a tab; no test-data tags on the risk record 2026-11-21 10:13:47 -06:00
rockdrigo 4fba4fa861 CaMa development view reads each table's column order 2026-11-21 05:03:52 -06:00
rockdrigo db4d743413 Governance: spec for the risk batches panel's domains 2026-11-21 04:48:43 -06:00
rockdrigo d6c52c8536 Governance: risk batches of CaMa beside CaCu's 2026-11-21 04:24:19 -06:00
rockdrigo 1969ffdb5f Merge origin/dev 2026-11-21 04:00:07 -06:00
rockdrigo 699d4b13e1 Merge remote-tracking branch 'origin/feature/cohorts-dbt-canonical' into dev-mvp 2026-11-21 03:59:50 -06:00
rockdrigo c5cbaaab13 CaMa development view on the survival tab; governance trains any scenario in the background 2026-11-21 03:28:13 -06:00
rockdrigo cc802cbb57 The CaMa risk spec builds a summary with the clinical scenario 2026-11-21 03:00:10 -06:00
rockdrigo e7a6398168 Merge origin/feature/tea-eeg-analysis 2026-11-21 02:51:31 -06:00
rockdrigo 62027f2216 Merge origin/ulises/tea-seguimiento 2026-11-21 02:51:31 -06:00
rockdrigo 88dc7537c2 Merge origin/feature/163-cama-risk-curves 2026-11-21 02:51:31 -06:00
rockdrigo 0cb9395cd6 Merge feature/cama-roundtrip 2026-11-21 02:51:31 -06:00
rockdrigo e74e3d8fd4 CaMa: a patient's risk in her record and a Supervivencia tab with the model's curves
The risk table takes a domain (CaCu by default); the CaMa record shows the mortality at 6, 12 and 18 months from the
model's index date. The Supervivencia tab draws the cohort's Kaplan-Meier with its band, the adjusted curve, the fractional
Weibull and the model's survival with its bootstrap interval; its wording comes from the model's settings.
2026-11-21 02:07:34 -06:00
edgar 0fc80bd29a Merge remote-tracking branch 'origin/feature/163-cama-risk-curves' into feature/cohorts-dbt-canonical 2026-11-21 02:06:26 -06:00
rockdrigo dae8bc517e CaMa follow-up: the clinical scenario as Post-tratamiento or En observación in the list, the record and its PDF 2026-11-21 01:55:05 -06:00
alberto 68e2930e65 chore(tea): drop the local simulated-server mode; TEA follow-up reads only the WebApi 2026-11-21 01:30:45 -06:00
Angel Capetillo Zavala bb957ec6a4 fix(indicadores): format the hover text of CaCu's donuts per sector 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 02e28e624b feat(indicadores): read CaCu category groups and stratified compositions from FHIR 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 08161db1c4 feat(indicadores): map CaCu measures to the indicator ids the page reads 2026-11-21 01:27:59 -06:00
ulises fa029d69b8 Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 67ae7f482f TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 304c563845 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises efe4404c4e Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:27:16 -06:00
edgar 7d180417d8 Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:11 -06:00
edgar 00f773dd75 CaCu patient record reads the patient's FHIR RiskAssessment
The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> and validates the searchset Bundle at the
boundary (simulado tag, the patient asked for, one index date, probabilities and intervals); it shows the model, the
risk's index date, the outcome, the evaluation and one row per horizon from each prediction's whenPeriod. The cohort's
definition and the PIMM variables are no longer shown; an empty Bundle is a patient without a confirmed risk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:11:56 -06:00
edgar 3bb1c8dd84 CaCu patient record shows the risk's index date
The record's index date is riesgo.fecha_indice (the model's decision point the horizons count from), not the cohort
member's; the field is optional in the contract and validated as an ISO date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:48 -06:00
AlbertoPMDM ef4f606648 fix(tea): one card per EEG metric and the electrode map within its column
(cherry picked from commit b53322ed72)
2026-11-20 21:56:05 -06:00
ulises 54b3e50ca5 TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:35:24 -06:00
ulises 680cc0adc6 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:06:15 -06:00
AlbertoPMDM b53322ed72 fix(tea): one card per EEG metric and the electrode map within its column 2026-11-20 19:52:10 -06:00
Manuel Aurrecoechea Castillo c32d2b6012 feat(indicadores): show full domain names and share CaMa's summary
CaCu and TEA use the same menu labels and compact summary layout as cáncer de mama.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 19:28:27 -06:00
rockdrigo 7aa3d2c6e6 Stratified bars: a sidebar to show or hide each stratum, and the breakdown in counts or in percent of each stratum 2026-11-20 17:03:41 -06:00
Angel Capetillo Zavala c2c6d9ef47 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:44:48 -06:00
angel d4d3ea3837 Merge pull request 'Restore published CaMa histopathology and mammography counts' (#14) from fix/cama-reversion-selectiva into dev 2026-11-20 10:03:41 -06:00
Angel Capetillo Zavala 3385df4ba3 Merge current WebApp dev into the CaMa selective rollback 2026-11-20 09:57:32 -06:00
Manuel Aurrecoechea Castillo 96b1cabb5a feat(cama): space the opportunity strip, share its period and unify history lines
The section sat flush against its cards, each card repeated the period, the history selector was taller than the summary, and each CaMa line used a different color.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 09:49:32 -06:00
Angel Capetillo Zavala 366591f247 fix(cama): restore published histopathology and mammography counts 2026-11-20 09:07:38 -06:00
angel 241631b884 Merge pull request 'Finalize CaMa wording, demo mammography counts and histologic classification' (#13) from feature/cama-clasificacion-histologica into dev 2026-11-20 00:52:29 -06:00
Angel Capetillo Zavala 6c063344a3 feat(cama): adjust summary wording, double mastography counts and classify histologic types
Reword the histopathologic confirmation note, the BI-RADS 4, 5 or 6 titles and the
radiologic interpretation time title. Show twice the BI-RADS 4, 5 or 6 mastography
counts in the FHIR and base data services. Add the histologic type classification
and a follow-up table column that appears only when a row carries tipo_histologico.
2026-11-20 00:32:27 -06:00
angel 2f5b1ce1f2 Merge pull request 'Feature/cama audit histopathology demo' (#12) from feature/cama-audit-histopathology-demo into dev
Reviewed-on: #12
2026-11-19 19:45:53 -06:00
Angel Capetillo Zavala 56b3ac6b0c feat(cama): add synthetic histopathology breakdown for demo 2026-11-19 19:36:18 -06:00
Angel Capetillo Zavala f6603ae76e fix(cama): align BI-RADS labels and remove historical detection chart 2026-11-19 19:04:22 -06:00
Manuel Aurrecoechea Castillo 21ae95b5ed 20261119 CaMa: ayuda en cada dona de BI-RADS
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:11:20 -06:00
Manuel Aurrecoechea Castillo ce2e86c045 20261119 CaMa: cada dona de BI-RADS lleva su título y la categoría más alta
El resumen ya no repite el porcentaje publicado; pacientes y mastografías se leen en su propia gráfica.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:05:40 -06:00
angel 0f8eb0ec94 Merge pull request 'Add unavailable CaMa diagnosis-to-treatment card' (#11) from feature/cama-diagnosis-to-treatment-card into dev 2026-11-19 17:51:43 -06:00
Angel Capetillo Zavala 2f6d419453 Add unavailable CaMa diagnosis-to-treatment card 2026-11-19 17:48:13 -06:00
Manuel Aurrecoechea Castillo f34f9e1607 20261119 favico 2026-11-19 17:17:45 -06:00
Manuel Aurrecoechea Castillo c7dd134fce 20261119 CaMa titulos ayuda filtros
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 17:13:07 -06:00
Manuel Aurrecoechea Castillo 03cc9c9800 20261119 CaMa: donas de BI-RADS y etiquetas del resumen
La oportunidad dice confirmación histopatológica, la tarjeta de mastografías muestra dos donas y Cómo leer puede reintentar los metadatos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:50:01 -06:00
AlbertoPMDM 04795a09cc feat(tea): read the EEG analysis's verdict, quality checks and age baselines 2026-11-19 15:43:27 -06:00
Manuel Aurrecoechea Castillo de3d247d0d 20261119 Favicon colores textos 2026-11-19 15:10:59 -06:00
Angel Capetillo Zavala ee87bcb8d0 test(webapp): seed the visual login session in indicadores specs
The indicadores navigation, sections and cancer-journey specs routed through
the real routes without a session, so authGuard redirected to LoginPage.
Add auth.testing helpers that seed and clear the sessionStorage session, use
them in those specs, and add a spec that /indicadores/<dominio> without a
session presents LoginPage with returnUrl.
2026-11-19 11:33:26 -06:00
Erick ivan aaeea7a7b0 refactor(auth): keep the session in the browser
The WebApi no longer authenticates, so the login validates against the accounts in auth.service.ts and the session lives in sessionStorage. The guard, the domain guard and the filtering of the import workspace and governance stay as they were; the interceptor and the /auth proxy entries go away because nothing answers 401.
2026-11-19 10:32:25 -06:00
Erick ivan 7f17681409 feat(auth): login screen and domain-scoped navigation
Session login against /auth/*, with a guard on every route and an interceptor that returns to the login on 401. The header, the import workspace and both governance panels only offer the account's own domains (auth/dominios.ts), and a batch opens on the account's database.

The sign-in screen follows the app's palette: logo above the title, the action button in the shared tokens, and no register or password-recovery rows.
2026-11-19 09:36:54 -06:00
angel d72c18756f Merge pull request 'test(indicadores): follow the published CAM-03 title and the Análisis tab' (#10) from fix/ci-spec-contracts into dev
Reviewed-on: #10
2026-11-19 00:09:54 -06:00
Angel Capetillo Zavala baf5edca42 test(indicadores): follow the published CAM-03 title and the Análisis tab
The history names CAM-03 «Resultado histopatológico»; the CAM-03 expectation in the F4C spec
now uses that title.

The CaMa page does not offer the Análisis tab while CAMA_ANALYSIS_ENABLED is off. The journey
specs that open it run only while the flag is on and are reported as skipped otherwise. The
domain-change spec selects patients through the page instead of through that tab, so it keeps
checking that the selection is cleared and that CaCu and TEA keep their sections.
2026-11-18 23:41:41 -06:00
Manuel Aurrecoechea Castillo fefa28ae7a 20261118 Pastilla Fix 2026-11-18 16:53:56 -06:00
Manuel Aurrecoechea Castillo a217ddae38 20261118 Color Fix 2026-11-18 16:10:11 -06:00
Manuel Aurrecoechea Castillo 97fcb37761 20261118 Sharts Colors 2026-11-18 15:43:23 -06:00
Manuel Aurrecoechea Castillo 58ff3870be 20261118 colorfix front
Cambio de los colores de las graficas para tener una mejor armonía de colores y evitar el uso de la unión de colores que interpreten ideas falsas
2026-11-18 15:16:13 -06:00
Angel Capetillo Zavala 439a039ff4 fix(cama): recuperar el tamaño responsivo de la dona BI-RADS 2026-11-18 14:58:54 -06:00
Angel Capetillo Zavala 049a9ca43c fix(cama): ocultar temporalmente la pestaña Análisis 2026-11-18 14:15:49 -06:00
Angel Capetillo Zavala f128f2e13a fix(cama): mostrar solo el conteo al pasar sobre la dona 2026-11-18 13:15:54 -06:00
Angel Capetillo Zavala 20b8c80aaf fix(cama): equilibrar centro y anillo de la dona 2026-11-18 12:56:27 -06:00
Angel Capetillo Zavala 8e85c91f15 fix(cama): completar ajustes visuales de indicadores 2026-11-18 12:23:17 -06:00
Angel Capetillo Zavala 1ac8d5c258 fix(cama): ajustar resumen y ocultar análisis 2026-11-18 09:25:38 -06:00
Angel Capetillo Zavala 23cd89e882 Adjust CaMa indicator labels 2026-11-17 12:44:25 -06:00
Angel Capetillo Zavala 47a0ab5f1b Connect CaMa dashboard to follow-up, analysis and L3 FHIR measures
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes dc37c54938 wording fixes 2026-11-17 02:17:24 -06:00
roberto 2834fac85c Merge pull request 'Kit exit: TEA over FHIR, dashboard-test presentation merged in' (#9) from feature/kit-exit-integration into dev
Reviewed-on: #9
2026-11-16 21:09:07 -06:00
320 changed files with 36046 additions and 1704 deletions
+15
View File
@@ -62,6 +62,17 @@
"optimization": false,
"extractLicenses": false,
"sourceMap": true
},
"simulado": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/app/app.config.ts",
"with": "src/app/app.config.simulado.ts"
}
]
}
},
"defaultConfiguration": "production"
@@ -77,6 +88,10 @@
},
"development": {
"buildTarget": "WebApp:build:development"
},
"simulado": {
"buildTarget": "WebApp:build:simulado",
"proxyConfig": "simulado/proxy.simulado.json"
}
},
"defaultConfiguration": "development"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 717 B

+38
View File
@@ -0,0 +1,38 @@
# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`)
Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso.
Todo es **inventado**. No forma parte de la WebApp que se entrega.
| Archivo | Qué es |
|---|---|
| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona |
| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` |
| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba |
| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) |
## Cómo se usa
1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`:
```
python experimentos/E27_modelo_or/simulado_plataforma.py
```
2. Levantar el servidor de prueba, desde `webapp-tea/`:
```
python simulado/servidor.py
```
3. En otra terminal, la página, desde `webapp-tea/`:
```
npx ng serve --configuration simulado --port 4300
```
4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente.
## El panel nuevo: «Relación con el ADOS-2»
En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05):
- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2);
- el aspecto del ADOS-2 (reactivo o dominio);
- el OR de la cohorte con su intervalo y su q;
- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0;
- lo que muestra su ADOS-2.
El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece.
+47
View File
@@ -0,0 +1,47 @@
{
"/api": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/imports": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/data": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/health": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/cacu": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/cama": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/tea": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/governance": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/reportes": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
}
}
+110
View File
@@ -0,0 +1,110 @@
"""
servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa.
Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega.
Responde lo que pide la sección de seguimiento de TEA en su contrato JSON:
- `/tea/seguimiento`: la lista, con filtros y páginas;
- `/tea/seguimiento/<id>`: la ficha, incluido el campo nuevo `relacion_ados2`.
A lo demás de `/tea/...` contesta vacío, para que la página cargue.
Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`.
python simulado/servidor.py # http://localhost:5051
npx ng serve --configuration simulado --port 4300
"""
from __future__ import annotations
import json
import math
import sys
from datetime import date, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
PUERTO = 5051
DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8"))
VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []}
def _num(q, k):
v = q.get(k, [None])[0]
try:
return float(v) if v is not None else None
except ValueError:
return None
def lista(q: dict) -> dict:
meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12
corte = q.get("corte", [date.today().isoformat()])[0]
page = max(1, int(q.get("page", ["1"])[0]))
size = min(200, max(1, int(q.get("page_size", ["25"])[0])))
filtro = q.get("alteraciones_eeg", [None])[0]
ps = DATOS["pacientes"]
if filtro in ("normal", "anormal"):
ps = [p for p in ps if p["alteraciones_eeg"] == filtro]
elif filtro == "sin_eeg_valido":
ps = [p for p in ps if p["ultimo_eeg"] is None]
if q.get("grupo_edad"):
ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))]
for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")):
a, b = _num(q, lo), _num(q, hi)
if a is not None:
ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)]
if q.get("estado_caso"):
ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]]
if q.get("alteracion"):
ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]]
total = len(ps)
por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)}
for t in DATOS["tipos_alteracion"]]
hasta = date.fromisoformat(corte)
return {
"simulado": True, "corte": corte,
"ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte},
"filtros": {"alteraciones_eeg": filtro},
"paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))},
"items": ps[(page - 1) * size: page * size],
"tipos_alteracion": DATOS["tipos_alteracion"],
"resumen_eeg": {"validadas": True, "con_eeg_valido": total,
"normales": sum(p["alteraciones_eeg"] == "normal" for p in ps),
"anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0,
"por_alteracion": por_alt},
}
class Manejador(BaseHTTPRequestHandler):
def _json(self, cuerpo, codigo=200):
datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8")
self.send_response(codigo)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(datos)))
self.end_headers()
self.wfile.write(datos)
def do_GET(self): # noqa: N802
u = urlparse(self.path)
ruta, q = u.path.rstrip("/"), parse_qs(u.query)
if ruta == "/tea/seguimiento":
return self._json(lista(q))
if ruta.startswith("/tea/seguimiento/"):
d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1]))
return self._json(d) if d else self._json({"error": "no encontrado"}, 404)
if "/fhir/" in ruta:
return self._json(VACIO_FHIR)
if ruta.endswith("/indicadores"):
return self._json([])
if ruta == "/health":
return self._json({"status": "ok", "simulado": True})
return self._json({"error": "sin datos simulados para esta ruta"}, 404)
def log_message(self, fmt, *args):
sys.stderr.write(" " + fmt % args + "\n")
if __name__ == "__main__":
print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)")
ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever()
+7 -5
View File
@@ -37,10 +37,11 @@ describe('Encabezado del marco', () => {
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
// Fails if the selector would point at a route the application does not have.
const paths = routes.map(r => r.path);
// The application's routes live under the guarded parent ('login' is its sibling).
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
});
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
it.each([['tea', 'Trastorno del espectro autista'], ['cacu', 'Cáncer cervicouterino'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
await ir('/indicadores/' + dominio);
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
@@ -59,7 +60,7 @@ describe('Encabezado del marco', () => {
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
await ir('/indicadores/cama');
const items = await abrirMenu();
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
expect(items.map(a => a.textContent?.trim())).toEqual(['Trastorno del espectro autista', 'Cáncer cervicouterino']);
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
});
@@ -68,7 +69,7 @@ describe('Encabezado del marco', () => {
const items = await abrirMenu();
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
expect(router.url).toBe('/indicadores/cacu');
expect(selector()!.textContent).toContain('CaCu');
expect(selector()!.textContent).toContain('Cáncer cervicouterino');
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
const ubicacion = TestBed.inject(Location);
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
@@ -79,7 +80,8 @@ describe('Encabezado del marco', () => {
await ir(url);
expect(selector()).toBeNull();
expect(root().querySelector('.platform-title')).toBeNull();
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
expect(root().querySelector('.site-header__section')).toBeNull();
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
});
+21
View File
@@ -0,0 +1,21 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { IndicadoresService } from './features/indicadores/indicadores.service';
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento
// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`).
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
]
};
+2
View File
@@ -12,6 +12,8 @@ export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
// La sesión es del navegador (`auth/auth.service.ts`): no hay interceptor
// porque la WebApi no responde 401.
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
+41 -23
View File
@@ -1,33 +1,51 @@
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
<header class="site-header">
<div class="site-header__content">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
@defer (on immediate) {
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
} @placeholder {
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
}
} @else {
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
@if (!sinCromo()) {
<header class="site-header">
<div class="site-header__content">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
@if (otherDomains().length) {
@defer (on immediate) {
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
} @placeholder {
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
}
} @else {
<!-- An account with a single domain has nothing to switch to: the domain is a label. -->
<span class="domain-selector domain-selector--espera">{{ domainLabels[domain] }}</span>
}
</nav>
}
</div>
</header>
} @else {
<nav class="site-header__nav" aria-label="Secciones">
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
}
</nav>
}
@if (usuario(); as sesion) {
<button
class="site-header__salir"
type="button"
(click)="salir()"
[attr.title]="'Cerrar sesión de ' + sesion.nombre"
[attr.aria-label]="'Cerrar sesión de ' + sesion.nombre"
>
<mat-icon aria-hidden="true">logout</mat-icon>
<span class="site-header__salir-nombre">{{ sesion.nombre }}</span>
</button>
}
</div>
</header>
}
<main class="app-main">
<router-outlet />
</main>
@if (!workspace()) {
@if (!workspace() && !sinCromo()) {
<footer class="site-footer">
<div class="site-footer__content">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
+57 -37
View File
@@ -1,49 +1,69 @@
import { Routes } from '@angular/router';
import { Home } from './home';
import { authGuard } from './auth/auth.guard';
import { dominioGuard } from './auth/dominio.guard';
import { DOMINIOS } from './features/indicadores/indicadores.models';
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
export const routes: Routes = [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
data: { workspace: true, breadcrumb: 'Casos por estatus' },
path: 'login',
title: 'Inicio de sesión | ISSSTELEON',
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
data: { sinCromo: true },
},
{
path: 'conectar',
title: 'Conectar datos | ISSSTELEON',
// Lazy: the workspace (and the ~15 Material modules it uses) only
// downloads when someone actually opens it.
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
data: { workspace: true, breadcrumb: 'Conectar datos' },
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
path: '',
canActivateChild: [authGuard],
children: [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
canActivate: [dominioGuard],
data: { workspace: true, breadcrumb: 'Casos por estatus', dominio: 'tea' },
},
{
path: 'conectar',
title: 'Conectar datos | ISSSTELEON',
// Lazy: the workspace (and the ~15 Material modules it uses) only
// downloads when someone actually opens it.
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
data: { workspace: true, breadcrumb: 'Conectar datos' },
},
{
path: 'gobernanza',
title: 'Gobernanza de modelos | ISSSTELEON',
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
},
{
path: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
// The page reads CaCu's measures: an account of another domain goes to its own.
canActivate: [dominioGuard],
data: { workspace: true, breadcrumb: 'Indicadores', dominio: 'cacu' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
title: 'Indicadores | ISSSTELEON',
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
canActivate: [dominioGuard],
loadComponent: loadIndicadores,
})),
{ path: '**', redirectTo: '' },
],
},
{
path: 'gobernanza',
title: 'Gobernanza de modelos | ISSSTELEON',
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
},
{
path: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
data: { workspace: true, breadcrumb: 'Indicadores' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
title: 'Indicadores | ISSSTELEON',
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
loadComponent: loadIndicadores,
})),
{ path: '**', redirectTo: '' },
];
+69 -19
View File
@@ -41,14 +41,6 @@
font-weight: 600;
}
.site-header__section {
text-decoration: none;
color: var(--color-text);
font-size: 15px;
font-weight: 500;
letter-spacing: 0.01em;
}
.app-main {
display: flex;
flex: 1;
@@ -89,11 +81,6 @@
width: clamp(132px, 42vw, 170px);
}
.site-header__section {
font-size: 13px;
text-align: right;
}
.site-footer__content {
min-height: 76px;
padding: 0 20px;
@@ -117,12 +104,75 @@
.domain-selector--espera {
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
min-height: 40px; padding: 0 16px; white-space: nowrap;
}
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
@media (max-width: 599px) {
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
.app-shell--indicadores .brand { margin-inline-end: auto; }
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
/* Session exit: the same action look as the home buttons, in header size. */
.site-header__salir {
align-items: center;
background: transparent;
border: 1px solid var(--color-action);
border-radius: 8px;
color: var(--color-text);
cursor: pointer;
display: inline-flex;
flex: none;
font: inherit;
font-size: 13px;
font-weight: 600;
gap: 6px;
margin-inline-start: var(--space-4);
min-height: 34px;
padding: 0 var(--space-3);
transition:
background-color 0.2s ease,
border-color 0.2s ease,
color 0.2s ease;
}
.site-header__salir:hover {
background: var(--color-action-hover);
border-color: var(--color-action);
}
.site-header__salir:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
.site-header__salir mat-icon {
color: var(--color-action);
font-size: 18px;
height: 18px;
width: 18px;
}
// Full domain names need their own track. On a wide header they sit beside the title;
// below 900px the name takes a row of its own so the logo and the exit stay together.
.app-shell--indicadores .site-header__content {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto auto;
grid-template-areas: "brand title domain salir";
align-items: center;
column-gap: 16px;
row-gap: 8px;
padding-block: 8px;
}
.app-shell--indicadores .brand { grid-area: brand; }
.app-shell--indicadores .platform-title { grid-area: title; margin: 0; overflow-wrap: normal; }
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { grid-area: domain; justify-self: end; }
.app-shell--indicadores .site-header__salir { grid-area: salir; margin-inline-start: 0; }
@media (max-width: 900px) {
.app-shell--indicadores .site-header__content {
grid-template-columns: auto minmax(0, 1fr);
grid-template-areas:
"brand salir"
"domain domain"
"title title";
}
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { justify-self: start; white-space: normal; }
.app-shell--indicadores .platform-title { font-size: 1.125rem; }
}
+105 -25
View File
@@ -1,46 +1,126 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter, Router } from '@angular/router';
import { of } from 'rxjs';
import { App } from './app';
import { routes } from './app.routes';
import { AuthService, Usuario } from './auth/auth.service';
const TODOS: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] };
/**
* Doble de la sesión: `App` lee la señal y los guards preguntan si hay sesión y
* qué dominios alcanza. Las pruebas de este archivo cubren el marco, no el
* inicio de sesión en sí (`auth/auth.service.spec.ts`).
*/
function authFalso(sesion: Usuario | null) {
return {
usuario: signal(sesion),
autenticado: signal(sesion !== null),
sesion: () => of(sesion),
puedeVer: (dominio: string) => sesion?.dominios.includes(dominio) ?? false,
logout: () => of(undefined),
limpiar: () => undefined,
};
}
async function montar(sesion: Usuario | null): Promise<Router> {
await TestBed.configureTestingModule({
imports: [App],
providers: [
provideRouter(routes),
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AuthService, useValue: authFalso(sesion) },
],
}).compileComponents();
return TestBed.inject(Router);
}
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
}).compileComponents();
});
async function render(url: string) {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl(url);
await TestBed.inject(Router).navigateByUrl(url).catch(() => false);
await fixture.whenStable();
fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
}
it('renders the ISSSTELEON shell and home page with its footer', async () => {
const page = await render('/');
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
expect(page.querySelector('.site-footer')).not.toBeNull();
describe('con sesión de administrador', () => {
beforeEach(() => montar(TODOS));
it('renders the ISSSTELEON shell and home page with its footer', async () => {
const page = await render('/');
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
expect(page.querySelector('.site-footer')).not.toBeNull();
});
it('home shows only the brand name as eyebrow and names the risk models action', async () => {
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
const page = await render('/');
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
expect(page.querySelector('.site-footer')).toBeNull();
}, 15000);
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
const page = await render('/gobernanza');
expect(page.querySelector('app-governance-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
expect(page.querySelector('.site-footer')).toBeNull();
});
it('el encabezado nombra al usuario de la sesión y ofrece cerrarla', async () => {
// Fails if the shell forgets the session: the user would have no way out.
const page = await render('/');
expect(page.querySelector('.site-header__salir')?.textContent).toContain('Administrador');
});
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
expect(page.querySelector('.site-footer')).toBeNull();
describe('con una cuenta de un solo dominio', () => {
beforeEach(() => montar({ usuario: 'cacu', nombre: 'Equipo CaCu', dominios: ['cacu'] }));
it('no deja abrir el dominio ajeno: la manda al suyo', async () => {
// Fails if the domain scope exists only on the server: the interface would show an empty page.
await render('/indicadores/cama');
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
}, 15000);
it('el encabezado no ofrece los otros dominios', async () => {
const page = await render('/indicadores/cacu');
expect(page.querySelector('app-domain-selector')).toBeNull();
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('Cáncer cervicouterino');
});
});
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
const page = await render('/gobernanza');
expect(page.querySelector('app-governance-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
expect(page.querySelector('.site-footer')).toBeNull();
describe('sin sesión', () => {
beforeEach(() => montar(null));
it('cualquier ruta manda al inicio de sesión y no muestra el marco', async () => {
const page = await render('/conectar');
expect(TestBed.inject(Router).url).toContain('/login');
expect(page.querySelector('.login')).not.toBeNull();
expect(page.querySelector('.site-header')).toBeNull();
expect(page.querySelector('.site-footer')).toBeNull();
expect(page.querySelector('app-connect-page')).toBeNull();
});
it('el destino pedido viaja en returnUrl para volver después de entrar', async () => {
await render('/gobernanza');
expect(TestBed.inject(Router).url).toContain('returnUrl=%2Fgobernanza');
});
});
});
+25 -3
View File
@@ -1,12 +1,14 @@
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
import { AuthService } from './auth/auth.service';
import { DomainSelector } from './domain-selector';
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
@Component({
imports: [RouterLink, RouterOutlet, DomainSelector],
imports: [MatIconModule, RouterLink, RouterOutlet, DomainSelector],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
@@ -14,6 +16,7 @@ import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
export class App {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly auth = inject(AuthService);
private readonly leafRouteData = toSignal(
this.router.events.pipe(
@@ -30,13 +33,32 @@ export class App {
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
/** The login screen (`data.sinCromo`) owns the whole window: no header, no footer. */
readonly sinCromo = computed(() => !!this.leafRouteData()['sinCromo']);
protected readonly usuario = this.auth.usuario;
protected readonly title = 'Plataforma de Indicadores';
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
protected readonly domainLabels: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', 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()));
/** Only the domains the account may see: the header never offers a forbidden one. */
private readonly permitidos = computed<readonly Dominio[]>(() => {
const sesion = this.auth.usuario();
return sesion ? DOMINIOS.filter(dominio => sesion.dominios.includes(dominio)) : DOMINIOS;
});
protected readonly otherDomains = computed(() =>
this.permitidos().filter(domain => domain !== this.activeDomain()));
protected salir(): void {
// Whether the server session was already gone, the browser ends up at the login screen.
this.auth.logout().subscribe({
next: () => void this.router.navigate(['/login']),
error: () => void this.router.navigate(['/login']),
});
}
}
+22
View File
@@ -0,0 +1,22 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
/**
* Sin sesión no hay ruta protegida: se manda al inicio de sesión y se recuerda
* `returnUrl` para volver a donde iba el usuario.
*/
export const authGuard: CanActivateFn = (_ruta, estado) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth
.sesion()
.pipe(
map(
(usuario) =>
usuario !== null ||
router.createUrlTree(['/login'], { queryParams: { returnUrl: estado.url } }),
),
);
};
+60
View File
@@ -0,0 +1,60 @@
// La sesión vive en el navegador (la WebApi no autentica): estas pruebas fijan
// el contrato del servicio —quién entra, qué dominios ve y qué queda guardado—
// porque de él dependen el guard de rutas y el recorte de los selectores.
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let auth: AuthService;
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({});
auth = TestBed.inject(AuthService);
});
it('entra con la contraseña correcta y deja al usuario en la señal', () => {
auth.login('cama', 'cama2026').subscribe();
expect(auth.usuario()).toEqual({ usuario: 'cama', nombre: 'Equipo CaMa', dominios: ['cama'] });
expect(auth.autenticado()).toBe(true);
});
it('rechaza una contraseña incorrecta sin abrir sesión', () => {
let error: Error | undefined;
auth.login('cama', 'otra').subscribe({ error: (e: Error) => (error = e) });
expect(error?.message).toContain('incorrectos');
expect(auth.autenticado()).toBe(false);
});
it('dice qué dominios puede ver la cuenta', () => {
auth.login('cama', 'cama2026').subscribe();
expect(auth.puedeVer('cama')).toBe(true);
expect(auth.puedeVer('cacu')).toBe(false);
expect(auth.puedeVer('tea')).toBe(false);
});
it('el administrador ve los tres dominios', () => {
auth.login('admin', 'admin2026').subscribe();
expect(['cacu', 'cama', 'tea'].every((dominio) => auth.puedeVer(dominio))).toBe(true);
});
it('cerrar sesión borra al usuario y lo guardado', () => {
auth.login('tea', 'tea2026').subscribe();
auth.logout().subscribe();
expect(auth.autenticado()).toBe(false);
expect(sessionStorage.getItem('isssteleon.sesion')).toBeNull();
});
it('la sesión sobrevive a una recarga de la pestaña', () => {
// Fails if the login is kept only in memory: a refresh would log the team out mid-task.
auth.login('cacu', 'cacu2026').subscribe();
TestBed.resetTestingModule();
TestBed.configureTestingModule({});
expect(TestBed.inject(AuthService).usuario()?.usuario).toBe('cacu');
});
});
+91
View File
@@ -0,0 +1,91 @@
import { Injectable, computed, signal } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
/** El usuario de la sesión, con los dominios que la interfaz le deja ver. */
export interface Usuario {
readonly usuario: string;
readonly nombre: string;
readonly dominios: readonly string[];
}
/**
* Cuentas de la interfaz. La WebApi no tiene autenticación: el inicio de sesión
* y el recorte por dominio viven aquí, en el navegador, para ordenar el trabajo
* de cada equipo. No son seguridad: cualquiera puede leer esta lista en el
* paquete de la aplicación y la API responde a quien la llame.
*/
const CUENTAS: readonly (Usuario & { contrasena: string })[] = [
{ usuario: 'admin', contrasena: 'admin2026', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] },
{ usuario: 'cacu', contrasena: 'cacu2026', nombre: 'Equipo CaCu', dominios: ['cacu'] },
{ usuario: 'cama', contrasena: 'cama2026', nombre: 'Equipo CaMa', dominios: ['cama'] },
{ usuario: 'tea', contrasena: 'tea2026', nombre: 'Equipo TEA', dominios: ['tea'] },
];
/** La sesión se guarda por pestaña: cerrar el navegador pide entrar de nuevo. */
const CLAVE = 'isssteleon.sesion';
/**
* Sesión local de la aplicación. Es la única fuente de verdad del usuario: el
* guard pregunta aquí, los paneles filtran dominios con `puedeVer` y salir solo
* borra el registro del navegador.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly usuarioActual = signal<Usuario | null>(this.leer());
readonly usuario = this.usuarioActual.asReadonly();
readonly autenticado = computed(() => this.usuarioActual() !== null);
/** Si la cuenta puede ver ese dominio. Sin sesión no se opina (los guards deciden). */
puedeVer(dominio: string): boolean {
const sesion = this.usuarioActual();
return sesion ? sesion.dominios.includes(dominio) : true;
}
/** La sesión guardada en esta pestaña; se resuelve al instante, sin servidor. */
sesion(): Observable<Usuario | null> {
return of(this.usuarioActual());
}
/** Valida contra la lista local; un error marca las credenciales como incorrectas. */
login(usuario: string, contrasena: string): Observable<Usuario> {
const cuenta = CUENTAS.find((c) => c.usuario === usuario.trim() && c.contrasena === contrasena);
if (!cuenta) return throwError(() => new Error('usuario o contraseña incorrectos'));
const sesion: Usuario = { usuario: cuenta.usuario, nombre: cuenta.nombre, dominios: [...cuenta.dominios] };
this.establecer(sesion);
return of(sesion);
}
logout(): Observable<void> {
this.limpiar();
return of(undefined);
}
limpiar(): void {
this.usuarioActual.set(null);
try {
sessionStorage.removeItem(CLAVE);
} catch {
// Almacenamiento deshabilitado: la sesión dura lo que la pestaña en memoria.
}
}
private establecer(sesion: Usuario): void {
this.usuarioActual.set(sesion);
try {
sessionStorage.setItem(CLAVE, JSON.stringify(sesion));
} catch {
// Idem: sin almacenamiento, la sesión no sobrevive a una recarga.
}
}
private leer(): Usuario | null {
try {
const crudo = sessionStorage.getItem(CLAVE);
if (!crudo) return null;
const sesion = JSON.parse(crudo) as Usuario;
return typeof sesion?.usuario === 'string' && Array.isArray(sesion.dominios) ? sesion : null;
} catch {
return null;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import { Usuario } from './auth.service';
/** Same key AuthService persists the visual session under. */
const CLAVE_SESION = 'isssteleon.sesion';
/**
* Seeds the browser-only visual session before the router and AuthService are created,
* so routes behind authGuard render instead of redirecting to /login. Pair every call
* with `limpiarSesionVisual()` in afterEach so the session never leaks between tests.
*/
export function iniciarSesionVisual(sesion: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] }): void {
sessionStorage.setItem(CLAVE_SESION, JSON.stringify(sesion));
}
export function limpiarSesionVisual(): void {
sessionStorage.removeItem(CLAVE_SESION);
}
+22
View File
@@ -0,0 +1,22 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
/**
* Cada cuenta ve solo sus dominios: una ruta con `data.dominio` ajeno manda a la
* cuenta a su primer dominio. Sin sesión no decide nada (`authGuard` ya la
* mandó al inicio de sesión).
*/
export const dominioGuard: CanActivateFn = (ruta) => {
const auth = inject(AuthService);
const router = inject(Router);
const pedido = ruta.data?.['dominio'] as string | undefined;
return auth.sesion().pipe(
map((usuario) => {
if (!usuario || !pedido || usuario.dominios.includes(pedido)) return true;
const propio = usuario.dominios[0];
return propio ? router.createUrlTree(['/indicadores', propio]) : router.createUrlTree(['/']);
}),
);
};
+27
View File
@@ -0,0 +1,27 @@
import { AuthService } from './auth.service';
/**
* Helpers for the screens that list domains (cargar información, gobernanza):
* an account only ever sees its own, and «Todos» only belongs to one that
* reaches every domain — the administrator.
*/
/** De la lista dada, las entradas cuyo dominio alcanza la cuenta. */
export function dominiosPermitidos<T extends { id: string }>(auth: AuthService, dominios: readonly T[]): T[] {
return dominios.filter((dominio) => auth.puedeVer(dominio.id));
}
/** Si la cuenta alcanza todos: solo entonces tiene sentido ofrecer «Todos». */
export function alcanzaTodos(auth: AuthService, dominios: readonly { id: string }[]): boolean {
return dominios.every((dominio) => auth.puedeVer(dominio.id));
}
/**
* El dominio con el que abre una pantalla: el único que alcanza la cuenta, o
* `null` («Todos») cuando alcanza varios. Sin sesión resuelta devuelve `null`,
* que es el comportamiento de siempre.
*/
export function dominioInicial<T extends string>(auth: AuthService, dominios: readonly { id: T }[]): T | null {
const propios = dominiosPermitidos(auth, dominios);
return propios.length === 1 ? propios[0].id : null;
}
+59
View File
@@ -0,0 +1,59 @@
<section class="login" aria-labelledby="login-titulo">
<div class="login__caja">
<img class="login__logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
<h1 class="login__titulo" id="login-titulo">Inicio de sesión</h1>
<form class="login__formulario" (ngSubmit)="ingresar()" novalidate>
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
<input
matInput
name="usuario"
[(ngModel)]="usuario"
placeholder="Usuario"
aria-label="Usuario"
autocomplete="username"
autocapitalize="none"
spellcheck="false"
/>
</mat-form-field>
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
<input
matInput
name="contrasena"
[(ngModel)]="contrasena"
[type]="verContrasena() ? 'text' : 'password'"
placeholder="Contraseña"
aria-label="Contraseña"
autocomplete="current-password"
/>
<button
mat-icon-button
matSuffix
type="button"
class="login__ojo"
(click)="mostrarContrasena()"
[attr.aria-label]="verContrasena() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="verContrasena()"
>
<mat-icon>{{ verContrasena() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</mat-form-field>
@if (error(); as mensaje) {
<p class="login__error" role="alert">{{ mensaje }}</p>
}
<button
type="submit"
class="login__ingresar"
[disabled]="!usuario.trim() || !contrasena || enviando()"
>
{{ enviando() ? 'Ingresando…' : 'Ingresar' }}
</button>
</form>
<p class="login__legal">©{{ anio }} Todos los derechos reservados.</p>
</div>
</section>
+170
View File
@@ -0,0 +1,170 @@
:host {
display: flex;
flex: 1;
min-width: 0;
/* The button borrows the home actions' palette: white with a thin gray border
until the form is complete, then `--color-action` (see styles.scss). */
--login-fondo: #f8f9fa;
--login-borde: #e9ecef;
}
.login {
align-items: center;
display: flex;
flex: 1;
justify-content: center;
/* The whole block sits a little below the middle: the logo above it gives the screen its weight. */
padding: var(--space-9) var(--space-5) var(--space-8);
}
.login__caja {
display: flex;
flex-direction: column;
gap: var(--space-4);
max-width: 340px;
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it: it is what fills the empty space. */
.login__logo {
align-self: center;
display: block;
margin-bottom: 0;
width: 260px;
animation: login-logo-entrada 600ms ease-out both;
}
@keyframes login-logo-entrada {
from {
opacity: 0;
transform: translateY(-8px);
}
to {
opacity: 1;
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.login__logo {
animation: none;
}
}
.login__titulo {
align-items: center;
color: var(--color-text);
display: flex;
font-family: var(--font-heading);
font-size: 1.375rem;
font-weight: 600;
gap: var(--space-4);
margin: 0 0 var(--space-2);
white-space: nowrap;
}
/* The two rules that flank the title, as in the reference screen. */
.login__titulo::before,
.login__titulo::after {
background: var(--color-border);
content: '';
flex: 1;
height: 1px;
}
.login__formulario {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.login__campo {
width: 100%;
--mat-form-field-container-height: 44px;
--mat-form-field-container-vertical-padding: 12px;
}
.login__ojo {
color: var(--color-text-secondary);
}
/* Edge paints its own reveal control over the password field; the eye in the field is ours. */
.login__campo input::-ms-reveal,
.login__campo input::-ms-clear {
display: none;
}
.login__error {
color: var(--mat-sys-error);
font-size: 0.875rem;
margin: calc(-1 * var(--space-1)) 0 0;
}
/* The button shares the fields' width: one column, one border, no icon and no underline.
Its border turns teal when the form is complete, and it fades in instead of switching. */
.login__ingresar {
align-items: center;
background: var(--login-fondo);
border: 1px solid var(--login-borde);
border-radius: 10px;
color: var(--color-text-secondary);
cursor: default;
display: flex;
font: inherit;
font-size: 0.9375rem;
font-weight: 500;
justify-content: center;
margin-top: var(--space-2);
min-height: 46px;
padding: 0 var(--space-5);
text-decoration: none;
transition:
background-color 260ms ease,
border-color 260ms ease,
color 260ms ease;
width: 100%;
}
.login__ingresar:not(:disabled) {
border-color: var(--color-action);
color: var(--color-text);
cursor: pointer;
}
.login__ingresar:hover:not(:disabled) {
background: var(--color-action-hover);
border-color: var(--color-action);
}
.login__ingresar:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
.login__ingresar:disabled {
background: var(--login-fondo);
border-color: var(--login-borde);
}
.login__legal {
color: var(--color-text-secondary);
font-size: 0.8125rem;
margin: var(--space-4) 0 0;
text-align: center;
}
@media (max-width: 600px) {
.login {
padding: var(--space-7) var(--space-4);
}
.login__caja {
max-width: 100%;
}
.login__logo {
width: 208px;
}
}
+61
View File
@@ -0,0 +1,61 @@
import { Component, OnInit, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from './auth.service';
/**
* Inicio de sesión: valida contra las cuentas locales de `AuthService` y, si el
* usuario ya tiene sesión, salta al destino. `returnUrl` lo pone el guard cuando
* una ruta protegida lo trajo aquí.
*/
@Component({
selector: 'app-login-page',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
styleUrl: './login-page.scss',
templateUrl: './login-page.html',
})
export class LoginPage implements OnInit {
private readonly auth = inject(AuthService);
private readonly router = inject(Router);
private readonly ruta = inject(ActivatedRoute);
protected usuario = '';
protected contrasena = '';
protected readonly verContrasena = signal(false);
protected readonly enviando = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly anio = new Date().getFullYear();
ngOnInit(): void {
// Quien ya inició sesión y abre /login vuelve derecho a la aplicación.
this.auth.sesion().subscribe((usuario) => {
if (usuario) void this.router.navigateByUrl(this.destino());
});
}
protected ingresar(): void {
if (!this.usuario.trim() || !this.contrasena || this.enviando()) return;
this.enviando.set(true);
this.error.set(null);
this.auth.login(this.usuario.trim(), this.contrasena).subscribe({
next: () => void this.router.navigateByUrl(this.destino()),
error: () => {
this.enviando.set(false);
this.error.set('Usuario o contraseña incorrectos.');
},
});
}
protected mostrarContrasena(): void {
this.verContrasena.update((visible) => !visible);
}
private destino(): string {
const pedido = this.ruta.snapshot.queryParamMap.get('returnUrl');
return pedido?.startsWith('/') && !pedido.startsWith('/login') ? pedido : '/';
}
}
@@ -17,7 +17,7 @@
aria-label="Base de datos destino"
[matTooltip]="store.domainLocked() ? 'Una carga va a una sola base; quita los flujos para cambiarla' : 'Base de datos destino'"
>
@for (domain of domains; track domain.id) {
@for (domain of domains(); track domain.id) {
<mat-button-toggle [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@@ -1,6 +1,6 @@
import { DragDropModule } from '@angular/cdk/drag-drop';
import { DecimalPipe } from '@angular/common';
import { Component, Injector, inject, signal } from '@angular/core';
import { Component, Injector, computed, inject, signal } from '@angular/core';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
@@ -12,6 +12,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Domain, TargetMeta } from '../../api/api.types';
import { AuthService } from '../../../auth/auth.service';
import { dominiosPermitidos } from '../../../auth/dominios';
import { DataConnection, SourceTable } from '../../domain/data-source';
import { PdfConnection } from '../../domain/pdf-source';
import { SqlConnection } from '../../domain/sql-source';
@@ -59,11 +61,13 @@ import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-di
})
export class ConnectPage {
readonly store = inject(ConnectWorkspaceStore);
private readonly auth = inject(AuthService);
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly injector = inject(Injector);
readonly domains = DOMAINS;
/** Only the account's own databases: the picker never offers a domain the server will reject. */
readonly domains = computed(() => dominiosPermitidos(this.auth, DOMAINS));
readonly paneOpen = signal(true);
readonly validatingAll = signal(false);
@@ -100,8 +100,8 @@
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Olvidar esta conexión guardada"
matTooltip="Olvidar"
aria-label="Eliminar esta conexión guardada"
matTooltip="Eliminar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
@@ -134,7 +134,7 @@
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Recordar servidor, usuario y base de datos (nunca la contraseña)
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
</mat-checkbox>
}
@@ -1,5 +1,6 @@
import { TestBed } from '@angular/core/testing';
import { Observable, firstValueFrom, of } from 'rxjs';
import { AuthService } from '../../auth/auth.service';
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
import { ImportsApi } from '../api/imports.api';
import { SourceGateway } from '../api/source-gateway';
@@ -32,6 +33,8 @@ describe('ConnectWorkspaceStore', () => {
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
{ provide: ImportsApi, useValue: imports },
{ provide: SourceGateway, useValue: {} },
// Sin sesión resuelta el alcance es todo; el caso restringido se arma en su propia prueba.
{ provide: AuthService, useValue: { puedeVer: () => true } },
],
});
store = TestBed.inject(ConnectWorkspaceStore);
@@ -52,6 +55,25 @@ describe('ConnectWorkspaceStore', () => {
expect(store.domain()).toBe('cacu');
});
it('opens on the account\'s own domain and refuses the others', () => {
// Fails if the destination database ignores the session: a CaMa team could load into CaCu's database.
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
ConnectWorkspaceStore,
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
{ provide: ImportsApi, useValue: imports },
{ provide: SourceGateway, useValue: {} },
{ provide: AuthService, useValue: { puedeVer: (dominio: string) => dominio === 'cama' } },
],
});
const restringido = TestBed.inject(ConnectWorkspaceStore);
expect(restringido.domain()).toBe('cama');
restringido.setDomain('cacu');
expect(restringido.domain()).toBe('cama');
});
it('removing a connection removes the flows built on its tables', () => {
const { connection } = flowFrom('a.csv', PACIENTE);
flowFrom('b.csv', PACIENTE);
@@ -2,6 +2,8 @@ import { Injectable, computed, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
import { AuthService } from '../../auth/auth.service';
import { dominiosPermitidos } from '../../auth/dominios';
import { ConnectorsApi } from '../api/connectors.api';
import { ImportsApi } from '../api/imports.api';
import { SourceGateway } from '../api/source-gateway';
@@ -11,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
import { ImportFlow } from '../domain/import-flow';
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
{ id: 'cacu', label: 'Cáncer cervicouterino', description: 'Cáncer cervicouterino' },
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
{ id: 'tea', label: 'Trastorno del espectro autista', description: 'Trastorno del espectro autista' },
];
/**
@@ -29,6 +31,7 @@ export const DOMAINS: { id: Domain; label: string; description: string }[] = [
export class ConnectWorkspaceStore {
private readonly gateway = inject(SourceGateway);
private readonly importsApi = inject(ImportsApi);
private readonly auth = inject(AuthService);
private readonly targetsError = signal<string | null>(null);
readonly allTargets = toSignal(
@@ -50,7 +53,8 @@ export class ConnectWorkspaceStore {
});
readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
private readonly _domain = signal<Domain>('cacu');
/** The destination database: the account's own when it only reaches one. */
private readonly _domain = signal<Domain>(this.dominioInicial());
private readonly _connections = signal<DataConnection[]>([]);
private readonly _flows = signal<ImportFlow[]>([]);
private readonly _selectedFlowId = signal<string | null>(null);
@@ -128,7 +132,12 @@ export class ConnectWorkspaceStore {
});
setDomain(domain: Domain): void {
if (!this.domainLocked()) this._domain.set(domain);
if (!this.domainLocked() && this.auth.puedeVer(domain)) this._domain.set(domain);
}
/** The first domain the account may see; every account has at least one (`WebApi` gives none other). */
private dominioInicial(): Domain {
return dominiosPermitidos(this.auth, DOMAINS)[0]?.id ?? 'cacu';
}
setOnConflict(strategy: ConflictStrategy): void {
+7
View File
@@ -1,10 +1,17 @@
:host { display: contents; }
.domain-selector {
flex: 0 0 auto;
max-width: 100%;
height: auto;
min-height: 40px;
background-color: var(--issste-accent);
color: var(--issste-text);
font-weight: 700;
line-height: 1.2;
white-space: nowrap;
}
@media (max-width: 900px) {
.domain-selector { white-space: normal; text-align: start; padding-block: 8px; }
}
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
@@ -1,4 +1,6 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia';
export type OrdenSeguimiento = 'reciente' | ProbabilidadClave;
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
export interface SeguimientoPaciente {
@@ -9,13 +11,20 @@ export interface SeguimientoPaciente {
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
dias_toma_diagnostico: number | null;
/** CaCu: her latest biopsy reported by the cut-off, with its grade. */
ultima_biopsia?: { fecha: string; grado: string | null } | null;
/** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */
probabilidades?: Partial<Record<ProbabilidadClave, ProbabilidadHorizonte[]>> | null;
prioridad: SeguimientoStatus | null;
}
export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; }
export interface SeguimientoResponse {
simulado: boolean;
corte: string;
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
filtros: { estatus: string | null };
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number };
/** The horizons the models give, in years, for ordering and showing the probabilities. */
horizontes_disponibles?: number[];
estatus_disponibles: SeguimientoStatus[];
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
@@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string {
export function latestStudy(item: SeguimientoPaciente): string | null {
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
}
/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */
export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined {
return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte);
}
/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival).
* Every patient or an unknown status shows none: each scenario has its own models. */
export const COLUMNAS_DE_PROBABILIDAD: Readonly<Record<string, readonly ProbabilidadClave[]>> = {
CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'],
};
export const ETIQUETA_PROBABILIDAD: Readonly<Record<ProbabilidadClave, string>> = {
lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia',
};
@@ -3,11 +3,20 @@ import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
import { identidadDe, identidadesDe } from './paciente-identidad';
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia'];
const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates.
const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string');
const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) =>
['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad'])
&& (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto']))));
export function validSeguimientoQuery(q: SeguimientoQuery) {
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
}
export function seguimientoResponse(v: unknown): SeguimientoResponse {
// The current authorization covers demonstration records only. Validate this
@@ -16,15 +25,18 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|| (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string))
|| (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios)))
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
const c = item['ultima_citologia'], h = item['ultimo_vph'];
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']))
&& biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']);
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
return v as unknown as SeguimientoResponse;
}
@@ -36,6 +48,8 @@ export class CacuSeguimientoService {
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
if (query.corte) params = params.set('corte', query.corte);
if (query.estatus) params = params.set('estatus', query.estatus);
if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden);
if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte);
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
}
}
@@ -36,12 +36,13 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
const root:HTMLElement=fixture.nativeElement;
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
expect(root.querySelector('h2')?.textContent).toBe('Modelos de riesgo asociados a cáncer cervicouterino');
expect(root.textContent).toContain('Ventana consultada:');
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
expect(root.textContent).toContain('Insatisfactoria');
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9);
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
@@ -96,4 +97,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
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();
http.expectNone(()=>true);
});
// Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the
// horizon stop reaching the API (the list is paginated, so ordering happens there).
it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => {
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' },
probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }],
cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] },
} : item);
const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } };
open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const fila = root.querySelector('tbody tr')!;
expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %');
expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)');
expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']);
fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1;
fixture.componentInstance.apply();
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1');
req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges();
expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)');
});
// Fails if the columns stop following the status filtered: each scenario has its own models.
it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => {
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' },
probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item);
const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } };
open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim());
expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)');
expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false);
expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)');
expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']);
fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia';
fixture.componentInstance.apply();
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
expect(req.request.params.has('orden')).toBe(false);
req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges();
expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false);
expect(root.querySelector('select[name="orden"]')).toBeNull();
});
});
@@ -1,20 +1,25 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
};
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
const HISTOLOGIA: Readonly<Record<string, string>> = {
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
};
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = {
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
};
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
+4 -3
View File
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
export interface Quantity { value?: number; unit?: string }
export interface Extension {
url: string;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[];
}
@@ -19,6 +19,7 @@ export interface Resource {
}
export interface Bundle extends Resource {
total?: number;
link?: { relation: string; url: string }[];
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
}
@@ -30,9 +31,9 @@ export function code(concept: Concept | undefined): string | undefined {
export function display(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.display ?? concept?.text;
}
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
const url = system.includes('://') ? system : CODE_SYSTEM + system;
const url = system.includes(':') ? system : CODE_SYSTEM + system;
return concept?.coding?.find(c => c.system === url)?.code;
}
// The extensions named `name` (the last segment of their URL).
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,842 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 8,
"link": [
{
"relation": "self",
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
}
],
"entry": [
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIOPSIAS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
"version": "0.2.0",
"name": "cama_biopsias",
"title": "Distribución de resultados de biopsia",
"status": "active",
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_biopsias"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grado"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
"version": "0.2.0",
"name": "cama_birads",
"title": "Distribución de BI-RADS",
"status": "active",
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS-CANCER-INVASOR",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"version": "0.1.0",
"name": "cama_birads_cancer_invasor",
"title": "BI-RADS de los cánceres invasores",
"status": "active",
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_cancer_invasor"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grupo_edad"
}
],
"text": "grupo_edad"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "estadio"
}
],
"text": "Estadio clínico"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "etapa"
}
],
"text": "Etapa"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "clasificacion"
}
],
"text": "Subtipo molecular"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "tamano"
}
],
"text": "Tamaño tumoral (T)"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-MASTOGRAFIA",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"version": "0.2.0",
"name": "cama_birads_456_mastografia",
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_mastografia"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-PACIENTE",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"version": "0.2.0",
"name": "cama_birads_456_paciente",
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_paciente"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"resource": {
"resourceType": "Measure",
"id": "CAMA-CONFIRMACION-BIRADS45",
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"version": "0.2.0",
"name": "cama_confirmacion_birads45",
"title": "Tasa de confirmación histopatológica",
"status": "active",
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C1"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "proportion"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "principal"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"description": "Denominador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"description": "Numerador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_numerador"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "episodio"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "increase"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"resource": {
"resourceType": "Measure",
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"version": "0.2.2",
"name": "cama_dias_toma_diagnostico",
"title": "Tiempo de tamizaje a diagnóstico",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
"resource": {
"resourceType": "Measure",
"id": "CAMA-EU38A",
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
"version": "0.2.1",
"name": "cama_eu38a",
"title": "Días de la toma de la mastografía a su resultado",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,835 @@
{
"resourceType": "Bundle",
"type": "collection",
"entry": [
{
"resource": {
"resourceType": "Observation",
"id": "ados2-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2",
"display": "ADOS-2"
}
]
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"component": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.modulo",
"display": "Módulo"
}
]
},
"valueCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.modulo.MODULO_2"
}
]
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.css",
"display": "Puntaje de severidad (CSS)"
}
]
},
"valueInteger": 8
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.clasificacion",
"display": "Clasificación"
}
]
},
"valueCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.clasificacion.AUTISMO"
}
]
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
"code": "SA",
"display": "Afecto social"
}
]
},
"valueInteger": 10
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
"code": "RRB",
"display": "Comportamiento restringido y repetitivo"
}
]
},
"valueInteger": 4
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.rrb_a4",
"display": "Uso estereotipado o idiosincrásico de palabras o frases"
}
]
},
"valueInteger": 1,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "RRB"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.rrb_d2",
"display": "Manierismos de manos y dedos y otros manierismos complejos"
}
]
},
"valueInteger": 2,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "RRB"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.rrb_d4",
"display": "Intereses inusualmente repetitivos o comportamientos estereotipados"
}
]
},
"valueInteger": 1,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "RRB"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_a6",
"display": "Señalar"
}
]
},
"valueInteger": 1,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_a7",
"display": "Señalar"
}
]
},
"valueInteger": 0,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 0
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b1",
"display": "Contacto visual inusual"
}
]
},
"valueInteger": 2,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b12",
"display": "Características de las iniciaciones sociales"
}
]
},
"valueInteger": 2,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b2",
"display": "Expresiones faciales dirigidas a otros"
}
]
},
"valueInteger": 1,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b3",
"display": "Expresiones faciales dirigidas a otros"
}
]
},
"valueInteger": 0,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 0
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b5",
"display": "Disfrute compartido durante la interacción"
}
]
},
"valueInteger": 2,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b6",
"display": "Iniciación espontánea de la atención conjunta"
}
]
},
"valueInteger": 1,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "ados2.sa_b8",
"display": "Características de las iniciaciones sociales"
}
]
},
"valueInteger": 1,
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
"valueCode": "SA"
}
]
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Procedure",
"id": "eeg-vista-previa",
"status": "completed",
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "eeg",
"display": "Electroencefalograma"
}
]
},
"subject": {
"reference": "Patient/vista-previa"
},
"performedDateTime": "1985-01-01",
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "DiagnosticReport",
"id": "eeg-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
"code": "eeg",
"display": "Electroencefalograma"
}
]
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"result": [
{
"reference": "Observation/calidad-bad-scalp-triage-vista-previa"
},
{
"reference": "Observation/calidad-clean-windows-vista-previa"
},
{
"reference": "Observation/calidad-internal-coverage-vista-previa"
},
{
"reference": "Observation/calidad-line-noise-vista-previa"
},
{
"reference": "Observation/calidad-triage-level-vista-previa"
},
{
"reference": "Observation/calidad-usable-scalp-vista-previa"
}
],
"conclusionCode": [
{
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/calidad",
"code": "MALO"
}
]
},
{
"coding": [
{
"system": "urn:tea:validation",
"code": "not-valid"
}
]
}
],
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/duracion-min",
"valueDecimal": 2.0
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/edad-meses",
"valueDecimal": 30.0
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/canales",
"valueInteger": 24
}
],
"conclusion": "EEG de mala calidad: no es válido para el estudio (nivel de triaje: no_analizable).",
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Observation",
"id": "calidad-bad-scalp-triage-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "urn:tea:validation",
"code": "bad-scalp-triage",
"display": "bad-scalp-triage"
}
],
"text": "bad-scalp-triage"
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "N"
}
]
}
],
"valueQuantity": {
"value": 0.0,
"unit": "electrodes"
},
"referenceRange": [
{
"high": {
"value": 2.0,
"unit": "electrodes"
}
}
],
"component": [
{
"code": {
"text": "decisive"
},
"valueBoolean": true
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Observation",
"id": "calidad-clean-windows-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "urn:tea:validation",
"code": "clean-windows",
"display": "clean-windows"
}
],
"text": "clean-windows"
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "N"
}
]
}
],
"valueQuantity": {
"value": 100.0,
"unit": "%"
},
"referenceRange": [
{
"low": {
"value": 60.0,
"unit": "%"
}
}
],
"component": [
{
"code": {
"text": "decisive"
},
"valueBoolean": true
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Observation",
"id": "calidad-internal-coverage-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "urn:tea:validation",
"code": "internal-coverage",
"display": "internal-coverage"
}
],
"text": "internal-coverage"
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "N"
}
]
}
],
"valueQuantity": {
"value": 1.0,
"unit": "fraction"
},
"referenceRange": [
{
"low": {
"value": 0.9,
"unit": "fraction"
}
}
],
"component": [
{
"code": {
"text": "decisive"
},
"valueBoolean": true
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Observation",
"id": "calidad-line-noise-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "urn:tea:validation",
"code": "line-noise",
"display": "line-noise"
}
],
"text": "line-noise"
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "N"
}
]
}
],
"valueQuantity": {
"value": 9.231034526452635,
"unit": "dB"
},
"referenceRange": [
{
"high": {
"value": 45.0,
"unit": "dB"
}
}
],
"component": [
{
"code": {
"text": "decisive"
},
"valueBoolean": false
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Observation",
"id": "calidad-triage-level-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "urn:tea:validation",
"code": "triage-level",
"display": "triage-level"
}
],
"text": "triage-level"
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "A"
}
]
}
],
"valueString": "no_analizable",
"component": [
{
"code": {
"text": "decisive"
},
"valueBoolean": true
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
},
{
"resource": {
"resourceType": "Observation",
"id": "calidad-usable-scalp-vista-previa",
"status": "final",
"code": {
"coding": [
{
"system": "urn:tea:validation",
"code": "usable-scalp",
"display": "usable-scalp"
}
],
"text": "usable-scalp"
},
"subject": {
"reference": "Patient/vista-previa"
},
"effectiveDateTime": "1985-01-01",
"interpretation": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
"code": "N"
}
]
}
],
"valueQuantity": {
"value": 19.0,
"unit": "electrodes"
},
"referenceRange": [
{
"low": {
"value": 12.0,
"unit": "electrodes"
}
}
],
"component": [
{
"code": {
"text": "decisive"
},
"valueBoolean": true
}
],
"meta": {
"tag": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
"code": "simulado",
"display": "Datos simulados"
}
]
}
}
}
]
}
@@ -0,0 +1,50 @@
// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click.
// Fixture: a host component that projects one line of text into the button.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { IndicadorAyuda } from './indicador-ayuda';
@Component({ imports: [IndicadorAyuda], template: `<app-indicador-ayuda etiqueta="Cómo leer: prueba" (opened)="aperturas = aperturas + 1">Texto de ayuda</app-indicador-ayuda>` })
class Host { aperturas = 0; }
describe('Ayuda redonda', () => {
function crear() {
const fixture = TestBed.createComponent(Host);
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const boton = () => root.querySelector<HTMLButtonElement>('.ayuda-boton')!;
const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim();
const ayuda = root.querySelector('.ayuda')!;
return { fixture, boton, texto, ayuda };
}
it('muestra el texto al pasar el cursor y lo oculta al salir', () => {
// Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned.
const { fixture, texto, ayuda } = crear();
expect(texto()).toBeUndefined();
ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges();
expect(texto()).toBe('Texto de ayuda');
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
expect(texto()).toBeUndefined();
});
it('un clic fija el texto hasta el siguiente clic', () => {
// Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it.
const { fixture, boton, texto, ayuda } = crear();
ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges();
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
expect(texto()).toBe('Texto de ayuda');
expect(boton().getAttribute('aria-expanded')).toBe('true');
boton().click(); fixture.detectChanges();
expect(texto()).toBeUndefined();
expect(boton().getAttribute('aria-expanded')).toBe('false');
});
it('avisa solo al abrirse con un clic y nombra el botón', () => {
// Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost.
const { fixture, boton } = crear();
boton().click(); boton().click(); boton().click(); fixture.detectChanges();
expect(fixture.componentInstance.aperturas).toBe(2);
expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba');
});
});
@@ -0,0 +1,39 @@
import { Component, input, output, signal } from '@angular/core';
// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click.
@Component({
selector: 'app-indicador-ayuda',
template: `
<div class="ayuda" (mouseenter)="sobre.set(true)" (mouseleave)="sobre.set(false)" (focusin)="sobre.set(true)" (focusout)="sobre.set(false)">
<button type="button" class="ayuda-boton" [attr.aria-label]="etiqueta()" [attr.aria-expanded]="visible()"
[attr.aria-controls]="visible() ? idPanel : null" (click)="alternar()"><span aria-hidden="true">?</span></button>
@if (visible()) {
<div class="ayuda-texto" role="tooltip" [id]="idPanel"><ng-content /></div>
}
</div>
`,
styles: `
:host { position: absolute; top: .5rem; right: .5rem; z-index: 2; }
.ayuda { position: relative; }
.ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0;
border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
.ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent);
border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; }
`,
})
export class IndicadorAyuda {
readonly etiqueta = input('Cómo leer');
readonly opened = output<void>();
readonly sobre = signal(false);
readonly fijo = signal(false);
private static contador = 0;
readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador;
visible() { return this.sobre() || this.fijo(); }
alternar() {
const abre = !this.fijo();
this.fijo.set(abre);
if (abre) this.opened.emit();
}
}
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
expect(fixture.nativeElement.querySelector('.catalog-metadata')).toBeNull();
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
// The internal panel heading is deliberately visually hidden and retains identity.
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
@@ -24,17 +24,21 @@ import { parTiempos } from './indicadores-tiempos-pareados';
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
import { parConteos } from './indicadores-conteos-pareados';
const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados'];
@Component({
selector: 'app-indicador-catalog-card',
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' },
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
template: `
<mat-card>
<header>
<div class="card-identity">
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</div>
</header>
@if (!conteos) {
<header>
<div class="card-identity">
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ indicador.titulo }}</h2>
</div>
</header>
}
@if (!sobrio) {
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
@@ -42,7 +46,7 @@ import { parConteos } from './indicadores-conteos-pareados';
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button>
}
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="conteos ? null : titleId">
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
@if (isEu7) {
<div #visibilityRegion class="eu7-region">
@@ -62,7 +66,7 @@ import { parConteos } from './indicadores-conteos-pareados';
</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()" />
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
</div>
} @else if (selectedFigure) {
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@@ -79,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados';
`,
styles: `
:host { display: flex; min-width: 0; margin: 0; }
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
.graphic-region { flex: 1; min-width: 0; }
:host(.dual-card) { grid-column: 1 / -1; }
:host(.doble) { grid-column: span 2; }
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
@@ -106,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados';
.card-identity { min-width: 0; }
h2, p { overflow-wrap: anywhere; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
h2.con-ayuda { padding-right: 2.5rem; }
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
min-width: 48px; min-height: 48px; color: var(--issste-text); }
.pin-toggle mat-icon { flex-shrink: 0; }
@@ -133,15 +139,17 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
});
}
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
get sobrio() { return this.dominio === 'cama'; }
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
get sobrio() { return true; }
// TEA's stacked case charts span two columns of its three-column grid.
get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); }
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
// Connected time pairs replace the diagnosis card with one coordinated box plot.
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
get tiempos() { return this.individual ? undefined : 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 ?? ''); }
@@ -168,6 +176,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
@Input({ required: true }) applied!: GlobalApplied;
@Input() independentPeriods = false;
@Input() pinned = false;
// Draws the indicator alone even when it belongs to a connected pair.
@Input() individual = false;
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
readonly pinChanged = output<void>();
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
@@ -5,6 +5,15 @@ p, h3, summary { overflow-wrap: anywhere; }
.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; }
.families { display: flex; flex-wrap: wrap; gap: .75rem; }
.family { flex: 1 1 16rem; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--issste-border); border-radius: 1rem; background: var(--issste-surface); }
.family button { display: inline-flex; align-items: center; gap: .55rem; }
.family .parent { width: 100%; justify-content: flex-start; border: 0; border-radius: 0; border-bottom: 1px solid var(--issste-border); font-weight: 650; background: color-mix(in srgb, var(--swatch) 14%, var(--issste-surface)); }
.family .children { display: flex; flex-wrap: wrap; gap: .4rem; padding: .55rem; }
.family .child { flex: 1 1 8rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
.family .parent[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 24%, var(--issste-surface)); box-shadow: inset 0 -3px 0 var(--swatch); }
.family .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); transform: scale(1.03); }
.family .swatch { width: .35rem; height: 1.15rem; border: 0; border-radius: .2rem; background: var(--swatch); }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
@@ -26,6 +35,23 @@ summary { cursor: pointer; padding-block: .75rem; }
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; }
.histo-meta { display: flex; justify-content: flex-end; align-items: flex-start; gap: .75rem; margin: -.85rem -.65rem 0 0; }
.view-context { display: flex; flex-direction: column; align-items: flex-end; gap: .1rem; margin: .2rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; }
.histo .figure { border-top: 0; }
.histo .figure + .figure { border-top: 1px solid var(--issste-border); padding-top: .25rem; }
.histo .help { position: relative; display: flex; justify-content: flex-end; padding-bottom: 0; }
.histo .help .methodology-toggle { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; font-weight: 800; font-size: 1rem; line-height: 1; background: var(--issste-accent); color: var(--issste-on-accent); }
.histo .help .methodology { position: absolute; z-index: 8; top: 100%; right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
.histo .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
.histo .tab-bar { display: flex; align-items: flex-end; gap: .5rem; border-bottom: 1px solid var(--issste-border); }
.histo .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
.histo .tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
.histo .tabs .tab[aria-selected=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
.histo .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
.histo .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
.histo .tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
.histo .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); }
.histo .tab .swatch, .histo .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
.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; }
@@ -34,4 +60,7 @@ 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); } }
@media (min-width: 1100px) {
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
}
@@ -1,21 +1,4 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
<h3>Dona por categoría</h3>
@if (donutGuide; as guide) {
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
</section>
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
</section>
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
@@ -24,6 +7,8 @@
@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) {
@let tituloMastografias = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en ' + m.periodo;
@let tituloPacientes = 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en ' + m.periodo;
@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>
@@ -32,22 +17,43 @@
</nav>
}
<div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
<section class="figure">
<div class="figure-head">
<h3>{{ tituloMastografias }}</h3>
<div class="help" (mouseenter)="openHelp('examenes')" (mouseleave)="hideHelp('examenes')" (focusin)="openHelp('examenes')" (focusout)="onHelpFocusOut('examenes', $event)">
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'"
[attr.aria-describedby]="helpWhich === 'examenes' ? 'cama-birads-ayuda-mastografias' : null" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
@if (helpWhich === 'examenes') {
<div class="methodology" id="cama-birads-ayuda-mastografias" role="tooltip">Cada mastografía cuenta en su propia categoría.</div>
}
</div>
</div>
@if (total) {
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="tituloMastografias" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section>
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
<section class="figure">
<div class="figure-head">
<h3>{{ tituloPacientes }}</h3>
<div class="help" (mouseenter)="openHelp('pacientes')" (mouseleave)="hideHelp('pacientes')" (focusin)="openHelp('pacientes')" (focusout)="onHelpFocusOut('pacientes', $event)">
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'"
[attr.aria-describedby]="helpWhich === 'pacientes' ? 'cama-birads-ayuda-pacientes' : null" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
@if (helpWhich === 'pacientes') {
<div class="methodology" id="cama-birads-ayuda-pacientes" role="tooltip">La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.</div>
}
</div>
</div>
@if (totalPacientes) {
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="tituloPacientes" />
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
</section>
</div>
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más alta) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
</table>
@@ -3,17 +3,28 @@
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; }
.figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
.figure-head h3 { margin: 0; }
.help { display: flex; flex: none; justify-content: flex-end; }
.help .methodology { position: absolute; z-index: 8; inset-block-start: calc(100% + .35rem); inset-inline-end: 0;
box-sizing: border-box; inline-size: min(34rem, 100%); background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
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)); } }
.help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
.help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; }
.figure + .figure { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-4); padding-top: var(--issste-space-4); }
@media (min-width: 1100px) {
.figures { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.figure + .figure { border-top: 0; margin-top: 0; padding-top: 0; border-inline-start: 1px solid var(--issste-border); padding-inline-start: var(--issste-space-6); }
}
app-plotly-chart { --plot-height: 400px; }
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
.donut-chart { --plot-min-width: 230px; }
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; }
@@ -1,15 +1,15 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, 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 { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
import { ConteosIncompatibles, donaConteos, donaPacientes, ModeloConteos, modelosConteos, ParConteos, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
@Component({
selector: 'app-indicador-conteos-pareados',
@@ -25,38 +25,45 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
@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;
patientsFigure?: PlotlyFigure;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
// On a narrow screen the donut's long label gives way to a legend under it.
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
private anchoDona = 390;
private anchoPacientes = 390;
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
get totalPacientes() { return this.model ? totalPacientes(this.model) : null; }
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
helpOpen = false;
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
// description of its own bars does not apply to them and is not used.
get donutGuide() {
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
helpWhich: 'examenes' | 'pacientes' | null = null;
private helpPinned: 'examenes' | 'pacientes' | null = null;
toggleHelp(which: 'examenes' | 'pacientes') {
if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
this.helpPinned = which;
this.openHelp(which);
}
openHelp(which: 'examenes' | 'pacientes') {
this.helpWhich = which;
}
hideHelp(which: 'examenes' | 'pacientes') {
if (this.helpPinned === which) return;
if (this.helpWhich === which) this.helpWhich = null;
}
onHelpFocusOut(which: 'examenes' | 'pacientes', event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
if (this.helpPinned === which) this.helpPinned = null;
if (this.helpWhich === which) this.helpWhich = null;
}
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]);
@@ -68,7 +75,7 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
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 clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.patientsFigure = undefined; }
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
@@ -108,12 +115,24 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.draw();
}
ajustarAnchoDona(ancho: number) {
if (ancho === this.anchoDona) return;
this.anchoDona = ancho;
const m = this.model;
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
}
ajustarAnchoPacientes(ancho: number) {
if (ancho === this.anchoPacientes) return;
this.anchoPacientes = ancho;
const m = this.model;
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
}
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified';
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
@@ -101,7 +101,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|| !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(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|| !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
this.status.set('incompatible'); return;
}
@@ -0,0 +1,29 @@
import { Component, Input } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
/** A figure the catalog does not publish yet: it keeps its place and title, with no figure and no number. */
@Component({
selector: 'app-indicador-figura-pendiente',
imports: [MatCardModule],
template: `
<mat-card>
<h2>{{ titulo }}</h2>
<p class="estado" role="status"><strong>Integración pendiente.</strong> {{ detalle }}</p>
<div class="vacio">Sin datos publicados</div>
</mat-card>
`,
styles: `
:host { display: flex; min-width: 0; margin: 0; }
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.estado { color: var(--issste-text-secondary); }
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
`,
})
export class IndicadorFiguraPendiente {
@Input({ required: true }) titulo!: string;
@Input() detalle = 'Este indicador aún no está publicado por el catálogo institucional.';
}
@@ -1,5 +1,12 @@
<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) {
<mat-card class="figure-card" [class.sin-marco]="ayudaRedonda" [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 && ayudaRedonda) {
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + selected.titulo" (opened)="!metadata && metadataRequested.emit()">
<ul class="ayuda-lista">@for (line of interpretation; track $index) { <li>{{ line }}</li> }</ul>
@if (state.status === 'ready' && state.footnotes?.length) {
@for (note of state.footnotes; track $index) { <p class="ayuda-nota">{{ note }}</p> }
}
</app-indicador-ayuda>
} @else if (selected) {
<section class="interpretation" [class.expanded]="methodologyExpanded()">
<button mat-stroked-button type="button" class="methodology-toggle"
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
@@ -37,8 +44,10 @@
@if (hasNoVisibleValues(figure)) {
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
}
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
@if (!ayudaRedonda) {
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
}
} @else {
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
}
@@ -84,7 +93,7 @@
</div>
}
@if (state.status === 'ready' && state.highlight; as h) {
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
<div class="highlight-legend" [class.sin-estado]="ayudaRedonda" 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 ?? '') {
@@ -22,6 +22,7 @@
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; }
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
.interpretation { grid-row: 1; }
.figure-legend { grid-row: 3; min-width: 0; }
@@ -37,7 +38,7 @@
:host(.methodology-expanded) .figure-card { grid-row: auto; }
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
@@ -117,6 +118,7 @@
.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; }
.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.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;
@@ -126,3 +128,6 @@
.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; }
.ayuda-lista { margin: 0; padding-left: 1.1rem; }
.ayuda-nota { margin: .5rem 0 0; }
@@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => {
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
});
it('con la ayuda redonda no repite el título ni el nombre de la figura', () => {
// Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title.
fixture.componentRef.setInput('ayudaRedonda', true);
ready({ data: [{ y: [1] }], layout: {} });
const root: HTMLElement = fixture.nativeElement;
expect(root.querySelector('.figure-title')).toBeNull();
expect(root.querySelector('.figure-id')).toBeNull();
expect(root.querySelector('.ayuda-boton')).not.toBeNull();
expect(root.querySelector('.interpretation')).toBeNull();
});
});
@@ -10,9 +10,11 @@ import { figureDisplayName } from './indicadores-figure-labels';
import { CategoryLabel } from './indicadores-axis-labels';
import { figureIdentity, identityElementId } from './indicadores-identities';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorAyuda } from './indicador-ayuda';
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
import { recolorFigure } from './indicadores-c2-palette';
// The panel owns requests; the card receives the original and its presentation copy.
export interface FigureState {
@@ -40,7 +42,7 @@ export interface FigureState {
selector: 'app-indicador-figure-card',
standalone: true,
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda],
templateUrl: './indicador-figure-card.html',
styleUrl: './indicador-figure-card.scss',
})
@@ -62,7 +64,8 @@ export class IndicadorFigureCard implements OnChanges {
}
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
legendColor(label: string, parent: boolean): string {
const trace = this.chartFigure?.data[parent && this.activeParent ? 1 : 0];
const painted = this.chartFigure ? recolorFigure(this.chartFigure) : undefined;
const trace = painted?.data[parent && this.activeParent ? 1 : 0];
const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined;
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
@@ -140,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges {
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);
}
// A round "?" button with the reading guide instead of the «Cómo leer» box.
@Input() ayudaRedonda = false;
@Input() selected?: Indicador;
@Input() metadata?: IndicadorMetadatos;
@Input({ required: true }) figuraId!: string;
@@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => {
fixture.componentRef.setInput('dominio', 'tea');
fixture.componentRef.setInput('indicador', catalog[0]);
fixture.componentRef.setInput('figuraId', 'f1');
// These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec.
fixture.componentRef.setInput('ayudaRedonda', false);
fixture.componentRef.setInput('tema', 'claro');
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
fixture.componentRef.setInput('applied', state.applied);
@@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => {
fixture = TestBed.createComponent(IndicadorFigurePanel);
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
fixture.componentRef.setInput('ayudaRedonda', false);
fixture.componentRef.setInput('applied', state.applied);
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
expect(JSON.stringify(state)).toBe(snapshot);
@@ -16,17 +16,58 @@ 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 { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
import { MatTooltipModule } from '@angular/material/tooltip';
@Component({
selector: 'app-indicador-figure-panel',
host: { '[class.ayuda-externa]': 'conAyudaRedonda' },
imports: [IndicadorFigureCard, MatTooltipModule],
template: `
<section class="figure-panel" [attr.aria-labelledby]="titleId">
<section class="figure-panel" [class.sin-linea]="conAyudaRedonda" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
@if (sidebar) {
<aside class="strata-sidebar" aria-label="Estratificación">
<fieldset class="sidebar-group">
<legend>Estratificar por</legend>
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
(click)="changeDimension('')">Sin estratificar</button>
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
@if (dimension && estratos.length > 1) {
<fieldset class="sidebar-group">
<legend>Mostrar</legend>
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
@for (e of estratos; track e.valor) {
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
}
</div>
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
</fieldset>
}
@if (dimension) {
<fieldset class="sidebar-group">
<legend>Medida</legend>
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
</fieldset>
}
</aside>
}
<header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
@@ -36,7 +77,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
</span>
}
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
<legend>Distribución</legend>
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
@@ -49,10 +90,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
}
@if (dimension) {
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
}
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
}
@@ -64,15 +111,15 @@ import { MatTooltipModule } from '@angular/material/tooltip';
</nav>
}
</header>
<app-indicador-figure-card [state]="result()" [selected]="indicador"
<app-indicador-figure-card [ayudaRedonda]="conAyudaRedonda" [state]="result()" [selected]="indicador"
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
<div class="stratified-detail">
@if (dimension && result().status === 'ready') {
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</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><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
</tbody></table></div>
</details>
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
@@ -84,6 +131,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
:host { display: grid; min-width: 0; }
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
.sin-linea .panel-controls { border-top: 0; padding-block: 0; }
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
@@ -117,6 +165,32 @@ import { MatTooltipModule } from '@angular/material/tooltip';
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
.donut-periods button:disabled { opacity: .45; }
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
shared with the neighbouring panel, so the bars line up with the donut. */
:host { container-type: inline-size; }
// A container is a containing block for absolute children; the round help must reach the outer card.
:host(.ayuda-externa) { container-type: normal; }
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
.sidebar-list { display: grid; gap: .25rem; }
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.sidebar-reset { margin-top: .5rem; }
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
@container (max-width: 559px) {
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
.strata-sidebar { position: static; }
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
}
.visually-hidden {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
@@ -128,6 +202,9 @@ export class IndicadorFigurePanel implements OnChanges {
@Input({ required: true }) indicador!: Indicador;
@Input() metadata?: IndicadorMetadatos;
@Input({ required: true }) figuraId!: string;
// Round "?" help instead of the «Cómo leer» box; TEA draws it unless told otherwise.
@Input() ayudaRedonda?: boolean;
get conAyudaRedonda() { return this.ayudaRedonda ?? this.dominio === 'tea'; }
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() independentPeriods = false;
@@ -165,7 +242,39 @@ export class IndicadorFigurePanel implements OnChanges {
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
}
dimension: DimensionEstrato | '' = '';
readonly etiquetaDimension = etiquetaDimension;
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
private medidaElegida?: MedidaEstrato;
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
changeMedida(medida: MedidaEstrato) {
if (medida === this.medida) return;
this.medidaElegida = medida;
this.representStratified();
}
cells: StratifiedCell[] = [];
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
estratos: StratumOption[] = [];
ocultos = new Set<string>();
toggleEstrato(valor: string) {
const ocultos = new Set(this.ocultos);
if (ocultos.has(valor)) ocultos.delete(valor);
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
else return;
this.ocultos = ocultos;
this.representStratified();
}
mostrarTodos() {
if (!this.ocultos.size) return;
this.ocultos = new Set();
this.representStratified();
}
private representStratified() {
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
try { this.result.set(this.presentStratified(this.stratifiedData)); }
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
}
}
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
private stratifiedData?: IndicadorDatos;
@@ -177,14 +286,18 @@ export class IndicadorFigurePanel implements OnChanges {
changeDimension(value: DimensionEstrato | '') {
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
if (this.dimension === value) return;
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
this.requestFigure();
}
chooseStratified() {
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
}
private presentStratified(data: IndicadorDatos): FigureState {
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
this.estratos = stratumOptions(data);
const publicados = new Set(this.estratos.map(e => e.valor));
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
this.cells = adapted.cells;
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
@@ -349,7 +462,9 @@ export class IndicadorFigurePanel implements OnChanges {
}
}
ngOnChanges(changes: SimpleChanges) {
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
}
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
this.titleId = identityElementId(identity) + '-title';
@@ -1,20 +1,27 @@
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
<section class="confirmacion histo" aria-label="Resultado histopatológico por categoría BI-RADS">
<div class="histo-meta">
<p class="view-context">
<span>{{ intervalLabel }}</span>
@if (contextPeriod) { <span>Periodo {{ contextPeriod }}</span> }
</p>
<div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
<button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
@if (helpOpen) {
<div class="methodology" id="histo-como-leer" role="tooltip">
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
}
}
}
</div>
}
</div>
}
</div>
</div>
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@@ -30,19 +37,25 @@
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
<div class="legend">
<div class="tab-bar">
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
@for (g of m.grupos; track g.id; let gi = $index) {
<button type="button" role="tab" class="tab" [id]="'histo-tab-' + g.id" [style.--swatch]="g.color" [attr.aria-selected]="selection?.grupo === g.id" [attr.aria-controls]="'histo-panel-' + g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
<div class="child-groups">
@for (g of m.grupos; track g.id) {
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id">
@for (c of m.categorias; track c.id; let ci = $index) {
@if (c.grupo === g.id) {
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
}
</div>
}
</div>
</div>
@@ -51,13 +64,10 @@
@if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
}
<ul class="rate-states">
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
</ul>
</section>
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
</section>
</div>
@@ -5,7 +5,7 @@ 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 { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { Celda } from './indicadores-confirmacion-citologia';
@@ -43,6 +43,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure;
helpOpen = false;
private helpPinned = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
@@ -54,7 +55,11 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
private readonly alCambiarAncho = () => this.draw();
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get intervalLabel() { return this.applied?.tipo === 'mes' ? 'Intervalo mensual' : 'Intervalo semestral'; }
get contextPeriod() {
return this.model?.periodo ?? this.periods[this.periodIndex]
?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : '');
}
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
@@ -71,7 +76,23 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
toggleHelp() {
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
this.helpPinned = true;
this.showHelp();
}
showHelp() {
if (this.helpOpen) return;
this.helpOpen = true;
this.metadataRequested.emit();
}
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
onHelpFocusOut(event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
this.helpPinned = false;
this.helpOpen = false;
}
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
@@ -27,6 +27,10 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
expect(fixture.nativeElement.querySelector('.period-label')).toBeNull();
fixture.componentRef.setInput('temporalReference', '2025-S2'); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.period-label').textContent).toBe('Periodo:');
expect(fixture.nativeElement.querySelector('.kpi-foot').textContent).toContain('2025-S2');
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
@@ -12,16 +12,23 @@ import { MatCardModule } from '@angular/material/card';
@if (value !== null && value !== undefined) {
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
}
@if (temporalReference) { <p>{{ temporalReference }}</p> }
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
<div class="kpi-foot">
@if (showPeriod && temporalReference) {
<p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
}
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</div>
</mat-card>
`,
styles: `
:host { display: block; min-width: 0; }
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
:host { display: flex; flex-direction: column; height: 100%; min-width: 0; }
mat-card { box-sizing: border-box; display: flex; flex-direction: column; flex: 1 1 auto; height: auto; min-height: 100%; padding: var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); box-shadow: none; }
.kpi-foot { margin-top: auto; }
.period { display: flex; flex-wrap: wrap; align-items: baseline; gap: .35rem; }
.period-label { font-weight: 600; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
h3, p { overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; }
@@ -30,9 +37,9 @@ import { MatCardModule } from '@angular/material/card';
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; }
// CaMa's cards are as tall as their grid row.
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section) .value { font-size: 1.65rem; }
`,
})
export class IndicadorKpiCard {
@@ -40,12 +47,18 @@ export class IndicadorKpiCard {
@Input() value?: string | number | null;
@Input() unit?: string;
@Input() temporalReference?: string;
// The opportunity strip shares one period, shown by the parent instead of on every card.
@Input() showPeriod = true;
@Input() loading = false;
@Input() notes: string[] = [];
@Input() state = 'Pendiente de definición';
// A card that shows its value needs no "Disponible" line.
@Input() quietWhenAvailable = false;
@Input() additionalInfo?: string;
get labeledPeriod(): boolean {
const text = this.temporalReference?.trim();
return !!text && text.split(',').every(part => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(part.trim()));
}
get informationLine(): string | undefined {
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
return [...new Set(lines)].join(' ');
@@ -39,7 +39,8 @@ describe('KPI búsqueda inicial del último dato visible', () => {
latest.flush(data(periods[0], 'suppressed'));
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
expect(fixture.componentInstance.result().value).toBe(5);
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1');
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2025-S1');
expect(fixture.nativeElement.textContent).not.toContain('Último dato visible');
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
http.expectNone(() => true);
});
@@ -182,15 +182,19 @@ describe('KPI integración con autoridad global', () => {
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
fixture.detectChanges();
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
const cards = [...fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')];
expect(cards).toHaveLength(5);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'),
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.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
expect(cards.filter(card => card.querySelector('.value')).every(card => card.querySelector('.kpi-state')?.classList.contains('visually-hidden'))).toBe(true);
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
@@ -19,14 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
[loading]="result().loading ?? false" [notes]="notes" [quietWhenAvailable]="true"
[showPeriod]="showPeriod" />
@if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`,
styles: `
:host { display: block; min-width: 0; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
:host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
`,
})
export class IndicadorKpiPanel implements OnChanges {
@@ -36,6 +37,7 @@ export class IndicadorKpiPanel implements OnChanges {
@Input() applied?: GlobalApplied;
@Input() availability?: PeriodAvailability;
@Input() initialPresentation = false;
@Input() showPeriod = false;
private readonly queries = inject(IndicadoresKpiQueries);
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly destroyRef = inject(DestroyRef);
@@ -43,6 +45,10 @@ export class IndicadorKpiPanel implements OnChanges {
private key = '';
readonly usedPeriod = signal<string | undefined>(undefined);
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
get notes(): string[] {
const notes = this.dominio === 'tea' ? this.result().notes ?? [] : [];
return this.definition.note ? [this.definition.note, ...notes] : notes;
}
get temporalReference() {
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');
@@ -2,11 +2,13 @@
<section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields compact">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select>
</mat-form-field>
<div class="interval">
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@@ -51,11 +53,13 @@
<section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select>
</mat-form-field>
<div class="interval">
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@@ -2,13 +2,30 @@
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
// CaMa's compact row: tighter fields and buttons, one line of text under it.
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
:host(.compacto) {
margin: 0;
@include mat.theme((density: -4));
// That theme also rewrites the corner scale, which turns this switch into a pill.
// The history switch keeps the slight rounding of the indicators pages.
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
--mat-sys-corner-full: 4px;
}
:host(.compacto) .interval mat-button-toggle-group {
--mat-button-toggle-height: 40px;
--mat-button-toggle-shape: 6px;
}
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
:host(.compacto) .apply-button { min-height: 40px; }
:host(.compacto) .period-builder button { min-height: 40px; }
section { min-width: 0; }
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
.fields { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
.period-builder mat-form-field { flex: 0 1 10rem; }
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
@@ -21,7 +38,7 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
.remove button { min-height: 44px; }
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
.fields.compact { align-items: center; }
.fields.compact { align-items: end; }
.fields.compact mat-form-field { flex: 0 1 14rem; }
.fields.compact .apply-button { margin-top: 0; }
@media (max-width: 550px) {
@@ -138,16 +138,11 @@ describe('UX-04 control asistido', () => {
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
expect(apply).toHaveBeenCalledTimes(1);
});
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', () => {
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
expect(labels).toContain('Intervalo de análisis');
expect(fixture.nativeElement.querySelector('.field-label').textContent).toBe('Intervalo de análisis');
expect(labels).not.toContain('Modalidad');
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
.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();
expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
});
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
@@ -1,6 +1,7 @@
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
@@ -10,7 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
@Component({
selector: 'app-indicador-period-filters',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
imports: [FormsModule, MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatInputModule, MatSelectModule],
host: { '[class.compacto]': 'compact' },
templateUrl: './indicador-period-filters.html',
styleUrl: './indicador-period-filters.scss',
@@ -0,0 +1,43 @@
<section class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
<h3 class="figure-title">Tiempos de la ruta del tamizaje</h3>
@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 los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</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) {
<div class="controls">
@if (m.period) { <p class="period">Periodo: {{ periodLabel(m.period) }}</p> }
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</div>
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
@else if (figure(); as figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
<details class="how-to-read"><summary>Cómo leer</summary>
<p class="note">
@if (view() === 'cumulative') {
Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él.
El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia.
} @else {
Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos,
y las medianas de los tramos no suman el acumulado.
}
</p>
</details>
}
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
<tbody>@for (row of m.rows; track row.step.id) {
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
}</tbody>
</table>
</div>
</details>
}
</section>
@@ -0,0 +1,14 @@
:host { display: block; min-width: 0; }
.route { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
h3 { font-size: 1rem; line-height: 1.5; }
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); }
.note { color: var(--issste-text-secondary); max-width: 70ch; }
app-plotly-chart { --plot-height: 360px; }
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,125 @@
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
// (`screening-route.spec.ts`).
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
import { Component, input } 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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { IndicadorDatos } from './indicadores.models';
import { ROUTE_IDS } from './screening-route';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
const MEDIANAS: Record<string, number> = {
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
};
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
});
describe('Ruta del tamizaje: componente', () => {
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
f = TestBed.createComponent(IndicadorScreeningRoute);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
});
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
// The shared request queue runs a few at a time: answer in waves until nothing is left.
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
const vistos: string[] = [];
for (;;) {
const pendientes = http.match(r => r.url.endsWith('/datos'));
if (!pendientes.length) return vistos;
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
f.detectChanges();
}
}
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
// visible, a measure is missing or repeated, or a control triggers a request.
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');
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
expect(f.componentInstance.status()).toBe('ready');
expect(charts()).toHaveLength(1);
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
f.componentInstance.selectView('steps'); f.detectChanges();
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
// the period follows the page's filter, with no request of its own
f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges();
expect(f.componentInstance.model()!.period).toBe('2025-S1');
expect(f.nativeElement.querySelector('mat-select')).toBeNull();
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
http.expectNone(() => true);
});
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
// Fails if the table drops an event or shows a suppressed box as a number.
f.detectChanges();
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
const text = f.nativeElement.querySelector('table').textContent as string;
expect(text).toContain('Resultado de citología');
expect(text).toContain('mediana 35.7');
expect(text).toContain('Suprimido');
});
it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => {
// Fails if the reading note goes back to an open paragraph under the chart.
f.detectChanges();
responder(id => payload(id));
const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement;
expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer');
expect(guia.open).toBe(false);
expect(guia.textContent).toContain('bigote: Q1 a Q3');
expect(f.nativeElement.querySelector('section > p.note')).toBeNull();
});
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
// Fails if an empty route draws a chart or hides the reason.
f.detectChanges();
responder(id => payload(id, 1));
expect(f.componentInstance.status()).toBe('empty');
expect(charts()).toHaveLength(0);
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
});
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
f.detectChanges();
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
f.detectChanges();
expect(f.componentInstance.status()).toBe('error');
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
expect(charts()).toHaveLength(0);
http.match(() => true); // the other requests of the first try were cancelled with it
f.componentInstance.retry(); f.detectChanges();
expect(f.componentInstance.status()).toBe('loading');
expect(responder().length).toBe(ROUTE_IDS.length);
expect(f.componentInstance.status()).toBe('ready');
});
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
// Fails if a payload that is not a duration is drawn as one.
f.detectChanges();
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
expect(f.componentInstance.status()).toBe('incompatible');
expect(charts()).toHaveLength(0);
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
});
});
@@ -0,0 +1,84 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { etiquetaPeriodo } from './indicadores-historico-figures';
import { httpMessage } from './indicadores-http';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
@Component({
selector: 'app-indicador-screening-route',
imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-screening-route.html',
styleUrl: './indicador-screening-route.scss',
})
export class IndicadorScreeningRoute {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly tipo = input<TipoPeriodo>('semestre');
/** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */
readonly periodos = input<readonly string[] | undefined>(undefined);
/** The measures load once the region is visible. */
readonly visible = input(true);
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
readonly message = signal('');
readonly view = signal<RouteView>('cumulative');
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
readonly model = computed(() => {
const data = this.payloads();
return data ? routeModel(data, this.tipo(), this.periodos()) : undefined;
});
readonly figure = computed(() => {
const model = this.model();
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
});
readonly periodLabel = etiquetaPeriodo;
readonly cellText = routeCellText;
private readonly snapshots = inject(IndicadoresSnapshots);
private subscription?: Subscription;
constructor() {
effect(() => {
const dominio = this.dominio(), tipo = this.tipo();
if (!this.visible()) { this.status.set('deferred'); return; }
untracked(() => this.load(dominio, tipo));
});
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
}
retry() { this.load(this.dominio(), this.tipo()); }
selectView(view: RouteView) { this.view.set(view); }
private load(dominio: Dominio, tipo: TipoPeriodo) {
this.subscription?.unsubscribe();
this.payloads.set(undefined);
this.status.set('loading');
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
next: data => {
try {
const model = routeModel(data, tipo, this.periodos());
this.payloads.set(data);
this.status.set(routeHasData(model) ? 'ready' : 'empty');
} catch (error) { this.failure(error); }
},
error: error => this.failure(error),
});
}
private failure(error: unknown) {
this.payloads.set(undefined);
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
? 'incompatible' : 'error');
}
}
@@ -0,0 +1,109 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
const miles = (v: number) => v.toLocaleString('es-MX');
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
const t = c2Theme(tema);
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
};
const config = { displayModeBar: false };
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
const t = c2Theme(tema);
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
return {
data: [{
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
marker: { color: C2_PALETTE.series[0] },
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
config,
};
}
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
const t = c2Theme(tema);
const grupos = c.grupos.filter(g => g.estado === 'disponible');
return {
data: [{
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
marker: { color: C2_PALETTE.series[1], size: 11 },
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
config,
};
}
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
const t = c2Theme(tema);
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
return {
data: [{
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
}],
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
plot_bgcolor: t.grid },
config,
};
}
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
const t = c2Theme(tema);
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
return {
actividad: {
data: [
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
],
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
config,
},
proporcion: {
data: [{
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
config,
},
};
}
@@ -0,0 +1,298 @@
// What this module covers: CaMa's descriptive analysis in the Analysis tab: the answers' validation, the cards, the
// figures built from them, the sections the component draws, the way from a figure to Seguimiento and the states
// without data, suppressed or not published.
// Fixtures (`fixtures/cama_analisis_real_*.json`): answers of the WebApi's `/cama/analisis` endpoints over the local
// installation's synthetic CaMa data at 2026-11-16, whole cohort: catalog, indicators (90 days), distribution by BI-RADS, by
// age group and by biopsy result, comparison by age group, map, trend by semester and by month, and the 403 body.
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresAnalisisDescriptivo, detalleTarjeta, valorTarjeta } from './indicadores-analisis-descriptivo';
import {
catalogoDescriptivo, comparacionDescriptiva, distribucionDescriptiva, mapaDescriptivo, resumenDescriptivo, tendenciaDescriptiva,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import catalogoData from './fixtures/cama_analisis_real_catalogo.json';
import resumenData from './fixtures/cama_analisis_real_resumen90.json';
import distBirads from './fixtures/cama_analisis_real_dist_birads.json';
import distEdad from './fixtures/cama_analisis_real_dist_edad.json';
import distBiopsia from './fixtures/cama_analisis_real_dist_biopsia.json';
import compBirads from './fixtures/cama_analisis_real_comp_birads.json';
import compEdad from './fixtures/cama_analisis_real_comp_edad.json';
import mapaData from './fixtures/cama_analisis_real_mapa.json';
import tendSem from './fixtures/cama_analisis_real_tend_sem.json';
import tendMes from './fixtures/cama_analisis_real_tend_mes.json';
import pequenoData from './fixtures/cama_analisis_real_pequeno.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
const CORTE = '2026-11-16';
describe('Respuestas del análisis descriptivo', () => {
it('las respuestas reales cumplen su contrato y nombran la cohorte que describen', () => {
// Pins down: every answer is accepted as the server sends it, names the cohort, scenario, revision and cut-off, and
// carries no `simulado` field. Fails if the contract drifts from what the client validates.
const todas = [catalogoDescriptivo(copia(catalogoData)), resumenDescriptivo(copia(resumenData)), distribucionDescriptiva(copia(distBirads)),
comparacionDescriptiva(copia(compEdad)), mapaDescriptivo(copia(mapaData))];
for (const r of todas) { expect(r.cohorte).toBe('cama_birads_v1'); expect(r.revision).toMatch(/^[0-9a-f]{64}$/); expect(r.corte).toBe(CORTE); expect('simulado' in r).toBe(false); }
expect(new Set(todas.map(r => r.revision)).size).toBe(1);
// The trend is activity, not the cohort: it names its cut-off, unit, population and biopsy scope, and no cohort, filters or test.
for (const t of [tendenciaDescriptiva(copia(tendSem)), tendenciaDescriptiva(copia(tendMes))]) {
expect(t.corte).toBe(CORTE); expect(t.unidad).toBe('reportes'); expect(t.poblacion).toBeTruthy(); expect(t.alcance_biopsias).toBeTruthy();
expect(Object.keys(t)).not.toEqual(expect.arrayContaining(['cohorte']));
for (const k of ['cohorte', 'revision', 'ventana', 'filtros', 'prueba', 'simulado']) expect(k in t).toBe(false);
}
});
it('una respuesta con un conteo publicado y suprimido a la vez, o sin cohorte, se rechaza', () => {
// Pins down: a suppressed item can't carry a count and a published one must; an answer without cohort context isn't read.
// Fails if the client draws figures from an answer that contradicts itself.
const d = copia(distBirads); d['items'][0].suprimido = true;
expect(() => distribucionDescriptiva(d)).toThrow();
const sin = copia(distBirads); delete sin['revision'];
expect(() => distribucionDescriptiva(sin)).toThrow();
const r = copia(resumenData); r['indicadores'][1].estado = 'suprimido';
expect(() => resumenDescriptivo(r)).toThrow();
});
it('las tarjetas escriben el valor, su intervalo y su denominador, o dicen por qué no hay cifra', () => {
// Pins down: a proportion reads «68.9»-style with its Wilson interval and `k de n pacientes`; a median reads its quartiles;
// a suppressed card has no value and says why. Fails if a card shows a number the answer doesn't publish.
const r = resumenDescriptivo(copia(resumenData));
const t = Object.fromEntries(r.indicadores.map(i => [i.clave, i]));
expect(valorTarjeta(t['cohorte'])).toBe('61');
expect(valorTarjeta(t['con_biopsia'])).toBe('68.9');
expect(detalleTarjeta(t['con_biopsia'])).toContain('IC 95 %: 56.4 a 79.1 %. 42 de 61 pacientes.');
expect(detalleTarjeta(t['dias_a_biopsia'])).toContain('Q1 a Q3: 19.3 a 30.8 días. 42 pacientes.');
const oculta = { ...t['con_biopsia'], estado: 'suprimido' as const, valor: null, ic_bajo: null, ic_alto: null };
expect(valorTarjeta(oculta)).toBeNull();
expect(detalleTarjeta(oculta)).toContain('Muy pocos pacientes');
});
});
describe('Figuras del análisis descriptivo', () => {
it('la distribución dibuja solo las categorías publicadas, con su intervalo, y deja las suprimidas fuera', () => {
// Pins down: BI-RADS 5 and 6 are suppressed in the real answer, so only BI-RADS 4 is drawn, at its share with its Wilson
// interval as asymmetric error bars; a hidden category is a gap, not a zero bar. Fails if a suppressed group is drawn.
const d = distribucionDescriptiva(copia(distBirads));
const [traza] = distribucionFigura(d, 'claro').data as Record<string, any>[];
expect(traza['y']).toEqual(['BI-RADS 4']);
expect(traza['x']).toEqual([54.1]);
expect(traza['error_x']['array'][0] + traza['x'][0]).toBeCloseTo(d.items[0].ic_alto!, 5);
});
it('la comparación dibuja un punto por grupo publicado con su intervalo', () => {
// Pins down: by age group three groups have enough patients with a result; each point is its share and the interval is
// asymmetric. Fails if a group without data or a hidden one gets a point.
const c = comparacionDescriptiva(copia(compEdad));
const [traza] = comparacionFigura(c, 'claro', 'Carcinoma invasor').data as Record<string, any>[];
expect(traza['y']).toEqual(['40 a 49 años', '50 a 59 años', '60 a 69 años'].map(e => expect.stringContaining(e.split(' ')[0])));
expect(traza['x']).toHaveLength(3);
expect(c.grupos.filter(g => g.estado === 'disponible').map(g => g.casos)).toEqual([5, 6, 8]);
});
it('el mapa deja en blanco las celdas que no se publican y conserva la posición de cada celda publicada', () => {
// Pins down: a hidden cell is `null` in the matrix (blank), never zero; published cells keep their row and column and carry
// the key that opens their patients. Fails if suppression turns into a zero or shifts a cell.
const m = mapaDescriptivo(copia(mapaData));
const [traza] = mapaFigura(m, 'claro', 'pacientes').data as Record<string, any>[];
const iFila = m.filas.categorias.findIndex(f => f.codigo === 'BIRADS_4'), iCol = m.columnas.categorias.findIndex(c => c.codigo === '50-59');
expect(traza['z'][iFila][iCol]).toBeNull();
const publicada = m.celdas.find(c => !c.suprimido && (c.n ?? 0) > 0)!;
const f = m.filas.categorias.findIndex(x => x.codigo === publicada.fila), c = m.columnas.categorias.findIndex(x => x.codigo === publicada.columna);
expect(traza['z'][f][c]).toBe(publicada.n);
expect(traza['customdata'][f][c]).toEqual([publicada.fila, publicada.columna]);
});
it('la tendencia dibuja los periodos y el porcentaje solo donde se publica, y marca el periodo en curso', () => {
// Pins down: by semester four periods carry a share with an interval; by month the months with fewer than five biopsies
// have no point; the period the cut-off cuts is labelled. Fails if an unpublished period gets a point.
const sem = tendenciaFiguras(tendenciaDescriptiva(copia(tendSem)), 'claro', 'x');
expect((sem.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(4);
const mes = tendenciaDescriptiva(copia(tendMes));
const figuras = tendenciaFiguras(mes, 'claro', 'x');
const publicados = mes.periodos.filter(p => p.maligno.estado === 'disponible').length;
expect((figuras.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(publicados);
expect((figuras.actividad.data[0] as Record<string, any>)['x'].at(-1)).toContain('(en curso)');
});
});
describe('Análisis descriptivo de CaMa (componente)', () => {
let fixture: ComponentFixture<IndicadoresAnalisisDescriptivo>, http: HttpTestingController;
let emitidas: { seleccion: any; origen: HTMLElement | null }[];
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresAnalisisDescriptivo], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresAnalisisDescriptivo); http = TestBed.inject(HttpTestingController);
emitidas = []; fixture.componentInstance.verPacientes.subscribe(e => emitidas.push(e));
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('corte', CORTE);
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const pide = (ruta: string) => http.expectOne(r => r.url === `/cama/analisis${ruta}`);
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
async function abrir() {
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData); pide('/resumen').flush(resumenData); pide('/distribucion').flush(distBirads);
pide('/comparacion').flush(compBirads); pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
}
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
it('no pide nada hasta que la pestaña se abre y entonces pide sus seis respuestas con el corte y la selección', async () => {
// Pins down: nothing before the tab is open; then the catalog, indicators (90-day horizon), distribution by BI-RADS,
// comparison by age group, map and semester trend, all at the cut-off and the whole cohort. Fails if a section is
// asked early or without the selection.
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const parametros = (ruta: string) => { const r = pide(ruta); const p = Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); r.flush({}, { status: 404, statusText: 'x' }); return p; };
expect(parametros('')).toEqual({ corte: CORTE, meses: '0' });
expect(parametros('/resumen')).toEqual({ corte: CORTE, meses: '0', horizonte: '90' });
expect(parametros('/distribucion')).toEqual({ corte: CORTE, meses: '0', por: 'birads' });
expect(parametros('/comparacion')).toEqual({ corte: CORTE, meses: '0', por: 'grupo_edad', medida: 'maligno' });
expect(parametros('/mapa')).toEqual({ corte: CORTE, meses: '0', filas: 'birads', columnas: 'grupo_edad', medida: 'maligno' });
expect(parametros('/tendencia')).toEqual({ corte: CORTE, tipo: 'semestre', periodos: '6' });
});
it('dibuja las tarjetas, las tablas y la lista de lo que no se puede calcular, con las mismas 61 pacientes en todas partes', async () => {
// Pins down: the cohort card, the distribution's total and its caption agree on 61 patients; the unavailable analyses
// are listed with their reasons; nothing says the data is simulated, provisional or a test. Fails if two parts of the tab
// count different patients or a banner of that kind appears.
await abrir();
const texto = root().textContent!;
expect(root().querySelectorAll('app-indicador-kpi-card')).toHaveLength(7);
expect(root().querySelector('app-indicador-kpi-card .value')?.textContent).toContain('61');
expect(root().querySelector('#desc-dist ~ div table caption, section[aria-labelledby="desc-dist"] caption')?.textContent).toContain('61 pacientes');
expect(texto).toContain('No disponible con las fuentes actuales');
for (const titulo of ['Supervivencia', 'Recaída', 'Adherencia al tratamiento']) expect(texto).toContain(titulo);
expect(texto).toContain('No hay estado vital');
expect(texto).not.toMatch(/simulad|demostraci|provisional|prueba de concepto|modo de desarrollo|datos de prueba/i);
});
it('una categoría suprimida dice «No publicado» sin botón y una publicada abre sus pacientes con la selección completa', async () => {
// Pins down: BI-RADS 5 (suppressed) has no «Ver pacientes» button; BI-RADS 4 has one and its click emits the filter, the
// label, the cut-off, the patients counted and the cohort context to quote back. Fails if a hidden group can be opened or
// the list would open another selection.
await abrir();
const fila = (codigo: string) => root().querySelector<HTMLElement>(`tr[data-codigo="${codigo}"]`)!;
expect(fila('BIRADS_5').textContent).toContain('No publicado'); expect(fila('BIRADS_5').querySelector('button')).toBeNull();
fila('BIRADS_4').querySelector<HTMLButtonElement>('button.ver')!.click();
expect(emitidas).toHaveLength(1);
expect(emitidas[0].seleccion).toMatchObject({ filtros: { birads: 'BIRADS_4' }, etiqueta: 'BI-RADS 4', corte: CORTE, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('cambiar la dimensión de la distribución vuelve a pedir solo esa sección', async () => {
// Pins down: choosing «Grupo de edad» asks `distribucion?por=grupo_edad` and nothing else, and its answer replaces the
// table. Fails if a choice in one section reloads the rest.
await abrir();
boton('Grupo de edad').click(); fixture.detectChanges();
const r = pide('/distribucion'); expect(r.request.params.get('por')).toBe('grupo_edad'); r.flush(distEdad); await asentar();
expect([...root().querySelectorAll('tr[data-codigo]')].map(tr => tr.getAttribute('data-codigo'))).toEqual(['<40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']);
http.expectNone(() => true);
boton('Resultado de la biopsia').click(); fixture.detectChanges(); pide('/distribucion').flush(distBiopsia); await asentar();
expect(root().querySelector('tr[data-codigo="SIN_BIOPSIA"]')?.textContent).toContain('19');
});
it('un grupo sin suficientes pacientes dice por qué, un 503 lo dice y un 404 queda pendiente, sin pantalla vacía', async () => {
// Pins down: a 403 on the distribution shows the fixed message; the indicators' 503 says the cohort isn't available and
// offers a retry; a 404 is «pendiente», not an error. Fails if a failure leaves the section empty or shows the body.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData);
pide('/resumen').flush({}, { status: 503, statusText: 'x' });
pide('/distribucion').flush(pequenoData, { status: 403, statusText: 'x' });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' });
pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
expect(root().textContent).toContain('La cohorte no está disponible en este momento.');
expect(root().querySelector('#desc-dist')!.parentElement!.querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(root().querySelector('#desc-dist')!.parentElement!.textContent).not.toContain('menos de 5 pacientes: su lista');
expect(root().querySelector('[aria-labelledby="desc-comp"] table')).toBeNull();
});
it('la comparación sin prueba válida lo dice; con prueba válida da el estadístico y su p', async () => {
// Pins down: by BI-RADS no table supports the test and the page says «No disponible» with the reason; by age group it
// gives chi-square, degrees of freedom and p. Fails if a p-value appears on a table the server called invalid.
await abrir();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toContain('No disponible. Hacen falta al menos dos grupos');
const c = fixture.componentInstance;
c.cambiarComparacion('grupo_edad', 'invasor'); fixture.detectChanges();
pide('/comparacion').flush(compEdad); await asentar();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toMatch(/χ² 0.089, 2 gl, p 0.957/);
});
it('la tendencia marca el periodo en curso y deja sin cifra el porcentaje que no se publica', async () => {
// Pins down: by month the table says «No publicado» where a month has too few biopsies and labels the current month.
// Fails if a hidden share is written as a number or the partial period looks whole.
await abrir();
fixture.componentInstance.cambiarTendencia('mes', 12); fixture.detectChanges(); pide('/tendencia').flush(tendMes); await asentar();
const tabla = root().querySelector('[aria-labelledby="desc-tend"] table')!;
expect(tabla.textContent).toContain('(en curso)');
expect(tabla.textContent).toContain('No publicado');
expect(new Set([...tabla.querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.trim())).has('No publicado')).toBe(true);
});
it('la actividad de reportes conserva su definición: solo cambia con el corte, nunca con la ventana ni los filtros', async () => {
// Pins down: «Aplicar» with another window and filters reloads the cohort sections with them but not the trend, and a new
// cut-off reloads the trend with only that cut-off, the period type and the count. Fails if the trend takes a filter or
// window it doesn't apply, or isn't refreshed when the cut-off changes.
await abrir();
const c = fixture.componentInstance;
c.meses = 3; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
const d = pide('/distribucion'); expect(d.request.params.get('meses')).toBe('3'); expect(d.request.params.get('grupo_edad')).toBe('50-59');
d.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
http.expectNone(r => r.url.endsWith('/tendencia'));
fixture.componentRef.setInput('corte', '2026-10-31'); await asentar();
const t = http.expectOne(r => r.url === '/cama/analisis/tendencia');
expect(Object.fromEntries(t.request.params.keys().map(k => [k, t.request.params.get(k)]))).toEqual({ corte: '2026-10-31', tipo: 'semestre', periodos: '6' });
t.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/distribucion', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
});
it('la actividad de reportes se presenta con su población, la unidad y el alcance de las biopsias, y sin prueba estadística', async () => {
// Pins down: the section names what it counts (reports, not patients), over whom, the scope of the biopsies and that the
// cohort selection doesn't apply; it has no chi-square paragraph. Fails if the text attributes the filters or implies a test.
await abrir();
const seccion = root().querySelector('[aria-labelledby="desc-tend"]')!.textContent!;
expect(seccion).toContain('Actividad de reportes en el tiempo');
expect(seccion).toContain('no depende de la cohorte, la ventana ni los filtros');
expect(seccion).toContain('Cuenta reportes, no pacientes');
expect(seccion).toContain((tendSem as any).alcance_biopsias);
expect(seccion).toContain('Reportes de biopsia');
expect(seccion).not.toMatch(/χ²|p-valor|prueba de homogeneidad/i);
});
it.each([0, 1, 3, 6, 12])('una barra de la distribución con la ventana de %i meses y filtros abre la lista con esa misma ventana', async (m) => {
// Pins down: the selection a published bar emits carries the window the analysis was computed over, the filters applied,
// the cut-off and the cohort context. Fails if a window turns into the whole cohort when the patients are opened.
await abrir();
const c = fixture.componentInstance;
c.meses = m; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
pide('').flush({}, { status: 404, statusText: 'x' }); pide('/resumen').flush({}, { status: 404, statusText: 'x' });
pide('/distribucion').flush({ ...(distBirads as any), ventana: { ...(distBirads as any).ventana, meses: m }, filtros: { birads: null, grupo_edad: '50-59', biopsia: null } });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' }); pide('/mapa').flush({}, { status: 404, statusText: 'x' });
await asentar();
root().querySelector<HTMLButtonElement>('tr[data-codigo="BIRADS_4"] button.ver')!.click();
expect(emitidas.at(-1)!.seleccion).toMatchObject({ filtros: { grupo_edad: '50-59', birads: 'BIRADS_4' }, corte: CORTE, meses: m, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('«No disponible con las fuentes actuales» es una sección plegable, cerrada al inicio, con todo su contenido al abrirla', async () => {
// Pins down: the unavailable analyses sit in a native disclosure (keyboard and screen reader for free), closed at first,
// with its heading as the summary and every title and reason in the list inside it; opening it shows the same text as
// before. Fails if it starts open, loses an entry or stops being reachable from the keyboard.
await abrir();
const plegable = root().querySelector<HTMLDetailsElement>('details[data-plegable="no-disponibles"]')!;
const resumen = plegable.querySelector('summary')!;
expect(plegable.open).toBe(false);
expect(resumen.querySelector('h2')!.textContent).toBe('No disponible con las fuentes actuales');
expect(root().querySelector('section[aria-labelledby="desc-no"] h2')!.id).toBe('desc-no');
expect(resumen.tabIndex).toBeGreaterThanOrEqual(0);
const entradas = [...plegable.querySelectorAll('li')].map(li => li.textContent);
expect(entradas.length).toBe((resumenData as any).no_disponibles.length);
for (const n of (resumenData as any).no_disponibles) expect(entradas.some(t => t!.includes(n.titulo) && t!.includes('No disponible. ' + n.motivo))).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(false);
});
});
@@ -0,0 +1,368 @@
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { Observable, Subscription } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import {
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
import type { SeleccionPacientes } from './indicadores-analisis';
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
const VACIA = { data: [], layout: {} } as PlotlyFigure;
const miles = (v: number) => v.toLocaleString('es-MX');
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
export function valorTarjeta(t: TarjetaAnalisis): string | null {
if (t.estado !== 'disponible' || t.valor === null) return null;
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
}
export function detalleTarjeta(t: TarjetaAnalisis): string {
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
const partes: string[] = [];
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
partes.push(t.descripcion);
return partes.join(' ');
}
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis-descriptivo',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="bloque" aria-labelledby="desc-resumen">
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
<form class="controles" (ngSubmit)="aplicar()">
<label>Ventana
<select name="meses" [(ngModel)]="meses">
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
</select></label>
<label>Categoría BI-RADS
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Grupo de edad
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Horizonte del seguimiento diagnóstico
<select name="horizonte" [(ngModel)]="horizonte">
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
</form>
@switch (resumen().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') { <p role="status">La cohorte no está disponible en este momento.</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button> }
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
}
@if (r(); as res) {
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
<div class="tarjetas">
@for (t of res.indicadores; track t.clave) {
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
}
</div>
}
</section>
<section class="bloque" aria-labelledby="desc-dist">
<h2 id="desc-dist">Distribución de pacientes</h2>
<div class="selector" role="group" aria-label="Distribuir por">
@for (d of dimensionesDist; track d.clave) {
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
}
</div>
@switch (distribucion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
}
@if (dist(); as d) {
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
@else {
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
<tbody>@for (i of d.items; track i.codigo) {
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Análisis de riesgos'">Ver pacientes</button> }</td></tr>
}</tbody></table>
</div>
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
}
}
</section>
<section class="bloque" aria-labelledby="desc-comp">
<h2 id="desc-comp">Comparación entre grupos</h2>
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
<div class="controles">
<label>Comparar por
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
<label>Resultado
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
</div>
@switch (comparacion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
}
@if (comp(); as c) {
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
<table><caption>{{ c.denominador }}</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
<tbody>@for (g of c.grupos; track g.codigo) {
<tr><th scope="row">{{ g.etiqueta }}</th>
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
}
</section>
<section class="bloque" aria-labelledby="desc-mapa">
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
<div class="selector" role="group" aria-label="Medida del mapa">
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
</div>
@switch (mapa().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
}
@if (m(); as mm) {
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Análisis de riesgos.</p>
<details><summary>Valores publicados</summary>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
</details>
}
</section>
<section class="bloque" aria-labelledby="desc-tend">
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
<div class="controles">
<label>Periodo
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
<label>Periodos a mostrar
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
</div>
@switch (tendencia().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
}
@if (t(); as tt) {
<div class="par">
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
</div>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
<tbody>@for (p of tt.periodos; track p.periodo) {
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
}
</section>
@if (r(); as res) {
<section class="bloque" aria-labelledby="desc-no">
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
<details class="plegable" data-plegable="no-disponibles">
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
<ul class="no-disponibles">
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
</ul>
</details>
</section>
}
`,
styles: `
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.bloque { 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, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
td { font-variant-numeric: tabular-nums; }
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.ver:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
.plegable > summary h2 { display: inline; }
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
`,
})
export class IndicadoresAnalisisDescriptivo {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly corte = input.required<string>();
readonly active = input(false);
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
readonly miles = miles; readonly decimal = decimal;
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
readonly por = signal('birads');
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
private readonly service = inject(AnalisisDescriptivoService);
private readonly destroy = inject(DestroyRef);
private readonly suscripciones = new Map<string, Subscription>();
private abierto = false; private corteCargado = ''; private tendCorte = '';
// The filters and window the sections were last asked with: one selection for all of them.
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
constructor() {
effect(() => {
const activa = this.active(), corte = this.corte();
if (!activa) return;
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
});
}
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
}
private pedido(): PedidoDescriptivo {
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
}
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
aplicar() {
this.pedidoVigente = this.pedido();
const p = this.pedidoVigente;
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
this.recargarDist(); this.recargarComp(); this.recargarMapa();
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
}
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
this.suscripciones.get(clave)?.unsubscribe();
destino.set({ estado: 'cargando' });
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
error: error => destino.set(this.fallo(error)),
}));
}
private fallo(error: unknown): Carga<never> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
}
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
}
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
if (!n) return;
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
this.verPacientes.emit({
origen: origen instanceof HTMLElement ? origen : null,
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
});
}
clicDist(evento: unknown) {
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
}
clicMapa(evento: unknown) {
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
}
}
@@ -55,3 +55,119 @@ export class AnalisisService {
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
}
}
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
export interface AnalisisSeleccion {
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
ventana: { meses: number; desde: string; hasta: string };
filtros: Record<string, string | null>;
}
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
}
export interface TarjetaAnalisis {
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
}
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
export interface PeriodoTendencia {
periodo: string; inicio: string; fin: string; incompleto: boolean;
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
maligno: Proporcion;
}
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
export interface TendenciaAnalisis {
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
denominador: string; periodos: PeriodoTendencia[];
}
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
return v as unknown as AnalisisCatalogoDescriptivo;
}
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
return v as unknown as ResumenAnalisis;
}
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
&& record(i['seleccion']))) invalidoDescriptivo();
return v as unknown as DistribucionAnalisis;
}
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
return v as unknown as ComparacionAnalisis;
}
export function mapaDescriptivo(v: unknown): MapaAnalisis {
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
return v as unknown as MapaAnalisis;
}
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
return v as unknown as TendenciaAnalisis;
}
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
return params;
}
@Injectable({ providedIn: 'root' })
export class AnalisisDescriptivoService {
private readonly http = inject(HttpClient);
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
}
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
}
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
}
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
}
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
}
}
@@ -1,12 +1,12 @@
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { analisisAgregado } from './indicadores-analisis.service';
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
import { agregado, agregadoJson, CONTEXTO, CORTE, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
@@ -80,7 +80,7 @@ class ChartStub { readonly plotClick = output<unknown>(); }
describe('Pestaña Análisis epidemiológico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
@@ -127,7 +127,7 @@ describe('Pestaña Análisis epidemiológico', () => {
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('abrir la lista en Seguimiento');
expect(text()).toContain('abrir la lista en Análisis de riesgos');
});
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
// Fails if the cards stay on screen without an answer with categories.
@@ -177,7 +177,7 @@ describe('Pestaña Análisis epidemiológico', () => {
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Análisis de riesgos');
});
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
@@ -1,5 +1,7 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { throwError } from 'rxjs';
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
@@ -45,3 +47,12 @@ export function listaCohorte(o: { corte?: string; filtros?: Record<string, strin
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
/**
* For specs of the analysis tab that are about its BI-RADS aggregate and its way to Seguimiento: the descriptive sections
* below it (catalog, indicators, distribution, comparison, map, trend) answer «not published» and never reach the test
* backend, so those specs keep counting only the requests they are about.
*/
export const sinAnalisisDescriptivo: HttpInterceptorFn = (req, next) =>
/^\/[a-z]+\/analisis(\/(resumen|distribucion|comparacion|mapa|tendencia))?$/.test(req.url)
? throwError(() => new HttpErrorResponse({ status: 404, url: req.url })) : next(req);
@@ -7,6 +7,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
@@ -20,7 +21,7 @@ type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estad
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
* patients the analysis counts there.
*/
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
@@ -54,7 +55,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
@@ -92,18 +93,18 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
<p class="aviso" role="status">{{ aviso() }}</p>
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
label="Pacientes por categoría BI-RADS" />
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Análisis de riesgos. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
<table>
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
<tbody>
@for (g of d.grupos; track g.codigo) {
<tr [attr.data-grupo]="g.codigo">
<th scope="row">{{ etiqueta(g.codigo) }}</th>
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Análisis de riesgos'">Ver pacientes</button> }</td>
</tr>
}
</tbody>
@@ -112,6 +113,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
}
</article>
</section>
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
`,
styles: `
:host { display: block; min-width: 0; }
@@ -166,6 +168,8 @@ export class IndicadoresAnalisis {
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
// The cut-off of the last query: the descriptive sections follow it.
readonly corteConsultado = signal(this.hoy);
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
@@ -206,6 +210,7 @@ export class IndicadoresAnalisis {
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.corteConsultado.set(this.corte);
this.pedidos.next(this.corte);
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
@@ -229,6 +234,12 @@ export class IndicadoresAnalisis {
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
}
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
this.verPacientes.emit(evento.seleccion);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
@@ -18,7 +18,7 @@ export function c1AlterationCapability(contract: string, representation: string)
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;');
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
// The any-alteration bar uses the second series colour; each alteration takes its own colour.
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
const color = (i: number) => COLORS[i % COLORS.length];
@@ -59,8 +59,8 @@ describe('Dona de dos anillos para C1', () => {
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'];
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, tomado de la paleta compartida', () => {
const colores = ['#A8C243', '#42C29C', '#9C42C2'];
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);
@@ -21,7 +21,7 @@ const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
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.
// Olive for the event, the next series colour for its complement; age groups keep their own colours.
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];
@@ -1,5 +1,5 @@
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
import { c2Fixture } from './indicadores-c2-adapter.testing';
import { FigureSelection } from './indicadores.models';
import { donutFixture } from './indicadores-donut-drilldown.testing';
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
const legend = donutLegend(final), view = donutSimpleView(final);
expect(legend).toEqual([
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
{ label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] },
]);
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] });
@@ -158,15 +158,20 @@ describe('C2: datos publicados a Plotly', () => {
});
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)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
const figure = supported(data, { ...selection, tema }).figure;
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
expect(c2Color('#D98E4A', 0)).toBe(C2_PALETTE.series[0]);
expect(c2Color('#B55A1F', 2)).toBe(C2_PALETTE.series[2]);
expect(c2Color('#9DBFE3', 1)).toBe('#9DBFE3');
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
});
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {

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