Compare commits

...

187 Commits

Author SHA1 Message Date
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
Roberto Treviño Cervantes be77c50b45 Merge dashboard-test: the CaMa dashboard's presentation over the FHIR measures, with TEA's history and summary kept 2026-11-15 05:37:15 -06:00
Roberto Treviño Cervantes 40d8c8655e Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration 2026-11-15 00:43:27 -06:00
alberto 4ffd3797b6 Indicators: the history chart and the KPI card read the total when a measure publishes more groups 2026-11-13 21:15:47 -06:00
alberto b42428b068 TEA: the EEG result measure draws one bar per alteration 2026-11-13 19:38:36 -06:00
rockdrigo d9009a2e1e Indicators read the WebApi's FHIR endpoint; TEA follow-up, period summary and patient views, history and highlight figures; side navigation removed 2026-11-13 17:03:23 -06:00
edgar bb2f49be37 Measures read from /<domain>/indicadores 2026-11-13 15:19:01 -06:00
edgar b68af3a48a KPIs page draws durations as boxes and reads a composition's categories from its first stratifier 2026-11-13 15:19:00 -06:00
edgar 7eb144e8fe KPIs page drawing CaCu's measures from the WebApi's FHIR MeasureReport bundles 2026-11-13 15:19:00 -06:00
Angel Capetillo Zavala c509cb7f87 Connect TEA screening views to FHIR 2026-11-13 14:28:04 -06:00
Angel Capetillo Zavala 5807f218b1 Add TEA status measure view 2026-11-13 14:28:04 -06:00
Roberto Treviño Cervantes 4d67b019a6 updating nlp policies; more robust recognition beyond rules 2026-11-13 11:52:42 -06:00
Roberto Treviño Cervantes 934a793da3 fix governance reqs; allow for sandboxed jupyter notebooks for testing 2026-11-13 11:52:42 -06:00
Roberto Treviño Cervantes e6abf44bef improve ingestion system to match isssteleon setup 2026-11-13 11:52:42 -06:00
Roberto Treviño Cervantes 0ee53fd286 Remember SQL connections in the browser, never the password 2026-11-12 01:13:34 -06:00
edgar 62cdb252ca Measures read from /<domain>/indicadores 2026-11-08 01:37:43 -06:00
edgar 8f2906fe6f KPIs page draws durations as boxes and reads a composition's categories from its first stratifier 2026-11-08 01:16:04 -06:00
edgar e8628508d8 KPIs page drawing CaCu's measures from the WebApi's FHIR MeasureReport bundles 2026-11-08 00:33:01 -06:00
edgar 53edec8692 feat(tea): periodos personalizados en Histórico
«Personalizado…» en «Periodos a mostrar» abre un diálogo con los periodos del
intervalo elegido, por año. Las figuras muestran solo los elegidos, sin volver
a consultar, y cada intervalo recuerda su propia selección.

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:07:22 +00:00
edgar 123232592f feat(indicadores): un solo periodo y selector de indicadores gráficos
- El filtro general admite un único periodo (Elegir periodo); agregar otro lo reemplaza.
- Buscar indicadores pasa a ser una lista desplegable con casillas; solo los
  indicadores marcados se muestran en Indicadores gráficos, con Mostrar todos.
2026-10-30 23:24:38 +00:00
edgar 2cbb994667 feat(tea): seguimiento con resumen por paciente y resumen por periodo
- Pestaña Seguimiento de TEA: tabla de pacientes con filtro de alteraciones EEG
  y fila desplegable con ADOS-2 por reactivo, calidad del EEG y mapa topográfico
  (GET /tea/seguimiento/<id>).
- Indicadores destacados: M21 y M22 (pacientes con TEA con y sin EEG).
- Con un solo periodo elegido, TEA muestra un párrafo de resumen en lugar de
  las tarjetas.
2026-10-30 23:24:38 +00:00
366 changed files with 42894 additions and 2654 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 },
]
};
+12
View File
@@ -2,11 +2,23 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { IndicadoresService } from './features/indicadores/indicadores.service';
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
import { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
// 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`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
]
};
+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 -25
View File
@@ -1,37 +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: '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: '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: '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' },
// 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: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
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 : '/';
}
}
+65 -1
View File
@@ -85,6 +85,8 @@ export interface PreviewResponse {
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
tables?: { name: string; options: Record<string, unknown>; kind: string }[];
source_metadata?: Record<string, unknown>;
/** Columns whose sampled cells hold files (PDF, images) that can be read as documents. */
document_columns?: string[];
}
export interface FileOptions {
@@ -134,6 +136,56 @@ export interface ImportSourcePayload extends SourceLocator {
label?: string;
column_mapping: Record<string, string>;
defaults?: Record<string, unknown>;
derived?: Record<string, DerivationRule>;
documents?: DocumentColumnsConfig;
/** Also store, on the patient, captions the documents print that the project's catalog already knows. */
catalog_fallback?: boolean;
}
// Derived fields and document columns
export type DerivationParamKind = 'column' | 'columns' | 'text' | 'integer' | 'mapping' | 'boolean';
export interface DerivationParam {
name: string;
kind: DerivationParamKind;
label: string;
required: boolean;
default: unknown;
}
/** One operation a derived field may use, as `/imports/derivations` lists it. */
export interface DerivationSpec {
op: string;
label: string;
description: string;
params: DerivationParam[];
}
export interface DerivationCatalog {
derivations: DerivationSpec[];
cases: string[];
}
/** `{op, ...params, case?}`: how one target field is computed from source columns. */
export type DerivationRule = { op: string; case?: string } & Record<string, unknown>;
/** A grouping or naming given as a column, a list of columns or a rule. */
export type ColumnRule = string | string[] | DerivationRule;
/** Which columns of a source hold documents, and how their records are formed. */
export interface DocumentColumnsConfig {
columns: string[];
group_by?: ColumnRule;
name_by?: ColumnRule;
file_field?: string;
segmentation?: string;
pages_per_record?: number;
ocr_mode?: OcrMode;
key_pattern?: string;
include_pattern?: string;
exclude_pattern?: string;
overrides?: Record<string, Record<string, unknown>>;
}
// Clinical documents
@@ -145,13 +197,19 @@ export interface DocumentSettings {
pages_per_record: number;
ocr_mode: OcrMode;
key_pattern: string;
/** Only documents whose text matches (regular expression, case and accents ignored). */
include_pattern?: string;
/** Documents whose text matches are left out. */
exclude_pattern?: string;
}
export interface ExtractedField {
value: unknown;
confidence: number;
/** etiqueta | patron | texto_libre | manual */
/** etiqueta | patron | texto_libre | medicion | columna_fuente | manual */
method: string;
/** What the report says about the mention: afirmado, negado, incierto, hipotetico, historico, presuntivo. */
assertion?: string | null;
raw?: string;
document?: string;
page_number?: number;
@@ -175,6 +233,10 @@ export interface ExtractedRecord {
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
sources: { document: string; page_numbers: number[] }[];
images: DocumentImage[];
/** `false` when the pages only name another kind of study than the target's; `null` when they name none. */
on_topic?: boolean | null;
/** Per field, the other values the extractors proposed, best first. */
alternatives?: Record<string, ExtractedField[]>;
}
export interface DocumentFieldSpec {
@@ -188,6 +250,8 @@ export interface DocumentExtraction extends PreviewResponse {
key_field: string | null;
fields: DocumentFieldSpec[];
records: ExtractedRecord[];
/** The extraction code's version and its ranker's, as stored with each row. */
nlp_version?: string;
}
export interface RowError {
+32 -3
View File
@@ -1,12 +1,41 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
import { Observable, shareReplay } from 'rxjs';
import {
BatchResult,
ConflictStrategy,
DerivationCatalog,
ImportSourcePayload,
PreviewResponse,
Row,
ValidationResult,
} from './api.types';
/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
/**
* POST /imports/validate (one source, writes nothing), POST /imports/commit
* (a batch, one transaction), the rows a source would write
* (POST /imports/mapped-preview), the columns documents add to a source
* (POST /imports/sources/document/columns) and the operations derived
* fields may use (GET /imports/derivations, fetched once).
*/
@Injectable({ providedIn: 'root' })
export class ImportsApi {
private readonly http = inject(HttpClient);
private catalog?: Observable<DerivationCatalog>;
derivations(): Observable<DerivationCatalog> {
this.catalog ??= this.http.get<DerivationCatalog>('/imports/derivations').pipe(shareReplay(1));
return this.catalog;
}
/** A source with document columns: its own columns plus every field and caption its documents print. */
documentColumns(source: ImportSourcePayload): Observable<PreviewResponse> {
return this.http.post<PreviewResponse>('/imports/sources/document/columns', { source });
}
mappedPreview(source: ImportSourcePayload, limit = 20): Observable<{ rows: Row[] }> {
return this.http.post<{ rows: Row[] }>('/imports/mapped-preview', { source, limit });
}
validate(source: ImportSourcePayload): Observable<ValidationResult> {
return this.http.post<ValidationResult>('/imports/validate', { source });
@@ -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);
@@ -85,6 +85,31 @@
</mat-form-field>
</form>
} @else {
@if (savedConnections().length) {
<div class="saved-connections">
<span class="saved-connections__label">Conexiones guardadas</span>
<div class="saved-connections__list">
@for (saved of savedConnections(); track saved.id) {
<div class="saved-connection">
<button type="button" class="saved-connection__pick" matRipple (click)="applySaved(saved)">
<mat-icon aria-hidden="true">storage</mat-icon>
<span>{{ saved.label }}</span>
</button>
<button
mat-icon-button
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Eliminar esta conexión guardada"
matTooltip="Eliminar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</div>
}
</div>
</div>
}
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
<mat-form-field appearance="outline" class="db-form__host">
<mat-label>Servidor</mat-label>
@@ -108,6 +133,9 @@
<input matInput type="password" formControlName="password" autocomplete="new-password" />
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
</mat-checkbox>
}
@if (testing()) {
@@ -80,6 +80,62 @@
color: var(--mat-sys-on-surface-variant);
}
.saved-connections {
margin-bottom: var(--space-4);
}
.saved-connections__label {
color: var(--mat-sys-on-surface-variant);
display: block;
font: var(--mat-sys-label-small);
margin-bottom: var(--space-1);
}
.saved-connections__list {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.saved-connection {
align-items: center;
background: var(--mat-sys-surface-variant);
border-radius: var(--mat-sys-corner-full);
display: flex;
gap: var(--space-1);
padding-right: var(--space-1);
}
.saved-connection__pick {
align-items: center;
background: none;
border: 0;
color: var(--mat-sys-on-surface-variant);
cursor: pointer;
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-1);
padding: var(--space-1) 0 var(--space-1) var(--space-3);
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
}
.saved-connection__forget {
--mdc-icon-button-state-layer-size: 28px;
height: 28px;
width: 28px;
mat-icon {
font-size: 16px;
height: 16px;
width: 16px;
}
}
.db-form {
display: grid;
gap: 0 var(--space-4);
@@ -1,6 +1,7 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -17,6 +18,7 @@ import { SourceGateway } from '../../api/source-gateway';
import { connectionsFor } from '../../domain/connection-registry';
import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
import { DataConnection } from '../../domain/data-source';
import { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections';
import { SqlConnection } from '../../domain/sql-source';
import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
import { FileDropzone } from '../file-dropzone/file-dropzone';
@@ -33,6 +35,7 @@ type View = 'catalog' | 'files' | 'database';
imports: [
FileDropzone,
MatButtonModule,
MatCheckboxModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -95,6 +98,7 @@ export class ConnectorGalleryDialog {
readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
readonly testing = signal(false);
readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
readonly remember = signal(false);
readonly engine = computed(() => this.entry()?.engine ?? null);
readonly serverEngine = computed(() => {
@@ -102,10 +106,29 @@ export class ConnectorGalleryDialog {
return engine && engine !== 'url' ? engine : null;
});
private readonly savedConnectionsAll = signal(listSavedSqlConnections());
/** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */
readonly savedConnections = computed(() => {
const engineId = this.serverEngine()?.id;
return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : [];
});
applySaved(saved: SavedSqlConnection): void {
this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user });
this.testResult.set(null);
}
forgetSaved(saved: SavedSqlConnection, event: Event): void {
event.stopPropagation();
removeSqlConnection(saved.id);
this.savedConnectionsAll.set(listSavedSqlConnections());
}
pick(entry: GalleryEntry): void {
if (!entry.available) return;
this.entry.set(entry);
this.testResult.set(null);
this.remember.set(false);
this.view.set(entry.engine ? 'database' : 'files');
}
@@ -143,6 +166,10 @@ export class ConnectorGalleryDialog {
connectDatabase(): void {
const ref = this.connectionRef();
if (!ref) return;
if (this.remember() && 'server' in ref) {
const { password: _password, ...shape } = ref.server;
saveSqlConnection({ label: this.connectionLabel(), ...shape });
}
this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
}
@@ -33,6 +33,15 @@
/>
<mat-hint>Expresión regular; ayuda a encontrar el expediente sin etiqueta.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="settings().include_pattern ?? ''" (ngModelChange)="updateSettings({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="settings().exclude_pattern ?? ''" (ngModelChange)="updateSettings({ exclude_pattern: $event })" />
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [value]="settings().ocr_mode" (valueChange)="updateSettings({ ocr_mode: $event })">
@@ -89,6 +98,12 @@
Confianza mínima {{ record.confidence | percent }}
</span>
</header>
@if (record.on_topic === false) {
<p class="record__off-topic" role="status">
<mat-icon aria-hidden="true">report</mat-icon>
Sus páginas mencionan otro tipo de estudio y no el de este destino; sus valores quedan vacíos para que los revise.
</p>
}
<table class="fields" aria-label="Campos extraídos">
<thead>
@@ -115,6 +130,21 @@
(change)="setValue(record, field.name, $any($event.target).value)"
[attr.aria-label]="'Valor de ' + field.name"
/>
@if (alternatives(record, field.name).length && !isOverridden(record, field.name)) {
<span class="fields__alternatives">
También:
@for (alternative of alternatives(record, field.name); track $index) {
<button
type="button"
class="fields__alternative"
(click)="pick(record, field.name, alternative)"
[matTooltip]="(methodLabels[alternative.method] ?? alternative.method) + ' · ' + (alternative.confidence | percent) + (alternative.line ? ' · “' + alternative.line + '”' : '')"
>
{{ alternative.value }}
</button>
}
</span>
}
@if (conflict) {
<span class="fields__conflict" [matTooltip]="'Otro documento dice: ' + conflict.discarded.value + ' (' + conflict.discarded.document + ' p. ' + conflict.discarded.page_number + ')'">
<mat-icon aria-hidden="true">compare_arrows</mat-icon>difiere
@@ -132,6 +162,9 @@
[attr.aria-label]="'Confianza ' + (found.confidence | percent)"
></mat-progress-bar>
<span class="method">{{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }}</span>
@if (found.assertion && assertionLabels[found.assertion]) {
<span class="method method--assertion">{{ assertionLabels[found.assertion] }}</span>
}
}
</td>
<td class="fields__evidence">
@@ -133,6 +133,47 @@
background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
}
.fields__alternatives {
align-items: center;
color: var(--mat-sys-on-surface-variant);
display: flex;
flex-wrap: wrap;
font: var(--mat-sys-label-small);
gap: 4px;
margin-top: 2px;
}
.fields__alternative {
background: var(--mat-sys-surface-container-high);
border: 0;
border-radius: 999px;
color: var(--mat-sys-on-surface);
cursor: pointer;
font: var(--mat-sys-label-small);
padding: 1px 8px;
&:hover,
&:focus-visible {
background: var(--mat-sys-secondary-container);
}
}
.method--assertion {
color: var(--mat-sys-tertiary);
display: block;
}
.record__off-topic {
align-items: center;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-2);
margin: 0 0 var(--space-2);
padding: var(--space-2) var(--space-3);
}
.fields__conflict {
align-items: center;
color: var(--mat-sys-error);
@@ -0,0 +1,67 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SourceGateway } from '../../api/source-gateway';
import { DocumentExtraction, ExtractedRecord } from '../../api/api.types';
import { DocumentReviewDialog } from './document-review-dialog';
/**
* The review of extracted documents: the other readings the extractors proposed can be picked as a correction, a
* record whose pages name another kind of study asks for review, and a qualified mention shows how it was qualified.
* The table is a stub holding one extraction already made, so no request is sent; the gateway is never called.
*/
describe('DocumentReviewDialog', () => {
const record: ExtractedRecord = {
index: 0,
key: 'K-1',
confidence: 0.9,
fields: { bx_cin_grado: { value: 'LIEAG', confidence: 0.9, method: 'texto_libre', assertion: 'presuntivo' } },
missing: [],
conflicts: [],
sources: [{ document: 'a.pdf', page_numbers: [1] }],
images: [],
on_topic: true,
alternatives: { bx_cin_grado: [{ value: 'LIEBG', confidence: 0.7, method: 'etiqueta', line: 'Diagnóstico: NIC I' }] },
};
function open(records: ExtractedRecord[]) {
const extraction = { key_field: 'pac_id_hospital', fields: [{ name: 'bx_cin_grado', kind: 'choice', required: false, labels: [] }], records } as unknown as DocumentExtraction;
const table = {
settings: () => ({}),
overrides: () => ({}),
extractions: signal({ biopsia: extraction }),
configure: vi.fn(),
};
TestBed.configureTestingModule({
imports: [DocumentReviewDialog],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: { table, target: { key: 'biopsia', domain: 'cacu', table: 'biopsia_cervical' }, segmentations: [] } },
{ provide: MatDialogRef, useValue: { close: vi.fn() } },
{ provide: SourceGateway, useValue: {} },
],
});
const fixture = TestBed.createComponent(DocumentReviewDialog);
fixture.detectChanges();
return fixture;
}
it('picks another reading as the correction', () => {
// Fails if the alternatives stop being offered or picking one stops recording it as an override.
const fixture = open([record]);
const dialog = fixture.componentInstance;
const [alternative] = dialog.alternatives(record, 'bx_cin_grado');
dialog.pick(record, 'bx_cin_grado', alternative);
expect(dialog.value(record, 'bx_cin_grado')).toBe('LIEBG');
expect(dialog.isOverridden(record, 'bx_cin_grado')).toBe(true);
});
it('shows how a mention was qualified and asks to review off-topic records', () => {
// Fails if the assertion label or the off-topic warning disappear from the page.
const fixture = open([record, { ...record, index: 1, on_topic: false }]);
expect(fixture.nativeElement.textContent).toContain('Presuntivo');
expect(fixture.componentInstance.needsReview()).toBe(1);
fixture.componentInstance.select(1);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('otro tipo de estudio');
});
});
@@ -33,9 +33,19 @@ const METHOD_LABELS: Record<string, string> = {
etiqueta: 'Etiqueta',
patron: 'Patrón',
texto_libre: 'Texto libre',
medicion: 'Medición',
columna_fuente: 'Columna',
manual: 'Manual',
};
/** How a value's mention is qualified, for the ones a reviewer should notice. */
const ASSERTION_LABELS: Record<string, string> = {
incierto: 'Incierto',
hipotetico: 'Hipotético',
historico: 'Antecedente',
presuntivo: 'Presuntivo',
};
const REVIEW_BELOW = 0.8;
/**
@@ -73,6 +83,7 @@ export class DocumentReviewDialog {
readonly target = this.data.target;
readonly segmentations = this.data.segmentations;
readonly methodLabels = METHOD_LABELS;
readonly assertionLabels = ASSERTION_LABELS;
readonly reviewBelow = REVIEW_BELOW;
readonly settings = signal<DocumentSettings>({ ...this.table.settings() });
@@ -133,7 +144,18 @@ export class DocumentReviewDialog {
}
recordNeedsReview(record: ExtractedRecord): boolean {
return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW;
return (
record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW || record.on_topic === false
);
}
alternatives(record: ExtractedRecord, field: string): ExtractedField[] {
return record.alternatives?.[field] ?? [];
}
/** Takes another reading the extractors proposed; the correction teaches the ranker once imported. */
pick(record: ExtractedRecord, field: string, alternative: ExtractedField): void {
this.setValue(record, field, alternative.value === null || alternative.value === undefined ? '' : String(alternative.value));
}
extracted(record: ExtractedRecord, field: string): ExtractedField | null {
@@ -55,6 +55,15 @@
</ng-template>
<div class="editor__panel"><app-column-mapper [flow]="f"></app-column-mapper></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon aria-hidden="true">functions</mat-icon>Reglas
@if (f.documents() || (f.derived() | keyvalue).length) {
<span class="tab-count">{{ (f.derived() | keyvalue).length + (f.documents() ? 1 : 0) }}</span>
}
</ng-template>
<div class="editor__panel"><app-mapping-rules [flow]="f"></app-mapping-rules></div>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label><mat-icon aria-hidden="true">table_view</mat-icon>Datos</ng-template>
<div class="editor__panel"><app-data-grid [flow]="f"></app-data-grid></div>
@@ -1,4 +1,4 @@
import { DecimalPipe } from '@angular/common';
import { DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, signal } from '@angular/core';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
@@ -13,12 +13,13 @@ import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
import { ColumnMapper } from '../column-mapper/column-mapper';
import { DataGrid } from '../data-grid/data-grid';
import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog';
import { MappingRules } from '../mapping-rules/mapping-rules';
import { FlowStatusChip } from '../shared/flow-status';
import { ValidationReport } from '../validation-report/validation-report';
const VALIDATION_TAB = 2;
const VALIDATION_TAB = 3;
/** Everything about the selected flow: its mapping, its data, its validation. */
/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
@Component({
selector: 'app-flow-editor',
imports: [
@@ -26,6 +27,8 @@ const VALIDATION_TAB = 2;
DataGrid,
DecimalPipe,
FlowStatusChip,
KeyValuePipe,
MappingRules,
MatBadgeModule,
MatButtonModule,
MatIconModule,
@@ -0,0 +1,238 @@
@let f = flow();
@let docs = documentForm();
<div class="rules">
<section class="rules__section" aria-labelledby="documents-title">
<header class="rules__header">
<h3 id="documents-title"><mat-icon aria-hidden="true">document_scanner</mat-icon>Documentos dentro de columnas</h3>
@if (f.documents()) {
<span class="rules__badge">Leyendo {{ f.documents()!.columns.length }} columna(s)</span>
}
</header>
<p class="rules__hint">
Si alguna columna guarda archivos (PDF o imágenes, como binario, hexadecimal o base64), se leen y todo lo que
imprimen (campos conocidos y cualquier otra etiqueta) aparece como columnas nuevas que puede asignar o usar en reglas.
Los valores que vienen de columnas de la fuente se respetan por encima de lo que diga el documento.
@if (f.documentColumns().length) {
Columnas con archivos detectadas: <strong>{{ f.documentColumns().join(', ') }}</strong>.
}
</p>
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Columnas con documentos</mat-label>
<mat-select multiple [ngModel]="docs.columns" (ngModelChange)="patchDocuments({ columns: $event })">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}@if (f.documentColumns().includes(name)) { (archivo) }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Agrupar registros por</mat-label>
<mat-select [ngModel]="docs.group_by" (ngModelChange)="patchDocuments({ group_by: $event })">
<mat-option value="">Por el identificador del paciente</mat-option>
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
<mat-hint>Las filas con el mismo valor forman un solo registro (p. ej. un número de estudio).</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Guardar el documento en</mat-label>
<mat-select [ngModel]="docs.file_field" (ngModelChange)="patchDocuments({ file_field: $event })">
<mat-option value="">No guardar</mat-option>
@for (field of fileFields(); track field.name) {
<mat-option [value]="field.name">{{ field.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>OCR</mat-label>
<mat-select [ngModel]="docs.ocr_mode" (ngModelChange)="patchDocuments({ ocr_mode: $event })">
<mat-option value="auto">Solo páginas escaneadas</mat-option>
<mat-option value="always">Todas las páginas</mat-option>
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Solo documentos que digan</mat-label>
<input matInput [ngModel]="docs.include_pattern" (ngModelChange)="patchDocuments({ include_pattern: $event })" />
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Omitir documentos que digan</mat-label>
<input matInput [ngModel]="docs.exclude_pattern" (ngModelChange)="patchDocuments({ exclude_pattern: $event })" />
</mat-form-field>
</div>
<mat-checkbox [checked]="f.catalogFallback()" (change)="f.setCatalogFallback($event.checked)">
Guardar también, en el expediente de cada paciente, las etiquetas de los documentos que el catálogo del proyecto ya
conoce
</mat-checkbox>
<p class="rules__hint">
Las etiquetas que nadie usa no se guardan: aparecen, solo con su nombre y cuántos registros las traen, en la
Bitácora de cargas.
</p>
<div class="rules__actions">
<button mat-flat-button type="button" [disabled]="documentsBusy()" (click)="applyDocuments()">
<mat-icon aria-hidden="true">play_arrow</mat-icon>Leer documentos
</button>
@if (f.documents()) {
<button mat-button type="button" (click)="clearDocuments()">Dejar de leerlos</button>
}
</div>
@if (documentsBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (documentsError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="derived-title">
<header class="rules__header">
<h3 id="derived-title"><mat-icon aria-hidden="true">functions</mat-icon>Campos calculados</h3>
</header>
<p class="rules__hint">
Para cuando las columnas no coinciden una a una con los campos: unir nombre y apellidos, separar un nombre completo,
tomar la primera columna con valor, extraer un dato de un texto o traducir códigos. Funciona igual con columnas de la
fuente y con lo leído de los documentos.
</p>
@for (item of rules(); track item.field) {
<div class="rule">
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
<strong>{{ item.field }}</strong>
<span class="rule__summary">{{ item.summary }}</span>
<button mat-icon-button type="button" [attr.aria-label]="'Quitar regla de ' + item.field" (click)="removeRule(item.field)">
<mat-icon>delete</mat-icon>
</button>
</div>
}
<div class="rules__grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Campo</mat-label>
<mat-select [ngModel]="ruleField()" (ngModelChange)="ruleField.set($event)">
@for (field of f.target.fields; track field.name) {
<mat-option [value]="field.name">{{ field.name }}@if (field.required) { * }</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Cómo calcularlo</mat-label>
<mat-select [ngModel]="ruleOp()" (ngModelChange)="chooseOp($event)">
@for (spec of catalog()?.derivations ?? []; track spec.op) {
<mat-option [value]="spec.op" [matTooltip]="spec.description">{{ spec.label }}</mat-option>
}
</mat-select>
@if (selectedSpec(); as spec) {
<mat-hint>{{ spec.description }}</mat-hint>
}
</mat-form-field>
@for (param of selectedSpec()?.params ?? []; track param.name) {
@switch (param.kind) {
@case ('column') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<mat-select [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('columns') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }} (en orden)</mat-label>
<mat-select multiple [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
@for (name of columnNames(); track name) {
<mat-option [value]="name">{{ name }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('integer') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput type="number" [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
@case ('boolean') {
<mat-checkbox [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">{{ param.label }}</mat-checkbox>
}
@case ('mapping') {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="rules__wide">
<mat-label>{{ param.label }}</mat-label>
<textarea matInput rows="3" placeholder="M = Masculino" [ngModel]="mappingText(param.name)" (ngModelChange)="setMappingText(param.name, $event)"></textarea>
<mat-hint>Una equivalencia por línea: valor = nuevo valor.</mat-hint>
</mat-form-field>
}
@default {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ param.label }}</mat-label>
<input matInput [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
</mat-form-field>
}
}
}
@if (selectedSpec()) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Mayúsculas</mat-label>
<mat-select [ngModel]="ruleCase()" (ngModelChange)="ruleCase.set($event)">
<mat-option value="">Sin cambio</mat-option>
<mat-option value="upper">MAYÚSCULAS</mat-option>
<mat-option value="lower">minúsculas</mat-option>
<mat-option value="title">Tipo Título</mat-option>
</mat-select>
</mat-form-field>
}
</div>
<div class="rules__actions">
<button mat-stroked-button type="button" [disabled]="!ruleField() || !selectedSpec()" (click)="addRule()">
<mat-icon aria-hidden="true">add</mat-icon>Agregar regla
</button>
</div>
@if (ruleError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
</section>
<section class="rules__section" aria-labelledby="result-title">
<header class="rules__header">
<h3 id="result-title"><mat-icon aria-hidden="true">preview</mat-icon>Resultado</h3>
<button mat-stroked-button type="button" [disabled]="previewBusy()" (click)="preview()">
<mat-icon aria-hidden="true">visibility</mat-icon>Ver cómo quedarían las filas
</button>
</header>
@if (previewBusy()) {
<mat-progress-bar mode="indeterminate" />
}
@if (previewError(); as error) {
<p class="rules__error" role="alert">{{ error }}</p>
}
@if (previewRows(); as rows) {
<div class="rules__table-wrap">
<table class="rules__table">
<thead>
<tr>
@for (column of previewColumns(); track column) {
<th scope="col">{{ column }}</th>
}
</tr>
</thead>
<tbody>
@for (row of rows; track $index) {
<tr>
@for (column of previewColumns(); track column) {
<td>{{ cell(row[column]) }}</td>
}
</tr>
} @empty {
<tr><td>La fuente no dio filas.</td></tr>
}
</tbody>
</table>
</div>
}
</section>
</div>
@@ -0,0 +1,113 @@
:host {
display: block;
}
.rules {
display: flex;
flex-direction: column;
gap: 24px;
padding: 16px;
}
.rules__section {
display: flex;
flex-direction: column;
gap: 12px;
}
.rules__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
h3 {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font: var(--mat-sys-title-medium);
}
}
.rules__badge {
font: var(--mat-sys-label-medium);
color: var(--mat-sys-primary);
}
.rules__hint {
margin: 0;
font: var(--mat-sys-body-small);
color: var(--mat-sys-on-surface-variant);
}
.rules__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 12px 16px;
align-items: start;
}
.rules__wide {
grid-column: 1 / -1;
}
.rules__actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.rules__error {
margin: 0;
color: var(--mat-sys-error);
font: var(--mat-sys-body-medium);
}
.rule {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 8px;
border-radius: 8px;
background: var(--mat-sys-surface-container);
}
.rule__summary {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant);
}
.rules__table-wrap {
overflow-x: auto;
max-height: 360px;
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 8px;
}
.rules__table {
border-collapse: collapse;
font: var(--mat-sys-body-small);
th,
td {
padding: 4px 8px;
border-bottom: 1px solid var(--mat-sys-outline-variant);
text-align: left;
white-space: nowrap;
max-width: 240px;
overflow: hidden;
text-overflow: ellipsis;
}
th {
position: sticky;
top: 0;
background: var(--mat-sys-surface-container-high);
}
}
@@ -0,0 +1,255 @@
import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { firstValueFrom } from 'rxjs';
import {
DerivationParam,
DerivationRule,
DerivationSpec,
DocumentColumnsConfig,
OcrMode,
Row,
apiErrorMessage,
} from '../../api/api.types';
import { ImportsApi } from '../../api/imports.api';
import { ImportFlow } from '../../domain/import-flow';
interface DocumentForm {
columns: string[];
group_by: string;
file_field: string;
ocr_mode: OcrMode;
include_pattern: string;
exclude_pattern: string;
}
/**
* What a plain column-to-field mapping can't express, for any kind of
* source: columns whose cells hold documents (read for every field and
* caption they print, which then become columns of their own), target
* fields computed from several columns, and a look at the rows as they
* would be written.
*
* The operations and their parameters come from the server
* (`/imports/derivations`), so a new operation needs no change here.
*/
@Component({
selector: 'app-mapping-rules',
imports: [
FormsModule,
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatTooltipModule,
],
templateUrl: './mapping-rules.html',
styleUrl: './mapping-rules.scss',
})
export class MappingRules {
readonly flow = input.required<ImportFlow>();
private readonly api = inject(ImportsApi);
readonly catalog = toSignal(this.api.derivations());
readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name));
readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob')));
readonly documentForm = signal<DocumentForm>(this.emptyDocumentForm());
readonly documentsBusy = signal(false);
readonly documentsError = signal<string | null>(null);
readonly ruleField = signal<string>('');
readonly ruleOp = signal<string>('');
readonly ruleParams = signal<Record<string, unknown>>({});
readonly ruleCase = signal<string>('');
readonly ruleError = signal<string | null>(null);
readonly previewRows = signal<Row[] | null>(null);
readonly previewBusy = signal(false);
readonly previewError = signal<string | null>(null);
readonly selectedSpec = computed<DerivationSpec | undefined>(() =>
this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()),
);
readonly rules = computed(() =>
Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })),
);
readonly previewColumns = computed(() => {
const rows = this.previewRows() ?? [];
return [...new Set(rows.flatMap((row) => Object.keys(row)))];
});
constructor() {
// The form follows the flow: what it has configured, or the columns the server flagged.
effect(() => {
const flow = this.flow();
const current = flow.documents();
this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() });
});
}
// -- documents -----------------------------------------------------------
patchDocuments(patch: Partial<DocumentForm>): void {
this.documentForm.update((form) => ({ ...form, ...patch }));
}
async applyDocuments(): Promise<void> {
const form = this.documentForm();
const flow = this.flow();
if (!form.columns.length) {
this.clearDocuments();
return;
}
flow.setDocuments({
columns: form.columns,
group_by: form.group_by || undefined,
file_field: form.file_field || undefined,
ocr_mode: form.ocr_mode,
include_pattern: form.include_pattern.trim() || undefined,
exclude_pattern: form.exclude_pattern.trim() || undefined,
});
this.documentsBusy.set(true);
this.documentsError.set(null);
try {
flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload())));
} catch (error) {
this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
} finally {
this.documentsBusy.set(false);
}
}
clearDocuments(): void {
this.flow().setDocuments(null);
this.documentsError.set(null);
}
// -- derived fields ------------------------------------------------------
chooseOp(op: string): void {
this.ruleOp.set(op);
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op);
this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)])));
this.ruleError.set(null);
}
setParam(name: string, value: unknown): void {
this.ruleParams.update((params) => ({ ...params, [name]: value }));
}
/** `clave = valor` lines, the text form of a `mapping` parameter. */
mappingText(name: string): string {
const value = this.ruleParams()[name];
return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : '';
}
setMappingText(name: string, text: string): void {
const entries = text
.split('\n')
.map((line) => line.split('='))
.filter((parts) => parts.length >= 2 && parts[0].trim())
.map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]);
this.setParam(name, Object.fromEntries(entries));
}
addRule(): void {
const spec = this.selectedSpec();
const field = this.ruleField();
if (!spec || !field) return;
const params = this.ruleParams();
const missing = spec.params.filter((param) => param.required && this.blank(params[param.name]));
if (missing.length) {
this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`);
return;
}
const rule: DerivationRule = { op: spec.op };
for (const param of spec.params) {
const value = params[param.name];
if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value;
}
if (this.ruleCase()) rule.case = this.ruleCase();
this.flow().setDerived(field, rule);
this.ruleField.set('');
this.ruleOp.set('');
this.ruleParams.set({});
this.ruleCase.set('');
this.ruleError.set(null);
}
removeRule(field: string): void {
this.flow().setDerived(field, null);
}
// -- preview ---------------------------------------------------------------
async preview(): Promise<void> {
this.previewBusy.set(true);
this.previewError.set(null);
try {
const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10));
this.previewRows.set(rows);
} catch (error) {
this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.'));
} finally {
this.previewBusy.set(false);
}
}
cell(value: unknown): string {
if (value === null || value === undefined) return '';
return typeof value === 'object' ? JSON.stringify(value) : String(value);
}
private describe(rule: DerivationRule): string {
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op);
const parts = (spec?.params ?? [])
.filter((param) => !this.blank(rule[param.name]))
.map((param) => `${param.label}: ${this.cell(rule[param.name])}`);
return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' · ');
}
private initial(param: DerivationParam): unknown {
if (param.kind === 'columns') return [];
if (param.kind === 'mapping') return {};
return param.default ?? (param.kind === 'boolean' ? false : '');
}
private blank(value: unknown): boolean {
return (
value === null ||
value === undefined ||
(typeof value === 'string' && !value.trim()) ||
(Array.isArray(value) && !value.length) ||
(typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)
);
}
private emptyDocumentForm(): DocumentForm {
return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' };
}
private formFrom(config: DocumentColumnsConfig): DocumentForm {
return {
columns: config.columns,
group_by: typeof config.group_by === 'string' ? config.group_by : '',
file_field: config.file_field ?? '',
ocr_mode: config.ocr_mode ?? 'auto',
include_pattern: config.include_pattern ?? '',
exclude_pattern: config.exclude_pattern ?? '',
};
}
}
@@ -92,4 +92,40 @@ describe('ImportFlow', () => {
expect(flow.autoMap()).toBe(1);
expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
});
it('counts a derived field as covered, and mapping a column onto it drops the rule', async () => {
// Fails if `missingRequired` ignores `derived`, or a field could be fed by a column and a rule at once.
const flow = loadedFlow();
flow.setDerived('pac_id_hospital', { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' });
expect(flow.missingRequired()).toEqual([]);
expect((await flow.toPayload()).derived).toEqual({ pac_id_hospital: { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' } });
flow.map('Clave', 'pac_id_hospital');
expect(flow.derived()).toEqual({});
expect((await flow.toPayload()).derived).toBeUndefined();
});
it('sends document columns without blank settings and swaps in their columns until they are dropped', async () => {
// Fails if blank document settings reach the payload, or the source's own columns are lost when documents are dropped.
const flow = loadedFlow();
const own = flow.sourceColumns();
flow.setDocuments({ columns: ['Clave'], group_by: '', include_pattern: undefined, ocr_mode: 'auto' });
expect((await flow.toPayload()).documents).toEqual({ columns: ['Clave'], ocr_mode: 'auto' });
expect(flow.missingRequired()).toEqual([]);
flow.useDocumentPreview(preview({ columns: [...own, { name: 'Tipo de persona', inferred_type: 'string' }] }));
expect(flow.sourceColumns().map((c) => c.name)).toContain('Tipo de persona');
flow.setDocuments(null);
expect(flow.sourceColumns()).toEqual(own);
expect((await flow.toPayload()).documents).toBeUndefined();
});
it('asks for the catalog fallback only when chosen', async () => {
// Fails if `catalog_fallback` is sent without the user switching it on, or not sent once they do.
const flow = loadedFlow();
expect((await flow.toPayload()).catalog_fallback).toBeUndefined();
flow.setCatalogFallback(true);
expect((await flow.toPayload()).catalog_fallback).toBe(true);
});
});
+82 -4
View File
@@ -2,6 +2,8 @@ import { Signal, computed, signal } from '@angular/core';
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
import {
CommitSourceResult,
DerivationRule,
DocumentColumnsConfig,
ImportSourcePayload,
PreviewResponse,
RowError,
@@ -47,9 +49,14 @@ export class ImportFlow {
readonly mapping = new MappingSet();
private readonly _preview = signal<PreviewResponse | null>(null);
/** The source's own preview, kept while document columns replace it. */
private _sourcePreview: PreviewResponse | null = null;
private readonly _loading = signal(false);
private readonly _error = signal<string | null>(null);
private readonly _defaults = signal<Record<string, string>>({});
private readonly _derived = signal<Record<string, DerivationRule>>({});
private readonly _documents = signal<DocumentColumnsConfig | null>(null);
private readonly _catalogFallback = signal(false);
private readonly _validation = signal<ValidationResult | null>(null);
private readonly _validating = signal(false);
private readonly _result = signal<CommitSourceResult | null>(null);
@@ -58,6 +65,12 @@ export class ImportFlow {
readonly loading: Signal<boolean> = this._loading.asReadonly();
readonly error: Signal<string | null> = this._error.asReadonly();
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
/** Target fields computed from source columns (`derived`), by field. */
readonly derived: Signal<Record<string, DerivationRule>> = this._derived.asReadonly();
/** Source columns read as documents, or `null` when none are. */
readonly documents: Signal<DocumentColumnsConfig | null> = this._documents.asReadonly();
/** Whether captions the catalog knows are stored too (`catalog_fallback`); off unless chosen. */
readonly catalogFallback: Signal<boolean> = this._catalogFallback.asReadonly();
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
readonly validating: Signal<boolean> = this._validating.asReadonly();
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
@@ -65,18 +78,28 @@ export class ImportFlow {
readonly sourceColumns = computed<SourceColumn[]>(() => this._preview()?.columns ?? []);
readonly totalRows = computed(() => this._preview()?.total_rows ?? null);
/** A field is covered when a column feeds it or it has a default value. */
/**
* A field is covered when a column feeds it, a rule computes it or it has
* a default value. With document columns, extraction may fill any field,
* so nothing is reported missing before validation says so.
*/
readonly missingRequired = computed<TargetField[]>(() => {
if (this._documents()) return [];
const mapped = this.mapping.byField();
const defaults = this._defaults();
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
const derived = this._derived();
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !derived[f.name] && !defaults[f.name]?.trim());
});
/** Columns no mapping, rule or document setting reads. */
readonly unmappedColumns = computed(() => {
const used = this.mapping.bySource();
const used = new Set([...this.mapping.bySource().keys(), ...this._documents()?.columns ?? []]);
return this.sourceColumns().filter((column) => !used.has(column.name));
});
/** Columns whose sampled cells hold documents. */
readonly documentColumns = computed<string[]>(() => this._preview()?.document_columns ?? []);
readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length);
readonly status = computed<FlowStatus>(() => {
@@ -84,7 +107,8 @@ export class ImportFlow {
if (this._error() || !this._preview()) return 'error';
if (this._result()) return 'loaded';
if (this._validating()) return 'validating';
if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) {
const assigned = this.mapping.size() + Object.keys(this.activeDefaults()).length + Object.keys(this._derived()).length;
if (this.missingRequired().length > 0 || (assigned === 0 && !this._documents())) {
return 'incomplete';
}
const validation = this._validation();
@@ -161,6 +185,9 @@ export class ImportFlow {
map(source: string, field: string): void {
this.mapping.assign(source, field);
if (this._derived()[field]) {
this._derived.update(({ [field]: _, ...rest }) => rest);
}
this.touch();
}
@@ -188,9 +215,51 @@ export class ImportFlow {
clearMapping(): void {
this.mapping.clear();
this._defaults.set({});
this._derived.set({});
this._documents.set(null);
this.touch();
}
/** Computes `field` with `rule`, replacing any column mapped to it; `null` removes the rule. */
setDerived(field: string, rule: DerivationRule | null): void {
if (rule) this.mapping.releaseField(field);
this._derived.update((derived) => {
const next = { ...derived };
if (rule) next[field] = rule;
else delete next[field];
return next;
});
this.touch();
}
setCatalogFallback(on: boolean): void {
this._catalogFallback.set(on);
this.touch();
}
/** Reads some of the source's columns as documents; `null` stops reading them. */
setDocuments(config: DocumentColumnsConfig | null): void {
this._documents.set(config && config.columns.length ? config : null);
if (!this._documents()) this.useDocumentPreview(null);
this.touch();
}
/**
* Shows, as the source's columns, its own plus every field and caption
* its documents print, so they can be mapped and used in rules; `null`
* goes back to the source's own columns.
*/
useDocumentPreview(preview: PreviewResponse | null): void {
if (preview) {
this._sourcePreview ??= this._preview();
this._preview.set({ ...preview, document_columns: this._sourcePreview?.document_columns ?? [] });
this.mapping.fillFrom(preview.suggested_mapping);
} else if (this._sourcePreview) {
this._preview.set(this._sourcePreview);
this._sourcePreview = null;
}
}
setDefault(field: string, value: string | null): void {
this._defaults.update((defaults) => {
const next = { ...defaults };
@@ -215,6 +284,9 @@ export class ImportFlow {
label: this.label,
column_mapping: this.mapping.toRecord(),
...(Object.keys(defaults).length ? { defaults } : {}),
...(Object.keys(this._derived()).length ? { derived: this._derived() } : {}),
...(this._documents() ? { documents: withoutBlanks(this._documents()!) } : {}),
...(this._catalogFallback() ? { catalog_fallback: true } : {}),
};
}
@@ -256,3 +328,9 @@ export class ImportFlow {
this._result.set(null);
}
}
function withoutBlanks(config: DocumentColumnsConfig): DocumentColumnsConfig {
return Object.fromEntries(
Object.entries(config).filter(([, value]) => value !== undefined && value !== null && value !== ''),
) as unknown as DocumentColumnsConfig;
}
@@ -0,0 +1,47 @@
import { listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from './saved-sql-connections';
describe('saved SQL connections', () => {
beforeEach(() => localStorage.clear());
it('never stores a password field', () => {
const saved = saveSqlConnection({ label: 'HIS · lector@his.local', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
expect(Object.keys(saved)).not.toContain('password');
expect(JSON.parse(localStorage.getItem('isssteleon.connect.savedSqlConnections')!)[0]).not.toHaveProperty('password');
});
it('upserts by connection shape instead of growing duplicates', () => {
const entry = { label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' };
saveSqlConnection(entry);
saveSqlConnection({ ...entry, label: 'HIS (renamed)' });
const all = listSavedSqlConnections();
expect(all.length).toBe(1);
expect(all[0].label).toBe('HIS (renamed)');
});
it('keeps connections to different servers separate', () => {
saveSqlConnection({ label: 'A', engine: 'mssql', host: 'a.local', port: 1433, database: 'HIS', user: 'lector' });
saveSqlConnection({ label: 'B', engine: 'mysql', host: 'b.local', port: 3306, database: 'HIS', user: 'lector' });
expect(listSavedSqlConnections().length).toBe(2);
});
it('removes a saved connection by id', () => {
const saved = saveSqlConnection({ label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
removeSqlConnection(saved.id);
expect(listSavedSqlConnections()).toEqual([]);
});
it('caps the list so it cannot grow without bound', () => {
for (let i = 0; i < 25; i++) {
saveSqlConnection({ label: `db${i}`, engine: 'mssql', host: `host${i}`, port: 1433, database: 'HIS', user: 'lector' });
}
expect(listSavedSqlConnections().length).toBeLessThanOrEqual(20);
});
it('degrades to an empty list rather than throwing when storage is unreadable', () => {
const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked');
});
expect(listSavedSqlConnections()).toEqual([]);
spy.mockRestore();
});
});
@@ -0,0 +1,59 @@
const STORAGE_KEY = 'isssteleon.connect.savedSqlConnections';
const MAX_SAVED = 20;
/**
* A database connection's shape, remembered across visits so the form
* doesn't need retyping. Never the password: credentials travel with every
* request and are never stored (see `sql-source.ts`), so reconnecting
* through a saved entry still asks for it.
*/
export interface SavedSqlConnection {
id: string;
label: string;
engine: string;
host: string;
port: number | null;
database: string;
user: string;
}
export type SavedSqlConnectionInput = Omit<SavedSqlConnection, 'id'>;
function connectionId(entry: SavedSqlConnectionInput): string {
return [entry.engine, entry.host, entry.port ?? '', entry.database, entry.user].join('|');
}
function readAll(): SavedSqlConnection[] {
try {
const raw = localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function writeAll(entries: SavedSqlConnection[]): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
} catch {
// Private browsing, a cleared/blocked store, or a full quota: the form
// just won't remember anything this time, nothing to surface to the user.
}
}
export function listSavedSqlConnections(): SavedSqlConnection[] {
return readAll();
}
/** Upserts by connection shape (engine/host/port/database/user), newest first. */
export function saveSqlConnection(entry: SavedSqlConnectionInput): SavedSqlConnection {
const saved: SavedSqlConnection = { ...entry, id: connectionId(entry) };
const rest = readAll().filter((existing) => existing.id !== saved.id);
writeAll([saved, ...rest].slice(0, MAX_SAVED));
return saved;
}
export function removeSqlConnection(id: string): void {
writeAll(readAll().filter((existing) => existing.id !== id));
}
@@ -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; 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));
}
}
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
afterEach(()=>{ fixture.destroy(); http.verify(); });
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
respond();
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
fixture.componentInstance.apply();
@@ -37,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();
@@ -92,17 +92,55 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
});
it('tea conserva su estado pendiente sin consultas de pacientes', () => {
const dominio = 'tea';
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
});
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
const service=TestBed.inject(CacuSeguimientoService);
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
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);
+55
View File
@@ -0,0 +1,55 @@
// The parts of FHIR R4 the WebApi's `/<domain>/fhir/` endpoints serve, read loosely: every field is optional and the
// readers below decide what a missing one means.
export interface Coding { system?: string; code?: string; display?: string }
export interface Concept { coding?: Coding[]; text?: string }
export interface Quantity { value?: number; unit?: string }
export interface Extension {
url: string;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[];
}
export interface Resource {
resourceType: string;
id?: string;
meta?: { tag?: Coding[] };
extension?: Extension[];
[field: string]: unknown;
}
export interface Bundle extends Resource {
total?: number;
link?: { relation: string; url: string }[];
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
}
export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/';
export function code(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.code;
}
export function display(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.display ?? concept?.text;
}
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
const url = system.includes(':') ? system : CODE_SYSTEM + system;
return concept?.coding?.find(c => c.system === url)?.code;
}
// The extensions named `name` (the last segment of their URL).
export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] {
return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name));
}
export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined {
return extensions(owner, name)[0];
}
export function resources(bundle: Bundle | undefined, type?: string): Resource[] {
return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type);
}
export function isSimulated(resource: Resource): boolean {
return !!resource.meta?.tag?.some(t => t.code === 'simulado');
}
// `Patient/P-1` -> `P-1`.
export function referenceId(reference: { reference?: string } | undefined): string | undefined {
return reference?.reference?.split('/').pop();
}
@@ -0,0 +1,85 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 1,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3",
"date": "2026-11-08T06:47:32.900609+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento",
"valueDate": "2026-11-08"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T06:47:32.766239+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 2
}
],
"measureScore": {
"value": 100.5,
"unit": "d",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
"valueDecimal": 70.25
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
"valueDecimal": 130.75
}
]
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
}
]
}
@@ -0,0 +1,127 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 1,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU13|0.3.2",
"date": "2026-11-08T00:28:51.413089+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:51.351883+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 0
}
],
"measureScore": {
"value": 0.0
},
"stratifier": [
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 0
}
],
"measureScore": {
"value": 0.0
}
}
]
}
]
}
]
}
}
]
}
@@ -0,0 +1,295 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 2,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU7|0.3.3",
"date": "2026-11-08T00:28:56.089006+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 4
}
],
"stratifier": [
{
"code": [
{
"text": "resultado"
}
],
"stratum": [
{
"value": {
"text": "LIEBG"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "NEGATIVO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 2
}
]
},
{
"value": {
"text": "SIN_DATO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
}
]
},
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
}
]
}
]
}
]
}
]
}
},
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU7|0.3.3",
"date": "2026-11-08T00:28:56.099338+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 4
}
],
"stratifier": [
{
"code": [
{
"text": "resultado"
}
],
"stratum": [
{
"value": {
"text": "LIEAG"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "NEGATIVO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "SIN_DATO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 2
}
]
}
]
},
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
}
]
}
]
}
]
}
]
}
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,155 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 2,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/IND1|0.3.2",
"date": "2026-11-08T00:28:50.038223+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 1
}
],
"measureScore": {
"value": 0.25
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
},
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/IND1|0.3.2",
"date": "2026-11-08T00:28:50.044435+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 1
}
],
"measureScore": {
"value": 0.25
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
}
]
}
@@ -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();
}
}
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
}
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
@@ -38,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());
@@ -47,13 +46,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
http.expectNone(() => true);
});
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
]);
http.expectNone(() => true);
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
for (const [id, label] of [
@@ -62,7 +57,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
['fig_c2_donas', 'Donas'],
['fig_c9_futura', 'Representación 5'],
]) {
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
const pending = request(id);
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
expect(pending.request.params.get('tema')).toBe('claro');
@@ -74,9 +69,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
}
http.expectNone(() => true);
});
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
});
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
@@ -98,9 +93,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
});
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
open(); const first = request('f'); expect(select().disabled).toBe(false);
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
open(); const first = request('f'); expect(panels()).toHaveLength(1);
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
expect(next.request.params.get('periodos')).toBe('2025-S1');
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
import { catchError, of, Subscription } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
@@ -26,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' },
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
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"
@@ -44,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">
@@ -64,19 +66,9 @@ 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) {
@if (!sobrio && (!pair.length || otherFigures.length)) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Representación gráfica</mat-label>
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
</mat-select>
</mat-form-field>
}
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@for (figure of displayFigures; track panelIdentity(figure)) {
<div class="representation-panel">
@@ -91,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; }
@@ -118,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; }
@@ -145,18 +139,19 @@ 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 otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
private updateNumeric() {
@@ -181,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>
}
@@ -83,7 +92,23 @@
</div>
</div>
}
@if (state.status === 'ready' && state.donutLegend?.length) {
@if (state.status === 'ready' && state.highlight; as h) {
<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 ?? '') {
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
@if (row.group; as g) {
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
}
@for (c of row.items; track c.id) {
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
}
</div>
}
</div>
} @else if (state.status === 'ready' && state.donutLegend?.length) {
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
@for (entry of state.donutLegend; track entry.label) {
<span class="donut-static-legend__item" role="listitem">
@@ -94,7 +119,7 @@
}
</div>
<div class="plot-slot" [hidden]="state.status !== 'ready'">
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
</div>
}
<div class="figure-footer" [hidden]="state.status !== 'ready'">
@@ -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); } }
@@ -113,3 +114,20 @@
@media (prefers-reduced-motion: reduce) {
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
}
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
.dark .highlight-legend { color: #eef1f7; }
.highlight-status { margin: 0; font-weight: 600; }
.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;
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 999px; font: inherit; cursor: pointer; }
.highlight-legend button:disabled { opacity: .45; cursor: default; }
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.highlight-legend .legend-swatch { border-radius: 50%; }
.highlight-legend .highlight-group { font-weight: 600; }
.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,8 +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 {
@@ -22,6 +25,10 @@ export interface FigureState {
categoryLabels?: readonly CategoryLabel[];
minimumPlotWidth?: number;
donutLegend?: readonly DonutLegendEntry[];
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
ownLayout?: boolean;
// Legend buttons that highlight one part of the figure (CaCu style).
highlight?: FigureHighlight;
plotWidth?: number;
plotHeight?: number;
message?: string;
@@ -35,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',
})
@@ -57,14 +64,15 @@ 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';
}
@Input({ required: true }) set state(value: FigureState) {
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
this.currentState = value;
if (value.status === 'ready') {
this.updateDonut();
@@ -87,7 +95,8 @@ export class IndicadorFigureCard implements OnChanges {
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
this.chartFigure = source && hierarchy
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
: source && this.state.donutLegend ? donutSimpleView(source) : source;
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
}
expandParent(parent: string) {
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
@@ -109,12 +118,33 @@ export class IndicadorFigureCard implements OnChanges {
target?.focus();
}
}
highlightSelection: HighlightSelection = {};
readonly highlightRows = highlightRows;
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
highlight(kind: 'group' | 'item', id: string) {
if (!this.state.highlight) return;
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
this.updateDonut();
}
highlightBack() {
const sel = this.highlightSelection;
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
this.updateDonut();
}
plotClicked(event: unknown) {
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
const point = event.points[0];
if (this.state.highlight) {
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
if (hit) this.highlight(hit.kind, hit.id);
return;
}
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
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);
@@ -215,10 +217,10 @@ describe('IndicadorFigurePanel', () => {
expect(JSON.stringify(page.result().figure)).toBe(original);
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
});
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
load(); figure().flush({ data: [], layout: {} });
const control = filters();
control.changeMode('manual');
control.select([]);
expect(control.canApply).toBe(false);
apply();
http.expectNone(req => req.url.includes('/figuras/'));
@@ -228,18 +230,13 @@ describe('IndicadorFigurePanel', () => {
expect(state?.applied?.selection.mode).toBe('todos');
apply();
const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(manual.request.params.get('periodos')).toBe('2025-S2');
control.select([]);
expect(manual.cancelled).toBe(false);
expect(control.canApply).toBe(false);
apply();
http.expectNone(req => req.url.includes('/figuras/'));
control.changeMode('todos');
apply();
expect(manual.cancelled).toBe(true);
const all = figure();
expect(all.request.params.has('periodos')).toBe(false);
all.flush({ data: [], layout: {} });
manual.flush({ data: [], layout: {} });
});
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
@@ -300,7 +297,7 @@ describe('IndicadorFigurePanel', () => {
});
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
const control = filters(); control.changeMode('manual');
const control = filters(); control.select([]);
control.year = '2025'; control.unit = 'S1'; control.add();
fixture.detectChanges();
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
@@ -308,9 +305,9 @@ describe('IndicadorFigurePanel', () => {
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
http.expectNone(r => r.url.includes('/figuras/'));
});
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025';
const control = filters(); control.select([]); control.year = '2025';
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
apply();
const req = figure();
@@ -320,7 +317,6 @@ describe('IndicadorFigurePanel', () => {
expect(page.result().figure).toBeUndefined();
expect(page.result().message).toContain('esta selección');
expect(page.result().message).not.toContain('2025');
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
expect(control.selectedPeriods).toEqual(periodos);
control.select([]);
page.requestFigure();
@@ -333,7 +329,7 @@ describe('IndicadorFigurePanel', () => {
});
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
load(); figure().flush({ data: [], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
control.unit = 'S2'; control.add();
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
@@ -344,17 +340,17 @@ describe('IndicadorFigurePanel', () => {
page.requestFigure();
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
retry.flush({ data: [], layout: {} });
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
expect(control.selectedPeriods).toEqual(['2025-S2']);
});
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
load(); figure().flush({ data: [], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
apply(); const old = figure();
control.unit = 'S2'; control.add();
expect(old.cancelled).toBe(false);
apply(); const current = figure();
expect(old.cancelled).toBe(true);
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(current.request.params.get('periodos')).toBe('2025-S2');
current.flush({ data: [{ y: [12] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['y']).toEqual([12]);
@@ -362,7 +358,7 @@ describe('IndicadorFigurePanel', () => {
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
fixture.detectChanges();
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
@@ -379,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);
@@ -13,17 +13,61 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
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 { 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')) {
@@ -33,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">
@@ -46,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> }
}
@@ -61,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> }
@@ -81,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; }
@@ -114,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;
@@ -125,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;
@@ -162,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;
@@ -174,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 }),
@@ -245,6 +361,26 @@ export class IndicadorFigurePanel implements OnChanges {
const state = this.presentStratified(data); this.stratifiedData = data; return state;
}));
}
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
const adapted = c1DonutFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
}));
}
if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => {
const adapted = c1AlterationFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: 400,
emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined };
}));
}
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
// Both panels, KPI and numeric table share the exact same transport key.
// Do not catch /datos errors here: a backend failure is a real error state.
@@ -265,6 +401,13 @@ export class IndicadorFigurePanel implements OnChanges {
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
}
const adapted = c2Figure(data, selection);
if (adapted.status === 'supported' && selection.dominio === 'tea') {
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
if (selection.figura === 'fig_c2_donas') {
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
}
return adapted.status === 'supported'
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
@@ -319,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);
});

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