Compare commits

..

28 Commits

Author SHA1 Message Date
rockdrigo c076e1e7a9 feat(indicadores): breakdown by CaMa's stratifiers, in counts or as each category's share of its stratum
The CaMa stratifiers (age, BRCA1/2, molecular classification, stage, tumour
size, early or advanced) now break down quantities of interest (BI-RADS
results, histological diagnosis) instead of being distributions of their own.

How:
- DimensionEstrato and DIMENSIONES_ESTRATO add brca, clasificacion,
  estadio, tamano and etapa; stratifiedCapabilities offers, in a fixed
  order, every one the indicator declares in `filtros`.
- etiquetaDimension names a dimension's button from the catalog's label;
  CaCu's two keep their wording.
- stratifiedBars takes a measure: counts, or each category's share of its
  stratum over the published stratum total (or the sum of its cells when
  all are published); a suppressed or unknown total leaves the stratum
  without percentages. The hover gives n of total; the values table adds
  the share.
- The bars panel has a «Conteos | Porcentaje en cada estrato» toggle; an
  indicator can open with the share (`medida_estrato: 'porcentaje'`).

Implications:
- Shares are derived in the browser from published counts; the server's
  suppression of small strata and totals is what keeps them safe.
- Other domains are unchanged: their dimensions, labels and counts stay.
2026-11-12 19:19:37 -06:00
rockdrigo 710790b98e feat(cama): «Análisis epidemiológico»: epidemiological figures, chosen comparisons, and curves and cells that open their patients
How:
- The tab is now «Análisis epidemiológico». Its first section,
  «Indicadores epidemiológicos», shows the cohort's figures at 24 months
  (GET /<domain>/analisis/indicadores, guarded by analisisIndicadores):
  cumulative incidence of cancer and of recurrence, follow-up adherence and
  survival, each with its interval, counts and assumptions.
- Stages publish a list of variables (two or more) instead of a fixed pair.
  The curves have their own menus: one variable and two or more of its
  values (`grupos`; with all of them the request names none, with one the
  page asks for another and sends nothing). Cox sits beside them, on the
  same groups.
- The heatmap has its own menus for rows and columns, always two distinct
  variables (cruceDeEtapa keeps a pair the stage owns); its answer adds the
  log-rank of each variable, plain and stratified by the other.
- A curve click, its «Ver pacientes» button in the risk table, or a
  coloured cell emits verPacientes with the scenario's population
  (`filtro_seguimiento`) and the values (seleccionDeCurva,
  seleccionDeCelda). The page opens Seguimiento with that selection.
- IndicadoresSeguimientoTabla takes the selection as an input: it asks the
  whole cohort (`meses = 0`, «Toda la cohorte», now in MESES_VENTANA) with
  those filters and says where the list comes from; «Quitar selección»
  goes back to the 3-month window. A new id applies a repeated click.

Implications:
- Seguimiento's contract gains `meses = 0` (no time window); the backend
  must accept it, or answer 400 until it does.
- The list behind a curve is patient-level: the drill-down needs the same
  access rule as Seguimiento, and the figures it comes from stay suppressed.
- Two more endpoints for the backend (/analisis/indicadores, and the new
  parameters grupos, filas and columnas).
2026-11-12 18:38:12 -06:00
rockdrigo d16804d416 feat(cama): «Análisis» by stage: development, recurrence and survival, each with its two NOM variables
The curves part held a single question. It now answers one per stage of the
disease: who reaches a cancer (development), who recurs after an invasive
cancer (recurrence) and who is alive two years after it (survival). Each
stage is stratified, filtered, tested (log-rank, Cox) and validated by its
own two variables.

How:
- The catalog now publishes stages (question, scenarios, estimators,
  measure, two variables, the NOM variables it needs with their status) and
  variables (NOM numeral, recorded or assumed, source, options). The
  answers add their stage, measure and `supuestos`; the subgroup grid is
  generic (fila, columna, dimension_filas, dimension_columnas).
- A stage selector leads the controls; choosing a stage starts from its
  first scenario and variable and keeps the estimator if the stage admits
  it (pedidoDeEtapa). Scenario and estimator choices show only when the
  stage has more than one. Strata and filters are the stage's variables,
  an assumed one marked «supuesto»; a curve click and a grid cell filter by
  them (pedidoAlElegir, celdaDelClic).
- The survival stage is drawn as survival from 100 % (nombreMedida); the
  others as cumulative incidence. What rests on assumed data is announced
  above the curves and in the grid.
- Diagnóstico lists the NOM variables of the stage and whether the schema
  records them; the validation table adds the source of each variable used.
- The curves part is now «Curvas (Kaplan-Meier)».

Implications:
- Recurrence and survival need data the schema does not record yet (stage,
  receptors, recurrence date, vital status); the mock assumes them and the
  page says so wherever they are used.
2026-11-12 14:04:58 -06:00
rockdrigo 05a55a673e feat(cama): «Análisis» in three parts: survival, subgroup explorer and cohort diagnostics
The tab held every figure and table in one long page. It now has three parts
under one set of controls (scenario, estimator, stratum and filters), each
answering one question.

How:
- Supervivencia: the cumulative incidence curves with their risk table, then
  the comparison of the groups (log-rank with Holm pairs beside the RMST).
- Explorador de subgrupos: a new BI-RADS by age-group grid of the incidence
  at the horizon (GET /<domain>/analisis/subgrupos, guarded by
  analisisSubgrupos: no published cell under the threshold), drawn by
  subgruposFigura with suppressed cells grey and named; and the Cox forest
  plot of the chosen stratum. A cell click filters both dimensions and opens
  its curves in Supervivencia (celdaDelClic reads only coloured cells).
- Diagnóstico de la cohorte: the cohort's statistical status (patients,
  events, median follow-up, events per parameter, suppression threshold),
  the C13 validation report and what the cohort cannot answer yet
  (blocked analyses and strata).
- The parts are a keyboard tab list; the grid is requested only when its
  part opens and again only when the scenario or estimator changes.

Implications:
- One more endpoint for the backend to implement, aggregate-only like the
  others; until then the explorer shows its error with a retry.
- The stratum and filters stay hidden in the explorer, where the grid
  ignores them; the forest plot follows the ones chosen in Supervivencia.
2026-11-12 13:49:20 -06:00
rockdrigo e803c38acf Merge origin/dashboard-test: CaMa wired to the published catalog, with the mock's views kept
dashboard-test is the base for every CaMa feature both branches built; this
branch's TEA and CaCu work (from the TEA mock) and its later CaMa views are
kept on top of it.

How:
- From dashboard-test: the opportunity strip with pending cards
  (camaKpiCards, CAMA_OPORTUNIDAD_KPIS), the histopathology view drawn from
  the published BI-RADS matrix, the pending histopathology card, the
  follow-up table component (app-seguimiento-tabla), the paired BI-RADS
  counts, the deferred domain selector in the header, the compact filter row
  for CaMa, the quiet «Disponible» state and the stricter KPI rules (no rate
  without a denominator, no median without observations).
- Kept from this branch: the single-period filters and the indicator
  selector of every domain (instead of the side navigation and «Modalidad»),
  TEA's Histórico grouping and summary paragraph, CaCu's views, the
  catalog-driven scenario and confirmation pickers, the Análisis tab, no
  pins or figure count below five indicators, and no representation
  selector on the cards.
- Histórico: this branch's component, which serves TEA and CaMa, with
  dashboard-test's fixed CaMa panel list (HISTORICO_CAMA) and pending
  panels; figures merged (dashboard-test's stricter series rules plus the
  shared scales, EEG colours and in-process chart of TEA).
- Specs: this branch's for shared components; dashboard-test's for its CaMa
  components. Expectations that contradicted the kept design (TEA without
  Histórico, «Modalidad», side navigation, four entries in
  KPI_BY_DOMAIN.cama) now state the merged behaviour.

Implications:
- CaMa search and pins never show; its cards are what the summary draws.
- The four CaMa opportunity cards are pending until the catalog publishes
  their indicator; the mock publishes all four.
- The histopathology view still has its label buttons and inner labels;
  this branch's expandable donut for CaMa is no longer used.
2026-11-12 13:35:44 -06:00
rockdrigo 6009aea83e feat(cama): «Análisis» tab with exploratory outcomes of the BI-RADS 4+ cohort
Breast cancer gets a tab between Histórico and Seguimiento that answers "how
often, and how fast, does a BI-RADS 4+ patient reach the event", by a
pre-specified stratum, with every number computed by the server and labelled
as descriptive.

How:
- AnalisisService reads GET /<domain>/analisis (scenarios, estimators, strata,
  filters, blocked analyses with their reasons) and
  GET /<domain>/analisis/resultados (C9b curves, risk table, log-rank with
  Holm pairs, RMST, C12 hazard ratios, C13 validation report).
- The guards accept demonstration data only, reject any key that only a
  patient row would carry (at any depth), a suppressed group with counts, and
  a published curve point with fewer at risk than the threshold.
- curvasFigura draws each published group as a step line with its 95 % band;
  forestFigura draws the HRs on a log axis, with an open marker when the
  proportional-hazards check fails. Both are pure functions of the answer.
- Clicking a curve keeps that group as a filter and stratifies by the other
  dimension (pedidoAlElegir); it only changes the request.
- Too few events, a 404 catalog and blocked analyses (recurrence, survival by
  stage, subtype and St. Gallen strata) are shown with their reason instead
  of an empty chart.
- CON_ANALISIS lists the domains with the tab: cama only.

Implications:
- The backend has neither endpoint yet: the tab shows "Funcionalidad
  pendiente de publicación" against the real WebApi. The contracts C9b, C12
  and C13 are drafts and need grooming before the kit implements them.
- No row-level data reaches the browser; suppression is the server's job and
  the client only double-checks it.
- Death as a competing event needs a vital status the schema doesn't have.
2026-11-12 12:42:49 -06:00
rockdrigo 502fc969f0 feat(indicadores): "Fijar indicador" only from five indicators, like the search
How: the catalog card gets a `fijable` input and shows its pin button only when
it is true; the page passes searchVisible(), so the button appears with the
search, from MIN_BUSQUEDA (5) indicators in Resumen. Below that, saved pins are
ignored when ordering the cards, so a pin from a longer catalog can't reorder
cards that offer no way to unpin.

Implications: cáncer de mama (three charts) has no pin buttons; CaCu and TEA
keep them. Pins stay saved and come back if the domain grows past the threshold.
2026-11-09 20:37:49 -06:00
rockdrigo 612a11fa6f style(indicadores): no figure count on the cards, and no repeated filter line where the view states its period
How: the catalog card no longer shows "N figuras publicadas". CaCu's
interactive view, the confirmation view and the paired counts drop their
"Filtro general aplicado: …" line: their status line or figure titles already
name the period ("2025-S2, selección: …"). The plain figure panels and the
paired times keep it, as it is their only statement of the period.

Implications: applies to every domain. The applied filter is still shown under
the general filters bar.
2026-11-09 20:36:19 -06:00
rockdrigo 8b7dd6ec19 style(cama): the confirmation donut's result labels outside the ring
How: in donaExpandible the outer ring's labels (result and share) use
textposition 'outside' with automargin, at 12px in the text colour, so they no
longer shrink to fit their slices; every result with patients is labelled,
including small ones. The figure is 440px tall with a 30px margin; automargin
widens the margins as the labels need and the three rings shrink together, so
they stay concentric. The group labels stay inside the inner ring.

Implications: on a narrow card the rings get smaller to leave room for the
labels. CaCu's confirmation donut (with buttons) is unchanged.
2026-11-09 20:26:23 -06:00
rockdrigo 59ce79d1a2 feat(cama): the detection-rate card without its Wilson interval line
How: the card shows the rate, its period and its one-line description, like
the other C1 cards. The `intervalo` option of KpiDefinition, the interval in
KpiResult and the card's line drawing are removed, since no card uses them.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Implications: domain switching now depends on the App shell; a page embedded
elsewhere has no way to change domain by itself. Specs that asserted the
in-page links now assert their absence, and app.spec covers the menu.
2026-11-09 18:10:58 -06:00
rockdrigo 39974b8533 feat(cama): TEA tabs, follow-up list from announced columns and histopathology donut by BI-RADS category 2026-11-09 17:55:34 -06:00
183 changed files with 2048 additions and 9556 deletions
+2 -246
View File
@@ -20,11 +20,9 @@
"@fontsource/roboto": "^5.3.0",
"@fontsource/roboto-mono": "^5.3.0",
"material-icons": "^1.13.14",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.1.8",
@@ -2703,30 +2701,6 @@
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.142.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.142.0.tgz",
@@ -3723,12 +3697,6 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.4",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",
@@ -4043,15 +4011,6 @@
"node": ">=12"
}
},
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.25",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz",
@@ -4142,35 +4101,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": {
"version": "4.29.0",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz",
@@ -4427,15 +4357,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/content-disposition": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -4639,12 +4560,6 @@
"node": ">=8"
}
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
@@ -5006,6 +4921,7 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-string-truncated-width": {
@@ -5070,12 +4986,6 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/finalhandler": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
@@ -5108,23 +5018,6 @@
"node": ">=6"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -5969,16 +5862,6 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": {
"version": "11.0.0",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.0.0.tgz",
@@ -6490,12 +6373,6 @@
"@oxc-parser/binding-win32-x64-msvc": "0.142.0"
}
},
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
@@ -6599,34 +6476,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/pdfmake": {
"version": "0.3.14",
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
"license": "MIT",
"dependencies": {
"linebreak": "^1.1.0",
"pdfkit": "^0.20.2",
"xmldoc": "^2.0.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6676,14 +6525,6 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT"
},
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
@@ -6914,12 +6755,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz",
@@ -7018,15 +6853,6 @@
"@parcel/watcher": "^2.4.1"
}
},
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -7361,12 +7187,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -7530,46 +7350,6 @@
"node": ">=20.18.1"
}
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@@ -8290,18 +8070,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -8319,18 +8087,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+1 -3
View File
@@ -23,11 +23,9 @@
"@fontsource/roboto": "^5.3.0",
"@fontsource/roboto-mono": "^5.3.0",
"material-icons": "^1.13.14",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.1.8",
-10
View File
@@ -2,21 +2,11 @@ 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),
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 },
]
};
-12
View File
@@ -6,12 +6,6 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page').
export const routes: Routes = [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
data: { workspace: true, breadcrumb: 'Casos por estatus' },
},
{
path: 'conectar',
title: 'Conectar datos | ISSSTELEON',
@@ -32,12 +26,6 @@ export const routes: Routes = [
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
data: { workspace: true, breadcrumb: 'Indicadores' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
+11
View File
@@ -30,6 +30,17 @@ describe('App', () => {
expect(page.querySelector('.site-footer')).not.toBeNull();
});
it('an indicators page shows the platform title and a menu named after its domain', async () => {
// Fails if the header stops naming the domain or offers the current one among the others.
const page = await render('/indicadores/cama');
expect(page.querySelector('.platform-title')?.textContent).toContain('Plataforma de Indicadores');
expect(page.querySelector('.domain-selector')?.textContent).toContain('Cáncer de mama');
(page.querySelector('.domain-selector') as HTMLButtonElement).click();
const options = Array.from(document.querySelectorAll('.mat-mdc-menu-panel a')).map(a => a.textContent?.trim());
expect(options).toEqual(['TEA', 'CaCu']);
expect(page.querySelector('.site-header__crumb')).toBeNull();
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull();
+1 -65
View File
@@ -85,8 +85,6 @@ 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 {
@@ -136,56 +134,6 @@ 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
@@ -197,19 +145,13 @@ 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 | medicion | columna_fuente | manual */
/** etiqueta | patron | texto_libre | 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;
@@ -233,10 +175,6 @@ 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 {
@@ -250,8 +188,6 @@ 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 {
+3 -32
View File
@@ -1,41 +1,12 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, shareReplay } from 'rxjs';
import {
BatchResult,
ConflictStrategy,
DerivationCatalog,
ImportSourcePayload,
PreviewResponse,
Row,
ValidationResult,
} from './api.types';
import { Observable } from 'rxjs';
import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
/**
* 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).
*/
/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
@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 });
@@ -85,31 +85,6 @@
</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="Olvidar esta conexión guardada"
matTooltip="Olvidar"
>
<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>
@@ -133,9 +108,6 @@
<input matInput type="password" formControlName="password" autocomplete="new-password" />
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Recordar servidor, usuario y base de datos (nunca la contraseña)
</mat-checkbox>
}
@if (testing()) {
@@ -80,62 +80,6 @@
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,7 +1,6 @@
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';
@@ -18,7 +17,6 @@ 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';
@@ -35,7 +33,6 @@ type View = 'catalog' | 'files' | 'database';
imports: [
FileDropzone,
MatButtonModule,
MatCheckboxModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -98,7 +95,6 @@ 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(() => {
@@ -106,29 +102,10 @@ 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');
}
@@ -166,10 +143,6 @@ 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,15 +33,6 @@
/>
<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 })">
@@ -98,12 +89,6 @@
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>
@@ -130,21 +115,6 @@
(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
@@ -162,9 +132,6 @@
[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,47 +133,6 @@
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);
@@ -1,67 +0,0 @@
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,19 +33,9 @@ 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;
/**
@@ -83,7 +73,6 @@ 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() });
@@ -144,18 +133,7 @@ export class DocumentReviewDialog {
}
recordNeedsReview(record: ExtractedRecord): boolean {
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));
return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW;
}
extracted(record: ExtractedRecord, field: string): ExtractedField | null {
@@ -55,15 +55,6 @@
</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, KeyValuePipe } from '@angular/common';
import { DecimalPipe } 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,13 +13,12 @@ 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 = 3;
const VALIDATION_TAB = 2;
/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
/** Everything about the selected flow: its mapping, its data, its validation. */
@Component({
selector: 'app-flow-editor',
imports: [
@@ -27,8 +26,6 @@ const VALIDATION_TAB = 3;
DataGrid,
DecimalPipe,
FlowStatusChip,
KeyValuePipe,
MappingRules,
MatBadgeModule,
MatButtonModule,
MatIconModule,
@@ -1,238 +0,0 @@
@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>
@@ -1,113 +0,0 @@
: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);
}
}
@@ -1,255 +0,0 @@
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,40 +92,4 @@ 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);
});
});
+4 -82
View File
@@ -2,8 +2,6 @@ import { Signal, computed, signal } from '@angular/core';
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
import {
CommitSourceResult,
DerivationRule,
DocumentColumnsConfig,
ImportSourcePayload,
PreviewResponse,
RowError,
@@ -49,14 +47,9 @@ 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);
@@ -65,12 +58,6 @@ 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();
@@ -78,28 +65,18 @@ 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, 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.
*/
/** A field is covered when a column feeds it or it has a default value. */
readonly missingRequired = computed<TargetField[]>(() => {
if (this._documents()) return [];
const mapped = this.mapping.byField();
const defaults = this._defaults();
const derived = this._derived();
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !derived[f.name] && !defaults[f.name]?.trim());
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
});
/** Columns no mapping, rule or document setting reads. */
readonly unmappedColumns = computed(() => {
const used = new Set([...this.mapping.bySource().keys(), ...this._documents()?.columns ?? []]);
const used = this.mapping.bySource();
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>(() => {
@@ -107,8 +84,7 @@ export class ImportFlow {
if (this._error() || !this._preview()) return 'error';
if (this._result()) return 'loaded';
if (this._validating()) return 'validating';
const assigned = this.mapping.size() + Object.keys(this.activeDefaults()).length + Object.keys(this._derived()).length;
if (this.missingRequired().length > 0 || (assigned === 0 && !this._documents())) {
if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) {
return 'incomplete';
}
const validation = this._validation();
@@ -185,9 +161,6 @@ 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();
}
@@ -215,51 +188,9 @@ 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 };
@@ -284,9 +215,6 @@ 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 } : {}),
};
}
@@ -328,9 +256,3 @@ 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;
}
@@ -1,47 +0,0 @@
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();
});
});
@@ -1,59 +0,0 @@
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));
}
@@ -12,7 +12,7 @@ import { ImportFlow } from '../domain/import-flow';
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
{ id: 'cama', label: 'CaMa', description: 'Cáncer de mama' },
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
];
@@ -1,9 +1,9 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number;
// Filters a list announces in `filtros_disponibles`, by key.
filtros?: Record<string, string>; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
export interface SeguimientoPaciente {
pac_id?: string;
id_seudonimo?: string;
id_seudonimo: string;
grupo_edad: string;
estatus: SeguimientoStatus;
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
@@ -2,7 +2,6 @@ import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
import { identidadDe, identidadesDe } from './paciente-identidad';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
@@ -20,12 +19,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || 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']));
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
})) throw new Error('Respuesta de seguimiento inválida');
return v as unknown as SeguimientoResponse;
}
@Injectable({ providedIn: 'root' })
@@ -1,20 +0,0 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
};
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
const HISTOLOGIA: Readonly<Record<string, string>> = {
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
};
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
@@ -1,7 +0,0 @@
// A cell that starts with one of these is read as a formula by spreadsheet programs once the text is pasted or converted.
const FORMULA_START = /^[=+\-@\t\r]/;
/** Text that is safe to write into a spreadsheet cell: a leading formula character is neutralised with an apostrophe. */
export function neutralizeFormula(text: string): string {
return FORMULA_START.test(text) ? `'${text}` : text;
}
@@ -1,23 +0,0 @@
const pad = (n: number) => String(n).padStart(2, '0');
/**
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
* patient identifier, because file names end up in download lists, backups and mail attachments.
*/
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
}
/** Hands a generated file to the browser's download. */
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.rel = 'noopener';
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
@@ -1,96 +0,0 @@
// Covers that nothing a user can read in the exports (PDF of the list, spreadsheet, PDF of one record) or in the
// individual record alludes to tests, simulation or a development environment, and that none carries a note line. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { strFromU8, unzipSync } from 'fflate';
import fixtureData from '../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { CamaPatientCard } from '../paciente-detalle/cama/cama-patient-card';
import { camaPatientDocument } from '../paciente-detalle/cama/cama-patient-pdf';
import { toCamaPatientSummary } from '../paciente-detalle/cama/cama-patient.models';
import { exportFilename } from './download-file';
import { TrackingExportBar } from './tracking-export-bar';
import { trackingDocument } from './tracking-pdf';
import { buildTrackingXlsx } from './tracking-xlsx';
import { TrackingSnapshot } from './tracking-export.models';
const NOTE_TEXT = 'Documento de consulta; verificar información con el expediente fuente';
const FORBIDDEN = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|ejemplo|valor cl[ií]nico|test/i;
const r = seguimientoTablaResponse(structuredClone(fixtureData));
const snapshot: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30));
function texts(node: unknown, out: string[] = []): string[] {
if (typeof node === 'string') out.push(node);
else if (Array.isArray(node)) node.forEach(n => texts(n, out));
else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out));
return out;
}
// Every text a PDF definition can print: header, footer, content and document properties.
const pdfTexts = (d: Record<string, any>) => [...texts(d['header']()), ...texts(d['footer'](1, 2)), ...texts(d['content']), ...texts(d['info'])];
describe('Documentos y ficha: sin leyendas alusivas a pruebas', () => {
// Fails if any text of the list PDF (frame, parameters, table, notes, properties) mentions tests or simulation.
it('the list PDF has no such wording and no note', () => {
const all = pdfTexts(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
expect(all.filter(t => FORBIDDEN.test(t))).toEqual([]);
expect(all).not.toContain(NOTE_TEXT);
});
// Fails if any cell, sheet name or parameter of the spreadsheet mentions tests or simulation.
it('the spreadsheet has no such wording and no note', async () => {
const files = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
const strings = strFromU8(files['xl/sharedStrings.xml']), workbook = strFromU8(files['xl/workbook.xml']);
expect(FORBIDDEN.test(strings.replace(/<[^>]+>/g, ' '))).toBe(false);
expect(FORBIDDEN.test(workbook.replace(/xmlns[^ >]*/g, ''))).toBe(false);
expect(strings).not.toContain(NOTE_TEXT);
expect(strings).not.toContain('Tipo de datos');
});
// Fails if the record's PDF mentions tests, simulation or the synthetic nature of the identifier.
it('the record PDF has no such wording and no note', () => {
const summary = toCamaPatientSummary(snapshot.items[0], snapshot.corte)!;
const all = pdfTexts(camaPatientDocument(summary, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
expect(all.filter(t => FORBIDDEN.test(t))).toEqual([]);
expect(all).not.toContain(NOTE_TEXT);
});
// Fails if the record on screen or the export buttons mention tests or simulation.
it('the record and the export buttons show no such wording', () => {
TestBed.configureTestingModule({ providers: [provideHttpClient()] });
const card = TestBed.createComponent(CamaPatientCard);
card.componentRef.setInput('summary', toCamaPatientSummary(snapshot.items[0], snapshot.corte)!);
card.detectChanges();
expect(FORBIDDEN.test(card.nativeElement.textContent)).toBe(false);
expect(card.nativeElement.textContent).not.toContain(NOTE_TEXT);
const bar = TestBed.createComponent(TrackingExportBar);
bar.componentRef.setInput('dominio', 'cama'); bar.componentRef.setInput('respuesta', r);
bar.detectChanges();
expect(FORBIDDEN.test(bar.nativeElement.textContent)).toBe(false);
});
});
describe('Documentos y ficha: nombre funcional del dominio', () => {
// Fails if "CaMa" (an internal name) or a wrong title reaches the titles, properties or text of a document.
it('both PDFs use the functional name, with accents, and never "CaMa"', () => {
const list = pdfTexts(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
const record = pdfTexts(camaPatientDocument(toCamaPatientSummary(snapshot.items[0], snapshot.corte)!, NOW, 'data:image/png;base64,AAAA') as Record<string, any>);
expect(list).toContain('Cáncer de mama');
expect(record).toContain('Ficha de paciente — Cáncer de mama');
expect(list.filter(t => /cama/i.test(t))).toEqual([]);
expect(record.filter(t => /cama/i.test(t))).toEqual([]);
});
// Fails if the spreadsheet names the report or its sheets with the internal name.
it('the spreadsheet names the report "Cáncer de mama" and never "CaMa"', async () => {
const files = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
const strings = strFromU8(files['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|');
expect(strings).toContain('|Cáncer de mama|');
expect(/cama/i.test(strings + strFromU8(files['xl/workbook.xml']).replace(/xmlns[^ >]*/g, ''))).toBe(false);
});
// Fails if a downloaded file name exposes the internal name or a patient.
it('file names use the functional name', () => {
expect(exportFilename('seguimiento-cancer-de-mama', snapshot.corte, 'xlsx', NOW)).not.toMatch(/cama|M-\d/i);
expect(exportFilename('ficha-cancer-de-mama', snapshot.corte, 'pdf', NOW)).not.toMatch(/cama|M-\d/i);
});
});
@@ -1,18 +0,0 @@
export type PdfDefinition = Record<string, unknown>;
let fontsReady = false;
/** Renders a pdfmake document definition. pdfmake and its Roboto fonts download only when the first PDF is made. */
export async function renderPdf(definition: PdfDefinition): Promise<Blob> {
const [{ default: pdfMake }, { default: roboto }] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/fonts/Roboto'),
]);
if (!fontsReady) {
pdfMake.addFontContainer(roboto);
// A document only carries inline data; it must never make pdfmake fetch an address.
pdfMake.setUrlAccessPolicy(() => false);
fontsReady = true;
}
return pdfMake.createPdf(definition).getBlob();
}
@@ -1,88 +0,0 @@
import { PdfDefinition } from './pdf-engine';
export const PDF_CONFIDENTIAL = 'Confidencial · uso interno';
export const LOGO_URL = 'assets/branding/isssteleon-logo.png';
// The logo is 1125 x 358 pixels.
const LOGO_WIDTH = 110;
export const COLORS = { ink: '#081839', accent: '#a8c243', muted: '#7a7a7a', rule: '#e3e7df', band: '#f0f3e8' } as const;
export interface PdfTemplateOptions {
/** Title in the page header and in the document properties. */
title: string;
/** Data URL of the institutional logo; without it the header shows the name as text. */
logo?: string;
now: Date;
/** Page size: reports are landscape letter, individual records portrait. */
orientation: 'landscape' | 'portrait';
}
/** The logo as a data URL, or `undefined` when it cannot be read (the header then falls back to text). */
export async function loadLogo(url = LOGO_URL): Promise<string | undefined> {
try {
const response = await fetch(url);
if (!response.ok) return undefined;
const blob = await response.blob();
return await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
} catch {
return undefined;
}
}
export function formatGenerated(now: Date): string {
return new Intl.DateTimeFormat('es-MX', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Mexico_City' }).format(now);
}
/**
* The institutional frame shared by every PDF: header with the logo, and the title on every
* page, footer with the generation time, the confidentiality line and "Página X de Y", and generic document properties
* (no author, no user). `content` is what goes between them.
*/
export function institutionalDocument(options: PdfTemplateOptions, content: unknown[]): PdfDefinition {
const margin = 36;
// Letter is 792 x 612 points; the header rule spans the page between its margins.
const usableWidth = (options.orientation === 'landscape' ? 792 : 612) - 2 * margin;
return {
pageSize: 'LETTER',
pageOrientation: options.orientation,
pageMargins: [margin, 84, margin, 52],
// Named, so the logo is embedded once and not again on every page.
images: options.logo ? { logo: options.logo } : {},
info: { title: options.title, author: 'ISSSTELEON', creator: 'ISSSTELEON', producer: 'ISSSTELEON' },
defaultStyle: { font: 'Roboto', fontSize: 9, color: COLORS.ink },
styles: {
h1: { fontSize: 15, bold: true, margin: [0, 0, 0, 6] },
h2: { fontSize: 11, bold: true, margin: [0, 10, 0, 4] },
muted: { color: COLORS.muted },
th: { bold: true, fillColor: COLORS.accent, color: COLORS.ink },
small: { fontSize: 8, color: COLORS.muted },
},
header: () => ({
margin: [margin, 20, margin, 0],
stack: [
{
columns: [
options.logo ? { image: 'logo', width: LOGO_WIDTH } : { text: 'ISSSTELEON', bold: true, fontSize: 14 },
{ text: options.title, alignment: 'center', width: '*', bold: true, fontSize: 12, margin: [0, 8, 0, 0] },
{ text: '', width: LOGO_WIDTH },
],
},
{ canvas: [{ type: 'line', x1: 0, y1: 8, x2: usableWidth, y2: 8, lineWidth: 1, lineColor: COLORS.accent }] },
],
}),
footer: (currentPage: number, pageCount: number) => ({
margin: [margin, 14, margin, 0],
columns: [
{ text: `Generado: ${formatGenerated(options.now)} (hora de la Ciudad de México)`, style: 'small' },
{ text: PDF_CONFIDENTIAL, style: 'small', alignment: 'center' },
{ text: `Página ${currentPage} de ${pageCount}`, style: 'small', alignment: 'right' },
],
}),
content,
};
}
-11
View File
@@ -1,11 +0,0 @@
// pdfmake ships no type declarations; only the calls the export layer makes are declared.
declare module 'pdfmake/build/pdfmake' {
interface PdfDocumentHandle { getBlob(): Promise<Blob>; getBuffer(): Promise<Uint8Array>; }
const pdfMake: { createPdf(definition: unknown): PdfDocumentHandle; addFontContainer(container: unknown): void; setUrlAccessPolicy(policy: (url: string) => boolean): void };
export default pdfMake;
}
declare module 'pdfmake/build/fonts/Roboto' {
const fontContainer: unknown;
export default fontContainer;
}
@@ -1,136 +0,0 @@
// Covers the export buttons of the follow-up table: when they are enabled, what they ask the service for, the file
// they hand to the browser, cancelling and the messages of each failure. Fixture: fixtures/cama_seguimiento.json.
// The service is a stub that pages the fixture; the download is observed through the anchor the browser would click.
import { TestBed } from '@angular/core/testing';
import { Observable, of, Subject } from 'rxjs';
import fixtureData from '../fixtures/cama_seguimiento.json';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { TrackingExportBar } from './tracking-export-bar';
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
const respuesta = (extra: Record<string, any> = {}) => seguimientoTablaResponse({ ...base(), ...extra });
describe('Exportación: botones', () => {
let requests: SeguimientoTablaQuery[], downloads: { name: string; blob: Blob }[], answers: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>;
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
beforeEach(() => {
requests = []; downloads = [];
// Like the API, the stub reports the filters it was asked to apply.
answers = q => of(respuesta({ filtros: { ...base()['filtros'], ...q.filtros }, paginacion: { page: q.page, page_size: q.page_size, total_items: 27, total_pages: 1 } }));
TestBed.configureTestingModule({
providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => { requests.push(q); return answers(q); } } }],
});
let pending: Blob | undefined;
vi.spyOn(URL, 'createObjectURL').mockImplementation(blob => { pending = blob as Blob; return 'blob:test'; });
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { downloads.push({ name: this.download, blob: pending! }); });
});
afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); });
function montar(response = respuesta(), habilitado = true) {
fixture = TestBed.createComponent(TrackingExportBar);
fixture.componentRef.setInput('dominio', 'cama');
fixture.componentRef.setInput('respuesta', response);
fixture.componentRef.setInput('habilitado', habilitado);
fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
}
const boton = (root: HTMLElement, texto: string) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes(texto)) as HTMLButtonElement | undefined;
const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } };
// Fails if the buttons stop being a bare group (the title row of the table holds them) or bring back their own block.
it('has no block of its own: only the buttons, and messages after them', () => {
const root = montar();
expect(root.querySelector('h3, section')).toBeNull();
expect(root.firstElementChild!.classList.contains('actions')).toBe(true);
});
// Fails if the button stops being available for a query that fits the limit.
it('enables the spreadsheet export for a query within the limit', () => {
expect(boton(montar(), 'Excel')!.disabled).toBe(false);
});
// Fails if the export is allowed above the limit or the reason is not shown: the user would get a silent subset.
it('disables the export above the limit and says why', () => {
const root = montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 5001, total_pages: 101 } }));
expect(boton(root, 'Excel')!.disabled).toBe(true);
expect(root.textContent).toContain('admite hasta 5,000 registros');
expect(root.textContent).toContain('Acota los filtros');
});
// Fails if the PDF is allowed above its own, lower limit, or if hitting it also blocks the spreadsheet.
it('limits the PDF to 1,000 rows while the spreadsheet still accepts the query', () => {
const root = montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 1001, total_pages: 21 } }));
expect(boton(root, 'PDF')!.disabled).toBe(true);
expect(boton(root, 'Excel')!.disabled).toBe(false);
expect(root.textContent).toContain('PDF admite hasta 1,000 registros');
});
// Fails if an empty result offers a file with no rows.
it('disables the export when there are no rows', () => {
expect(boton(montar(respuesta({ paginacion: { page: 1, page_size: 50, total_items: 0, total_pages: 0 }, items: [] })), 'Excel')!.disabled).toBe(true);
});
// Fails if the export reads a query that is about to be replaced by the one being loaded.
it('disables the export while a page is loading', () => {
expect(boton(montar(respuesta(), false), 'Excel')!.disabled).toBe(true);
});
// Fails if the file is built from the form instead of the shown answer, or the name carries a patient id.
it('exports the shown query in full and downloads a file named without any patient', async () => {
const root = montar(respuesta({ filtros: { ...base()['filtros'], estatus: 'BENIGNO' } }));
boton(root, 'Excel')!.click();
await esperar();
expect(requests[0]).toMatchObject({ corte: '2026-10-20', meses: 3, page: 1, page_size: 200, filtros: { estatus: 'BENIGNO' } });
expect(downloads).toHaveLength(1);
expect(downloads[0].name).toMatch(/^seguimiento-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/);
expect(downloads[0].name).not.toMatch(/M-\d/);
expect(downloads[0].blob.size).toBeGreaterThan(1000);
expect(root.textContent).toContain('Se generó el archivo con 27 registros');
});
// Fails if the success message of one query stays on screen after another query is shown.
it('drops the result message when another query is shown, but keeps it while paging', async () => {
const root = montar();
boton(root, 'Excel')!.click();
await esperar();
expect(root.textContent).toContain('Se generó el archivo');
// Another page of the same query: the message stays.
fixture.componentRef.setInput('respuesta', respuesta({ items: [], paginacion: { page: 2, page_size: 10, total_items: 27, total_pages: 3 } }));
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
expect(root.textContent).toContain('Se generó el archivo');
// Another filter: the message goes.
fixture.componentRef.setInput('respuesta', respuesta({ filtros: { ...base()['filtros'], prioridad: 'ALTA' }, paginacion: { page: 1, page_size: 50, total_items: 9, total_pages: 1 } }));
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
expect(root.textContent).not.toContain('Se generó el archivo');
});
// Fails if cancelling leaves the export running or still downloads a file afterwards.
it('stops and downloads nothing when cancelled', async () => {
const never = new Subject<SeguimientoTablaResponse>();
answers = () => never;
const root = montar();
boton(root, 'Excel')!.click();
fixture.detectChanges();
expect(root.textContent).toContain('Preparando exportación');
boton(root, 'Cancelar')!.click();
fixture.detectChanges();
never.next(respuesta());
await esperar();
expect(downloads).toEqual([]);
expect(boton(root, 'Cancelar')).toBeUndefined();
expect(boton(root, 'Excel')!.disabled).toBe(false);
});
// Fails if a failed read is shown as success or leaves the buttons locked.
it('shows an error and unlocks the buttons when the service fails', async () => {
answers = () => { throw new Error('boom'); };
const root = montar();
boton(root, 'Excel')!.click();
await esperar();
expect(root.querySelector('[role="alert"]')!.textContent).toContain('No se pudo generar el archivo');
expect(downloads).toEqual([]);
expect(boton(root, 'Excel')!.disabled).toBe(false);
});
});
@@ -1,145 +0,0 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { Dominio } from '../indicadores.models';
import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
import { downloadBlob, exportFilename } from './download-file';
import { EXPORT_LIMITS, ExportFormat, ExportInconsistent, ExportLimitExceeded, TrackingSnapshot } from './tracking-export.models';
import { fetchAllTracking, queryOf } from './tracking-export-source';
type State = 'idle' | 'working' | 'error';
const FORMAT_LABEL: Record<ExportFormat, string> = { xlsx: 'Excel (.xlsx)', pdf: 'PDF' };
/**
* Export buttons of a follow-up list. They export the answer on screen (its cut-off, window and filters) and every
* row it matches, not the visible page; a query above a format's limit is refused with a message, never truncated.
*/
@Component({
selector: 'app-seguimiento-exportar',
imports: [DecimalPipe],
template: `
<div class="actions" role="group" aria-label="Exportar resultados"
[attr.title]="'Se exportan los ' + (total() | number) + ' registros de la consulta mostrada, no solo la página visible.'">
@for (formato of formatos; track formato) {
<button type="button" [disabled]="!available(formato)" (click)="exportar(formato)">Exportar {{ label[formato] }}</button>
}
@if (estado() === 'working') { <button type="button" (click)="cancelar()">Cancelar</button> }
</div>
@for (formato of formatos; track formato) {
@if (total() > limits[formato]) {
<p class="message hint">{{ label[formato] }} admite hasta {{ limits[formato] | number }} registros; la consulta tiene {{ total() | number }}. Acota los filtros para exportar.</p>
}
}
@if (estado() === 'working') { <p class="message" role="status">{{ progressText() }}</p> }
@if (estado() === 'error') { <p class="message" role="alert">{{ mensaje() }}</p> }
@if (listo()) { <p class="message" role="status">{{ listo() }}</p> }
`,
// The host takes no box of its own: the buttons sit in the title row that holds it, and each message
// takes a full line below that row.
styles: `
:host { display: contents; }
.message { flex: 0 0 100%; margin: 0; }
.hint { color: var(--issste-text-secondary); }
.actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem; margin-inline-start: auto; }
button { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px;
padding: .6rem 1rem; min-height: 44px; box-sizing: border-box; font: inherit; cursor: pointer; }
button:disabled { opacity: .5; cursor: default; }
button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
`,
})
export class TrackingExportBar {
readonly dominio = input.required<Dominio>();
/** The answer on screen: its metadata says which query to export. */
readonly respuesta = input.required<SeguimientoTablaResponse>();
/** False while a page is being loaded, so the export never reads a query that is about to change. */
readonly habilitado = input(true);
/** How the analysis named the selection this answer belongs to; it travels into the files. */
readonly seleccion = input<string | undefined>(undefined);
private readonly service = inject(SeguimientoTablaService);
private subscription?: Subscription;
readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf'];
readonly label = FORMAT_LABEL;
readonly limits = EXPORT_LIMITS;
readonly estado = signal<State>('idle');
readonly mensaje = signal('');
readonly listo = signal('');
readonly progress = signal({ fetched: 0, total: 0 });
readonly total = computed(() => this.respuesta().paginacion.total_items);
readonly progressText = computed(() => {
const { fetched, total } = this.progress();
return total ? `Leyendo registros: ${fetched} de ${total}…` : 'Preparando exportación…';
});
// Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it.
private readonly queryKey = computed(() => {
const r = this.respuesta();
return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]);
});
constructor() {
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
effect(() => {
this.queryKey();
untracked(() => {
if (this.estado() === 'working') {
this.subscription?.unsubscribe();
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
});
});
}
available(formato: ExportFormat): boolean {
return this.habilitado() && this.estado() !== 'working' && this.total() > 0 && this.total() <= EXPORT_LIMITS[formato];
}
exportar(formato: ExportFormat) {
if (!this.available(formato)) return;
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
this.subscription?.unsubscribe();
const clave = this.queryKey(), seleccion = this.seleccion();
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
next: event => {
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
},
error: error => this.fallar(error),
});
}
cancelar() {
this.subscription?.unsubscribe();
this.estado.set('idle');
}
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
try {
// Each generator (and its library) downloads only when its button is used.
const blob = formato === 'xlsx'
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
// The query on screen changed while the file was being made: it is not the one that was asked for.
if (clave !== this.queryKey()) return;
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
this.estado.set('idle');
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
} catch {
this.fallar(new Error('generation'));
}
}
private fallar(error: unknown) {
this.estado.set('error');
const estatus = error instanceof HttpErrorResponse ? error.status : 0;
this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.'
: estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.'
: estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.'
: error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.'
: 'No se pudo generar el archivo. Intenta nuevamente.');
}
}
@@ -1,157 +0,0 @@
// Covers the files of a list opened from the analysis: they state the selection, the cut-off and «Toda la cohorte», and
// hold exactly the patients the table holds, over several pages; and an export never outlives the query it was made for.
// Fixture: fixtures/cama_seguimiento.json, whose rows are repeated to make a list of several pages.
import { TestBed } from '@angular/core/testing';
import { Observable, of, Subject } from 'rxjs';
import { strFromU8, unzipSync } from 'fflate';
import fixtureData from '../fixtures/cama_seguimiento.json';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { TrackingExportBar } from './tracking-export-bar';
import { CONTEXTO } from '../indicadores-analisis.testing';
import { fetchAllTracking, queryOf } from './tracking-export-source';
import { TrackingSnapshot } from './tracking-export.models';
import { trackingDocument } from './tracking-pdf';
import { buildTrackingXlsx } from './tracking-xlsx';
const ETIQUETA = 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 5';
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
// A cohort of `n` patients, M-0001 onwards, served in the pages that were asked for, with the filters it applied.
function cohorte(n: number) {
const plantilla = (base()['items'] as Record<string, unknown>[])[0];
const todos = Array.from({ length: n }, (_, i) => ({ ...plantilla, id_seudonimo: `M-${String(i + 1).padStart(4, '0')}` }));
return (q: SeguimientoTablaQuery): SeguimientoTablaResponse => seguimientoTablaResponse({
...base(), ventana: { meses: q.meses, desde: '2025-01-01', hasta: '2026-10-20' }, corte: q.corte ?? '2026-10-20',
filtros: { ...base()['filtros'], ...q.filtros }, ...(q.contexto ?? {}),
paginacion: { page: q.page, page_size: q.page_size, total_items: n, total_pages: Math.ceil(n / q.page_size) },
items: todos.slice((q.page - 1) * q.page_size, q.page * q.page_size),
});
}
const consulta = (extra: Partial<SeguimientoTablaQuery> = {}): SeguimientoTablaQuery =>
({ corte: '2026-10-20', meses: 0, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO, ...extra });
const textos = (nodo: unknown, salida: string[] = []): string[] => {
if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida));
return salida;
};
describe('Archivos de una selección del análisis', () => {
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery) => of(cohorte(450)(q)) } as unknown as SeguimientoTablaService;
it('el PDF y el XLSX dicen la selección, el corte y «Toda la cohorte», y traen los mismos pacientes que la tabla en todas sus páginas', async () => {
// Fails if a file loses the selection, calls the whole cohort «0 meses», or its patients differ from the table's pages.
const q = consulta();
// The table, page by page (50 per page), as the user would walk it.
const filasTabla: string[] = [];
for (let p = 1; p <= 9; p++) filasTabla.push(...cohorte(450)({ ...q, page: p }).items.map(i => String(i['id_seudonimo'])));
let snapshot!: TrackingSnapshot;
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({
next: e => { if (e.kind === 'done') snapshot = { ...e.snapshot, seleccion: ETIQUETA }; }, error: fallo, complete: ok }));
expect(snapshot.items.map(i => String(i['id_seudonimo']))).toEqual(filasTabla);
expect(new Set(filasTabla).size).toBe(450);
const pdf = textos(trackingDocument(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)), 'data:image/png;base64,AAAA'));
expect(pdf).toContain('Selección del análisis'); expect(pdf).toContain(ETIQUETA);
expect(pdf).toContain('Fecha de corte'); expect(pdf).toContain('2026-10-20');
expect(pdf).toContain('Toda la cohorte, al 2026-10-20');
expect(pdf.some(t => /0 meses/.test(t))).toBe(false);
expect(pdf.filter(t => /^M-\d{4}$/.test(t))).toEqual(filasTabla);
const PROHIBIDO = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|mock|valor cl[ií]nico/i;
expect(pdf.filter(t => PROHIBIDO.test(t))).toEqual([]);
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)))).arrayBuffer()));
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']);
expect(cadenas).toContain(ETIQUETA); expect(cadenas).toContain('Selección del análisis'); expect(cadenas).toContain('Toda la cohorte, al 2026-10-20');
expect(cadenas).not.toMatch(/0 meses/);
expect(cadenas.replace(/<[^>]+>/g, ' ')).not.toMatch(PROHIBIDO);
expect([...cadenas.matchAll(/M-\d{4}/g)].map(m => m[0]).filter((v, i, a) => a.indexOf(v) === i)).toEqual(filasTabla);
});
it('sin una selección los archivos no llevan esa línea y conservan la ventana de meses', async () => {
// Fails if a plain list gets a selection line, or a window of months stops being written as dates and months.
const q = consulta({ meses: 3, filtros: {} });
let snapshot!: TrackingSnapshot;
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = e.snapshot; }, error: fallo, complete: ok }));
const pdf = textos(trackingDocument(snapshot, new Date(), 'data:image/png;base64,AAAA'));
expect(pdf).not.toContain('Selección del análisis');
expect(pdf).toContain('2025-01-01 al 2026-10-20 (3 meses)');
});
it('la consulta de una respuesta conserva la cohorte y su revisión, y todas las páginas del archivo la citan', async () => {
// Fails if the export reads a cohort's list without quoting its revision (the server refuses it) or from another one.
const respuesta = cohorte(450)(consulta());
expect(queryOf(respuesta)).toMatchObject({ corte: '2026-10-20', meses: 0, page: 1, page_size: 200, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
const pedidas: SeguimientoTablaQuery[] = [];
const espia = { consultar: (_d: string, q: SeguimientoTablaQuery) => { pedidas.push(q); return of(cohorte(450)(q)); } } as unknown as SeguimientoTablaService;
await new Promise<void>((ok, fallo) => fetchAllTracking(espia, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
expect(pedidas.map(q => q.page).sort()).toEqual([1, 2, 3]);
expect(pedidas.every(q => q.contexto?.revision === CONTEXTO.revision && q.contexto?.cohorte === CONTEXTO.cohorte && q.meses === 0)).toBe(true);
// A plain list quotes no cohort.
expect(queryOf(seguimientoTablaResponse(base())).contexto).toBeUndefined();
});
it('una página posterior de otra revisión hace fallar la lectura', async () => {
// Fails if a file mixes pages of two revisions of the cohort.
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, contexto: { ...CONTEXTO, revision: 'f'.repeat(64) } }) : cohorte(450)(q));
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
expect(error).toBeInstanceOf(Error);
});
it('una página posterior que pierde un filtro hace fallar la lectura: no se exporta un subconjunto de otra consulta', async () => {
// Fails if a file mixes the pages of the selection with a page of another population.
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, filtros: {} }) : cohorte(450)(q));
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
expect(error).toBeInstanceOf(Error);
});
});
describe('Exportación: la consulta cambia mientras se exporta', () => {
let respuestas: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>, descargas: string[];
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
beforeEach(() => {
descargas = [];
respuestas = q => of(cohorte(27)(q));
TestBed.configureTestingModule({ providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } }] });
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
});
afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); });
const montar = (r: SeguimientoTablaResponse, seleccion?: string) => {
fixture = TestBed.createComponent(TrackingExportBar);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('respuesta', r);
fixture.componentRef.setInput('seleccion', seleccion); fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
};
const excel = (root: HTMLElement) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes('Excel')) as HTMLButtonElement;
const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } };
it('un archivo de una selección se llama como tal y no lleva a ningún paciente en el nombre', async () => {
// Fails if the file of a selection is told apart from a plain list by nothing, or names a patient.
const root = montar(cohorte(27)(consulta()), ETIQUETA);
excel(root).click(); await esperar();
expect(descargas).toHaveLength(1);
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/);
expect(descargas[0]).not.toMatch(/M-\d|cama/i);
});
it('si la consulta en pantalla cambia mientras se lee, se cancela y no se descarga nada', async () => {
// Fails if a list read for the old selection is downloaded as the one now on screen.
const lenta = new Subject<SeguimientoTablaResponse>();
respuestas = () => lenta;
const root = montar(cohorte(27)(consulta()), ETIQUETA);
excel(root).click(); fixture.detectChanges();
expect(root.textContent).toContain('Preparando exportación');
fixture.componentRef.setInput('respuesta', cohorte(27)(consulta({ filtros: { birads: 'BIRADS_6' } })));
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
lenta.next(cohorte(27)(consulta()));
await esperar();
expect(descargas).toEqual([]);
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió; se canceló la exportación');
expect(excel(root).disabled).toBe(false);
});
it('si cambia mientras se genera el archivo, tampoco se descarga', async () => {
// Fails if a file finished after the selection changed still reaches the downloads.
const root = montar(cohorte(27)(consulta()), ETIQUETA);
excel(root).click();
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
await esperar();
expect(descargas).toEqual([]);
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió');
});
});
@@ -1,122 +0,0 @@
// Covers the layer that reads every row of a follow-up query: the page size it asks for, the cut-off and filters it
// keeps, the limit that refuses instead of truncating, the checks that the pages form one list, and cancellation.
// Fixture: fixtures/cama_seguimiento.json (27 synthetic rows). `servidor` pages it like the API does and counts
// the requests it receives.
import { Observable, of, Subject, toArray, lastValueFrom } from 'rxjs';
import fixtureData from '../fixtures/cama_seguimiento.json';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent } from './tracking-export.models';
import { fetchAllTracking, queryOf } from './tracking-export-source';
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
const TOTAL = (base()['items'] as unknown[]).length;
// A server that pages the fixture. `tweak` can alter the answer of a page to simulate a list that changes, and
// `size` makes it serve smaller pages than asked for, so that 27 rows span several pages.
function servidor(tweak: (page: number, answer: Record<string, any>) => Record<string, any> = (_, a) => a, size?: number) {
const requests: SeguimientoTablaQuery[] = [];
const service = {
consultar(_dominio: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> {
requests.push(q);
const d = base(), all = d['items'] as unknown[], tam = size ?? q.page_size;
d['items'] = all.slice((q.page - 1) * tam, q.page * tam);
d['paginacion'] = { page: q.page, page_size: tam, total_items: all.length, total_pages: Math.max(1, Math.ceil(all.length / tam)) };
d['corte'] = q.corte ?? d['corte'];
d['ventana'] = { ...d['ventana'], meses: q.meses };
d['filtros'] = { ...d['filtros'], ...q.filtros };
return of(seguimientoTablaResponse(tweak(q.page, d)));
},
};
return { service: service as unknown as SeguimientoTablaService, requests };
}
const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5, filtros: { estatus: 'BENIGNO' } };
const eventos = (obs: Observable<TrackingExportEvent>) => lastValueFrom(obs.pipe(toArray()));
describe('Exportación: lectura completa del seguimiento', () => {
// Fails if the layer asks for the page size the user was looking at instead of the largest one, or loses a row.
it('reads every row in pages of 200 and returns them in the server order, whatever page the user was on', async () => {
const { service, requests } = servidor();
const out = await eventos(fetchAllTracking(service, 'cama', { ...consulta, page: 3 }, 5000));
const done = out.at(-1)!;
expect(done.kind).toBe('done');
if (done.kind !== 'done') return;
expect(done.snapshot.items).toHaveLength(TOTAL);
expect(done.snapshot.items.map(i => i['id_seudonimo'])).toEqual((base()['items'] as Record<string, any>[]).map(i => i['id_seudonimo']));
expect(requests.map(r => r.page_size)).toEqual([200]);
});
// Fails if later pages are asked without the first answer's cut-off and filters, which would mix two lists.
it('keeps the cut-off, window and filters of the shown query in every request', async () => {
const { service, requests } = servidor(undefined, 10);
await eventos(fetchAllTracking(service, 'cama', consulta, 5000));
expect(requests).toHaveLength(3);
for (const r of requests) expect(r).toMatchObject({ corte: '2026-10-20', meses: 3, filtros: { estatus: 'BENIGNO' } });
});
// Fails if progress stops being reported or does not end at the announced total.
it('reports progress up to the announced total and then the finished snapshot', async () => {
const { service } = servidor();
const out = await eventos(fetchAllTracking(service, 'cama', consulta, 5000));
expect(out[0]).toEqual({ kind: 'progress', fetched: TOTAL, total: TOTAL });
expect(out.at(-1)!.kind).toBe('done');
});
// Fails if a query above the limit starts downloading pages, or if it returns a subset without saying so.
it('refuses a query above the limit before asking for more pages and never returns a subset', async () => {
const { service, requests } = servidor();
await expect(eventos(fetchAllTracking(service, 'cama', consulta, TOTAL - 1))).rejects.toBeInstanceOf(ExportLimitExceeded);
expect(requests).toHaveLength(1);
});
// Fails if the limit becomes exclusive: a list of exactly the limit must still be exported.
it('accepts a query that is exactly at the limit', async () => {
const { service } = servidor();
const out = await eventos(fetchAllTracking(service, 'cama', consulta, TOTAL));
expect(out.at(-1)!.kind).toBe('done');
});
// Fails if an answer that did not apply the asked filter is accepted: the file would list other patients.
it('fails when the server does not report the filters that were asked for', async () => {
const { service } = servidor((_page, a) => ({ ...a, filtros: { ...a['filtros'], estatus: null } }));
await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent);
});
// Fails if a total that changes between pages is accepted: the file would mix two states of the list.
it('fails when the total changes between pages', async () => {
const { service } = servidor((page, a) => page === 1 ? a : { ...a, paginacion: { ...a['paginacion'], total_items: TOTAL + 1 } }, 10);
await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent);
});
// Fails if a repeated row (the same id on two pages) is accepted as if it were two patients.
it('fails when a row repeats across pages', async () => {
const { service } = servidor((page, a) => page === 1 ? a : { ...a, items: [(base()['items'] as unknown[])[0]] }, 10);
await expect(eventos(fetchAllTracking(service, 'cama', consulta, 5000))).rejects.toBeInstanceOf(ExportInconsistent);
});
// Fails if cancelling (unsubscribing) leaves requests pending or still emits events afterwards.
it('stops asking when the subscriber cancels', () => {
const first = new Subject<SeguimientoTablaResponse>();
const requests: SeguimientoTablaQuery[] = [];
const service = { consultar: (_d: string, q: SeguimientoTablaQuery) => { requests.push(q); return first; } } as unknown as SeguimientoTablaService;
const seen: TrackingExportEvent[] = [];
const subscription = fetchAllTracking(service, 'cama', consulta, 5000).subscribe(e => seen.push(e));
subscription.unsubscribe();
first.next(seguimientoTablaResponse(base()));
expect(requests).toHaveLength(1);
expect(seen).toEqual([]);
});
// Fails if an invalid query reaches the network instead of failing inside the stream.
it('turns an invalid query into an error of the stream', async () => {
const real = { consultar: (_d: string, _q: SeguimientoTablaQuery) => { throw new Error('invalid'); } } as unknown as SeguimientoTablaService;
await expect(eventos(fetchAllTracking(real, 'cama', consulta, 5000))).rejects.toThrow('invalid');
});
});
describe('Exportación: consulta de una respuesta', () => {
// Fails if the export is built from the form being edited instead of what the shown answer says it applied.
it('rebuilds the query from the answer: cut-off, window months and only the filters that were applied', () => {
const answer = seguimientoTablaResponse({ ...base(), filtros: { estatus: 'BENIGNO', birads: null, grupo_edad: null, prioridad: null } });
expect(queryOf(answer)).toEqual({ corte: answer.corte, meses: answer.ventana.meses, page: 1, page_size: 200, filtros: { estatus: 'BENIGNO' } });
});
});
@@ -1,64 +0,0 @@
import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs';
import { Dominio } from '../indicadores.models';
import { identidadesDe } from '../paciente-identidad';
import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models';
const CONCURRENCY = 3;
/** The query that produced a shown answer: its cut-off, window and the filters the server applied. */
export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQuery {
return {
corte: response.corte,
meses: response.ventana.meses,
page: 1,
page_size: PAGE_SIZE_MAX,
filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])),
// A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server.
contexto: contextoDe(response),
};
}
// The server must report having applied the window and the filters that were asked for; otherwise the file would
// hold rows of another query under the title of this one.
const sameQuery = consultaAplicada;
/**
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
* Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list.
*/
export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q));
return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe(
switchMap(first => {
const { total_items: total, total_pages: pages } = first.paginacion;
if (!sameQuery(query, first)) throw new ExportInconsistent('The answer does not apply the query that was asked');
if (total > limit) throw new ExportLimitExceeded(total, limit);
// The rest of the pages are asked for exactly what the first one was, with the cut-off it answered.
const pinned = { ...query, corte: first.corte, page_size: PAGE_SIZE_MAX };
const collected = new Map<number, TrackingRow[]>([[1, first.items]]);
const count = () => [...collected.values()].reduce((sum, rows) => sum + rows.length, 0);
const rest = from(Array.from({ length: Math.max(0, pages - 1) }, (_, i) => i + 2)).pipe(
mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY),
tap(({ page, answer }) => {
if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages
|| answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read');
collected.set(page, answer.items);
}),
map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })),
);
return rest.pipe(
startWith<TrackingExportEvent>({ kind: 'progress', fetched: first.items.length, total }),
concatWith(defer(() => {
const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows);
// Every row has the identity the table shows, and no patient (or episode) appears on two pages.
if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total');
return of<TrackingExportEvent>({
kind: 'done',
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
});
})),
);
}),
);
}
@@ -1,66 +0,0 @@
// Covers how a follow-up snapshot becomes table cells (shared by the spreadsheet and the PDF), the formula
// neutraliser and the file name policy. Fixture: fixtures/cama_seguimiento.json.
import fixtureData from '../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { neutralizeFormula } from './cell-sanitizer';
import { exportFilename } from './download-file';
import { displayText, exportColumns, flatTable, UNAVAILABLE } from './tracking-export-table';
import { TrackingSnapshot } from './tracking-export.models';
function snapshot(): TrackingSnapshot {
const r = seguimientoTablaResponse(structuredClone(fixtureData));
return { corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
}
describe('Exportación: tabla plana', () => {
// Fails if a detail column is dropped or reordered: the spreadsheet would lose the date next to its value.
it('places each detail after its value, labelled with its column', () => {
const { columns } = flatTable(snapshot());
expect(columns.map(c => c.key)).toEqual(['id_seudonimo', 'grupo_edad', 'estatus', 'birads', 'mastografia_fecha', 'biopsia', 'biopsia_fecha', 'dias_mastografia_diagnostico', 'prioridad']);
expect(columns.find(c => c.key === 'mastografia_fecha')!.label).toBe('Última mastografía: Fecha');
});
// Fails if a number is exported as text (it could not be summed or sorted) or a text column as a number.
it('marks as numeric only the columns whose present values are all numbers', () => {
const { columns } = flatTable(snapshot());
expect(columns.filter(c => c.numeric).map(c => c.key)).toEqual(['dias_mastografia_diagnostico']);
});
// Fails if a missing value is invented (0, '') instead of kept as null, which would pass as clinical data.
it('keeps a missing value as null and the rows in the snapshot order', () => {
const s = snapshot();
const { columns, rows } = flatTable(s);
const at = columns.findIndex(c => c.key === 'biopsia');
expect(rows).toHaveLength(s.items.length);
expect(rows.map(r => r[0])).toEqual(s.items.map(i => i['id_seudonimo']));
expect(rows.some(r => r[at] === null)).toBe(true);
});
// Fails if the document and the screen stop agreeing on how a missing value reads.
it('reads a missing value as the table does', () => {
expect(displayText(null)).toBe(UNAVAILABLE);
expect(displayText(undefined)).toBe(UNAVAILABLE);
expect(displayText(12)).toBe('12');
expect(exportColumns(snapshot()).find(c => c.key === 'birads')!.details).toEqual([{ key: 'mastografia_fecha', label: 'Fecha' }]);
});
});
describe('Exportación: texto de celdas y nombres de archivo', () => {
// Fails if a value that starts like a formula is written as is: opening the file could run it.
it.each(['=1+1', '+SUM(A1)', '-2+3', '@cmd', '\tx', '\rx'])('neutralises %j', text => {
expect(neutralizeFormula(text)).toBe(`'${text}`);
});
// Fails if ordinary labels are altered by the neutraliser.
it('leaves ordinary text untouched', () => {
for (const text of ['Pendiente de biopsia', 'BI-RADS 4A', '2026-10-20', '']) expect(neutralizeFormula(text)).toBe(text);
});
// Fails if a file name carries a patient identifier or characters that are unsafe in a path.
it('names files after the report and the cut-off, never a patient', () => {
const name = exportFilename('seguimiento-cancer-de-mama', '2026-10-20', 'xlsx', new Date(2026, 10, 12, 15, 30));
expect(name).toBe('seguimiento-cancer-de-mama_corte-2026-10-20_20261112-1530.xlsx');
expect(exportFilename('ficha-cancer-de-mama', '../2026-10-20', 'pdf', new Date(2026, 0, 2, 3, 4))).toBe('ficha-cancer-de-mama_corte-2026-10-20_20260102-0304.pdf');
expect(name).not.toMatch(/M-\d+/);
});
});
@@ -1,36 +0,0 @@
import { SeguimientoValor } from '../seguimiento-tabla.service';
import { TrackingSnapshot } from './tracking-export.models';
export const UNAVAILABLE = 'No disponible';
/** A column as the follow-up table shows it: the value and, under it, its labelled details. */
export interface ExportColumn { key: string; label: string; details: { key: string; label: string }[]; }
/** One flat column of a spreadsheet; a detail becomes a column of its own so it can be filtered and sorted. */
export interface FlatColumn { key: string; label: string; numeric: boolean; }
export interface FlatTable { columns: FlatColumn[]; rows: SeguimientoValor[][]; }
/** The columns the answer announced, in its order. */
export function exportColumns(snapshot: TrackingSnapshot): ExportColumn[] {
return snapshot.columnas.map(c => ({ key: c.clave, label: c.etiqueta, details: (c.detalles ?? []).map(d => ({ key: d.clave, label: d.etiqueta })) }));
}
/** Text of a value as the table shows it, `null` included. */
export function displayText(value: SeguimientoValor | undefined): string {
return value === null || value === undefined ? UNAVAILABLE : String(value);
}
/** Every detail after its value, with a column numeric only when each present value is a number. */
export function flatTable(snapshot: TrackingSnapshot): FlatTable {
const columns: FlatColumn[] = [];
for (const column of exportColumns(snapshot)) {
columns.push({ key: column.key, label: column.label, numeric: false });
for (const detail of column.details) columns.push({ key: detail.key, label: `${column.label}: ${detail.label}`, numeric: false });
}
for (const column of columns) {
const present = snapshot.items.map(item => item[column.key]).filter(v => v !== null && v !== undefined);
column.numeric = present.length > 0 && present.every(v => typeof v === 'number');
}
return { columns, rows: snapshot.items.map(item => columns.map(column => item[column.key] ?? null)) };
}
@@ -1,38 +0,0 @@
import { etiquetaVentana, SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service';
/** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */
export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const;
export type ExportFormat = keyof typeof EXPORT_LIMITS;
export type TrackingRow = Record<string, SeguimientoValor>;
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
export interface TrackingSnapshot {
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
seleccion?: string;
corte: string;
ventana: SeguimientoTablaResponse['ventana'];
filtros: SeguimientoTablaResponse['filtros'];
filtros_disponibles: SeguimientoTablaResponse['filtros_disponibles'];
columnas: SeguimientoTablaResponse['columnas'];
items: TrackingRow[];
}
/** The window as the files state it: the whole cohort up to the cut-off, or the dates and months of the window. */
export function ventanaConsultada(snapshot: Pick<TrackingSnapshot, 'ventana'>): string {
const { meses, desde, hasta } = snapshot.ventana;
return meses === 0 ? `Toda la cohorte, al ${hasta}` : `${desde} al ${hasta} (${etiquetaVentana(meses)})`;
}
export type TrackingExportEvent =
| { kind: 'progress'; fetched: number; total: number }
| { kind: 'done'; snapshot: TrackingSnapshot };
export class ExportLimitExceeded extends Error {
constructor(readonly total: number, readonly limit: number) {
super(`The query has ${total} rows and the limit is ${limit}`);
}
}
/** The pages did not describe one stable list (the total changed, a page repeated or a row was lost). */
export class ExportInconsistent extends Error {}
@@ -1,112 +0,0 @@
// Covers the follow-up PDF: the institutional frame (logo, title, footer), the parameters it
// prints, the table that repeats its header across pages, and that the document really renders to a PDF file.
// Fixture: fixtures/cama_seguimiento.json. The logo is a 1x1 PNG data URL; the real logo is read in the browser.
import fixtureData from '../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { COLORS, PDF_CONFIDENTIAL } from './pdf-template';
import { buildTrackingPdf, trackingDocument } from './tracking-pdf';
import { TrackingSnapshot } from './tracking-export.models';
const PIXEL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30));
function snapshot(mutate: (s: TrackingSnapshot) => void = () => undefined): TrackingSnapshot {
const r = seguimientoTablaResponse(structuredClone(fixtureData));
const s: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: { ...r.filtros, prioridad: 'ALTA' }, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
mutate(s);
return s;
}
// Every string of a nested document definition, to look for text without depending on its structure.
function texts(node: unknown, out: string[] = []): string[] {
if (typeof node === 'string') out.push(node);
else if (Array.isArray(node)) node.forEach(n => texts(n, out));
else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out));
return out;
}
describe('Exportación: PDF de seguimiento', () => {
const definition = (s = snapshot()) => trackingDocument(s, NOW, PIXEL) as Record<string, any>;
// Fails if the report stops being landscape letter, which the nine columns need.
it('is a landscape letter document with generic properties', () => {
const d = definition();
expect(d['pageSize']).toBe('LETTER');
expect(d['pageOrientation']).toBe('landscape');
expect(d['info']).toMatchObject({ author: 'ISSSTELEON', creator: 'ISSSTELEON', producer: 'ISSSTELEON', title: 'Cáncer de mama' });
});
// Fails if the logo or the title are missing from the header: every page must carry them.
it('puts the logo and the title in the header of every page', () => {
const d = definition();
const header = d['header']();
const found = texts(header);
// The logo is named in the header and defined once, so it is embedded once however many pages there are.
expect(JSON.stringify(header)).toContain('"image":"logo"');
expect(d['images']).toEqual({ logo: PIXEL });
expect(found).toContain('Cáncer de mama');
});
// Fails if the header breaks when the logo cannot be read: the report must still be produced.
it('falls back to the name as text when there is no logo', () => {
const d = trackingDocument(snapshot(), NOW) as Record<string, any>;
expect(JSON.stringify(d['header']())).not.toContain('"image"');
expect(texts(d['header']())).toContain('ISSSTELEON');
});
// Fails if the footer loses the page count, the confidentiality line or the generation time.
it('has a footer with the generation time, the confidentiality line and "Página X de Y"', () => {
const found = texts(definition()['footer'](2, 7));
expect(found).toContain('Página 2 de 7');
expect(found).toContain(PDF_CONFIDENTIAL);
expect(found.some(t => t.startsWith('Generado: 12 nov 2026, 3:30 p.m.'))).toBe(true);
});
// Fails if the parameters stop saying what query the report answers.
it('prints the cut-off, the window, every filter with its option and the number of rows', () => {
const s = snapshot();
const found = texts(definition(s)['content']);
for (const t of ['Fecha de corte', s.corte, `${s.ventana.desde} al ${s.ventana.hasta} (3 meses)`, 'Prioridad', 'Alta', 'Todos', 'Registros', String(s.items.length)]) expect(found).toContain(t);
});
// Fails if the table stops repeating its header across pages or lets a row split between two pages.
it('repeats the header row and keeps each row on one page', () => {
const table = definition()['content'].find((n: any) => n.table?.headerRows)!.table;
expect(table.headerRows).toBe(1);
expect(table.dontBreakRows).toBe(true);
expect(table.body).toHaveLength(snapshot().items.length + 1);
expect(table.body[0].map((cell: { text: string }) => cell.text)).toEqual(['Identificador seudónimo', 'Grupo de edad', 'Estatus de seguimiento', 'Última mastografía', 'Resultado histopatológico', 'Días de mastografía a diagnóstico', 'Prioridad']);
});
// Fails if details stop appearing under their value, or a missing value is drawn as something other than "No disponible".
it('shows each detail under its value and a missing value as "No disponible"', () => {
const s = snapshot();
const found = texts(definition(s)['content']);
expect(found).toContain(`Fecha: ${s.items.find(i => i['mastografia_fecha'])!['mastografia_fecha']}`);
expect(found).toContain('No disponible');
});
// Fails if the rows lose their alternating band, which keeps long rows readable across a page.
it('bands every other row and leaves the header row to its own style', () => {
const { layout } = definition()['content'].find((n: any) => n.table?.headerRows);
expect([layout.fillColor(0), layout.fillColor(1), layout.fillColor(2)]).toEqual([undefined, undefined, COLORS.band]);
});
// Fails if an empty query produces a table with only a header, which reads as a broken report.
it('says so when there are no rows', () => {
expect(texts(definition(snapshot(x => { x.items = []; }))['content'])).toContain('No hay registros para los filtros aplicados.');
});
// Fails if pdfmake, its fonts or the document definition no longer produce a real, multipage PDF. The logo is left
// out because the test browser (jsdom) has no `Worker`, which pdfmake needs to decode a PNG; the image path is
// checked in a real browser.
it('renders a multipage PDF file for a long list', async () => {
const many = snapshot(x => { x.items = Array.from({ length: 120 }, (_, i) => ({ ...x.items[i % x.items.length], id_seudonimo: `M-${String(i).padStart(4, '0')}` })); });
const blob = await buildTrackingPdf(many, NOW);
const bytes = new Uint8Array(await blob.arrayBuffer());
const text = new TextDecoder('latin1').decode(bytes);
expect(blob.type === 'application/pdf' || blob.type === '').toBe(true);
expect(text.startsWith('%PDF-')).toBe(true);
expect(text.trimEnd().endsWith('%%EOF')).toBe(true);
expect((text.match(/\/Type \/Page\b/g) ?? []).length).toBeGreaterThan(3);
}, 30000);
});
@@ -1,63 +0,0 @@
import { renderPdf, PdfDefinition } from './pdf-engine';
import { COLORS, institutionalDocument, loadLogo } from './pdf-template';
import { displayText, exportColumns } from './tracking-export-table';
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
export const TRACKING_TITLE = 'Cáncer de mama';
const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 };
const zebra = { ...rule, fillColor: (row: number) => (row === 0 ? undefined : row % 2 === 0 ? COLORS.band : undefined) };
/** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */
function parameters(snapshot: TrackingSnapshot) {
const rows: unknown[][] = [
...(snapshot.seleccion ? [['Selección del análisis', snapshot.seleccion]] : []),
['Fecha de corte', snapshot.corte],
['Ventana consultada', ventanaConsultada(snapshot)],
...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']),
['Registros', String(snapshot.items.length)],
];
return { table: { widths: [130, '*'], body: rows.map(([k, v]) => [{ text: k, bold: true }, v]) }, layout: rule };
}
/** The follow-up table: the columns the answer announced, each value with its labelled details under it. */
function dataTable(snapshot: TrackingSnapshot) {
const columns = exportColumns(snapshot);
const cell = (column: (typeof columns)[number], item: Record<string, string | number | null>) => {
const value = item[column.key];
const parts: unknown[] = [value === null || value === undefined ? { text: displayText(value), italics: true, color: COLORS.muted } : { text: String(value) }];
for (const detail of column.details) {
const v = item[detail.key];
if (v !== null && v !== undefined) parts.push({ text: `${detail.label}: ${v}`, style: 'small' });
}
return parts.length === 1 ? parts[0] : { stack: parts };
};
return {
table: {
headerRows: 1,
dontBreakRows: true,
widths: columns.map((_, i) => (i === 0 ? 62 : '*')),
body: [
columns.map(c => ({ text: c.label, style: 'th' })),
...snapshot.items.map(item => columns.map(c => cell(c, item))),
],
},
layout: zebra,
};
}
/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */
export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition {
return institutionalDocument({ title: TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
{ text: 'Resultados de seguimiento', style: 'h1' },
parameters(snapshot),
{ text: 'Pacientes', style: 'h2' },
snapshot.items.length ? dataTable(snapshot) : { text: 'No hay registros para los filtros aplicados.', style: 'muted' },
{ text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] },
]);
}
/** A PDF with the follow-up rows over several pages, repeating the header row. */
export async function buildTrackingPdf(snapshot: TrackingSnapshot, now = new Date(), logo?: string): Promise<Blob> {
return renderPdf(trackingDocument(snapshot, now, logo ?? await loadLogo()));
}
@@ -1,119 +0,0 @@
// Covers the spreadsheet of a follow-up export by reading the generated file back: its sheets, native filter, frozen
// header, the simulated-data notice, numbers, empty cells, neutralised text and the absence of author metadata.
// The reader is `fflate`, the zip library `write-excel-file` itself uses. Fixture: fixtures/cama_seguimiento.json.
import { strFromU8, unzipSync } from 'fflate';
import fixtureData from '../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { buildTrackingXlsx, columnLetter, DATA_SHEET, PARAMETERS_SHEET } from './tracking-xlsx';
import { TrackingSnapshot } from './tracking-export.models';
function snapshot(mutate: (s: TrackingSnapshot) => void = () => undefined): TrackingSnapshot {
const r = seguimientoTablaResponse(structuredClone(fixtureData));
const s: TrackingSnapshot = { corte: r.corte, ventana: r.ventana, filtros: { ...r.filtros, estatus: 'BENIGNO' }, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items };
mutate(s);
return s;
}
async function leer(s: TrackingSnapshot) {
const blob = await buildTrackingXlsx(s, new Date(Date.UTC(2026, 10, 12, 21, 30)));
const files = unzipSync(new Uint8Array(await blob.arrayBuffer()));
const text = (name: string) => strFromU8(files[name]);
return { files, text, sheet1: text('xl/worksheets/sheet1.xml'), sheet2: text('xl/worksheets/sheet2.xml'), workbook: text('xl/workbook.xml'), strings: text('xl/sharedStrings.xml') };
}
describe('Exportación: archivo XLSX', () => {
// Fails if the file stops being a spreadsheet of two sheets, the data first and the parameters second.
it('has the data sheet first and the parameters sheet second', async () => {
const { workbook } = await leer(snapshot());
expect(workbook.indexOf(`name="${DATA_SHEET}"`)).toBeGreaterThan(-1);
expect(workbook.indexOf(`name="${PARAMETERS_SHEET}"`)).toBeGreaterThan(workbook.indexOf(`name="${DATA_SHEET}"`));
});
// Fails if the native filter is lost or placed outside the header row and the rows .
it('adds a native filter over the header and every row, starting at the header row', async () => {
const s = snapshot();
const { sheet1, workbook } = await leer(s);
const last = columnLetter(9);
expect(sheet1).toContain(`<autoFilter ref="A1:${last}${s.items.length + 1}"/>`);
// The schema orders the filter after the data: a wrong order makes Excel repair the file.
expect(sheet1.indexOf('</sheetData>')).toBeLessThan(sheet1.indexOf('<autoFilter'));
expect(workbook).toContain(`_xlnm._FilterDatabase`);
expect(workbook).not.toContain('<definedNames/>');
});
// Fails if the header row stops being frozen, which hides the column names while scrolling.
it('freezes the header row', async () => {
const { sheet1 } = await leer(snapshot());
expect(sheet1).toContain('ySplit="1"');
expect(sheet1).toContain('state="frozen"');
});
// Fails if the file regains a note or banner row: the headers must be the first row of the data sheet.
it('starts the data sheet with the column headers and has no note anywhere', async () => {
const s = snapshot();
const { strings, sheet1 } = await leer(s);
const shared = [...strings.matchAll(/<si>(.*?)<\/si>/g)].map(m => m[1].replace(/<[^>]+>/g, ''));
expect(sheet1).toMatch(new RegExp('<row r="1"><c r="A1"[^>]*t="s"><v>' + shared.indexOf('Identificador seudónimo') + '</v>'));
expect(sheet1).not.toContain('<mergeCells');
expect(shared.filter(x => /^Nota$|Documento de consulta|expediente/i.test(x))).toEqual([]);
expect(shared).not.toContain('Tipo de datos');
expect((sheet1.match(/<row /g) ?? []).length).toBe(s.items.length + 1);
});
// Fails if the headers, the sheet of parameters or the filter labels lose what query the file answers.
it('records the cut-off, the window, the filters applied and the total in the parameters sheet', async () => {
const s = snapshot();
const { strings, sheet2 } = await leer(s);
for (const text of [s.corte, `${s.ventana.desde} al ${s.ventana.hasta}`, 'Estatus de seguimiento', 'Benigno, regresa a tamizaje', 'Todos', 'Cáncer de mama']) expect(strings).toContain(text);
expect(sheet2).toContain(`<v>${s.items.length}</v>`);
});
// Fails if the generation moment is written without the time zone it refers to.
it('writes the generation time in Mexico City time', async () => {
const { strings } = await leer(snapshot());
expect(strings).toContain('hora de la Ciudad de México');
// 21:30 UTC is 15:30 in Mexico City (UTC-6 in November).
expect(strings).toContain('3:30 p.m.');
});
// Fails if a number is stored as text, or if a missing value becomes a value of its own.
it('stores days as numbers and leaves missing values as empty cells', async () => {
const s = snapshot();
const { sheet1, strings } = await leer(s);
const days = s.items.filter(i => typeof i['dias_mastografia_diagnostico'] === 'number');
expect(days.length).toBeGreaterThan(0);
expect(sheet1).toMatch(new RegExp(`<c r="H\\d+"[^>]*><v>${days[0]['dias_mastografia_diagnostico']}</v></c>`));
expect(strings).not.toContain('No disponible');
});
// Fails if text that starts like a formula reaches the file as it is.
it('neutralises a value that starts like a formula', async () => {
const s = snapshot(x => { x.items[0] = { ...x.items[0], biopsia: '=HYPERLINK("http://example.test")' }; });
const { strings } = await leer(s);
expect(strings).toContain(`'=HYPERLINK`);
expect(strings).not.toMatch(/<t[^>]*>=HYPERLINK/);
});
// Fails if the library starts writing author or application properties, which would leak who made the file.
it('carries no document properties that identify an author', async () => {
const { files } = await leer(snapshot());
expect(Object.keys(files).filter(name => name.startsWith('docProps'))).toEqual([]);
});
// Fails if the sheet gains hidden sheets, external links or macros.
it('has no hidden sheets, external links or macros', async () => {
const { files, workbook } = await leer(snapshot());
expect(workbook).not.toContain('state="hidden"');
expect(Object.keys(files).filter(name => /externalLinks|vbaProject|activeX|embeddings/i.test(name))).toEqual([]);
});
// Fails if no rows turns into an invalid filter range or a failure instead of a file with headers.
it('produces a valid file when the query has no rows', async () => {
const { sheet1 } = await leer(snapshot(x => { x.items = []; }));
expect(sheet1).toContain('<autoFilter ref="A1:I1"/>');
});
// Fails if column letters beyond Z are wrong, which would put the filter on the wrong columns.
it('names columns past Z', () => {
expect([1, 26, 27, 52, 53].map(columnLetter)).toEqual(['A', 'Z', 'AA', 'AZ', 'BA']);
});
});
@@ -1,86 +0,0 @@
import type { Feature, SheetData } from 'write-excel-file/browser';
import { neutralizeFormula } from './cell-sanitizer';
import { flatTable } from './tracking-export-table';
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
export const DATA_SHEET = 'Seguimiento';
export const PARAMETERS_SHEET = 'Parámetros';
const INK = '#081839';
const ACCENT = '#a8c243';
const header = (value: string) => ({ value, fontWeight: 'bold' as const, textColor: INK, backgroundColor: ACCENT, wrap: true, alignVertical: 'center' as const });
/** Spreadsheet column letters: 1 is A, 27 is AA. */
export function columnLetter(n: number): string {
let letters = '';
for (; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + ((n - 1) % 26)) + letters;
return letters;
}
/** `write-excel-file` has no filter option: this extension adds the sheet's native filter over the header row. */
function nativeFilter(range: string): Feature<Blob | ArrayBuffer> {
const [first, last] = range.split(':').map(cell => cell.replace(/([A-Z]+)(\d+)/, '$$$1$$$2'));
return {
files: {
transform: {
'xl/worksheets/sheet{id}.xml': {
transform: (content, _options, { sheetIndex }) => sheetIndex === 0 ? content.replace('</sheetData>', `</sheetData><autoFilter ref="${range}"/>`) : content,
},
'xl/workbook.xml': {
transform: content => content.replace('<definedNames/>',
`<definedNames><definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'${DATA_SHEET}'!${first}:${last}</definedName></definedNames>`),
},
},
},
};
}
function generatedAt(now: Date): string {
return new Intl.DateTimeFormat('es-MX', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Mexico_City' }).format(now) + ' (hora de la Ciudad de México)';
}
/** The rows of the parameters sheet: what query this file answers and what its empty cells mean. */
export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData {
const row = (label: string, value: string | number) => [{ value: label, fontWeight: 'bold' as const }, typeof value === 'number' ? { value, type: Number } : { value: neutralizeFormula(value), type: String }];
const filters = snapshot.filtros_disponibles.map(f => {
const code = snapshot.filtros[f.clave];
return row(f.etiqueta, f.opciones.find(o => o.codigo === code)?.etiqueta ?? 'Todos');
});
return [
[header('Parámetro'), header('Valor')],
row('Reporte', 'Cáncer de mama'),
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
row('Fecha de corte', snapshot.corte),
row('Ventana consultada', ventanaConsultada(snapshot)),
...filters,
row('Total de registros', snapshot.items.length),
row('Generado', generatedAt(now)),
row('Celdas vacías', 'Indican dato no registrado, no ausencia clínica.'),
] as SheetData;
}
function width(label: string, values: readonly unknown[]): number {
const longest = values.reduce<number>((max, v) => Math.max(max, v === null || v === undefined ? 0 : String(v).length), Math.min(label.length, 28));
return Math.min(40, Math.max(12, longest + 2));
}
/** A spreadsheet with the follow-up rows (native filter, frozen header) and a sheet with the query's parameters. */
export async function buildTrackingXlsx(snapshot: TrackingSnapshot, now = new Date()): Promise<Blob> {
const { default: writeXlsxFile } = await import('write-excel-file/browser');
const { columns, rows } = flatTable(snapshot);
const data = [
columns.map(c => header(c.label)),
...rows.map(row => row.map((value, i) => {
if (value === null) return null;
return columns[i].numeric ? { value: value as number, type: Number } : { value: neutralizeFormula(String(value)), type: String };
})),
] as SheetData;
const range = `A1:${columnLetter(columns.length)}${rows.length + 1}`;
return writeXlsxFile([
{
sheet: DATA_SHEET, data, stickyRowsCount: 1,
columns: columns.map((c, i) => ({ width: width(c.label, rows.map(r => r[i])) })),
},
{ sheet: PARAMETERS_SHEET, data: parameterRows(snapshot, now), columns: [{ width: 26 }, { width: 90 }] },
], { features: [nativeFilter(range)] }).toBlob();
}
-54
View File
@@ -1,54 +0,0 @@
// 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;
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;
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 URL).
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();
}
@@ -1,85 +0,0 @@
{
"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"
}
]
}
}
}
]
}
@@ -1,127 +0,0 @@
{
"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
}
}
]
}
]
}
]
}
}
]
}
@@ -1,295 +0,0 @@
{
"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
}
]
}
]
}
]
}
]
}
}
]
}
@@ -1,155 +0,0 @@
{
"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"
}
]
}
}
}
]
}
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
// The card doesn't count its figures; the figures themselves show what is published.
expect(fixture.nativeElement.textContent).not.toContain('figuras publicadas');
// 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());
@@ -17,7 +17,8 @@ import { IndicadoresService } from './indicadores.service';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { vistaConfirmacion } from './indicadores-confirmacion-citologia';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama';
import { parTiempos } from './indicadores-tiempos-pareados';
@@ -35,7 +36,7 @@ import { parConteos } from './indicadores-conteos-pareados';
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</div>
</header>
@if (!sobrio) {
@if (!sobrio && fijable) {
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
(click)="pinChanged.emit()">
@@ -43,7 +44,6 @@ import { parConteos } from './indicadores-conteos-pareados';
</button>
}
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
@if (isEu7) {
<div #visibilityRegion class="eu7-region">
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
@@ -111,8 +111,6 @@ import { parConteos } from './indicadores-conteos-pareados';
.pin-toggle mat-icon { flex-shrink: 0; }
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
mat-form-field { width: 100%; margin-top: var(--issste-space-4); }
.catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4);
border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
@media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } }
`,
})
@@ -136,14 +134,16 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
get sobrio() { return this.dominio === 'cama'; }
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
get isEu7() { return !!vistaEscenario(this.dominio, this.indicador); }
// CaMa's histopathology has its own view (isHistopatologia); the confirmation view is CaCu's cytology.
get isConfirmacion() { return !this.isHistopatologia && !!vistaConfirmacion(this.dominio, this.indicador); }
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
// Connected time pairs replace the diagnosis card with one coordinated box plot.
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
// Exams and patients of the same finding, drawn together on the exams' card.
get conteos() { return parConteos(this.dominio, this.indicador.id); }
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
private updateNumeric() {
@@ -168,6 +168,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
@Input({ required: true }) applied!: GlobalApplied;
@Input() independentPeriods = false;
@Input() pinned = false;
// Pinning reorders a long grid; with a few cards there is nothing to bring forward.
@Input() fijable = true;
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
readonly pinChanged = output<void>();
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
@@ -1,5 +1,4 @@
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<section class="confirmacion" [attr.aria-label]="'Confirmación histopatológica, ' + vista.textos.filas.toLowerCase()">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
@@ -16,7 +15,7 @@
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@@ -30,9 +29,13 @@
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
@if (status() === 'empty') { <p role="status">{{ vista.textos.vacio }}</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
@if (!vista.botones) {
<p class="hint">Haz clic en un anillo de la dona para elegir un grupo o un resultado; el centro regresa un paso, hasta el total.</p>
}
<!-- Without visible buttons they stay for the keyboard, shown while one has the focus. -->
<div class="legend" [class.solo-teclado]="!vista.botones" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
@@ -46,9 +49,9 @@
</div>
</div>
<div class="figures">
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
<section class="figure rates"><h3>{{ vista.textos.filas }}, {{ m.periodo }}</h3>
@if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + m.periodo + ', ' + selectionLabel" />
<app-plotly-chart [figure]="ratesFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, tasas ' + vista.textos.filas.toLowerCase() + ', ' + m.periodo + ', ' + selectionLabel" />
}
<ul class="rate-states">
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
@@ -56,16 +59,16 @@
</section>
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
<app-plotly-chart [figure]="donutFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin ' + vista.textos.sujetos + ' con biopsia en el periodo.' }}</p> }
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de contingencia de citología y biopsia" tabindex="0">
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de contingencia, ' + indicador.titulo" tabindex="0">
<table><caption>Tabla de contingencia de {{ vista.textos.sujetos }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">{{ vista.textos.encabezado }}</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
<tbody>@for (fila of m.filas; track fila.id) {
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
}</tbody>
@@ -7,8 +7,12 @@ p, h3, summary { overflow-wrap: anywhere; }
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; }
.hint { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.legend.solo-teclado:not(:focus-within) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
// The donut is the control: its slices and centre answer to the pointer.
.donut app-plotly-chart { cursor: pointer; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
border-radius: var(--issste-radius); color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
button:disabled { opacity: .5; cursor: default; }
@@ -5,15 +5,12 @@ 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 { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas,
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
Celda, tasas } from './indicadores-confirmacion-citologia';
// Figures of the kit whose "Cómo leer" describes this coordinated view.
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
Celda, Tasa, tasas, vistaConfirmacion } from './indicadores-confirmacion-citologia';
@Component({
selector: 'app-indicador-confirmacion-citologia',
@@ -45,17 +42,20 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
private loaded = false;
private pages: ModeloConfirmacion[] = [];
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === (this.vista.botones ? this.model.base : undefined); }
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
readonly estadoTasa = estadoTasa;
// CaCu's words when the catalog doesn't name this indicator, so the messages still read.
get vista() { return vistaConfirmacion(this.dominio, this.indicador) ?? CONFIRMACION_CACU; }
estadoTasa(t: Tasa) { return estadoTasa(t, this.vista.textos.sujetos); }
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
get readingGuide() {
const details = this.metadata?.figuras_detalle ?? [];
return FIGURAS.flatMap(([figura, nombre]) => {
// Figures of the kit whose "Cómo leer" describes this coordinated view.
const figuras = [['fig_c2_donas', 'Dona de resultados de biopsia'], ['fig_c2_barras', 'Tasas ' + this.vista.textos.filas.toLowerCase()]] as const;
return figuras.flatMap(([figura, nombre]) => {
const detail = details.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
@@ -65,7 +65,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: this.vista.estrato })
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
@@ -84,7 +84,8 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
const vista = vistaConfirmacion(this.dominio, this.indicador);
if (!vista || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return;
}
@@ -92,12 +93,12 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
{ estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({
{ estrato: vista.estrato }).pipe(timeout({ first: 40000 })).subscribe({
next: datos => {
if (key !== this.key) return;
try {
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods, vista);
this.pages = this.periods.map(p => modeloConfirmacion(datos, p, vista));
// The most recent period first, as the prototype; navigation goes back.
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
} catch (error) { this.failure(error); }
@@ -115,7 +116,8 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
}
private activatePeriod() {
this.model = this.pages[this.periodIndex];
this.selection = this.model ? seleccionBase(this.model) : undefined;
// With buttons the view opens on the base group; without, on the total, as CaCu's interactive donut.
this.selection = this.model ? (this.vista.botones ? seleccionBase(this.model) : {}) : undefined;
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
}
changePeriod(step: number) {
@@ -124,7 +126,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
}
select(trace: string, index = 0) {
if (!this.model || !this.selection || this.status() !== 'ready') return;
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
this.selection = (this.vista.botones ? clicConfirmacion : clicDona)(this.model, this.selection, trace, index); this.draw();
}
plotClicked(event: unknown) {
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
@@ -132,7 +134,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
}
private draw() {
if (!this.model || !this.selection) return;
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
this.donutFigure = (this.vista.botones ? donaConfirmacion : donaExpandible)(this.model, this.selection, this.tema);
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
this.changeDetector.markForCheck();
}
@@ -38,10 +38,6 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
private subscription?: Subscription;
private key = '';
private loaded = false;
// On a narrow screen the donut's long label gives way to a legend under it.
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
@@ -111,9 +107,9 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
this.donutFigure = donaConteos(m, this.par, this.tema);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -1,5 +1,4 @@
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
@@ -16,24 +15,24 @@
}
@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 resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de dona y barras EU7">
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<nav class="periods" [attr.aria-label]="'Periodos de dona y barras, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
<div class="legend" role="group" [attr.aria-label]="'Explorar grupos y categorías, ' + indicador.titulo">
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección">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.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
@@ -48,27 +47,27 @@
<div class="figures">
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
@if (m.total !== null && m.total > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="indicador.titulo + ', dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
<p>{{ sinDatoNote }}</p>
</section>
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
<section class="figure"><h3>{{ selectionLabel }} por {{ etiquetaEstrato }}, {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada {{ etiquetaEstrato }}; excluye «{{ m.sinDatoEtiqueta }}».</p>
@if (m.escenarios.length && barsFigure) {
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="indicador.titulo + ', barras por ' + etiquetaEstrato + ', ' + m.periodo + ', ' + selectionLabel" />
}
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>Datos generales, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
</table>
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
<table><caption>Por {{ etiquetaEstrato }}, {{ m.periodo }}, porcentajes sin «{{ m.sinDatoEtiqueta }}»</caption>
<thead><tr><th scope="col">{{ etiquetaEstrato.charAt(0).toUpperCase() + etiquetaEstrato.slice(1) }}</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
</table>
</div>
@@ -8,7 +8,7 @@ p, h3, summary { overflow-wrap: anywhere; }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
border-radius: var(--issste-radius); color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
button:disabled { opacity: .5; cursor: default; }
@@ -126,7 +126,7 @@ describe('EU7 integración Angular y caché compartida', () => {
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
expect(f.nativeElement.textContent).not.toContain('987654');
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores, Distribución de resultados citológicos"]').tabIndex).toBe(0);
});
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
@@ -4,16 +4,14 @@ import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
import { barras, Celda, clic, dona, esEu7, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta, vistaEscenario } from './indicadores-eu7-escenario';
@Component({
selector: 'app-indicador-eu7-escenario',
@@ -44,13 +42,16 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private key = '';
private loaded = false;
private pages: Modelo[] = [];
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
get sinDatoNote() {
const m = this.model;
if (!m) return '';
if (m.vacio) return 'No hay registros publicados en este periodo.';
const n = m.sinDato.n;
if (this.vista && !esEu7(this.vista)) return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: `Fuera de la dona: ${n} pacientes con «${m.sinDatoEtiqueta}»${m.total === null ? '' : ` de ${m.total + n}`}.`;
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
@@ -69,7 +70,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
get readingGuide() {
const details = this.metadata?.figuras_detalle ?? [];
return EU7_FIGURES.flatMap(([figura, nombre]) => {
const figuras = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por ' + this.etiquetaEstrato]] as const;
return figuras.flatMap(([figura, nombre]) => {
const detail = details.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
@@ -99,10 +101,11 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
const vista = this.vista;
if (!vista || this.indicador.contrato !== 'C2'
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|| !stratifiedCapabilities(this.indicador).includes(vista.estrato) || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return;
}
const key = this.key;
@@ -110,13 +113,13 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
this.status.set('loading');
this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: vista.estrato }),
]).pipe(timeout({ first: 40000 })).subscribe({
next: ([general, escenarios]) => {
if (key !== this.key) return;
try {
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
this.pages = this.periods.map(p => modelo(general, escenarios, p));
this.pages = this.periods.map(p => modelo(general, escenarios, p, vista.estrato));
this.periodIndex = 0; this.activatePeriod();
} catch (error) { this.failure(error); }
},
@@ -151,7 +154,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private draw() {
if (!this.model) return;
this.donutFigure = dona(this.model, this.selection, this.tema);
this.barsFigure = barras(this.model, this.selection, this.tema);
this.barsFigure = barras(this.model, this.selection, this.tema, `% de pacientes de cada ${this.etiquetaEstrato}`);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
@@ -120,7 +120,7 @@
.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; }
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); font: inherit; cursor: pointer; }
.highlight-legend button:disabled { opacity: .45; cursor: default; }
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
@@ -15,8 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots';
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
import { MatTooltipModule } from '@angular/material/tooltip';
@@ -49,10 +48,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> }
}
@@ -71,8 +76,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@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> }
@@ -105,7 +110,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
.distribution-dimensions { margin-top: .75rem; }
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); color: var(--issste-text);
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
@@ -165,6 +170,18 @@ 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;
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.' }); }
}
}
cells: StratifiedCell[] = [];
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
@@ -184,7 +201,7 @@ export class IndicadorFigurePanel implements OnChanges {
}
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);
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida);
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 }),
@@ -259,15 +276,6 @@ export class IndicadorFigurePanel implements OnChanges {
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.
@@ -13,13 +13,14 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
}
@if (temporalReference) { <p>{{ temporalReference }}</p> }
<!-- A card with its value shows nothing more; «Disponible» stays only for screen readers. -->
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</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; min-width: 0; }
mat-card { box-sizing: border-box; flex: 1 1 auto; padding: var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); box-shadow: none; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
@@ -5,7 +5,9 @@ import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { CACU_RESULTADO_KPI, CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN as KPI_BASE } from './indicadores-kpi';
// CaMa's cards are its opportunity strip: the catalog here publishes all four, so none is pending.
const KPI_BY_DOMAIN = { ...KPI_BASE, cama: CAMA_OPORTUNIDAD_KPIS };
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorDatos, Dominio } from './indicadores.models';
import { IndicadoresMemory } from './indicadores-memory';
@@ -52,6 +54,18 @@ describe('KPI integración con autoridad global', () => {
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
}
// Answers every card by its URL until none is waiting: a domain with more cards than the concurrent
// requests gets them in batches.
function flushAll(domain: Dominio, extra: Partial<IndicadorDatos> = {}) {
for (let reqs = requests(); reqs.length; reqs = requests()) {
// A flushed answer can cancel its siblings (a new anchor period); those are not answered.
for (const r of reqs.filter(r => !r.cancelled)) {
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.includes('/' + d.id + '/'));
r.flush({ ...response(index, domain, r.request.params.get('periodos') ?? '2025-S1'), ...extra });
}
fixture.detectChanges();
}
}
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
fixture.componentInstance.applyFilters(); fixture.detectChanges();
@@ -71,8 +85,8 @@ describe('KPI integración con autoridad global', () => {
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
expect(panels()[3].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
expect(panels()[4].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.');
expect(panels()[3].result().info).toBe('2 de 5 pacientes con TEA positivo tienen un EEG ligado.');
expect(panels()[4].result().info).toBe('2 de 5 pacientes con TEA positivo no tienen ningún EEG ligado.');
});
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
@@ -104,8 +118,9 @@ describe('KPI integración con autoridad global', () => {
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama')));
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); expect(requests().every(r => r.request.url.startsWith('/cama/'))).toBe(true); flushAll('cama');
// CaMa's last cards start after its first batch and are cancelled by the change of domain.
load('cacu'); const restored = requests().filter(r => !r.cancelled); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
});
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
@@ -178,22 +193,21 @@ describe('KPI integración con autoridad global', () => {
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
for (const domain of ['cacu', 'cama'] as const) {
load(domain);
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
fixture.detectChanges();
flushAll(domain, { notas: ['Nota del pie de la figura.'] });
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7', '7']);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined]
: ['pacientes', '%', 'días (mediana)', 'días (mediana)']);
// «Disponible» stays for screen readers, visually hidden; any other state is the visible message.
expect(cards.map(card => card.querySelector('.kpi-state:not(.visually-hidden)')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'),
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
]));
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
// CaCu and CaMa cards say only their own line; the kit notes are the figure footer.
expect(fixture.nativeElement.textContent).not.toContain('Nota del pie de la figura.');
}
});
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
@@ -213,7 +227,7 @@ describe('KPI integración con autoridad global', () => {
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
for (const domain of ['cacu', 'cama'] as const) {
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges();
flushAll(domain);
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
}
load('cacu', false, ['2025-S1'], true);
@@ -225,7 +239,7 @@ describe('KPI integración con autoridad global', () => {
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
const old = requests(); expect(old).toHaveLength(1);
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
requests().forEach((r, i) => r.flush(response(i, 'cama')));
flushAll('cama');
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
resumed[0].flush(response(0)); fixture.detectChanges();
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
@@ -19,15 +19,12 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true" />
@if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`,
styles: `
:host { display: block; min-width: 0; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
`,
// The card fills the panel, so cards in one grid row are as tall as the row.
styles: ':host { display: flex; flex-direction: column; min-width: 0; } app-indicador-kpi-card { flex: 1 1 auto; }',
})
export class IndicadorKpiPanel implements OnChanges {
@Input({ required: true }) dominio!: Dominio;
@@ -1,35 +0,0 @@
import { Component, inject, Input, OnChanges, signal } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, PlotlyFigure } from './indicadores.models';
import { proportionFigure } from './measure-report';
import { MeasureReportService } from './measure-report.service';
/** A proportion drawn from the WebApi's FHIR `MeasureReport`s: the data comes as the standard, the figure is ours. */
@Component({
selector: 'app-indicador-measure-report',
imports: [MatProgressBarModule, PlotlyChart],
template: `
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicador" /> }
@if (status() === 'error') { <p role="alert">No se pudo cargar el indicador.</p> }
@if (figure(); as figure) { <app-plotly-chart [figure]="figure" [label]="titulo" /> }
`,
})
export class IndicadorMeasureReport implements OnChanges {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) indicador!: string;
@Input({ required: true }) titulo!: string;
@Input({ required: true }) periodos!: string[];
@Input() estrato?: string;
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly figure = signal<PlotlyFigure | undefined>(undefined);
private readonly service = inject(MeasureReportService);
ngOnChanges() {
this.status.set('loading');
this.service.series(this.dominio, this.indicador, this.periodos).subscribe({
next: series => { this.figure.set(proportionFigure(series, this.titulo, this.estrato)); this.status.set('ready'); },
error: () => { this.figure.set(undefined); this.status.set('error'); },
});
}
}
@@ -19,6 +19,7 @@
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
</div>
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
@if (availability) {
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
@else if (availability.status === 'error') {
@@ -64,9 +65,11 @@
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
}
</mat-select>
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
</mat-form-field>
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
</div>
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
@if (availability) {
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
@else if (availability.status === 'error') {
@@ -93,11 +96,6 @@
</div>
}
@if (error) { <p class="error" role="alert">{{ error }}</p> }
<p class="draft-summary">Selección en edición: {{ summary }}</p>
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
</section>
}
@@ -8,15 +8,14 @@
:host(.compacto) .apply-button { min-height: 40px; }
:host(.compacto) .period-builder button { min-height: 40px; }
section { min-width: 0; }
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
.period-builder mat-form-field { flex: 0 1 10rem; }
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; }
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; }
.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
.draft-summary { font-weight: 500; }
.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); }
.fields { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); }
mat-form-field { flex: 0 1 14rem; min-width: 0; }
.period-builder mat-form-field { flex: 0 1 9rem; }
.period-builder button { min-height: 40px; }
p { overflow-wrap: anywhere; line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.4; }
.filter-help, .applied-summary { color: var(--issste-text-secondary); }
.pending { color: var(--issste-text); font: var(--mat-sys-body-small); border-left: 3px solid var(--issste-accent); padding-left: var(--issste-space-2); }
.error { color: var(--mat-sys-error); }
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
.remove button { min-height: 44px; }
@@ -25,6 +24,5 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
.fields.compact mat-form-field { flex: 0 1 14rem; }
.fields.compact .apply-button { margin-top: 0; }
@media (max-width: 550px) {
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
.period-builder button { margin-top: 0; }
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; }
}
@@ -22,13 +22,6 @@ describe('UX-04 control asistido', () => {
return fixture.debugElement.queryAll(By.css('mat-form-field'))
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
}
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
control.year = '2025'; control.unit = 'S1'; control.add();
control.unit = 'S2'; control.add();
expect(control.selectedPeriods).toEqual(['2025-S2']);
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
});
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: {
@@ -1,40 +1,129 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { AnalisisAgregado } from './indicadores-analisis.service';
import { etiquetaBirads } from './etiquetas-cohorte';
import { c2Theme } from './indicadores-c2-palette';
import { AnalisisResultados, AnalisisSubgrupos } from './indicadores-analisis.service';
export { etiquetaBirads };
const DIAS_POR_MES = 30.4375;
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const miles = (v: number) => v.toLocaleString('es-MX');
/** The code of the published bar that was clicked, from its `customdata`; a suppressed bar or an empty click gives nothing. */
export function grupoDelClic(evento: unknown, agregado: AnalisisAgregado | undefined): string | undefined {
const punto = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0];
const codigo = punto?.customdata;
return typeof codigo === 'string' && agregado?.grupos.some(g => g.codigo === codigo && !g.suprimido) ? codigo : undefined;
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
function transparente(hex: string, alfa: number) {
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
return m ? `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alfa})` : hex;
}
// What the stage measures: the cumulative incidence of its event, or the survival (alive at t).
export const nombreMedida = (medida: 'incidencia' | 'supervivencia') => medida === 'supervivencia' ? 'Supervivencia' : 'Incidencia acumulada';
/**
* Patients per BI-RADS category. A suppressed category is drawn as an empty grey bar that says it is not published,
* never as a zero; each bar carries its code, so a click can only change the filters of the list, never read rows.
* The stage's measure per published group (cumulative incidence, or survival in the survival stage): a step line with its 95 % band. The curve ends where the
* answer suppressed it (fewer at risk than the threshold); each line carries its group in `meta`, so a click
* can only change the filters, never read rows.
*/
export function gruposFigura(d: AnalisisAgregado, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), s = C2_PALETTE.states;
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
const data: Record<string, unknown>[] = [];
const supervivencia = r.medida === 'supervivencia';
let maximo = 1, minimo = 100;
for (const g of r.grupos.filter(x => !x.suprimido)) {
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
if (!puntos.length) continue;
const x = puntos.map(c => +(c.t / DIAS_POR_MES).toFixed(2));
maximo = Math.max(maximo, ...puntos.map(c => c.ic_alto!)); minimo = Math.min(minimo, ...puntos.map(c => c.ic_bajo!));
const comun = { type: 'scatter', mode: 'lines', x, legendgroup: g.grupo, line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false };
data.push({ ...comun, y: puntos.map(c => c.ic_bajo) });
data.push({ ...comun, y: puntos.map(c => c.ic_alto), fill: 'tonexty', fillcolor: transparente(g.color, tema === 'oscuro' ? .28 : .16) });
data.push({
type: 'scatter', mode: 'lines', x, y: puntos.map(c => c.valor), name: `${escapar(g.etiqueta)} (n = ${miles(g.n!)}, ${miles(g.eventos!)} eventos)`,
legendgroup: g.grupo, meta: g.grupo, line: { shape: 'hv', width: 2.5, color: g.color },
customdata: puntos.map(c => [pct(c.valor!), pct(c.ic_bajo!), pct(c.ic_alto!), miles(c.n_riesgo!), miles(c.n_eventos!)]),
hovertemplate: `<b>${escapar(g.etiqueta)}</b><br>Mes %{x:.1f}: %{customdata[0]} % (IC 95 %: %{customdata[1]} a %{customdata[2]})<br>En riesgo: %{customdata[3]} · eventos acumulados: %{customdata[4]}<extra></extra>`,
});
}
return {
data: [{
type: 'bar', x: d.grupos.map(g => etiquetaBirads(g.codigo)), y: d.grupos.map(g => g.suprimido ? 0 : g.n),
customdata: d.grupos.map(g => g.codigo),
marker: { color: d.grupos.map(g => g.suprimido ? s.noData : C2_PALETTE.series[0]) },
text: d.grupos.map(g => g.suprimido ? 'No publicado' : miles(g.n!)), textposition: 'outside', cliponaxis: false,
hovertemplate: d.grupos.map(g => g.suprimido
? `<b>${etiquetaBirads(g.codigo)}</b><br>Menos de ${d.umbral_supresion} pacientes: no se publica<extra></extra>`
: `<b>${etiquetaBirads(g.codigo)}</b><br>${miles(g.n!)} pacientes<extra></extra>`),
}],
data,
layout: {
autosize: true, height: 360, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 32, l: 56, r: 16, b: 56 }, showlegend: false,
xaxis: { title: { text: 'Categoría BI-RADS' }, fixedrange: true, automargin: true },
yaxis: { title: { text: 'Pacientes' }, gridcolor: p.grid, zeroline: false, fixedrange: true, rangemode: 'tozero' },
autosize: true, height: 460, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 64, r: 16, b: 96 }, hovermode: 'closest',
legend: { orientation: 'h', y: -0.22, itemclick: false, itemdoubleclick: false },
xaxis: { title: { text: 'Meses desde el origen' }, range: [0, meses], dtick: 6, gridcolor: p.grid, zeroline: false, fixedrange: true },
yaxis: { title: { text: nombreMedida(r.medida) + ' (%)' }, range: supervivencia ? [Math.max(0, minimo - 10), 100] : [0, Math.min(100, maximo * 1.1)],
gridcolor: p.grid, zeroline: false, fixedrange: true, ticksuffix: ' %' },
},
config: { displayModeBar: false },
};
}
/** Hazard ratio of each group against the reference, on a log axis; an open marker flags a failed proportional-hazards check. */
export function forestFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), e = r.efectos;
if (e.estado !== 'listo' || !e.filas.length) return { data: [], layout: {} };
const etiquetas = [`${escapar(e.etiqueta_referencia ?? e.referencia ?? '')} (referencia)`, ...e.filas.map(f => escapar(f.etiqueta))];
const falla = (ph: number | null) => ph !== null && ph < .05;
const minimo = Math.min(1, ...e.filas.map(f => f.ic_bajo)), maximo = Math.max(1, ...e.filas.map(f => f.ic_alto));
return {
data: [
{ type: 'scatter', mode: 'markers', x: [1], y: [etiquetas[0]], marker: { symbol: 'diamond', size: 10, color: p.outline }, hoverinfo: 'skip', showlegend: false },
{
type: 'scatter', mode: 'markers', x: e.filas.map(f => f.hr), y: etiquetas.slice(1), showlegend: false,
error_x: { type: 'data', symmetric: false, array: e.filas.map(f => f.ic_alto - f.hr), arrayminus: e.filas.map(f => f.hr - f.ic_bajo), color: p.text, thickness: 1.5, width: 6 },
marker: { size: 11, color: e.filas.map(f => falla(f.ph_p) ? p.background : p.text), line: { color: p.text, width: 2 }, symbol: 'square' },
customdata: e.filas.map(f => [f.ic_bajo.toLocaleString('es-MX'), f.ic_alto.toLocaleString('es-MX'), miles(f.n_eventos), falla(f.ph_p) ? '<br>Riesgos no proporcionales: el HR promedia un efecto que cambia.' : '']),
hovertemplate: '%{y}<br>HR %{x:.2f} (IC 95 %: %{customdata[0]} a %{customdata[1]})<br>%{customdata[2]} eventos%{customdata[3]}<extra></extra>',
},
],
layout: {
autosize: true, height: Math.max(220, 70 + 44 * etiquetas.length), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 16, r: 24, b: 56 },
xaxis: { type: 'log', title: { text: 'Razón de riesgos (HR), escala logarítmica' }, range: [Math.log10(minimo * .7), Math.log10(maximo * 1.4)], gridcolor: p.grid, zeroline: false, fixedrange: true },
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
shapes: [{ type: 'line', xref: 'x', yref: 'paper', x0: 1, x1: 1, y0: 0, y1: 1, line: { color: p.outline, dash: 'dot', width: 1.5 } }],
},
config: { displayModeBar: false },
};
}
/**
* The stage's measure at the horizon by its two variables (rows and columns). A suppressed cell is drawn grey with its
* reason, never as a colour; each cell carries its pair of codes, so a click only changes the filters.
*/
export function subgruposFigura(s: AnalisisSubgrupos, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), horizonte = Math.round(s.horizonte_dias / DIAS_POR_MES);
const celda = (f: string, c: string) => s.celdas.find(x => x.fila === f && x.columna === c);
const z = s.filas.map(f => s.columnas.map(c => { const x = celda(f.codigo, c.codigo); return x && !x.suprimido ? x.valor : null; }));
const texto = s.filas.map(f => s.columnas.map(c => {
const x = celda(f.codigo, c.codigo);
if (!x || x.suprimido) return '<span style="opacity:.75">Suprimido</span>';
const meses = Math.round(x.t_dias! / DIAS_POR_MES);
return `<b>${pct(x.valor!)} %</b><br>${miles(x.eventos!)} de ${miles(x.n!)}${meses < horizonte ? `<br>a ${meses} meses` : ''}`;
}));
const ayuda = s.filas.map(f => s.columnas.map(c => {
const x = celda(f.codigo, c.codigo);
if (!x || x.suprimido) return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}: suprimido (${(x?.motivo ?? 'sin datos').toLowerCase()})`;
return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}<br>${pct(x.valor!)} % (IC 95 %: ${pct(x.ic_bajo!)} a ${pct(x.ic_alto!)})<br>${miles(x.eventos!)} eventos en ${miles(x.n!)} pacientes`;
}));
const maximo = Math.max(1, ...z.flat().filter((v): v is number => v !== null));
return {
data: [
// The grey layer under the colour: the cells the answer suppressed.
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z: z.map(r => r.map(v => v === null ? 1 : null)),
colorscale: [[0, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9'], [1, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9']], showscale: false, hoverinfo: 'skip', xgap: 3, ygap: 3 },
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z, zmin: 0, zmax: maximo, xgap: 3, ygap: 3,
customdata: s.filas.map(f => s.columnas.map(c => [f.codigo, c.codigo])), text: ayuda, hovertemplate: '%{text}<extra></extra>',
colorscale: [[0, tema === 'oscuro' ? '#1B3A5B' : '#EAF1F8'], [1, tema === 'oscuro' ? '#9DBFE3' : '#1F5F8B']],
colorbar: { title: { text: nombreMedida(s.medida) + ' (%)' }, ticksuffix: ' %', thickness: 12 } },
],
layout: {
autosize: true, height: 80 + 64 * s.filas.length, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 16, r: 16, b: 56 },
xaxis: { title: { text: escapar(s.dimension_columnas.etiqueta) }, side: 'bottom', fixedrange: true, automargin: true },
yaxis: { title: { text: escapar(s.dimension_filas.etiqueta) }, autorange: 'reversed', fixedrange: true, automargin: true },
annotations: s.filas.flatMap((f, i) => s.columnas.map((c, j) => {
const v = z[i][j];
return { x: c.etiqueta, y: f.etiqueta, xref: 'x', yref: 'y', showarrow: false, text: texto[i][j], font: { size: 12, color: v !== null && v > maximo * .55 ? '#FFFFFF' : p.text } };
})),
},
config: { displayModeBar: false },
};
}
export const mesesDe = (dias: number) => Math.round(dias / DIAS_POR_MES);
@@ -1,30 +1,91 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { Dominio, requireDominio } from './indicadores.models';
// The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many
// patients of the cohort fall in each BI-RADS category at a cut-off (`GET /<dominio>/analisis/indicadores?corte=`).
// It is a descriptive count, not an incidence or a survival estimate, and it never carries patient rows. The answer
// names the cohort, the scenario and a `revision` of the cohort that the patients' list must quote back: a list asked
// for with another revision is refused, so a group opened from this count is always the group that was counted.
export interface GrupoAnalisis { codigo: string; n: number | null; suprimido: boolean; }
export interface AnalisisAgregado {
simulado: true; cohorte: string; revision: string; escenario: string; corte: string; umbral_supresion: number;
unidad: string; denominador: string; grupos: GrupoAnalisis[];
// Exploratory outcomes of a domain's cohort: what can be asked (`/analisis`) and its aggregate answer
// (`/analisis/resultados`). The answer is curves (C9b), tests, effects (C12) and checks (C13), never patient rows.
// The analysis goes by stages (development, recurrence, survival). Each stage has its scenarios, its estimators
// and the two variables it is stratified and filtered by; each variable says its NOM numeral and whether the schema
// records it or the answer assumes it.
export interface AnalisisOpcion { clave: string; etiqueta: string; }
// `filtro_seguimiento`: the follow-up list's filters that list this scenario's population.
export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; etapa: string; filtro_seguimiento: Record<string, string>; }
export interface AnalisisEstimador extends AnalisisOpcion { nota: string; }
export type EstadoVariable = 'registrado' | 'supuesto';
export interface AnalisisVariable extends AnalisisOpcion { nom: string; estado: EstadoVariable; fuente: string; opciones: { codigo: string; etiqueta: string }[]; }
export interface AnalisisEtapa extends AnalisisOpcion {
pregunta: string; escenarios: string[]; estimadores: string[]; medida: 'incidencia' | 'supervivencia';
// The variables the stage can be compared by: one at a time in the curves, two at a time in the grid.
variables: string[]; evento_supuesto: string | null;
// Every variable the NOM asks for at this stage, and whether the schema has it.
requeridas: { variable: string; nom: string; estado: string }[];
}
/** What a patients' list must quote back to open a group of the aggregate. */
export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; }
export interface AnalisisBloqueado { clave: string; titulo: string; motivo: string; }
export interface AnalisisCatalogo {
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
etapas: AnalisisEtapa[]; escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[];
variables: AnalisisVariable[]; bloqueados: AnalisisBloqueado[];
}
// `grupos`: the values of the variable to compare, two or more; empty compares them all.
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; grupos: string[]; filtros: Record<string, string>; }
export interface PedidoSubgrupos { escenario: string; estimador: string; filas: string; columnas: string; }
// The log-rank of one variable of the grid, plain and at equal value of the other one.
export interface PruebaCruzada {
variable: string; etiqueta: string; estratificada_por: string; etiqueta_estrato: string;
logrank: { chi2: number; gl: number; p: number; grupos: number } | null; estratificado: { chi2: number; gl: number; p: number; grupos: number } | null;
}
// One epidemiological figure of the cohort at the horizon (incidence, recurrence, adherence or survival).
export interface IndicadorEpidemiologico {
clave: string; titulo: string; etapa: string; unidad: string; descripcion: string; supuesto: string | null; suprimido: boolean;
n: number | null; eventos: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; t_dias: number | null;
}
export interface AnalisisIndicadores { simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; indicadores: IndicadorEpidemiologico[]; }
/** Today as the date input writes it, in the user's own calendar day. */
export function hoyIso(ahora = new Date()) {
const dos = (n: number) => String(n).padStart(2, '0');
return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`;
export interface GrupoAnalisis { grupo: string; etiqueta: string; color: string; suprimido: boolean; motivo: string | null; n: number | null; eventos: number | null; competitivos: number | null; }
// C9b: one row per group and event time; a suppressed row ends the published curve.
export interface PuntoCurva { grupo: string; t: number; estimador: 'KM' | 'CIF'; valor: number | null; ic_bajo: number | null; ic_alto: number | null; n_riesgo: number | null; n_eventos: number | null; suprimido: 0 | 1; }
// C12
export interface FilaEfecto { termino: string; etiqueta: string; hr: number; ic_bajo: number; ic_alto: number; n_eventos: number; metodo: 'cox' | 'bayes'; ph_p: number | null; }
export interface Efectos { estado: 'listo' | 'insuficiente' | 'no_aplica'; motivo: string | null; metodo: string; referencia: string | null; etiqueta_referencia?: string; filas: FilaEfecto[]; }
// C13
export interface FilaValidacion { chequeo: string; escopo: string; estadistico: number | null; p: number | null; umbral: number | null; aprobado: boolean | null; nota: string | null; version_modelo: string; sql_sha: string | null; }
export interface AnalisisResultados {
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
etapa: string; medida: 'incidencia' | 'supervivencia';
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; grupos_elegidos: string[] | null;
// What of this answer rests on data the schema does not record.
supuestos: string[];
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
tabla_riesgo: { cortes_dias: number[]; filas: { grupo: string; cortes: (number | null)[] }[] };
pruebas: {
logrank: { chi2: number; gl: number; p: number } | null;
pares: { a: string; b: string; p: number; p_holm: number }[];
rmst: { grupo: string; rmst: number; dif: number | null; ic_bajo: number | null; ic_alto: number | null }[];
rmst_referencia?: string; nota: string | null;
};
efectos: Efectos; validacion: FilaValidacion[]; avisos: string[];
}
// The BI-RADS by age-group grid: the incidence at the horizon in each cell, or the reason it is suppressed.
export interface CeldaSubgrupo {
fila: string; columna: string; suprimido: boolean; motivo: string | null;
n: number | null; eventos: number | null; t_dias: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
}
export interface AnalisisSubgrupos {
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; escenario: string; estimador: string;
etapa: string; medida: 'incidencia' | 'supervivencia'; supuestos: string[];
dimension_filas: AnalisisOpcion; dimension_columnas: AnalisisOpcion; pruebas: PruebaCruzada[];
filas: { codigo: string; etiqueta: string }[]; columnas: { codigo: string; etiqueta: string }[]; celdas: CeldaSubgrupo[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
const numONulo = (v: unknown) => v === null || num(v);
const lista = (v: unknown, f: (x: unknown) => boolean) => Array.isArray(v) && v.every(f);
const opcion = (v: unknown) => record(v) && text(v['clave']) && text(v['etiqueta']);
// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
function sinFilasDePaciente(v: unknown): boolean {
@@ -32,26 +93,88 @@ function sinFilasDePaciente(v: unknown): boolean {
if (!record(v)) return true;
return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
}
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
/** Validates the aggregate before anything is drawn: aggregates only, and nothing published under the threshold. */
export function analisisAgregado(v: unknown): AnalisisAgregado {
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
if (!record(v) || v['simulado'] !== true) return invalido();
const umbral = v['umbral_supresion'], grupos = v['grupos'];
if (!sinFilasDePaciente(v) || !text(v['cohorte']) || !text(v['escenario']) || !isoDate(v['corte']) || !text(v['unidad']) || !text(v['denominador'])
|| !text(v['revision']) || !/^[0-9a-f]{64}$/.test(v['revision']) || typeof umbral !== 'number' || !Number.isFinite(umbral) || umbral < 1
|| !Array.isArray(grupos) || !grupos.length
|| !grupos.every(g => record(g) && text(g['codigo']) && typeof g['suprimido'] === 'boolean'
&& (g['suprimido'] ? g['n'] === null : typeof g['n'] === 'number' && Number.isInteger(g['n']) && g['n'] >= umbral))
|| new Set(grupos.map(g => (g as GrupoAnalisis).codigo)).size !== grupos.length) return invalido();
return v as unknown as AnalisisAgregado;
export function analisisCatalogo(v: unknown): AnalisisCatalogo {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (!text(v['corte']) || !num(v['horizonte_dias']) || !num(v['umbral_supresion'])
|| !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion']) && text(e['etapa'])
&& record(e['filtro_seguimiento']) && Object.values(e['filtro_seguimiento']).every(text)) || !(v['escenarios'] as unknown[]).length
|| !lista(v['estimadores'], e => opcion(e) && record(e) && text(e['nota'])) || !(v['estimadores'] as unknown[]).length
|| !lista(v['variables'], x => opcion(x) && record(x) && text(x['nom']) && ['registrado', 'supuesto'].includes(x['estado'] as string)
&& text(x['fuente']) && lista(x['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
|| !lista(v['etapas'], e => opcion(e) && record(e) && text(e['pregunta']) && ['incidencia', 'supervivencia'].includes(e['medida'] as string)
&& lista(e['escenarios'], text) && (e['escenarios'] as unknown[]).length > 0 && lista(e['estimadores'], text) && (e['estimadores'] as unknown[]).length > 0
&& lista(e['variables'], text) && (e['variables'] as unknown[]).length >= 2 && lista(e['requeridas'], record)) || !(v['etapas'] as unknown[]).length
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|| !sinFilasDePaciente(v)) invalido();
return v as unknown as AnalisisCatalogo;
}
export function analisisResultados(v: unknown): AnalisisResultados {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (!['incidencia', 'supervivencia'].includes(v['medida'] as string) || !lista(v['supuestos'], text)) invalido();
const pob = v['poblacion'], tabla = v['tabla_riesgo'], pruebas = v['pruebas'], efectos = v['efectos'];
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador']) || !text(v['estrato'])
|| !record(v['filtros']) || !record(pob) || !numONulo(pob['n']) || !numONulo(pob['eventos'])
|| !lista(v['grupos'], g => record(g) && text(g['grupo']) && text(g['etiqueta']) && text(g['color']) && typeof g['suprimido'] === 'boolean'
&& numONulo(g['n']) && numONulo(g['eventos']) && (!g['suprimido'] || g['n'] === null && g['eventos'] === null))
|| !lista(v['curvas'], c => record(c) && text(c['grupo']) && num(c['t']) && (c['estimador'] === 'KM' || c['estimador'] === 'CIF')
&& (c['suprimido'] === 1 ? c['valor'] === null && c['n_riesgo'] === null : num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['n_riesgo'])))
|| !record(tabla) || !lista(tabla['cortes_dias'], num) || !lista(tabla['filas'], f => record(f) && text(f['grupo']) && lista(f['cortes'], numONulo))
|| !record(pruebas) || !lista(pruebas['pares'], record) || !lista(pruebas['rmst'], record)
|| !record(efectos) || !['listo', 'insuficiente', 'no_aplica'].includes(efectos['estado'] as string)
|| !lista(efectos['filas'], f => record(f) && text(f['termino']) && num(f['hr']) && num(f['ic_bajo']) && num(f['ic_alto']) && num(f['n_eventos']))
|| !lista(v['validacion'], f => record(f) && text(f['chequeo']) && text(f['escopo']) && (f['aprobado'] === null || typeof f['aprobado'] === 'boolean'))
|| !lista(v['avisos'], text)) invalido();
// A published point must stay at or above the threshold of patients at risk.
const umbral = v['umbral_supresion'] as number;
if ((v['curvas'] as PuntoCurva[]).some(c => c.suprimido === 0 && c.n_riesgo! < umbral)) invalido();
return v as unknown as AnalisisResultados;
}
export function analisisSubgrupos(v: unknown): AnalisisSubgrupos {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
const eje = (x: unknown) => lista(x, o => record(o) && text(o['codigo']) && text(o['etiqueta']));
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador'])
|| !eje(v['filas']) || !eje(v['columnas']) || !opcion(v['dimension_filas']) || !opcion(v['dimension_columnas']) || !lista(v['supuestos'], text)
|| !lista(v['pruebas'], x => record(x) && text(x['variable']) && text(x['estratificada_por']) && (x['logrank'] === null || record(x['logrank'])) && (x['estratificado'] === null || record(x['estratificado'])))
|| !lista(v['celdas'], c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean'
&& (c['suprimido'] ? c['n'] === null && c['eventos'] === null && c['valor'] === null
: num(c['n']) && num(c['eventos']) && num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['t_dias'])))) invalido();
// A published cell never has fewer patients or events than the threshold.
const umbral = v['umbral_supresion'] as number;
if ((v['celdas'] as CeldaSubgrupo[]).some(c => !c.suprimido && (c.n! < umbral || c.eventos! < umbral))) invalido();
return v as unknown as AnalisisSubgrupos;
}
export function analisisIndicadores(v: unknown): AnalisisIndicadores {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (!sinFilasDePaciente(v) || !num(v['umbral_supresion']) || !lista(v['indicadores'], x => record(x) && text(x['clave']) && text(x['titulo'])
&& text(x['descripcion']) && typeof x['suprimido'] === 'boolean'
&& (x['suprimido'] ? x['valor'] === null && x['eventos'] === null : num(x['valor']) && num(x['n']) && num(x['eventos'])))) invalido();
// A published figure never stands on fewer patients than the threshold.
if ((v['indicadores'] as IndicadorEpidemiologico[]).some(x => !x.suprimido && x.n! < (v['umbral_supresion'] as number))) invalido();
return v as unknown as AnalisisIndicadores;
}
@Injectable({ providedIn: 'root' })
export class AnalisisService {
private readonly http = inject(HttpClient);
agregado(dominio: Dominio, corte: string) {
if (!isoDate(corte)) throw new Error('Fecha de corte inválida');
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
catalogo(dominio: Dominio) {
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis`).pipe(map(analisisCatalogo));
}
resultados(dominio: Dominio, pedido: AnalisisPedido) {
let params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('estrato', pedido.estrato);
if (pedido.grupos.length) params = params.set('grupos', pedido.grupos.join(','));
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/resultados`, { params }).pipe(map(analisisResultados));
}
subgrupos(dominio: Dominio, pedido: PedidoSubgrupos) {
const params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('filas', pedido.filas).set('columnas', pedido.columnas);
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/subgrupos`, { params }).pipe(map(analisisSubgrupos));
}
indicadores(dominio: Dominio) {
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`).pipe(map(analisisIndicadores));
}
}
@@ -3,74 +3,178 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { analisisAgregado } from './indicadores-analisis.service';
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
import {
IndicadoresAnalisis, SeleccionPacientes, celdaDelClic, cruceDeEtapa, grupoDelClic, pedidoDeEtapa, seleccionDeCelda, seleccionDeCurva,
} from './indicadores-analisis';
import { curvasFigura, forestFigura, subgruposFigura } from './indicadores-analisis-figuras';
import {
AnalisisCatalogo, AnalisisIndicadores, AnalisisResultados, AnalisisSubgrupos, analisisCatalogo, analisisIndicadores, analisisResultados, analisisSubgrupos,
} from './indicadores-analisis.service';
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
// sends to Seguimiento, and the tab's requests and states. The fixtures are in indicadores-analisis.testing.ts.
// Covers the «Análisis epidemiológico» tab of breast cancer: the guards of its answers (aggregates only, nothing
// under the threshold), the figures built from them, the selections a curve or a cell sends to Seguimiento, and the
// tab's requests: the epidemiological figures, the curves of two or more values of one variable, and the heatmap of
// two distinct variables.
// Fixtures, all built below: `catalogo` (two stages, development with three variables and survival with two, one of
// them assumed; one blocked analysis), `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model),
// `subgrupos` (a two-by-two BI-RADS and age grid with one suppressed cell and its crossed tests) and `indicadores`
// (one published figure and one suppressed).
describe('Respuesta del análisis', () => {
it('admite el agregado de la cohorte, con la extensión de grupos y el arreglo de indicadores vacío', () => {
// Fails if the real answer (with the fields the prototype leaves empty) stops being accepted.
expect(analisisAgregado(agregadoJson()).grupos).toHaveLength(6);
const catalogo = (): AnalisisCatalogo => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
etapas: [
{ clave: 'desarrollo', etiqueta: 'Desarrollo', pregunta: '¿Quién llega a cáncer?', escenarios: ['diagnostico', 'incidencia'], estimadores: ['cif', 'km'],
medida: 'incidencia', variables: ['birads', 'grupo_edad', 'brca'], evento_supuesto: null,
requeridas: [{ variable: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado' }] },
{ clave: 'supervivencia', etiqueta: 'Supervivencia', pregunta: '¿Quién sigue viva?', escenarios: ['supervivencia'], estimadores: ['km'],
medida: 'supervivencia', variables: ['estadio', 'grupo_edad'], evento_supuesto: 'Estado vital supuesto.',
requeridas: [{ variable: 'Estado vital y causa de muerte', nom: '16.8', estado: 'supuesto' }] },
],
escenarios: [
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más', etapa: 'desarrollo', filtro_seguimiento: {} },
{ clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna', etapa: 'desarrollo', filtro_seguimiento: { resultado: 'BENIGNO' } },
{ clave: 'supervivencia', etiqueta: 'Supervivencia', evento: 'Muerte', origen: 'Diagnóstico', poblacion: 'Cáncer invasor', etapa: 'supervivencia', filtro_seguimiento: { resultado: 'INVASOR' } },
],
estimadores: [{ clave: 'km', etiqueta: '1 − Kaplan-Meier', nota: 'Censura la muerte.' }, { clave: 'cif', etiqueta: 'Aalen-Johansen', nota: 'Muerte competitiva.' }],
variables: [
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado', fuente: 'mastografia.birads',
opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }, { codigo: 'B6', etiqueta: 'BI-RADS 6' }] },
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', nom: '16.5', estado: 'registrado', fuente: 'paciente.fecha_nacimiento',
opciones: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }] },
{ clave: 'brca', etiqueta: 'BRCA1/2', nom: 'Factores de riesgo', estado: 'supuesto', fuente: 'Prueba genética.',
opciones: [{ codigo: 'BRCA1', etiqueta: 'Mutación BRCA1' }, { codigo: 'NEGATIVO', etiqueta: 'Sin mutación' }] },
{ clave: 'estadio', etiqueta: 'Estadio clínico', nom: '10.3.2', estado: 'supuesto', fuente: 'Nota de oncología.',
opciones: [{ codigo: 'I', etiqueta: 'Estadio I' }, { codigo: 'IV', etiqueta: 'Estadio IV' }] },
],
bloqueados: [{ clave: 'sobrevida', titulo: 'Sobrevida por etapa clínica', motivo: 'No hay etapa clínica ni estado vital.' }],
});
const punto = (grupo: string, t: number, valor: number, n_riesgo: number, n_eventos: number) =>
({ grupo, t, estimador: 'CIF' as const, valor, ic_bajo: valor * .8, ic_alto: valor * 1.2, n_riesgo, n_eventos, suprimido: 0 as const });
const resultados = (): AnalisisResultados => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {}, grupos_elegidos: null,
poblacion: { n: null, eventos: null, totales_ocultos: true, seguimiento_mediano_dias: 700 },
grupos: [
{ grupo: 'B4A', etiqueta: 'BI-RADS 4A', color: '#1F5F8B', suprimido: false, motivo: null, n: 180, eventos: 11, competitivos: null },
{ grupo: 'B5', etiqueta: 'BI-RADS 5', color: '#C26A2B', suprimido: false, motivo: null, n: 120, eventos: 100, competitivos: null },
{ grupo: 'B6', etiqueta: 'BI-RADS 6', color: '#4E8A4B', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, competitivos: null },
],
curvas: [punto('B4A', 0, 0, 180, 0), punto('B4A', 90, 4, 150, 7), punto('B4A', 730, 6, 90, 11),
punto('B5', 0, 0, 120, 0), punto('B5', 40, 70, 30, 85),
{ grupo: 'B5', t: 300, estimador: 'CIF', valor: null, ic_bajo: null, ic_alto: null, n_riesgo: null, n_eventos: null, suprimido: 1 }],
tabla_riesgo: { cortes_dias: [0, 365, 730], filas: [{ grupo: 'B4A', cortes: [180, 130, 90] }, { grupo: 'B5', cortes: [120, 6, null] }] },
pruebas: { logrank: { chi2: 120.5, gl: 1, p: 1e-20 }, pares: [{ a: 'B4A', b: 'B5', p: 1e-20, p_holm: 1e-20 }],
rmst: [{ grupo: 'B4A', rmst: 700, dif: null, ic_bajo: null, ic_alto: null }, { grupo: 'B5', rmst: 210, dif: -490, ic_bajo: -520, ic_alto: -460 }],
rmst_referencia: 'B4A', nota: 'Prueba de Gray pendiente.' },
efectos: { estado: 'listo', motivo: null, metodo: 'cox', referencia: 'B4A', etiqueta_referencia: 'BI-RADS 4A',
filas: [{ termino: 'B5', etiqueta: 'BI-RADS 5', hr: 30, ic_bajo: 16, ic_alto: 59, n_eventos: 100, metodo: 'cox', ph_p: .01 }] },
validacion: [{ chequeo: 'Eventos por grupo', escopo: 'BI-RADS 6', estadistico: null, p: null, umbral: 5, aprobado: false, nota: 'Menos de 5 eventos', version_modelo: 'mock-0.1', sql_sha: null }],
avisos: ['Análisis descriptivo, no causal.', 'Horizonte de 2 años (730 días).', 'Requiere el estado vital.'],
});
const subgrupos = (): AnalisisSubgrupos => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
dimension_filas: { clave: 'birads', etiqueta: 'Categoría BI-RADS' }, dimension_columnas: { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
pruebas: [{ variable: 'birads', etiqueta: 'Categoría BI-RADS', estratificada_por: 'grupo_edad', etiqueta_estrato: 'Grupo de edad',
logrank: { chi2: 90, gl: 1, p: 1e-10, grupos: 2 }, estratificado: { chi2: 85, gl: 1, p: 1e-9, grupos: 2 } },
{ variable: 'grupo_edad', etiqueta: 'Grupo de edad', estratificada_por: 'birads', etiqueta_estrato: 'Categoría BI-RADS', logrank: null, estratificado: null }],
filas: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }],
columnas: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }],
celdas: [
{ fila: 'B4A', columna: '40-49', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, t_dias: null, valor: null, ic_bajo: null, ic_alto: null },
{ fila: 'B4A', columna: '50-59', suprimido: false, motivo: null, n: 60, eventos: 6, t_dias: 730, valor: 10, ic_bajo: 4, ic_alto: 20 },
{ fila: 'B5', columna: '40-49', suprimido: false, motivo: null, n: 40, eventos: 36, t_dias: 120, valor: 90, ic_bajo: 78, ic_alto: 96 },
{ fila: 'B5', columna: '50-59', suprimido: false, motivo: null, n: 50, eventos: 45, t_dias: 730, valor: 92, ic_bajo: 81, ic_alto: 97 },
],
});
const indicadores = (): AnalisisIndicadores => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, indicadores: [
{ clave: 'desarrollo', titulo: 'Incidencia de cáncer a 24 meses', etapa: 'desarrollo', unidad: '%', descripcion: 'Llegan a cáncer.', supuesto: null,
suprimido: false, n: 600, eventos: 274, valor: 45.7, ic_bajo: 41.6, ic_alto: 49.6, t_dias: 730 },
{ clave: 'recaida', titulo: 'Recaída a 24 meses', etapa: 'recaida', unidad: '%', descripcion: 'Recaen.', supuesto: 'Recaída supuesta.',
suprimido: true, n: null, eventos: null, valor: null, ic_bajo: null, ic_alto: null, t_dias: null },
],
});
describe('Respuestas del análisis', () => {
it('admiten solo agregados de demostración', () => {
// Fails if the guards stop rejecting real records or anything shaped like a patient row, at any depth.
expect(analisisResultados(resultados()).grupos).toHaveLength(3);
expect(analisisCatalogo(catalogo()).etapas).toHaveLength(2);
expect(analisisIndicadores(indicadores()).indicadores).toHaveLength(2);
expect(() => analisisResultados({ ...resultados(), simulado: false })).toThrow();
expect(() => analisisResultados({ ...resultados(), pruebas: { ...resultados().pruebas, items: [{ id_seudonimo: 'M-1' }] } })).toThrow();
expect(() => analisisCatalogo({ ...catalogo(), pacientes: [] })).toThrow();
});
it('rechaza lo que no es un agregado: filas de paciente, un grupo suprimido con conteo o un grupo publicado bajo el umbral', () => {
// Fails if a guard stops rejecting patient rows at any depth, or a count that should be hidden.
expect(() => analisisAgregado({ ...agregadoJson(), simulado: false })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), pacientes: [] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false, items: [{ id_seudonimo: 'M-1' }] }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_4', n: 3, suprimido: true }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 4, suprimido: false }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_5', n: 7, suprimido: false }] })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), revision: 'abc' })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), corte: '2026-13-40' })).toThrow();
expect(() => analisisAgregado({ ...agregadoJson(), grupos: [] })).toThrow();
it('rechazan cifras bajo el umbral: un punto de curva, un grupo suprimido con conteos, una celda o un indicador', () => {
// Fails if a curve's tail, a suppressed group, a heatmap cell or an epidemiological figure can carry counts under the threshold.
const r = resultados();
expect(() => analisisResultados({ ...r, curvas: [...r.curvas, punto('B4A', 740, 7, 3, 12)] })).toThrow();
expect(() => analisisResultados({ ...r, grupos: r.grupos.map(g => g.suprimido ? { ...g, n: 4 } : g) })).toThrow();
expect(() => analisisSubgrupos({ ...subgrupos(), celdas: subgrupos().celdas.map(c => c.suprimido ? c : { ...c, eventos: 3 }) })).toThrow();
expect(() => analisisIndicadores({ ...indicadores(), indicadores: [{ ...indicadores().indicadores[0], n: 3 }] })).toThrow();
});
it('una etapa necesita al menos dos variables para comparar', () => {
// Fails if a stage with a single variable reaches the curves or the heatmap, which compare two or more.
expect(() => analisisCatalogo({ ...catalogo(), etapas: [{ ...catalogo().etapas[0], variables: ['birads'] }] })).toThrow();
});
});
describe('Figura del análisis', () => {
it('dibuja una barra por categoría con sus pacientes y la suprimida vacía, gris y sin cifra', () => {
// Fails if a suppressed category is drawn as a zero count, or loses its explanation.
const fig = gruposFigura(agregado(), 'claro');
const barra = fig.data[0];
expect(barra['x']).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(barra['y']).toEqual([0, 0, 0, 0, 6, 0]);
expect((barra['text'] as string[]).filter(t => t === 'No publicado')).toHaveLength(5);
expect((barra['hovertemplate'] as string[])[0]).toContain('Menos de 5 pacientes: no se publica');
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
describe('Figuras del análisis', () => {
it('dibuja una curva con su banda por grupo publicado y la corta donde la respuesta la suprime', () => {
// Fails if a suppressed group gets a trace, the curve runs past its suppressed tail, or a line loses its group.
const fig = curvasFigura(resultados(), 'claro');
const lineas = fig.data.filter(t => t['meta']);
expect(lineas.map(t => t['meta'])).toEqual(['B4A', 'B5']);
expect(fig.data).toHaveLength(6);
expect(lineas[1]['y'] as number[]).toEqual([0, 70]);
});
it('un clic solo da el código de una barra publicada', () => {
// Fails if a click on a suppressed or unknown bar could open its list.
expect(grupoDelClic({ points: [{ customdata: 'BIRADS_5' }] }, agregado())).toBe('BIRADS_5');
expect(grupoDelClic({ points: [{ customdata: 'BIRADS_4' }] }, agregado())).toBeUndefined();
expect(grupoDelClic({ points: [{ customdata: 'OTRO' }] }, agregado())).toBeUndefined();
expect(grupoDelClic({ points: [{}] }, agregado())).toBeUndefined();
expect(grupoDelClic(undefined, agregado())).toBeUndefined();
it('en la etapa de supervivencia la curva baja desde 100 % y el eje dice Supervivencia', () => {
// Fails if the survival stage is drawn on the incidence axis.
const r = resultados();
const fig = curvasFigura({ ...r, medida: 'supervivencia', curvas: r.curvas.map(c => c.valor === null ? c : { ...c, valor: 100 - c.valor, ic_bajo: 100 - c.ic_alto!, ic_alto: 100 - c.ic_bajo! }) }, 'claro');
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Supervivencia (%)');
expect((fig.data.find(t => t['meta'] === 'B4A')!['y'] as number[])[0]).toBe(100);
});
it('escribe los códigos como en la clínica', () => {
expect(etiquetaBirads('BIRADS_4A')).toBe('BI-RADS 4A');
expect(etiquetaBirads('OTRO')).toBe('OTRO');
it('marca vacío el HR con riesgos no proporcionales y no dibuja nada sin modelo', () => {
// Fails if the forest plot hides the PH warning or draws an effect the answer did not publish.
const fig = forestFigura(resultados(), 'claro');
expect((fig.data[1]['marker'] as { color: string[] }).color[0]).toBe('#FFFFFF');
expect(forestFigura({ ...resultados(), efectos: { ...resultados().efectos, estado: 'insuficiente', filas: [] } }, 'claro').data).toEqual([]);
});
it('el mapa de calor dibuja gris lo suprimido y nombra sus dos variables', () => {
// Fails if a suppressed cell is drawn as a colour, or the axes stop naming the variables chosen.
const fig = subgruposFigura(subgrupos(), 'claro');
expect((fig.data[1]['z'] as (number | null)[][])[0]).toEqual([null, 10]);
expect((fig.data[0]['z'] as (number | null)[][])[0]).toEqual([1, null]);
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Categoría BI-RADS');
expect((fig.layout['annotations'] as { text: string }[])[2].text).toContain('a 4 meses');
});
});
describe('Selección que va a Seguimiento', () => {
it('un grupo publicado lleva su filtro, el corte, el nombre, cuántas pacientes cuenta y la cohorte con su revisión', () => {
// Fails if the list is opened without the cohort's revision, at another cut-off, or on another group.
expect(seleccionDeGrupo(agregado(), 'BIRADS_5')).toEqual({
filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 6, contexto: CONTEXTO });
describe('Selecciones que van a Seguimiento', () => {
it('una curva lleva la población del escenario y el valor del grupo', () => {
// Fails if a curve opens a list wider than its own patients, or names another group.
const pedido = { escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} };
expect(grupoDelClic({ points: [{ data: { meta: 'IV' } }] })).toBe('IV');
expect(grupoDelClic({ points: [{ data: {} }] })).toBeUndefined();
expect(seleccionDeCurva(catalogo(), pedido, 'IV')).toEqual({ filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio clínico, Estadio IV' });
expect(seleccionDeCurva(catalogo(), pedido, 'XX')).toBeUndefined();
});
it('un grupo suprimido o desconocido no abre nada y dice por qué', () => {
// Fails if the list of a group the answer hid could be opened.
expect(motivoSinLista(agregado(), 'BIRADS_4')).toBe(MOTIVO_GRUPO_SUPRIMIDO);
expect(seleccionDeGrupo(agregado(), 'BIRADS_4')).toBeUndefined();
expect(seleccionDeGrupo(agregado(), 'OTRO')).toBeUndefined();
expect(motivoSinLista(agregado(), 'BIRADS_5')).toBeUndefined();
it('una celda lleva sus dos valores, y una celda gris nada', () => {
// Fails if a click on a suppressed cell could open the patients the answer hid.
expect(celdaDelClic({ points: [{ customdata: ['B5', '40-49'], z: 90 }] })).toEqual({ fila: 'B5', columna: '40-49' });
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
expect(seleccionDeCelda(catalogo(), subgrupos(), { fila: 'B5', columna: '40-49' }))
.toEqual({ filtros: { birads: 'B5', grupo_edad: '40-49' }, etiqueta: 'Cáncer confirmado: BI-RADS 5 y 40-49 años' });
});
it('hoy se escribe como la fecha de un campo de fecha, en el día del usuario', () => {
expect(hoyIso(new Date(2026, 10, 3, 23, 59))).toBe('2026-11-03');
it('cada etapa abre con su primera variable y su primer cruce, y conserva un cruce que le pertenece', () => {
// Fails if a stage keeps another stage's variable or an estimator it does not admit.
expect(pedidoDeEtapa(catalogo(), 'supervivencia', { escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', grupos: ['B5', 'B6'], filtros: {} }))
.toEqual({ escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} });
const [desarrollo, supervivencia] = catalogo().etapas;
expect(cruceDeEtapa(desarrollo, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'brca', columnas: 'birads' });
expect(cruceDeEtapa(supervivencia, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'estadio', columnas: 'grupo_edad' });
});
});
@@ -86,150 +190,106 @@ describe('Pestaña Análisis epidemiológico', () => {
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const text = () => root().textContent as string;
const pedido = (corte = hoyIso()) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte);
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
// The date goes in as the user would type it; ngModel writes its value in a microtask.
async function escribirCorte(valor: string) {
// A form control is registered in a microtask after its first render: it is only ready to be typed into after that.
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
const c = root().querySelector('input[name="corte"]') as HTMLInputElement;
c.value = valor; c.dispatchEvent(new Event('input', { bubbles: true })); c.dispatchEvent(new Event('change', { bubbles: true }));
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
expect(c.value, 'el campo conserva lo escrito').toBe(valor === '2026-02-31' ? '' : valor);
}
const text = () => fixture.nativeElement.textContent as string;
const curvas = () => http.expectOne(r => r.url === '/cama/analisis/resultados');
const abrir = () => {
fixture.componentRef.setInput('active', true); fixture.detectChanges();
http.expectOne('/cama/analisis').flush(catalogo()); fixture.detectChanges();
http.expectOne('/cama/analisis/indicadores').flush(indicadores());
};
it('no pide nada hasta abrirse; luego pide el agregado al corte de hoy y lo dibuja con su tabla', () => {
// Fails if the tab loads while hidden, or its first request stops carrying a cut-off.
it('no pide nada hasta abrirse; luego los indicadores y la primera variable con todos sus valores', () => {
// Fails if the tab loads while hidden, or its first request stops being the stage's first variable.
fixture.detectChanges();
http.expectNone(() => true);
http.expectNone('/cama/analisis');
abrir();
expect(text()).toContain('Pacientes por categoría BI-RADS');
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('No estima incidencia, recurrencia ni supervivencia.');
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => f.querySelector('th')!.textContent!.trim())).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(filas.map(f => f.children[1].textContent!.trim())).toEqual(['No publicado', 'No publicado', 'No publicado', 'No publicado', '6', 'No publicado']);
const req = curvas();
expect(['escenario', 'estimador', 'estrato', 'grupos'].map(k => req.request.params.get(k))).toEqual(['diagnostico', 'cif', 'birads', null]);
req.flush(resultados()); fixture.detectChanges();
expect(text()).toContain('Indicadores epidemiológicos');
expect(text()).toContain('IC 95 %: 41.6 a 49.6 %');
expect(text()).toContain('Dato oculto por tamaño');
expect(text()).toContain('Grupos suprimidos: BI-RADS 6');
});
it('encabeza la vista y deriva las dos tarjetas de los estados de los grupos, sin sumar pacientes', () => {
// Fails if the cards count patients instead of categories, appear before an answer, or the heading and denominator are lost.
abrir();
expect(root().querySelector('h2')!.textContent).toBe('Análisis epidemiológico');
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const tarjetas = Array.from(root().querySelectorAll('app-indicador-kpi-card')) as HTMLElement[];
expect(tarjetas.map(t => t.querySelector('h3')!.textContent)).toEqual(['Categorías publicadas', 'Categorías no publicadas']);
expect(tarjetas.map(t => t.querySelector('.value')!.textContent!.trim())).toEqual(['1', '5']);
expect(tarjetas[0].textContent).toContain('de 6 categorías BI-RADS');
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('abrir la lista en Seguimiento');
it('compara dos o más grupos: con uno avisa y no consulta; con todos no los nombra', () => {
// Fails if a single group is sent for a log-rank, or a full selection is sent as a list.
abrir(); curvas().flush(resultados());
const tab = fixture.componentInstance;
tab.elegirGrupos(['B5']); fixture.detectChanges();
http.expectNone(r => r.url === '/cama/analisis/resultados');
expect(text()).toContain('Elija al menos dos grupos para comparar.');
tab.elegirGrupos(['B4A', 'B5']);
let req = curvas(); expect(req.request.params.get('grupos')).toBe('B4A,B5'); req.flush(resultados());
tab.elegirGrupos(['B4A', 'B5', 'B6']);
req = curvas(); expect(req.request.params.has('grupos')).toBe(false); req.flush(resultados());
tab.estratificar('brca');
req = curvas(); expect([req.request.params.get('estrato'), req.request.params.get('grupos')]).toEqual(['brca', null]); req.flush(resultados());
});
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
// Fails if the cards stay on screen without an answer with categories.
abrir();
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
expect(Array.from(root().querySelectorAll('app-indicador-kpi-card .value')).map(v => v.textContent!.trim())).toEqual(['0', '6']);
fixture.componentInstance.consultar(); fixture.detectChanges();
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
it('el mapa de calor se pide al abrir su parte, con filas y columnas distintas que se eligen por separado', () => {
// Fails if the grid loads with the tab, repeats a request without a change, or accepts the same variable twice.
abrir(); curvas().flush(resultados());
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
const tab = fixture.componentInstance;
tab.elegirVista('subgrupos'); fixture.detectChanges();
let req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'grupo_edad']);
req.flush(subgrupos()); fixture.detectChanges();
expect(text()).toContain('Estratificado por la otra');
tab.cruzar({ columnas: 'birads' }); fixture.detectChanges();
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
tab.cruzar({ columnas: 'brca' }); fixture.detectChanges();
req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'brca']);
req.flush(subgrupos());
});
it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => {
// Fails if a slow answer replaces the aggregate of a later cut-off.
abrir();
const primera = pedido(); primera.flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
await escribirCorte('2026-09-01');
expect(fixture.componentInstance.corte).toBe('2026-09-01');
boton('Consultar')!.click(); fixture.detectChanges();
const lenta = pedido('2026-09-01');
// The button is disabled while a query runs, so the later query comes from the code (a retry, a programmatic refresh).
expect(boton('Consultar')!.disabled).toBe(true);
await escribirCorte('2026-08-01'); fixture.componentInstance.consultar(); fixture.detectChanges();
expect(lenta.cancelled).toBe(true);
pedido('2026-08-01').flush(agregadoJson({ corte: '2026-08-01' })); fixture.detectChanges();
expect(text()).toContain('Fecha de corte: 2026-08-01.');
});
it('una fecha que no es de calendario no sale del navegador', async () => {
// Fails if an invalid cut-off is sent to the server.
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
await escribirCorte('2026-02-31'); boton('Consultar')!.click(); fixture.detectChanges();
http.expectNone(() => true);
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte');
});
it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => {
// Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost.
abrir();
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.');
expect(text()).not.toContain('Sin pacientes');
expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true);
});
it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => {
// Fails if the table offers the patients of a hidden group.
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
});
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
it('una curva, su botón de la tabla o una celda emiten la selección para Seguimiento', () => {
// Fails if a click stops reaching Seguimiento, or sends a selection without the scenario's population.
const emitidas: SeleccionPacientes[] = [];
fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
(root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement).click();
fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_5' }] });
fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_4' }] });
expect(emitidas).toHaveLength(2);
expect(emitidas[0]).toEqual(emitidas[1]);
expect(emitidas[0]).toMatchObject({ filtros: { birads: 'BIRADS_5' }, corte: hoyIso(), esperados: 6, contexto: { ...CONTEXTO } });
abrir(); curvas().flush(resultados()); fixture.detectChanges();
fixture.componentInstance.clicCurva({ points: [{ data: { meta: 'B5' } }] });
(fixture.nativeElement.querySelector('.riesgo .ver') as HTMLButtonElement).click();
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/subgrupos').flush(subgrupos()); fixture.detectChanges();
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B5', '50-59'], z: 92 }] });
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B4A', '40-49'], z: null }] });
expect(emitidas.map(e => e.filtros)).toEqual([{ birads: 'B5' }, { birads: 'B4A' }, { birads: 'B5', grupo_edad: '50-59' }]);
});
it('al volver restaura el foco en el control de origen y no repite ninguna consulta', () => {
// Fails if coming back from Seguimiento loses the focus or the answer already loaded.
fixture.componentInstance.verPacientes.subscribe(() => undefined);
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const origen = root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement;
origen.focus(); origen.click();
(document.activeElement as HTMLElement | null)?.blur();
fixture.componentInstance.restaurar();
http.expectNone(() => true);
expect(document.activeElement).toBe(origen);
expect(fixture.componentInstance.datos()?.grupos).toHaveLength(6);
it('cambiar de etapa pide su primera variable y anuncia lo supuesto', () => {
// Fails if a stage keeps another stage's variable or an estimator it does not admit, or hides its assumptions.
abrir(); curvas().flush(resultados());
fixture.componentInstance.elegirEtapa('supervivencia'); fixture.detectChanges();
const req = curvas();
expect(['escenario', 'estimador', 'estrato'].map(k => req.request.params.get(k))).toEqual(['supervivencia', 'km', 'estadio']);
req.flush({ ...resultados(), etapa: 'supervivencia', medida: 'supervivencia', escenario: 'supervivencia', estimador: 'km', estrato: 'estadio',
supuestos: ['Estado vital supuesto.'] });
fixture.detectChanges();
expect(text()).toContain('¿Quién sigue viva?');
expect(fixture.nativeElement.querySelector('.supuestos')?.textContent).toContain('Estado vital supuesto.');
expect(fixture.nativeElement.querySelector('#analisis-curvas h2')?.textContent).toContain('Supervivencia a 24 meses');
});
it('sin endpoint publicado queda pendiente, sin mostrarse como un error', () => {
// Fails if a 404 is shown as a broken page instead of a feature not yet published.
abrir(); pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
it('el diagnóstico muestra el estado de la cohorte, la validación y las variables de la NOM', () => {
// Fails if the cohort's status loses a figure, or a hidden total is shown as a number.
abrir(); curvas().flush(resultados()); fixture.detectChanges();
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
expect(diagnostico.querySelector('.requeridas')?.textContent).toContain('Categoría BI-RADS');
expect(diagnostico.querySelector('tr.falla')?.textContent).toContain('No cumple');
});
it('las flechas mueven entre las tres partes', () => {
// Fails if the parts stop behaving as a keyboard tab list.
abrir(); curvas().flush(resultados()); fixture.detectChanges();
const lista = fixture.nativeElement.querySelector('.subsecciones') as HTMLElement;
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
expect(fixture.componentInstance.vista()).toBe('diagnostico');
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
expect(fixture.componentInstance.vista()).toBe('curvas');
});
it('sin análisis publicado queda pendiente', () => {
// Fails if a 404 on the catalog is shown as an error instead of a feature not yet published.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
http.expectOne('/cama/analisis').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(text()).toContain('Funcionalidad pendiente de publicación');
expect(root().querySelector('[role=alert]')).toBeNull();
});
it('con la cohorte no disponible (503) lo dice y deja reintentar; el reintento repite la misma consulta', () => {
// Fails if a cohort that is not configured is hidden, or the retry asks for another date.
abrir(); pedido().flush({ error: 'Cohorte no disponible' }, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
expect(text()).toContain('La cohorte no está disponible en este momento.');
boton('Reintentar consulta')!.click(); fixture.detectChanges();
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
expect(root().querySelector('tbody')).not.toBeNull();
});
it('un error del servicio se muestra con su reintento y con el mensaje fijo, nunca con el cuerpo', () => {
// Fails if a real failure is swallowed or the server's own text reaches the page.
abrir(); pedido().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges();
expect(root().querySelector('[role=alert]')?.textContent).toContain('El servicio encontró un error interno');
expect(text()).not.toContain('detalle interno');
expect(boton('Reintentar consulta')).toBeDefined();
});
it('una respuesta fuera de contrato no se dibuja', () => {
// Fails if an answer with patient rows or counts under the threshold reaches the page.
abrir(); pedido().flush({ ...agregadoJson({ corte: hoyIso() }), pacientes: [{ id_seudonimo: 'M-0001' }] }); fixture.detectChanges();
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
expect(root().querySelector('tbody')).toBeNull();
expect(text()).not.toContain('M-0001');
});
});
@@ -1,47 +0,0 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
export const CORTE = '2026-10-20';
export const CONTEXTO = { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: REVISION };
/** One published category (BI-RADS 5, six patients) and five suppressed ones. */
export const agregado = (extra: Partial<AnalisisAgregado> = {}): AnalisisAgregado => ({
simulado: true, ...CONTEXTO, corte: CORTE, umbral_supresion: 5, unidad: 'paciente',
denominador: 'pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
grupos: [
{ codigo: 'BIRADS_4', n: null, suprimido: true }, { codigo: 'BIRADS_4A', n: null, suprimido: true }, { codigo: 'BIRADS_4B', n: null, suprimido: true },
{ codigo: 'BIRADS_4C', n: null, suprimido: true }, { codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_6', n: null, suprimido: true },
],
...extra,
});
/**
* The answer of the cohort's list as the API sends it: only the two filters it announces, with the code as their label,
* the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown),
* and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off.
*/
export function listaCohorte(o: { corte?: string; filtros?: Record<string, string>; page?: number; size?: number; n?: number; meses?: number; revision?: string } = {}): Record<string, any> {
const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0, revision = REVISION } = o;
const todos = Array.from({ length: n }, (_, i) => ({
id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01',
biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null,
}));
const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c }));
return {
simulado: true, ...CONTEXTO, revision, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha',
filtros: { birads: null, grupo_edad: null, ...filtros },
filtros_disponibles: [
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) },
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: opciones(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']) }],
columnas: [
{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
{ clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] },
{ clave: 'biopsia', etiqueta: 'Resultado histopatológico', detalles: [{ clave: 'biopsia_fecha', etiqueta: 'Fecha de reporte' }] }],
paginacion: { page, page_size: size, total_items: n, total_pages: Math.max(1, Math.ceil(n / size)) },
items: todos.slice((page - 1) * size, page * size),
};
}
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
@@ -1,240 +1,535 @@
import { Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, untracked } from '@angular/core';
import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service';
import { curvasFigura, forestFigura, mesesDe, nombreMedida, subgruposFigura } from './indicadores-analisis-figuras';
import {
AnalisisCatalogo, AnalisisEtapa, AnalisisIndicadores, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable,
IndicadorEpidemiologico, PedidoSubgrupos,
} from './indicadores-analisis.service';
import { httpMessage } from './indicadores-http';
import { Dominio, Tema } from './indicadores.models';
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' };
/**
* The patients behind a group of the aggregate, for the page to open them in Seguimiento: the list's filters, how to
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
* patients the analysis counts there.
*/
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
export const formatoP = (p: number | null) => p === null ? '—' : p < .001 ? '< 0.001' : p.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
export type VistaAnalisis = 'curvas' | 'subgrupos' | 'diagnostico';
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
{ id: 'curvas', etiqueta: 'Curvas (Kaplan-Meier)' },
{ id: 'subgrupos', etiqueta: 'Mapa de calor entre variables' },
{ id: 'diagnostico', etiqueta: 'Diagnóstico de la cohorte' },
];
// The patients behind a curve or a heatmap cell: the follow-up list's filters and how to name the selection.
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; }
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
export { hoyIso };
/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
const g = agregado.grupos.find(x => x.codigo === codigo);
return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
/** The cell of the grid: its row and column codes, from the coloured layer only (grey cells are suppressed). */
export function celdaDelClic(evento: unknown): { fila: string; columna: string } | undefined {
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
const c = punto?.customdata;
return Array.isArray(c) && typeof c[0] === 'string' && typeof c[1] === 'string' && typeof punto?.z === 'number' ? { fila: c[0], columna: c[1] } : undefined;
}
/** The selection of a published group: the whole group of the cohort at the cut-off it was counted at, nothing else. */
export function seleccionDeGrupo(agregado: AnalisisAgregado, codigo: string): SeleccionPacientes | undefined {
const g = agregado.grupos.find(x => x.codigo === codigo);
if (!g || motivoSinLista(agregado, codigo)) return undefined;
return { filtros: { birads: codigo }, etiqueta: `Categoría BI-RADS: ${etiquetaBirads(codigo)}`, corte: agregado.corte, esperados: g.n,
contexto: { cohorte: agregado.cohorte, escenario: agregado.escenario, revision: agregado.revision } };
/** The group of the clicked curve, from the line's `meta`; bands and empty clicks give nothing. */
export function grupoDelClic(evento: unknown): string | undefined {
const punto = (evento as { points?: { data?: { meta?: unknown } }[] } | undefined)?.points?.[0];
return typeof punto?.data?.meta === 'string' ? punto.data.meta : undefined;
}
/** The scrolling ancestor of an element, or the document's own scroller. */
function contenedorDeScroll(el: HTMLElement): HTMLElement {
for (let n = el.parentElement; n; n = n.parentElement) {
const overflow = getComputedStyle(n).overflowY;
if ((overflow === 'auto' || overflow === 'scroll') && n.scrollHeight > n.clientHeight) return n;
}
return (el.ownerDocument.scrollingElement ?? el.ownerDocument.documentElement) as HTMLElement;
/** The stage a scenario belongs to. */
export const etapaDe = (catalogo: AnalisisCatalogo, escenario: string | undefined): AnalisisEtapa | undefined =>
catalogo.etapas.find(e => e.escenarios.includes(escenario ?? ''));
/** The request a stage opens with: its first scenario and variable, all its values, the estimator if the stage admits it. */
export function pedidoDeEtapa(catalogo: AnalisisCatalogo, clave: string, actual?: AnalisisPedido): AnalisisPedido {
const etapa = catalogo.etapas.find(e => e.clave === clave) ?? catalogo.etapas[0];
const estimador = actual && etapa.estimadores.includes(actual.estimador) ? actual.estimador : etapa.estimadores[0];
return { escenario: etapa.escenarios[0], estimador, estrato: etapa.variables[0], grupos: [], filtros: {} };
}
// Epidemiological analysis of the breast cohort. For now: how many patients of the cohort are in each BI-RADS category at
// a cut-off, as a count (not an incidence or a survival estimate). A published category opens its patients in Seguimiento;
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
/** The grid a stage opens with: its first two variables, or the current ones while they belong to it. */
export function cruceDeEtapa(etapa: AnalisisEtapa, actual?: { filas: string; columnas: string }) {
const valido = actual && actual.filas !== actual.columnas && etapa.variables.includes(actual.filas) && etapa.variables.includes(actual.columnas);
return valido ? { filas: actual.filas, columnas: actual.columnas } : { filas: etapa.variables[0], columnas: etapa.variables[1] };
}
/** The follow-up filters of a curve: the scenario's population and the group's value of the compared variable. */
export function seleccionDeCurva(catalogo: AnalisisCatalogo, pedido: AnalisisPedido, grupo: string): SeleccionPacientes | undefined {
const escenario = catalogo.escenarios.find(e => e.clave === pedido.escenario), variable = catalogo.variables.find(v => v.clave === pedido.estrato);
if (!escenario || !variable) return undefined;
const valor = variable.opciones.find(o => o.codigo === grupo);
if (!valor) return undefined;
return { filtros: { ...escenario.filtro_seguimiento, [variable.clave]: grupo }, etiqueta: `${escenario.etiqueta}: ${variable.etiqueta}, ${valor.etiqueta}` };
}
/** The follow-up filters of a grid cell: the scenario's population and both values. */
export function seleccionDeCelda(catalogo: AnalisisCatalogo, sub: AnalisisSubgrupos, celda: { fila: string; columna: string }): SeleccionPacientes | undefined {
const escenario = catalogo.escenarios.find(e => e.clave === sub.escenario);
const fila = sub.filas.find(f => f.codigo === celda.fila), columna = sub.columnas.find(c => c.codigo === celda.columna);
if (!escenario || !fila || !columna) return undefined;
return { filtros: { ...escenario.filtro_seguimiento, [sub.dimension_filas.clave]: celda.fila, [sub.dimension_columnas.clave]: celda.columna },
etiqueta: `${escenario.etiqueta}: ${fila.etiqueta} y ${columna.etiqueta}` };
}
// Epidemiological analysis of the BI-RADS 4+ cohort. On top, the cohort's figures (incidence of cancer and of
// recurrence, follow-up adherence and survival). Then, by stage (development, recurrence, survival), three parts:
// the Kaplan-Meier curves of two or more values of one variable, the heatmap of two distinct variables, and the
// cohort's diagnostics. A curve or a cell opens its patients in Seguimiento; nothing else leaves the aggregates.
// Nothing is requested until the tab is first opened, and the grid only once its part is.
@Component({
selector: 'app-indicadores-analisis',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
<p class="nota">Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.</p>
@if (datos(); as d) {
<p class="contexto">Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.</p>
<div class="tarjetas">
<app-indicador-kpi-card title="Categorías publicadas" [value]="publicadas()" state="Disponible" [quietWhenAvailable]="true"
[additionalInfo]="'de ' + d.grupos.length + ' categorías BI-RADS.'" />
<app-indicador-kpi-card title="Categorías no publicadas" [value]="d.grupos.length - publicadas()" state="Disponible" [quietWhenAvailable]="true"
[additionalInfo]="'Con menos de ' + d.umbral_supresion + ' pacientes: su conteo y su lista no se publican.'" />
</div>
}
<form class="controles" (ngSubmit)="consultar()">
<label>Fecha de corte <input name="corte" type="date" required [(ngModel)]="corte" [max]="hoy" /></label>
<button type="submit" mat-stroked-button [disabled]="carga().estado === 'cargando'">Consultar</button>
</form>
<article class="panel" aria-labelledby="birads-titulo">
<h3 id="birads-titulo">Pacientes por categoría BI-RADS</h3>
@switch (carga().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Consultando el análisis" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') {
<p role="status">La cohorte no está disponible en este momento.</p>
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
}
@case ('error') {
<div role="alert"><p>{{ $any(carga()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
}
@switch (catalogo().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando el análisis" /> }
@case ('pendiente') { <p role="status" class="panel">Funcionalidad pendiente de publicación.</p> }
@case ('error') { <div role="alert" class="panel"><p>{{ $any(catalogo()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentarCatalogo()">Reintentar consulta</button></div> }
}
@if (cat(); as c) {
<section class="epidemiologicos" aria-labelledby="indicadores-epidemiologicos">
<h2 id="indicadores-epidemiologicos">Indicadores epidemiológicos</h2>
<p class="nota">De toda la cohorte, a {{ meses(c.horizonte_dias) }} meses. Descriptivos, no causales.</p>
@switch (indicadores().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores epidemiológicos" /> }
@case ('error') { <div role="alert"><p>{{ $any(indicadores()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarIndicadores()">Reintentar consulta</button></div> }
}
@if (datos(); as d) {
@if (todasSuprimidas()) {
<p class="nota">Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.</p>
}
<p class="aviso" role="status">{{ aviso() }}</p>
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
label="Pacientes por categoría BI-RADS" />
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
<table>
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<tbody>
@for (g of d.grupos; track g.codigo) {
<tr [attr.data-grupo]="g.codigo">
<th scope="row">{{ etiqueta(g.codigo) }}</th>
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
</tr>
}
</tbody>
</table>
@if (ind(); as i) {
<div class="kpis">
@for (x of i.indicadores; track x.clave) {
<app-indicador-kpi-card [title]="x.titulo" [value]="x.valor === null ? null : x.valor.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 })"
[unit]="x.unidad" [state]="x.suprimido ? 'Dato oculto por tamaño' : 'Disponible'" [quietWhenAvailable]="true" [additionalInfo]="infoIndicador(x)" />
}
</div>
}
</article>
</section>
</section>
<div class="controles">
<span id="analisis-etapa" class="etiqueta">Etapa</span>
<mat-button-toggle-group class="etapas" aria-labelledby="analisis-etapa" hideSingleSelectionIndicator [value]="etapa()?.clave" (change)="elegirEtapa($event.value)">
@for (e of c.etapas; track e.clave) { <mat-button-toggle [value]="e.clave">{{ e.etiqueta }}</mat-button-toggle> }
</mat-button-toggle-group>
@if (escenariosEtapa().length > 1) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Escenario</mat-label>
<mat-select [value]="pedido()!.escenario" (selectionChange)="cambiar({ escenario: $event.value })">
@for (e of escenariosEtapa(); track e.clave) { <mat-option [value]="e.clave">{{ e.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
}
@if (estimadoresEtapa().length > 1) {
<span id="analisis-estimador" class="etiqueta">Estimador</span>
<mat-button-toggle-group aria-labelledby="analisis-estimador" hideSingleSelectionIndicator [value]="pedido()!.estimador" (change)="cambiar({ estimador: $event.value })">
@for (e of estimadoresEtapa(); track e.clave) { <mat-button-toggle [value]="e.clave" [attr.title]="e.nota">{{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }}</mat-button-toggle> }
</mat-button-toggle-group>
} @else { <span class="etiqueta">Kaplan-Meier</span> }
</div>
@if (escenario(); as e) {
<p class="contexto">@if (etapa(); as et) { <strong>{{ et.pregunta }}</strong><br> }{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
}
<div class="subsecciones" role="tablist" aria-label="Partes del análisis" (keydown)="teclaVista($event)">
@for (v of VISTAS; track v.id) {
<button type="button" role="tab" [id]="'analisis-tab-' + v.id" [attr.aria-controls]="'analisis-' + v.id" [attr.aria-selected]="vista() === v.id"
[tabIndex]="vista() === v.id ? 0 : -1" (click)="elegirVista(v.id)">{{ v.etiqueta }}</button>
}
</div>
<!-- Curves: two or more values of one variable, compared by log-rank and Cox. -->
<section id="analisis-curvas" role="tabpanel" aria-labelledby="analisis-tab-curvas" [hidden]="vista() !== 'curvas'">
<div class="controles-panel">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Comparar por</mat-label>
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
@for (v of variablesEtapa(); track v.clave) {
<mat-option [value]="v.clave">{{ v.etiqueta }}@if (v.estado === 'supuesto') { <span class="motivo"> · supuesto</span> }</mat-option>
}
</mat-select>
</mat-form-field>
@if (variableCurvas(); as v) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Grupos a comparar</mat-label>
<mat-select multiple [value]="gruposMostrados()" (selectionChange)="elegirGrupos($event.value)">
@for (o of v.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
}
@if (pocosGrupos()) { <span class="aviso-grupos" role="alert">Elija al menos dos grupos para comparar.</span> }
</div>
@switch (resultados().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
}
@if (res(); as r) {
<p class="resumen" role="status">
@if (r.poblacion.n !== null) { {{ miles(r.poblacion.n) }} pacientes · {{ miles(r.poblacion.eventos ?? 0) }} eventos }
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
</p>
@if (r.supuestos.length) {
<div class="supuestos" role="note"><strong>Datos supuestos en el mock.</strong>
<ul>@for (t of r.supuestos; track t) { <li>{{ t }}</li> }</ul></div>
}
<div class="paneles">
<article class="panel ancho">
<h2>{{ nombreMedida() }} a {{ meses(r.horizonte_dias) }} meses por {{ variableCurvas()?.etiqueta?.toLowerCase() }}</h2>
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una curva para ver sus pacientes en Seguimiento.</p>
@if (figuraCurvas().data.length) {
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
[label]="nombreMedida() + ' por ' + (variableCurvas()?.etiqueta ?? 'grupo')" />
<table class="riesgo">
<caption>Pacientes en riesgo</caption>
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }<th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<tbody>
@for (f of r.tabla_riesgo.filas; track f.grupo) {
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }
<td><button type="button" class="ver" (click)="verGrupo(f.grupo)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(f.grupo) + ' en Seguimiento'">Ver pacientes</button></td></tr>
}
</tbody>
</table>
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con esta selección.</p> }
@if (suprimidos().length) { <p class="nota">Grupos suprimidos: {{ textoSuprimidos() }}.</p> }
<p class="nota">La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.</p>
@for (a of r.avisos.slice(2); track a) { <p class="nota">{{ a }}</p> }
</article>
<article class="panel">
<h2>Comparación entre grupos</h2>
@if (r.pruebas.logrank; as lr) {
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
@if (r.pruebas.pares.length > 1) {
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
</table>
}
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
@if (r.pruebas.rmst.length) {
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
}</tbody>
</table>
}
</article>
<article class="panel">
<h2>Razón de riesgos (Cox)</h2>
@if (r.efectos.estado === 'listo') {
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
<p class="nota">Modelo de Cox de una variable ({{ variableCurvas()?.etiqueta?.toLowerCase() }}), contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
} @else {
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
}
</article>
</div>
}
</section>
<!-- Heatmap: two distinct variables of the stage, each tested plain and at equal value of the other. -->
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
@if (cruce(); as x) {
<div class="controles-panel">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Filas</mat-label>
<mat-select [value]="x.filas" (selectionChange)="cruzar({ filas: $event.value })">
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.columnas">{{ v.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Columnas</mat-label>
<mat-select [value]="x.columnas" (selectionChange)="cruzar({ columnas: $event.value })">
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.filas">{{ v.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
</div>
}
<div class="paneles">
<article class="panel ancho">
<h2>{{ nombreMedida() }} a {{ meses(c.horizonte_dias) }} meses@if (sub(); as s) { por {{ s.dimension_filas.etiqueta.toLowerCase() }} y {{ s.dimension_columnas.etiqueta.toLowerCase() }} }</h2>
@switch (subgrupos().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa de calor" /> }
@case ('error') { <div role="alert"><p>{{ $any(subgrupos()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarSubgrupos(true)">Reintentar consulta</button></div> }
}
@if (sub(); as s) {
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus pacientes en Seguimiento.</p>
@if (s.supuestos.length) { <p class="nota">Supuesto en el mock: {{ s.supuestos.join(' ') }}</p> }
<app-plotly-chart [style.--plot-height]="figuraSubgrupos().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraSubgrupos()" (plotClick)="clicCelda($event)"
[label]="nombreMedida() + ' por ' + s.dimension_filas.etiqueta + ' y ' + s.dimension_columnas.etiqueta" />
<p class="nota">Cada celda dice el porcentaje, los eventos y las pacientes. Una celda gris tiene menos de {{ s.umbral_supresion }} pacientes o eventos. «A N meses» marca una celda cuya curva termina antes del horizonte.</p>
<table>
<caption>Log-rank de cada variable</caption>
<thead><tr><th scope="col">Variable</th><th scope="col">Log-rank</th><th scope="col">Estratificado por la otra</th></tr></thead>
<tbody>@for (pr of s.pruebas; track pr.variable) {
<tr><td>{{ pr.etiqueta }}</td>
<td>{{ pr.logrank ? 'χ² ' + pr.logrank.chi2.toLocaleString('es-MX') + ', ' + pr.logrank.gl + ' gl, p ' + formatoP(pr.logrank.p) : 'Menos de dos grupos con eventos suficientes' }}</td>
<td>{{ pr.estratificado ? 'p ' + formatoP(pr.estratificado.p) + ' (por ' + pr.etiqueta_estrato.toLowerCase() + ')' : '—' }}</td></tr>
}</tbody>
</table>
<p class="nota">El log-rank estratificado compara los grupos de una variable dentro de cada valor de la otra: si la diferencia desaparece, la explicaba la otra variable.</p>
}
</article>
</div>
</section>
<!-- Diagnostics: the statistical status of the cohort and the checks behind every figure. -->
<section id="analisis-diagnostico" role="tabpanel" aria-labelledby="analisis-tab-diagnostico" [hidden]="vista() !== 'diagnostico'">
@if (res(); as r) {
<div class="estado-cohorte">
<div class="dato"><span class="cifra">{{ r.poblacion.n === null ? 'Oculto' : miles(r.poblacion.n) }}</span><span>pacientes en la población</span></div>
<div class="dato"><span class="cifra">{{ r.poblacion.eventos === null ? 'Oculto' : miles(r.poblacion.eventos) }}</span><span>eventos en {{ meses(r.horizonte_dias) }} meses</span></div>
<div class="dato"><span class="cifra">{{ r.poblacion.seguimiento_mediano_dias === null ? 'Sin dato' : meses(r.poblacion.seguimiento_mediano_dias) + ' meses' }}</span><span>seguimiento mediano</span></div>
<div class="dato"><span class="cifra">{{ eventosPorParametro() ?? '—' }}</span><span>eventos por parámetro (mínimo 10)</span></div>
<div class="dato"><span class="cifra">{{ r.umbral_supresion }}</span><span>umbral de supresión</span></div>
</div>
@if (r.poblacion.totales_ocultos) { <p class="nota">Los totales se ocultan porque un grupo está suprimido y se podría deducir.</p> }
<article class="panel">
<h2>Reporte de validación</h2>
<p class="nota">De las curvas: {{ escenario()?.etiqueta?.toLowerCase() }}, por {{ variableCurvas()?.etiqueta?.toLowerCase() }}.</p>
<table class="validacion">
<thead><tr><th scope="col">Chequeo</th><th scope="col">Alcance</th><th scope="col">Valor</th><th scope="col">Umbral</th><th scope="col">Resultado</th><th scope="col">Nota</th></tr></thead>
<tbody>@for (v of r.validacion; track $index) {
<tr [class.falla]="v.aprobado === false">
<td>{{ v.chequeo }}</td><td>{{ v.escopo }}</td>
<td>{{ v.p !== null ? 'p ' + formatoP(v.p) : v.estadistico !== null ? v.estadistico.toLocaleString('es-MX') : '—' }}</td>
<td>{{ v.umbral === null ? '—' : v.umbral.toLocaleString('es-MX') }}</td>
<td>{{ v.aprobado === null ? 'No aplica' : v.aprobado ? 'Cumple' : 'No cumple' }}</td>
<td>{{ v.nota ?? '' }}</td>
</tr>
}</tbody>
</table>
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
</article>
}
@if (etapa(); as et) {
<article class="panel requeridas">
<h2>Variables de la NOM para la etapa de {{ et.etiqueta.toLowerCase() }}</h2>
<p class="nota">Lo que hay que registrar para estratificar estas curvas, ajustar Cox y aplicar el log-rank. Las de esta etapa:
@for (v of variablesEtapa(); track v.clave) { {{ v.etiqueta }} ({{ v.estado === 'registrado' ? 'registrada' : 'supuesta' }}){{ $last ? '.' : ';' }} }</p>
<table>
<thead><tr><th scope="col">Variable</th><th scope="col">NOM</th><th scope="col">En el esquema</th></tr></thead>
<tbody>@for (v of et.requeridas; track v.variable) {
<tr [class.falta]="v.estado !== 'registrado'"><td>{{ v.variable }}</td><td>{{ v.nom }}</td><td>{{ v.estado }}</td></tr>
}</tbody>
</table>
</article>
}
<section class="pendientes" aria-labelledby="analisis-pendientes">
<h2 id="analisis-pendientes">Lo que la cohorte aún no permite</h2>
<div class="tarjetas">
@for (b of c.bloqueados; track b.clave) { <article class="bloqueado"><h3>{{ b.titulo }}</h3><p>{{ b.motivo }}</p></article> }
</div>
</section>
</section>
}
`,
styles: `
:host { display: block; min-width: 0; }
/* Positioned so the absolutely placed visually-hidden labels belong to this view: otherwise they are laid out against the document and give it a vertical scroll of its own. */
.analisis { position: relative; display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.analisis > * { margin: 0; }
/* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */
:host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.controles mat-form-field { min-width: 12rem; }
.controles mat-form-field:first-child { min-width: 20rem; }
.contexto, .resumen { margin: var(--issste-space-3) 0 0; font: var(--mat-sys-body-medium); color: var(--issste-text); }
.resumen { margin: 0 0 var(--issste-space-4); color: var(--issste-text-secondary); }
.motivo, .nota, .etiqueta { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2, h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-4); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; }
input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
/* The live region stays in the page, so what is written into it is announced; empty, it takes no room. */
.aviso { padding: var(--issste-space-2) var(--issste-space-3); border-left: 4px solid var(--issste-accent); font: var(--mat-sys-body-medium); }
.aviso:empty { padding: 0; border: 0; margin: 0; }
.panel.ancho { grid-column: 1 / -1; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
p { margin: var(--issste-space-3) 0 0; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
.tabla-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
table { width: 100%; margin-top: var(--issste-space-4); border-collapse: collapse; font: var(--mat-sys-body-medium); }
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
td:nth-child(2) { font-variant-numeric: tabular-nums; }
td:last-child { min-width: 11rem; }
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.riesgo td { text-align: right; font-variant-numeric: tabular-nums; }
.validacion tr.falla td { font-weight: 600; }
.estado-modelo { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
.estado-modelo.insuficiente { border-style: solid; }
.pendientes { margin-top: var(--issste-space-6); }
.tarjetas { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.bloqueado { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); background: transparent; }
.bloqueado h3 { margin: 0; font: var(--mat-sys-title-small); }
.epidemiologicos { margin-bottom: var(--issste-space-6); }
.epidemiologicos .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); grid-auto-rows: 1fr; gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.controles-panel { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
.controles-panel mat-form-field { min-width: 14rem; }
.ver { padding: 0; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.aviso-grupos { color: var(--issste-text); font-weight: 600; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@media (max-width: 600px) { .panel { padding: var(--issste-space-4); } .controles label, .controles input { width: 100%; } }
.subsecciones { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin: var(--issste-space-4) 0; border-bottom: 1px solid var(--issste-border); }
.subsecciones button { padding: var(--issste-space-2) var(--issste-space-4); border: 0; border-bottom: 3px solid transparent; background: none; color: var(--issste-text-secondary);
font: var(--mat-sys-title-small); cursor: pointer; min-height: 44px; }
.subsecciones button[aria-selected='true'] { color: var(--issste-text); border-bottom-color: var(--issste-accent); }
.subsecciones button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.supuestos { margin: 0 0 var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border-left: 4px solid var(--issste-accent);
background: var(--issste-surface); color: var(--issste-text); font: var(--mat-sys-body-medium); }
.supuestos ul { margin: var(--issste-space-1) 0 0; padding-left: var(--issste-space-6); }
.requeridas { margin-top: var(--issste-space-6); }
.requeridas tr.falta td:last-child { font-weight: 600; }
.comparacion { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 960px) { .comparacion { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.estado-cohorte { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: var(--issste-space-4); margin-bottom: var(--issste-space-4); }
.dato { display: flex; flex-direction: column; gap: var(--issste-space-1); padding: var(--issste-space-4); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.dato .cifra { color: var(--issste-text); font-size: 1.5rem; font-weight: 500; line-height: 1.2; }
@media (max-width: 600px) { .controles { padding: var(--issste-space-3); } .controles mat-form-field, .controles mat-form-field:first-child { min-width: 100%; } }
`,
})
export class IndicadoresAnalisis {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The patients of a group, for the page to open them in Seguimiento.
// The patients of a curve or a heatmap cell, for the page to open them in Seguimiento.
readonly verPacientes = output<SeleccionPacientes>();
readonly formatoP = formatoP;
readonly miles = (v: number) => v.toLocaleString('es-MX');
readonly etiqueta = etiquetaBirads;
readonly motivo = MOTIVO_GRUPO_SUPRIMIDO;
readonly hoy = hoyIso();
readonly meses = mesesDe;
readonly VISTAS = VISTAS;
private readonly service = inject(AnalisisService);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly pedidos = new Subject<string>();
readonly catalogo = signal<Carga<AnalisisCatalogo>>({ estado: 'cargando' });
readonly resultados = signal<Carga<AnalisisResultados>>({ estado: 'cargando' });
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
readonly indicadores = signal<Carga<AnalisisIndicadores>>({ estado: 'cargando' });
readonly pedido = signal<AnalisisPedido | undefined>(undefined);
readonly cruce = signal<{ filas: string; columnas: string } | undefined>(undefined);
readonly vista = signal<VistaAnalisis>('curvas');
readonly pocosGrupos = signal(false);
private readonly pedidos = new Subject<AnalisisPedido>();
private readonly pedidosSubgrupos = new Subject<PedidoSubgrupos>();
private readonly catalogos = new Subject<void>();
private readonly pedidosIndicadores = new Subject<void>();
private abierto = false;
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; });
// How many categories the answer publishes; the rest are suppressed. Counts categories only, never patients.
readonly publicadas = computed(() => this.datos()?.grupos.filter(g => !g.suprimido).length ?? 0);
// The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published.
readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido));
readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; });
private subgruposDe?: string;
readonly cat = computed(() => { const c = this.catalogo(); return c.estado === 'listo' ? c.datos : undefined; });
readonly res = computed(() => { const r = this.resultados(); return r.estado === 'listo' ? r.datos : undefined; });
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
readonly ind = computed(() => { const i = this.indicadores(); return i.estado === 'listo' ? i.datos : undefined; });
readonly escenario = computed(() => this.cat()?.escenarios.find(e => e.clave === this.pedido()?.escenario));
readonly estimadorElegido = computed(() => this.cat()?.estimadores.find(e => e.clave === this.pedido()?.estimador));
readonly etapa = computed(() => { const c = this.cat(); return c ? etapaDe(c, this.pedido()?.escenario) : undefined; });
readonly nombreMedida = computed(() => nombreMedida(this.etapa()?.medida ?? 'incidencia'));
readonly variablesEtapa = computed(() => (this.etapa()?.variables ?? [] as readonly string[])
.map(k => this.cat()?.variables.find(v => v.clave === k)).filter((v): v is AnalisisVariable => !!v));
readonly escenariosEtapa = computed(() => this.cat()?.escenarios.filter(e => this.etapa()?.escenarios.includes(e.clave)) ?? []);
readonly estimadoresEtapa = computed(() => this.cat()?.estimadores.filter(e => this.etapa()?.estimadores.includes(e.clave)) ?? []);
readonly variableCurvas = computed(() => this.variablesEtapa().find(v => v.clave === this.pedido()?.estrato));
// Every value when none was picked; the selector shows them checked.
readonly gruposMostrados = computed(() => { const p = this.pedido(); return p?.grupos.length ? p.grupos : this.variableCurvas()?.opciones.map(o => o.codigo) ?? []; });
readonly suprimidos = computed(() => this.res()?.grupos.filter(g => g.suprimido) ?? []);
readonly textoSuprimidos = computed(() => this.suprimidos().map(g => `${g.etiqueta} (${(g.motivo ?? 'suprimido').toLowerCase()})`).join('; '));
readonly figuraCurvas = computed(() => { const r = this.res(); return r ? curvasFigura(r, this.tema()) : { data: [], layout: {} }; });
readonly figuraForest = computed(() => { const r = this.res(); return r ? forestFigura(r, this.tema()) : { data: [], layout: {} }; });
readonly figuraSubgrupos = computed(() => { const s = this.sub(); return s ? subgruposFigura(s, this.tema()) : { data: [], layout: {} }; });
readonly eventosPorParametro = computed(() => {
const fila = this.res()?.validacion.find(v => v.chequeo === 'Eventos por parámetro');
return fila?.estadistico == null ? null : fila.estadistico.toLocaleString('es-MX');
});
constructor() {
const destroy = inject(DestroyRef);
const cargar = (corte: string): Observable<Carga<AnalisisAgregado>> => {
let fuente: Observable<AnalisisAgregado>;
try { fuente = this.service.agregado(this.dominio(), corte); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); }
return fuente.pipe(
map((datos): Carga<AnalisisAgregado> => ({ estado: 'listo', datos })),
catchError(error => of(this.fallo(error))),
startWith<Carga<AnalisisAgregado>>({ estado: 'cargando' }));
};
this.pedidos.pipe(switchMap(cargar), takeUntilDestroyed(destroy)).subscribe(c => { this.aviso.set(''); this.carga.set(c); });
const cargar = <T>(fuente: () => Observable<T>, pendiente = false) => fuente().pipe(
map((datos): Carga<T> => ({ estado: 'listo', datos })),
catchError(error => of<Carga<T>>(pendiente && error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
startWith<Carga<T>>({ estado: 'cargando' }));
this.catalogos.pipe(switchMap(() => cargar(() => this.service.catalogo(this.dominio()), true)), takeUntilDestroyed(destroy)).subscribe(carga => {
this.catalogo.set(carga);
if (carga.estado === 'listo' && !this.pedido()) {
this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
this.cargarIndicadores();
}
});
this.pedidos.pipe(switchMap(p => cargar(() => this.service.resultados(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.resultados.set(c));
this.pedidosSubgrupos.pipe(switchMap(p => cargar(() => this.service.subgrupos(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.subgrupos.set(c));
this.pedidosIndicadores.pipe(switchMap(() => cargar(() => this.service.indicadores(this.dominio()))), takeUntilDestroyed(destroy)).subscribe(c => this.indicadores.set(c));
// The grid follows the stage, the scenario, the estimator and its two variables; it is asked for when its part is open.
effect(() => {
const vista = this.vista(), pedido = this.pedido(), cruce = this.cruce();
if (vista === 'subgrupos' && pedido && cruce) untracked(() => this.cargarSubgrupos());
});
effect(() => {
if (!this.active() || this.abierto) return;
untracked(() => { this.abierto = true; this.consultar(); });
untracked(() => { this.abierto = true; this.catalogos.next(); });
});
}
private fallo(error: unknown): Carga<AnalisisAgregado> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la fecha de corte. Revisa la fecha.' };
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
}
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
cambiar(cambio: Partial<AnalisisPedido>) {
const pedido: AnalisisPedido = { escenario: '', estimador: '', estrato: '', grupos: [], filtros: {}, ...this.pedido(), ...cambio };
this.pedido.set(pedido);
this.pocosGrupos.set(false);
const etapa = this.cat() && etapaDe(this.cat()!, pedido.escenario);
if (etapa) this.cruce.set(cruceDeEtapa(etapa, this.cruce()));
this.pedidos.next(pedido);
}
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.pedidos.next(this.corte);
// A stage keeps the estimator when it admits it, and starts from its first scenario and variable.
elegirEtapa(clave: string) {
const c = this.cat();
if (c && clave !== this.etapa()?.clave) this.cambiar(pedidoDeEtapa(c, clave, this.pedido()));
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
// A click on a published bar is the same as its «Ver pacientes» button; a suppressed bar does nothing.
clicGrupo(evento: unknown) {
const codigo = grupoDelClic(evento, this.datos());
if (!codigo) return;
const fila = Array.from(this.host.nativeElement.querySelectorAll<HTMLElement>('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo);
this.verGrupo(codigo, fila?.querySelector<HTMLElement>('button.ver') ?? this.host.nativeElement.querySelector<HTMLElement>('.plot-viewport'));
estratificar(estrato: string) { this.cambiar({ estrato, grupos: [] }); }
// Two or more values are compared; with all of them checked, the request names none.
elegirGrupos(grupos: string[]) {
if (grupos.length < 2) { this.pocosGrupos.set(true); return; }
const todos = this.variableCurvas()?.opciones.length ?? 0;
this.cambiar({ grupos: grupos.length === todos ? [] : grupos });
}
// The patients of a published group: the page opens them in Seguimiento. Where the user was is kept for the way back.
verGrupo(codigo: string, origen?: EventTarget | null) {
const d = this.datos();
if (!d) return;
this.aviso.set(motivoSinLista(d, codigo) ?? '');
const seleccion = seleccionDeGrupo(d, codigo);
if (!seleccion) return;
const el = origen instanceof HTMLElement ? origen : null;
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
cruzar(cambio: Partial<{ filas: string; columnas: string }>) {
const actual = this.cruce();
if (!actual) return;
const siguiente = { ...actual, ...cambio };
if (siguiente.filas !== siguiente.columnas) this.cruce.set(siguiente);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
if (!r) return;
if (r.area.isConnected) r.area.scrollTop = r.arriba;
(r.origen?.isConnected ? r.origen : this.host.nativeElement.querySelector<HTMLElement>('input[name="corte"]'))?.focus({ preventScroll: true });
this.retorno = undefined;
infoIndicador(x: IndicadorEpidemiologico) {
if (x.suprimido) return x.descripcion;
const intervalo = x.ic_bajo !== null && x.ic_alto !== null ? `IC 95 %: ${x.ic_bajo.toLocaleString('es-MX')} a ${x.ic_alto.toLocaleString('es-MX')} %. ` : '';
const conteo = x.clave === 'adherencia' ? `${this.miles(x.eventos!)} de ${this.miles(x.n!)} pacientes. ` : `${this.miles(x.eventos!)} eventos en ${this.miles(x.n!)} pacientes. `;
return intervalo + conteo + x.descripcion + (x.supuesto ? ' ' + x.supuesto : '');
}
clicCurva(evento: unknown) {
const grupo = grupoDelClic(evento);
if (grupo) this.verGrupo(grupo);
}
verGrupo(grupo: string) {
const c = this.cat(), p = this.pedido(), seleccion = c && p ? seleccionDeCurva(c, p, grupo) : undefined;
if (seleccion) this.verPacientes.emit(seleccion);
}
clicCelda(evento: unknown) {
const celda = celdaDelClic(evento), c = this.cat(), s = this.sub();
const seleccion = celda && c && s ? seleccionDeCelda(c, s, celda) : undefined;
if (seleccion) this.verPacientes.emit(seleccion);
}
elegirVista(vista: VistaAnalisis) { this.vista.set(vista); }
teclaVista(event: KeyboardEvent) {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
event.preventDefault();
const i = VISTAS.findIndex(v => v.id === this.vista());
const j = event.key === 'Home' ? 0 : event.key === 'End' ? VISTAS.length - 1 : (i + (event.key === 'ArrowRight' ? 1 : -1) + VISTAS.length) % VISTAS.length;
this.vista.set(VISTAS[j].id);
(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>('[role="tab"]')[j]?.focus();
}
cargarSubgrupos(forzar = false) {
const p = this.pedido(), x = this.cruce();
if (!p || !x) return;
const pedido = { escenario: p.escenario, estimador: p.estimador, ...x };
const clave = JSON.stringify(pedido);
if (!forzar && clave === this.subgruposDe) return;
this.subgruposDe = clave;
this.pedidosSubgrupos.next(pedido);
}
cargarIndicadores() { this.pedidosIndicadores.next(); }
etiqueta(grupo: string) { return this.res()?.grupos.find(g => g.grupo === grupo)?.etiqueta ?? grupo; }
reintentar() { const p = this.pedido(); if (p) this.pedidos.next(p); }
reintentarCatalogo() { this.catalogos.next(); }
}
@@ -1,63 +0,0 @@
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { FigureSelection, IndicadorDatos } from './indicadores.models';
const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({
periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
});
const datos = (filas: Record<string, unknown>[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({
id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente',
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [],
grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' },
grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
});
const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
describe('Barras por alteración para C1', () => {
it('solo aplica a C1 con la figura por alteración', () => {
expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true);
expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false);
expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false);
});
it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => {
const result = c1AlterationFigure(datos(), selection);
if (result.status !== 'supported') throw new Error(result.reason);
const [trace] = result.figure.data as Record<string, unknown>[];
expect(result.figure.data.length).toBe(1);
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']);
expect(trace['y']).toEqual([55, 25, 0]);
expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']);
expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]);
expect(result.total).toBe(20);
expect(result.notes).toEqual(['Datos ficticios.']);
expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']);
expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2');
});
it('varios periodos se dibujan lado a lado, uno por serie', () => {
const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' });
const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] };
const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
const traces = result.figure.data as Record<string, unknown>[];
expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']);
expect(traces[0]['y']).toEqual([25, 12.5, 12.5]);
expect(result.figure.layout['showlegend']).toBe(true);
expect(result.total).toBe(28);
expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]);
});
it('un periodo sin niños con EEG bueno no dibuja ceros', () => {
const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection);
if (result.status !== 'supported') throw new Error(result.reason);
expect((result.figure.data[0] as Record<string, unknown>)['y']).toEqual([null, null, null]);
expect(result.total).toBe(0);
});
it('rechaza datos que no son los grupos por alteración de la selección', () => {
expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported');
expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported');
expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported');
});
});
@@ -1,71 +0,0 @@
import { percentNumber } from './indicadores-format';
import { FigureHighlight } from './indicadores-highlight';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with
// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL
// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side.
export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion';
const TOTAL = 'TOTAL';
const ANY_LABEL = 'Alguna alteración';
export type C1AlterationResult = { status: 'unsupported'; reason: string }
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
export function c1AlterationCapability(contract: string, representation: string): boolean {
return contract === 'C1' && representation === C1_ALTERATION_BARS;
}
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
const color = (i: number) => COLORS[i % COLORS.length];
export function c1AlterationFigure(data: IndicadorDatos, selection: FigureSelection): C1AlterationResult {
const unsupported = (reason: string): C1AlterationResult => ({ status: 'unsupported', reason });
if (!c1AlterationCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
if (data['estrato'] != null) return unsupported('Esta figura no admite una dimensión');
const periods = selection.periodos ? data.periodos.filter(p => selection.periodos!.includes(p)) : data.periodos;
if (!periods.length) return unsupported('No hay periodos publicados para esta selección');
const published = data['grupos'];
const groups = Object.entries(published && typeof published === 'object' ? published : {}).filter(([id]) => id !== TOTAL);
if (!groups.length) return unsupported('El indicador no publica grupos por alteración');
const bars = [{ id: TOTAL, label: ANY_LABEL }, ...groups.map(([id, label]) => ({ id, label: String(label) }))];
const cells = periods.map(period => bars.map(bar =>
data.filas.filter(r => r['periodo'] === period && r['grupo'] === bar.id && r['estrato'] == null)));
if (cells.some(row => row.some(found => found.length !== 1))) return unsupported('Grupos por alteración incompletos');
const rows = cells.map(row => row.map(([r]) => r));
if (rows.some(row => row.some(r => (r['suprimido'] !== 0 && r['suprimido'] !== false)
|| !count(r['numerador']) || !count(r['denominador']) || r['numerador'] > r['denominador'])))
return unsupported('Conteos por alteración suprimidos o no verificables');
const theme = c2Theme(selection.tema);
const x = bars.map(b => escape(b.label));
const single = periods.length === 1;
const traces = rows.map((row, p) => {
const y = row.map(r => (r['denominador'] as number) ? 100 * (r['numerador'] as number) / (r['denominador'] as number) : null);
return { type: 'bar', name: periods[p], x, y,
marker: { color: single ? bars.map((_, i) => color(i)) : color(p), line: { color: theme.background, width: 1 } },
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
customdata: row.map(r => [r['numerador'], r['denominador']]),
hovertemplate: '%{x}' + (single ? '' : ', %{fullData.name}') + '<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} niños)<extra></extra>' };
});
const figure: PlotlyFigure = {
data: traces,
layout: { autosize: true, height: 400, barmode: 'group', margin: { t: 56, l: 72, r: 24, b: single ? 64 : 96 }, showlegend: !single,
legend: { orientation: 'h', y: -0.3, itemclick: false, itemdoubleclick: false },
title: { text: escape(String(data['titulo'] ?? data.id)) + (single ? ', ' + periods[0] : '') },
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
xaxis: { type: 'category', title: { text: 'Alteración del EEG' }, automargin: true },
yaxis: { title: { text: '% de niños con EEG de buena calidad' }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
config: { displayModeBar: false },
};
const highlight: FigureHighlight = { groups: [], traces: traces.map((_, t) => t), allLabel: 'Todas las alteraciones',
items: bars.map((b, i) => ({ id: b.id, label: b.label, color: single ? color(i) : theme.line,
points: traces.map((_, t) => ({ trace: t, index: i })) })) };
// Children with a first good EEG over the periods drawn: zero means there is nothing to draw a share of.
const total = rows.reduce((sum, row) => sum + (row[0]['denominador'] as number), 0);
return { status: 'supported', figure, highlight, total, notes: Array.isArray(data.notas) ? [...data.notas] : [] };
}
@@ -149,19 +149,6 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2);
expect(graficas()).toHaveLength(3);
});
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
montar(false);
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
expect(notas).toHaveLength(2);
for (const nota of notas) {
expect(nota.open).toBe(false);
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
expect(nota.querySelector('p')!.textContent).toContain('Datos suprimidos, sombreados en la figura: 2025 S1.');
}
notas[0].open = true;
expect(notas[0].open).toBe(true);
expect(notas[1].open).toBe(false);
});
});
describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
@@ -259,18 +259,13 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(ids).toContain('cama_birads_456_mastografia');
expect(fixture.nativeElement.querySelector('.catalog-grid').textContent).not.toContain('Distribución de resultados de biopsia');
});
it('la cabecera de CaMa dice «Cáncer de mama», sin subtítulo superior, y el bloque de filtros queda simplificado', () => {
it('los rótulos de CaMa dicen «cáncer de mama»', () => {
load(KPI_BY_DOMAIN.cama);
const text = fixture.nativeElement.textContent as string;
expect(fixture.nativeElement.querySelector('#dashboard-title').textContent.trim()).toBe('Cáncer de mama');
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
expect(text).not.toContain('Cáncer de mama, investigación');
expect(text).toContain('Cáncer de mama, investigación');
expect(text).toContain('Explora los indicadores de cáncer de mama.');
expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros generales');
expect(fixture.nativeElement.querySelector('.global-filters .section-description')).toBeNull();
expect(text).not.toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
expect(text).not.toContain('Filtro general aplicado');
expect(text).not.toContain('Existe reporte en al menos un indicador del dominio.');
expect(text).toContain('Filtros generales de cáncer de mama');
expect(text).toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
});
it('Disponible queda visualmente oculto y sigue en un único estado accesible en CaMa', () => {
const card = TestBed.createComponent(IndicadorKpiCard);
@@ -318,8 +313,7 @@ describe('Filtros generales de CaMa: periodo único', () => {
expect(text).not.toContain('Modalidad');
expect(text).not.toContain('Selección en edición');
expect(text).not.toContain('Sin cambios pendientes');
expect(text).not.toContain('Filtro general aplicado');
expect(text).not.toContain('Existe reporte en al menos un indicador del dominio.');
expect(text).toContain('Filtro general aplicado: 2025-S2. Existe reporte en al menos un indicador del dominio.');
});
it('elegir otro periodo deja un solo periodo en el borrador y avisa que hay cambios sin aplicar', () => {
// Fails if the control keeps more than one period, or if the pending notice is lost.
@@ -346,4 +340,10 @@ describe('Filtros generales de CaMa: periodo único', () => {
expect(control.canApply).toBe(false);
expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.');
});
it('los demás dominios usan la misma selección de un periodo, sin la fila compacta', () => {
// Every domain selects one period; fails if the compact row of CaMa leaks to CaCu or TEA.
mount(false, { mode: 'todos' }, { mode: 'todos' });
expect(labels()).toEqual(['Intervalo de análisis', 'Periodo seleccionado']);
expect(fixture.nativeElement.querySelector('.fields.compact')).toBeNull();
});
});
@@ -105,12 +105,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
expect(titles()).toEqual(before);
});
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => {
// Fails if CaMa's simplified section leaks into the other domains.
it.each(['tea', 'cacu'] as const)('%s conserva el selector de indicadores y los fijados desde cinco indicadores', domain => {
// Fails if CaMa's simplified section leaks into the other domains. In every domain the cards carry no
// representation selector or figure count, and there is no floating navigation: the selector replaces it.
open(domain, OTRO(domain));
expect(root().querySelector('.catalog-search')).not.toBeNull();
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
expect(section().textContent).toContain('2 figuras publicadas');
expect(root().querySelector('.graphic-navigation-trigger')).toBeNull();
expect(section().textContent).not.toContain('figuras publicadas');
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
});
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
@@ -34,7 +34,7 @@ describe('Cambio de dominio con consultas pendientes', () => {
expect(text()).not.toContain('Indicador de CaMa');
});
it('los controles propios de cada dominio se conservan al ir y volver', () => {
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
// CaCu keeps its search and pins; CaMa, with fewer cards, does not have them; neither state contaminates the other.
const abrir = (d: 'cacu' | 'cama', n: number) => {
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
@@ -44,17 +44,14 @@ describe('Cambio de dominio con consultas pendientes', () => {
abrir('cacu', 6);
expect(el().querySelector('.catalog-search')).not.toBeNull();
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
expect(el().textContent).toContain('Intervalo de análisis');
abrir('cama', 6);
expect(el().querySelector('.catalog-search')).toBeNull();
expect(el().querySelector('.pin-toggle')).toBeNull();
expect(el().textContent).not.toContain('Buscar indicadores');
expect(el().textContent).not.toContain('cacu_');
abrir('cacu', 6);
// On the way back the page state (not only the DOM) says CaCu has its search again.
expect(fixture.componentInstance.dominio).toBe('cacu');
expect(fixture.componentInstance.searchVisible()).toBe(true);
expect(el().textContent).toContain('Intervalo de análisis');
expect(el().textContent).not.toContain('cama_');
});
});
@@ -1,136 +0,0 @@
// Covers how the breast cohort is written for the user (BI-RADS and age groups), that the requests keep the codes, that
// the cut-off the user chose reaches the list, the record and the files, and what the record says of a biopsy whose
// report date is known while its result is not. Fixture: listaCohorte() in indicadores-analisis.testing.ts.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { strFromU8, unzipSync } from 'fflate';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
import { fetchAllTracking, queryOf } from './export/tracking-export-source';
import { trackingDocument } from './export/tracking-pdf';
import { buildTrackingXlsx } from './export/tracking-xlsx';
const CORTE_ELEGIDO = '2026-09-01';
const textos = (nodo: unknown, salida: string[] = []): string[] => {
if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida));
return salida;
};
describe('Etiquetas de la cohorte', () => {
it('escribe las categorías BI-RADS y los grupos de edad como en la clínica, y deja lo demás como llegó', () => {
// Fails if a confirmed code is shown raw, or a code whose meaning is not confirmed is invented.
expect(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'].map(etiquetaBirads)).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO'].map(etiquetaEdad)).toEqual(
['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(etiquetaBirads('BIRADS_7')).toBe('BIRADS_7'); expect(etiquetaEdad('OTRO')).toBe('OTRO');
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
});
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
const r = seguimientoTablaResponse(listaCohorte());
expect(r.filtros_disponibles[0].opciones.map(o => [o.codigo, o.etiqueta]).slice(0, 2)).toEqual([['BIRADS_4', 'BI-RADS 4'], ['BIRADS_4A', 'BI-RADS 4A']]);
expect(r.filtros_disponibles[1].opciones.map(o => o.etiqueta)).toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(r.items[0]).toMatchObject({ birads: 'BI-RADS 5', birads_codigo: 'BIRADS_5', grupo_edad: '50 a 59 años', grupo_edad_codigo: '50-59' });
const histo = listaCohorte();
(histo['items'] as Record<string, unknown>[])[0]['biopsia'] = 'CARCINOMA_INVASOR';
expect(seguimientoTablaResponse(histo).items[0]).toMatchObject({ biopsia: 'Carcinoma invasor', biopsia_codigo: 'CARCINOMA_INVASOR' });
expect(r.filtros).toEqual({ birads: null, grupo_edad: null });
const plana = listaCohorte(); delete plana['cohorte'];
expect(seguimientoTablaResponse(plana).items[0]).toMatchObject({ birads: 'BIRADS_5', grupo_edad: '50-59' });
});
});
describe('La lista de la cohorte con etiquetas legibles y el corte elegido', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('active', false);
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const seleccion = (esperados = 6): SeleccionSeguimiento => ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE_ELEGIDO, esperados, contexto: CONTEXTO, id: 1 });
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const celdas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent!.replace(/\s+/g, ' ').trim()));
it('muestra BI-RADS y grupos de edad legibles en las filas y en los filtros, pero la petición sigue enviando los códigos', async () => {
// Fails if the user reads codes, or a filter chosen by its label is sent as text instead of its code.
fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion()); fixture.detectChanges();
let r = solicitud();
expect(parametros(r)).toMatchObject({ corte: CORTE_ELEGIDO, birads: 'BIRADS_5', meses: '0', ...CONTEXTO });
r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await asentar();
expect(celdas()[1].slice(1, 3)).toEqual(['60 a 69 años', 'BI-RADS 5 Fecha: 2025-02-01']);
expect(root().textContent).not.toMatch(/BIRADS_5|60-69/);
expect([...campo('Grupo de edad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
const s = campo('Grupo de edad').querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === '60 a 69 años')!.value;
s.dispatchEvent(new Event('change')); await asentar();
[...root().querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); fixture.detectChanges();
r = solicitud();
expect(parametros(r)).toMatchObject({ grupo_edad: '60-69', birads: 'BIRADS_5', corte: CORTE_ELEGIDO });
r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5', grupo_edad: '60-69' } }));
});
it('el corte elegido en el análisis llega a la lista, a la ficha y a todas las páginas de la exportación', async () => {
// Fails if the list, the record or a page of the file is read at another cut-off than the one the user chose.
fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion(450)); fixture.detectChanges();
solicitud().flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); await asentar();
// The record, opened from the row that was clicked.
(root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar();
expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE_ELEGIDO}.`);
// The files: every page asks for the same cut-off, and the answer must give it back.
const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 }));
const pedidas: SeguimientoTablaQuery[] = [];
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> => {
pedidas.push(q); return of(seguimientoTablaResponse(listaCohorte({ corte: q.corte, filtros: q.filtros as Record<string, string>, page: q.page, size: q.page_size, n: 450 }))); } } as unknown as SeguimientoTablaService;
expect(queryOf(respuesta)).toMatchObject({ corte: CORTE_ELEGIDO, meses: 0, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
expect(pedidas.map(q => q.corte)).toEqual([CORTE_ELEGIDO, CORTE_ELEGIDO, CORTE_ELEGIDO]);
});
});
describe('Ficha y archivos de una fila con biopsia reportada y resultado desconocido', () => {
const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO }));
const fila = (i: number) => respuesta.items[i];
const NOW = new Date(Date.UTC(2026, 10, 13, 18, 0));
it('la ficha dice «Fecha de reporte», conserva «No disponible» para el resultado, el estatus y la prioridad, y escribe BI-RADS y edad legibles', () => {
// Fails if the date of a biopsy report is called the date of the biopsy, or an unknown result is filled in.
const resumen = toCamaPatientSummary(fila(2), CORTE_ELEGIDO, respuesta.columnas)!;
expect(resumen).toMatchObject({ birads: 'BI-RADS 5', ageGroup: '50 a 59 años', histopathology: null, biopsyDate: '2025-02-15', biopsyDateLabel: 'Fecha de reporte', status: null, priority: null });
TestBed.configureTestingModule({ providers: [provideHttpClient()] });
const card = TestBed.createComponent(CamaPatientCard);
card.componentRef.setInput('summary', resumen); card.detectChanges();
const t = (card.nativeElement.textContent as string).replace(/\s+/g, ' ');
expect(t).toContain('Resultado: No disponible'); expect(t).toContain('Fecha de reporte: 2025-02-15');
expect(t).toContain('Categoría BI-RADS: BI-RADS 5'); expect(t).toContain('50 a 59 años');
expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).toMatch(/Prioridad\s*No disponible/); expect(t).toMatch(/Días de mastografía a diagnóstico\s*No disponible/);
expect(t).not.toContain('Fecha de biopsia');
const pdf = textos(camaPatientDocument(resumen, NOW, 'data:image/png;base64,AAAA'));
expect(pdf).toContain('Fecha de reporte'); expect(pdf).not.toContain('Fecha de biopsia');
// A list whose columns do not rename the date keeps the record's own wording.
expect(toCamaPatientSummary(fila(2), CORTE_ELEGIDO)!.biopsyDateLabel).toBeUndefined();
});
it('los archivos escriben las etiquetas, no los códigos, y la fila con fecha de reporte sin resultado sale con la celda vacía', async () => {
// Fails if a file carries codes the user cannot read, or invents a result for a report whose result is unknown.
const snapshot = { corte: respuesta.corte, ventana: respuesta.ventana, filtros: respuesta.filtros, filtros_disponibles: respuesta.filtros_disponibles, columnas: respuesta.columnas, items: respuesta.items, seleccion: 'Categoría BI-RADS: BI-RADS 5' };
const pdf = textos(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA'));
expect(pdf).toContain('BI-RADS 5'); expect(pdf).toContain('50 a 59 años'); expect(pdf.some(t => /BIRADS_|50-59/.test(t))).toBe(false);
expect(pdf).toContain('Fecha de reporte: 2025-02-15');
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|');
expect(cadenas).toContain('|BI-RADS 5|'); expect(cadenas).toContain('|60 a 69 años|'); expect(cadenas).not.toMatch(/BIRADS_|\|50-59\|/);
expect(cadenas).toContain('Resultado histopatológico: Fecha de reporte');
});
});
@@ -9,11 +9,11 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { GlobalApplied } from './indicadores-memory';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, CONFIRMACION_CAMA, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
periodosConfirmacion, rangoTasas, seleccionBase, seleccionEtiqueta, tasas, vistaConfirmacion, wilson } from './indicadores-confirmacion-citologia';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
@@ -62,7 +62,7 @@ describe('Confirmación histopatológica: modelo', () => {
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
const m = modeloConfirmacion(d, '2026-S2');
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
expect(tasas(m, seleccionBase(m)).map(estadoTasa)).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
expect(tasas(m, seleccionBase(m)).map(t => estadoTasa(t))).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
const s = modeloConfirmacion(d, '2026-S2');
@@ -223,3 +223,65 @@ describe('Confirmación histopatológica: componente', () => {
card.destroy(); http.expectNone(() => true);
});
});
// Cáncer de mama's configuration of the same view. Fixture: a one-period answer of cama_histopatologia_birads
// built below, with two BI-RADS categories published and biopsies without a result kept apart.
describe('Confirmación histopatológica de cáncer de mama', () => {
const categorias = {
BENIGNO: { etiqueta: 'Benigno', color: '#9DBFE3', grupo: 'NO_MALIGNO' }, RIESGO_B3: { etiqueta: 'Lesión de riesgo (B3)', color: '#2F6DB3', grupo: 'NO_MALIGNO' },
IN_SITU: { etiqueta: 'Carcinoma in situ', color: '#D9822B', grupo: 'MALIGNO' }, INVASOR: { etiqueta: 'Carcinoma invasor', color: '#B5482E', grupo: 'MALIGNO' },
SIN_DATO: { etiqueta: 'Sin resultado histopatológico', color: '#BDBDBD', grupo: 'SIN_DATO' },
};
const n: Record<string, Record<string, number>> = {
BIRADS_5: { BENIGNO: 3, RIESGO_B3: 0, IN_SITU: 11, INVASOR: 38, SIN_DATO: 3 },
BIRADS_4A: { BENIGNO: 91, RIESGO_B3: 15, IN_SITU: 1, INVASOR: 7, SIN_DATO: 9 },
};
const datos = () => ({ id: 'cama_histopatologia_birads', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'birads',
valores_estrato: Object.keys(n), categorias, grupos_de_categoria: { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' },
filas: Object.entries(n).flatMap(([estrato, c]) => Object.entries(c).map(([categoria, v]) =>
({ periodo: '2025-S2', grupo: 'TOTAL', estrato, categoria, n: v, suprimido: 0 }))) }) as IndicadorDatos;
it('la elige el dominio y el indicador', () => {
// Fails if the view stops being found for cáncer de mama, or leaks to another indicator.
expect(vistaConfirmacion('cama', { id: 'cama_histopatologia_birads' })).toBe(CONFIRMACION_CAMA);
expect(vistaConfirmacion('cama', { id: 'cacu_confirmacion_citologia' })).toBeUndefined();
});
it('filas BI-RADS de la más grave a la menor, base maligna y sin resultado aparte', () => {
// Fails if the rows don't follow the configuration, the base isn't malignancy or «Sin dato» enters the rate.
const m = modeloConfirmacion(datos(), '2025-S2', CONFIRMACION_CAMA), base = seleccionBase(m);
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_6', 'BIRADS_5', 'BIRADS_4C', 'BIRADS_4B', 'BIRADS_4A']);
expect(base).toEqual({ grupo: 'MALIGNO' });
expect(lectura(m, base)).toBe('Detección de cáncer (valor predictivo positivo)');
const t = tasas(m, base);
expect(t[1].k).toBe(49); expect(t[1].fila.den).toBe(52);
expect(t[4].k).toBe(8); expect(t[4].fila.den).toBe(114);
expect(estadoTasa(t[0], m.vista.textos.sujetos)).toBe('Sin pacientes con biopsia');
});
});
describe('Dona interactiva como la de CaCu (sin botones)', () => {
const vista = { ...CONFIRMACION_CAMA, id: 'cacu_confirmacion_citologia', estrato: 'citologia_alto_grado' as const, filas: CONFIRMACION_CACU.filas, base: 'LIEAG' };
const modelo = () => modeloConfirmacion(respuesta(), '2026-S2', vista);
it('total → grupo → resultado y el centro regresa un paso hasta el total', () => {
// Fails if the centre stops returning to the total, or a group click no longer narrows to it.
const m = modelo(), g = m.grupos.findIndex(x => x.id === m.base), c = m.grados.findIndex(x => x.grupo === m.base);
let s = clicDona(m, {}, 'grupos', g); expect(s).toEqual({ grupo: m.base });
s = clicDona(m, s, 'categorias', c); expect(s).toEqual({ grupo: m.base, categoria: m.grados[c].id });
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({ grupo: m.base });
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({});
expect(clicDona(m, { grupo: m.base }, 'grupos', g)).toEqual({});
const otra = m.grados.findIndex(x => x.grupo !== m.base);
expect(clicDona(m, { grupo: m.base }, 'categorias', otra)).toEqual({ grupo: m.base });
});
it('el grupo elegido llena los dos anillos y el total cuenta el grupo base en las tasas', () => {
// Fails if the other group's slices stay (no expansion), or the total stops reading as the base rate.
const m = modelo(), base = m.grupos.find(x => x.id === m.base)!;
const d = donaExpandible(m, { grupo: m.base }, 'claro');
const exterior = d.data[2]['values'] as number[];
m.grados.forEach((g, i) => expect(exterior[i] === 0).toBe(g.grupo !== m.base));
expect((d.data[1]['values'] as number[]).filter(v => v > 0)).toHaveLength(1);
expect(d.data[0]['text']).toEqual([`<b>${base.grados.reduce((s, c) => s + m.totales[c]!, 0)}</b><br>${base.etiqueta}`]);
expect(tasas(m, {}).map(t => t.k)).toEqual(tasas(m, seleccionBase(m)).map(t => t.k));
expect(lectura(m, {})).toBe(vista.textos.base);
});
});
@@ -1,4 +1,4 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
@@ -24,6 +24,36 @@ export const FILAS_CITOLOGIA = [
] as const;
export const Z95 = 1.959963984540054;
// One confirmation view: which indicator and stratum, its fixed rows (most severe on top), the grade whose group is
// the base view (the true positives), the grade read as a false positive, and the words the view uses.
export interface VistaConfirmacion {
id: string; estrato: DimensionEstrato; filas: readonly { id: string; etiqueta: string }[];
base: string; falsoPositivo: string;
// With buttons, the choice is made on them; without, on the donut (donaExpandible), whose centre names it.
botones: boolean;
textos: { base: string; falsoPositivo: string; sinConfirmacion: string; filas: string; encabezado: string; sujetos: string; vacio: string };
}
export const CONFIRMACION_CACU: VistaConfirmacion = {
id: ID_CONFIRMACION, estrato: ESTRATO_CITOLOGIA, filas: FILAS_CITOLOGIA, base: 'LIEAG', falsoPositivo: 'NORMAL', botones: true,
textos: { base: 'Verdaderos positivos (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia no confirmó lesión',
sinConfirmacion: 'Sin confirmación de alto grado', filas: 'Por resultado de la citología', encabezado: 'Citología', sujetos: 'mujeres',
vacio: 'No hay citologías de alto grado publicadas para este periodo.' },
};
// Cáncer de mama: the biopsies by the BI-RADS of the mammogram that led to them; the base is malignancy.
export const CONFIRMACION_CAMA: VistaConfirmacion = {
id: 'cama_histopatologia_birads', estrato: 'birads', base: 'INVASOR', falsoPositivo: 'BENIGNO', botones: false,
filas: [{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6' }, { id: 'BIRADS_5', etiqueta: 'BI-RADS 5' }, { id: 'BIRADS_4C', etiqueta: 'BI-RADS 4C' },
{ id: 'BIRADS_4B', etiqueta: 'BI-RADS 4B' }, { id: 'BIRADS_4A', etiqueta: 'BI-RADS 4A' }],
textos: { base: 'Detección de cáncer (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia resultó benigna',
sinConfirmacion: 'Sin malignidad', filas: 'Por categoría BI-RADS', encabezado: 'BI-RADS', sujetos: 'pacientes',
vacio: 'No hay biopsias publicadas para este periodo.' },
};
const VISTAS_CONFIRMACION: Readonly<Partial<Record<Dominio, VistaConfirmacion>>> = { cacu: CONFIRMACION_CACU, cama: CONFIRMACION_CAMA };
export function vistaConfirmacion(dominio: Dominio, indicador: Pick<Indicador, 'id'>): VistaConfirmacion | undefined {
const vista = VISTAS_CONFIRMACION[dominio];
return vista?.id === indicador.id ? vista : undefined;
}
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
@@ -37,9 +67,10 @@ export interface FilaCitologia {
export interface ModeloConfirmacion {
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; vista: VistaConfirmacion;
}
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
// Without a group, the total: every result is shown and the rates count the base group.
export interface SeleccionConfirmacion { grupo?: string; categoria?: string; }
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
export class ConfirmacionIncompatible extends Error {}
@@ -81,8 +112,8 @@ function rgba(hex: string, alfa: number): string {
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
/** Validated periods of one stratified response, in request order or sorted. */
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[], vista = CONFIRMACION_CACU): string[] {
if (datos.id !== vista.id || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== vista.estrato
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
@@ -93,8 +124,8 @@ export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solici
}
/** One /datos payload -> the contingency table of a single period. */
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): ModeloConfirmacion {
periodosConfirmacion(datos, datos.tipo_periodo);
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista = CONFIRMACION_CACU): ModeloConfirmacion {
periodosConfirmacion(datos, datos.tipo_periodo, undefined, vista);
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
@@ -112,8 +143,8 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
grados: propios.map(g => g.id) };
});
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.');
// The base view is the group of the view's base grade (CaCu: "LIEAG o más"): the true positives.
const base = grados.find(g => g.id === vista.base)?.grupo ?? fail(`El catálogo no publica el grado ${vista.base}.`);
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
const index = new Map<string, Record<string, unknown>>();
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
@@ -128,11 +159,11 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
}
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined;
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos de citología inválidos.');
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos inválidos.');
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
if (!totales.every(registro)) fail('Totales de citología inválidos.');
const filas = FILAS_CITOLOGIA.map(({ id, etiqueta }) => {
if (!totales.every(registro)) fail('Totales por estrato inválidos.');
const filas = vista.filas.map(({ id, etiqueta }) => {
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
@@ -148,15 +179,26 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
return { periodo, grados, grupos, base, filas, totales: porGrado,
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])] };
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])], vista };
}
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.grados ?? [];
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === (sel.grupo ?? m.base))?.grados ?? [];
}
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'Todos los resultados';
}
/** CaCu's interactive donut: a group narrows to it, a result is chosen inside its group, the centre steps back
* (result -> its group -> the total), and choosing the chosen entry again also steps back. */
export function clicDona(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
if (traza === 'grupos') { const g = m.grupos[indice]?.id; return !g ? sel : sel.grupo === g && !sel.categoria ? {} : { grupo: g }; }
if (traza !== 'categorias') return sel;
const c = m.grados[indice];
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
}
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
@@ -169,9 +211,9 @@ export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
}
/** The axis title says what the rate reads. */
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
if (!sel.categoria && sel.grupo === m.base) return 'Verdaderos positivos (valor predictivo positivo)';
if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión';
if (!sel.categoria) return 'Sin confirmación de alto grado';
if (!sel.categoria && (sel.grupo ?? m.base) === m.base) return m.vista.textos.base;
if (sel.categoria === m.vista.falsoPositivo) return m.vista.textos.falsoPositivo;
if (!sel.categoria) return m.vista.textos.sinConfirmacion;
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
}
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
@@ -184,8 +226,8 @@ export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[]
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
});
}
export function estadoTasa(t: Tasa): string {
return t.fila.den === 0 ? 'Sin mujeres con biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
export function estadoTasa(t: Tasa, sujetos = 'mujeres'): string {
return t.fila.den === 0 ? `Sin ${sujetos} con biopsia` : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
}
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
export function rangoTasas(valores: Tasa[]): [number, number] {
@@ -199,14 +241,14 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
const p = c2Theme(tema);
const valores = tasas(m, sel);
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === (sel.grupo ?? m.base))!.color;
const y = valores.map(t => t.fila.etiqueta);
return { data: [{
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
marker: { size: 12, color }, cliponaxis: false,
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
customdata: valores.map(t => t.k === null ? [estadoTasa(t, m.vista.textos.sujetos), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
}], layout: {
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
@@ -215,7 +257,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
font: { size: 12, color: p.text },
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
text: t.k === null ? estadoTasa(t, m.vista.textos.sujetos) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
}, config: { displayModeBar: false } };
}
@@ -227,7 +269,7 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
const exterior = m.grados.map(g => m.totales[g.id]!);
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
@@ -242,3 +284,41 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
/** Donut without buttons, drawn like CaCu's interactive one: the chosen group fills both rings (the other's
* slices are zero, so its results expand), a chosen result keeps its colour and its siblings fade, and the
* centre names the choice. The traces keep their names and counts, so a choice animates. */
export function donaExpandible(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
const p = c2Theme(tema), total = m.conBiopsia;
const nGrupo = (g: GrupoGrados) => g.grados.reduce((s, c) => s + m.totales[c]!, 0);
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(g) : 0);
const exterior = m.grados.map(g => !sel.grupo || sel.grupo === g.grupo ? m.totales[g.id]! : 0);
const centro = sel.categoria ? m.totales[sel.categoria]! : sel.grupo ? nGrupo(m.grupos.find(g => g.id === sel.grupo)!) : total;
const rotulos = (values: number[], labels: string[], pct: boolean) => {
const suma = values.reduce((s, n) => s + n, 0);
return values.map((v, i) => !suma || v / suma < .05 ? '' : escapar(labels[i]) + (pct ? '<br>' + shareText(v, suma) : ''));
};
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'text', textposition: 'inside',
insidetextorientation: 'horizontal' };
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`<b>${miles(centro)}</b><br>${escapar(sel.grupo || sel.categoria ? seleccionEtiqueta(m, sel) : 'Con biopsia')}`],
textfont: { size: 16, color: p.text }, marker: { colors: [p.background] },
hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Todos los resultados') + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
// Outer labels go outside the ring with a leader line, at full size; automargin makes room for them and
// shrinks the three rings together, so they stay concentric.
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.grados.map(g => escapar(g.etiqueta)), textposition: 'outside', automargin: true,
text: exterior.map((v, i) => v ? escapar(m.grados[i].etiqueta) + '<br>' + shareText(v, exterior.reduce((s, n) => s + n, 0)) : ''),
textfont: { size: 12, color: p.text }, customdata: custom(exterior),
marker: { colors: m.grados.map(g => rgba(g.color, sel.categoria && g.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 440, margin: { t: 30, l: 30, r: 30, b: 30 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
@@ -91,49 +91,6 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
});
});
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
type Figura = { data: Record<string, any>[]; layout: { annotations: Record<string, any>[]; margin: Record<string, number>; showlegend: boolean } };
const dona = (compacta = false) => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro', compacta) as unknown as Figura;
// Fails if the long label of the 4 without subcategory goes back inside the ring (where it is cut), loses its
// percentage or its guide line, or if the short labels or the centre total change.
it('2025-S2: la etiqueta larga sale del anillo, horizontal y con línea guía; las cortas y el total se conservan', () => {
const f = dona(), t = f.data[0], llamada = f.layout.annotations[1];
expect(t['text'][0]).toBe('');
expect(t['text'][1]).toBe('');
expect(t['text'][4]).toMatch(/^BI-RADS 5<br>54[.,]5 %$/);
expect(t['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations[0]['text']).toBe('<b>33</b><br>mastografías');
expect(f.layout.annotations).toHaveLength(2);
expect(llamada['text']).toBe('BI-RADS 4<br>(sin subcategoría)<br>45.5 %');
// A guide line: an arrow without head from the label to a point inside the slice, and no text rotation.
expect(llamada['showarrow']).toBe(true);
expect(llamada['arrowhead']).toBe(0);
expect(llamada['textangle']).toBeUndefined();
});
// Fails if the label can reach the neighbouring chart: its side must keep a margin, and it sits on the side of its slice.
it('reserva espacio del lado de la etiqueta y la coloca del lado de su segmento', () => {
const f = dona(), llamada = f.layout.annotations[1];
// The slice is 45 % of a clockwise ring: its middle points right, so label and margin are on the right.
expect(llamada['xanchor']).toBe('left');
expect(llamada['ax']).toBeGreaterThan(0);
expect(f.layout.margin['r']).toBeGreaterThanOrEqual(110);
expect(f.layout.margin['l']).toBeLessThan(20);
expect(f.layout.showlegend).toBe(false);
});
// Fails if a narrow screen keeps a label that needs side room instead of moving to a legend under the donut.
it('en pantalla estrecha no hay llamada: la dona usa una leyenda debajo', () => {
const f = dona(true);
expect(f.layout.annotations).toHaveLength(1);
expect(f.layout.showlegend).toBe(true);
expect((f.layout as Record<string, any>)['legend']['orientation']).toBe('h');
expect(f.layout.margin['r']).toBeLessThan(20);
expect(f.data[0]['values']).toEqual([15, 0, 0, 0, 18, 0]);
});
});
describe('Conteos pareados de CaMa: lo que no se calcula', () => {
it('no hay razón de mastografías por paciente en la figura ni en el modelo', () => {
// Fails if a "≈ x por paciente" annotation comes back: exams of a category include those of patients whose
@@ -44,8 +44,6 @@ export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly strin
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
const COLOR_NEUTRO = '#8A9199';
// Labels longer than «BI-RADS 4A» do not fit inside the ring.
const LARGO_ETIQUETA_INTERIOR = 12;
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
@@ -104,49 +102,19 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
// Geometry the callouts rely on. The ring is height-bound (a 400 px figure with a 10 px margin above and below and
// the pie over 90 % of that height), so its radius does not depend on the width of the card.
const ALTO_DONA = 400, MARGEN_VERTICAL = 10, RADIO_DONA = Math.round((ALTO_DONA - 2 * MARGEN_VERTICAL) * .9 / 2);
const MARGEN_ROTULO = 120, SALIDA_ROTULO = 28;
/**
* Exams by category around their total; nothing is drawn when a cell is unknown. A long label does not fit in the
* ring: it is drawn outside, horizontal and on two lines, joined to its slice by a guide line, on the side of the
* slice with room reserved for it so it never reaches the neighbouring chart. On a narrow card (`compacta`) the
* callouts give way to a legend under the donut.
*/
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, compacta = false): PlotlyFigure {
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const total = totalExamenes(m);
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
const larga = (i: number) => m.examenes[i].etiqueta.length > LARGO_ETIQUETA_INTERIOR && n[i] > 0;
const porcentaje = (i: number) => percentNumber(100 * n[i] / total) + ' %';
const dibujadas = (i: number) => !larga(i) && n[i] / total >= .05;
// Each long label is a callout whose guide line ends inside its slice.
let antes = 0;
const llamadas = n.flatMap((v, i) => {
const angulo = 2 * Math.PI * (antes + v / 2) / total;
antes += v;
if (compacta || !larga(i)) return [];
const seno = Math.sin(angulo), coseno = Math.cos(angulo), dentro = Math.round(RADIO_DONA * .8), fuera = RADIO_DONA + SALIDA_ROTULO - dentro;
const etiqueta = escapar(m.examenes[i].etiqueta), corte = etiqueta.indexOf(' (');
return [{ x: .5, y: .5, xref: 'paper', yref: 'paper', xshift: Math.round(dentro * seno), yshift: Math.round(dentro * coseno),
ax: Math.round(fuera * seno), ay: Math.round(-fuera * coseno), axref: 'pixel', ayref: 'pixel', showarrow: true, arrowhead: 0, arrowwidth: 1, arrowcolor: p.text,
text: (corte > 0 ? etiqueta.slice(0, corte) + '<br>' + etiqueta.slice(corte + 1) : etiqueta) + '<br>' + porcentaje(i),
align: seno >= 0 ? 'left' : 'right', xanchor: seno >= 0 ? 'left' : 'right', yanchor: 'middle', font: { size: 12, color: p.text }, lado: seno >= 0 ? 'r' : 'l' }];
});
const lado = (l: string) => llamadas.some(a => a.lado === l) ? MARGEN_ROTULO : 10;
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
text: n.map((_, i) => dibujadas(i) ? escapar(m.examenes[i].etiqueta) + '<br>' + porcentaje(i) : ''),
domain: { x: [0, 1], y: [.05, .95] },
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: compacta ? ALTO_DONA + 40 : ALTO_DONA, showlegend: compacta, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_VERTICAL, b: compacta ? 70 : MARGEN_VERTICAL, l: lado('l'), r: lado('r') },
...(compacta ? { legend: { orientation: 'h', x: .5, xanchor: 'center', y: -.02, yanchor: 'top', font: { size: 12 } } } : {}),
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }, ...llamadas.map(({ lado: _lado, ...a }) => a)] }, config: { displayModeBar: false } };
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
}
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
@@ -0,0 +1,25 @@
import eu7 from './fixtures/eu7-c2-ejemplos.json';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { modelo, vistaEscenario } from './indicadores-eu7-escenario';
// Covers what lets a domain reuse CaCu's interactive donut and bars without code of its own: the view is
// chosen by the catalog's `escenario`. The follow-up list announced by the answer is covered by
// `seguimiento-tabla.service.spec.ts` and `indicadores-seguimiento-tabla.spec.ts`.
// Fixture: `eu7-c2-ejemplos.json` (CaCu's EU7 answers, relabelled here as another stratum).
describe('Vista de dona y barras por estrato', () => {
const item = (extra: Partial<Indicador> = {}): Indicador => ({ id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'], ...extra });
it('la elige el campo escenario del catálogo, y CaCu EU7 la conserva sin él', () => {
// Fails if the view goes back to being recognised by CaCu's indicator id only.
expect(vistaEscenario('cama', item({ escenario: { estrato: 'birads', etiqueta: 'categoría BI-RADS' } }))?.estrato).toBe('birads');
expect(vistaEscenario('cacu', item({ id: 'cacu_eu7' }))?.estrato).toBe('estatus_seguimiento');
expect(vistaEscenario('cama', item())).toBeUndefined();
});
it('arma el modelo con otro indicador y otro estrato', () => {
// Fails if `modelo` checks CaCu's id or its stratum instead of the ones it is given.
const relabel = (d: unknown, estrato: string | null) => ({ ...structuredClone(d) as IndicadorDatos, id: 'cama_histopatologia_birads', ...(estrato ? { estrato } : {}) });
const general = relabel(eu7.general, null), porBirads = relabel(eu7.estatus_seguimiento, 'birads');
expect(modelo(general, porBirads, '2025-S2', 'birads').total).toBe(946);
expect(() => modelo(general, porBirads, '2025-S2')).toThrow();
});
});
@@ -1,11 +1,18 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
// A C2 distribution with category groups, next to the same categories by one stratum. Unknown cells never become zero.
export const ESTRATO = 'estatus_seguimiento';
const SIN_DATO = 'SIN_DATO';
// CaCu's EU7 predates the catalog's `escenario` field.
const EU7: VistaEscenario = { estrato: ESTRATO, etiqueta: 'escenario clínico' };
export function vistaEscenario(dominio: Dominio, indicador: Indicador): VistaEscenario | undefined {
if (indicador.escenario) return indicador.escenario;
return dominio === 'cacu' && indicador.id === 'cacu_eu7' ? EU7 : undefined;
}
export const esEu7 = (vista: VistaEscenario) => vista === EU7;
export interface Seleccion { grupo?: string; categoria?: string; }
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
export interface Grupo { id: string; etiqueta: string; color: string; }
@@ -64,7 +71,7 @@ function catalogo(data: IndicadorDatos): Categoria[] {
/** Validate the common temporal scope before exposing any period's figures. */
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
for (const d of [general, escenarios]) {
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
if (d.id !== general.id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|| new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string'
|| !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
@@ -80,10 +87,10 @@ export function periodosCompatibles(general: IndicadorDatos, escenarios: Indicad
}
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo {
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string, estrato: DimensionEstrato = ESTRATO): Modelo {
periodosCompatibles(general, porEscenario, general.tipo_periodo);
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo)
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== estrato || !general.periodos.includes(periodo)
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
@@ -212,7 +219,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
config: { displayModeBar: false } };
}
/** Selection never changes the original denominator or renormalizes a subset. */
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
export function barras(m: Modelo, sel: Seleccion, tema: Tema, eje = '% de pacientes del escenario con resultado'): PlotlyFigure {
const p = c2Theme(tema);
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
const y = m.escenarios.map(s => escapar(s.etiqueta));
@@ -235,7 +242,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
xaxis: { title: { text: eje }, ticksuffix: ' %', gridcolor: p.grid,
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
File diff suppressed because one or more lines are too long
@@ -1,208 +0,0 @@
// What this module covers: the indicator page and TEA's follow-up over the WebApi's FHIR endpoint. The catalog and
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
// the shapes the page reads and passed through the same checks.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
periodosDesde, Report,
} from './indicadores-fhir';
import * as fx from './indicadores-fhir.fixtures';
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
import { c2Figure } from './indicadores-c2-adapter';
import { datosValidos } from './indicadores.service';
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
import { IndicadorDatos } from './indicadores.models';
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
describe('Indicadores sobre FHIR', () => {
it('el catálogo sale de cada Measure con los ids, contratos, figuras y estratos de la página', () => {
// Pins down: ids with underscores, the contract and figures from the extensions, the age stratum of a C1 and none
// for a C2 (its stratifier holds the categories). Fails if the catalog stops matching the page's TEA ids.
const catalog = resources(fx.measures).map(m => indicadorDeMeasure(m as Measure));
const m21 = catalog.find(i => i.id === 'M21_diagnosticados_con_eeg')!;
expect(m21).toMatchObject({ contrato: 'C1', figuras: ['fig_c1_barras_edad'], tipos_periodo: ['semestre', 'mes'], estratos: ['grupo_edad'], sentido: 'mayor_mejor' });
expect(catalog.find(i => i.id === 'M28_casos_por_estado')).toMatchObject({ contrato: 'C2', estratos: [] });
expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' });
});
it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => {
// Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and
// that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures
// hold none for M30). Fails if the groups are dropped or renamed on the way, or the figure stops reading them.
const m30 = measure('M30-resultado-eeg');
const pop = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
const group = (code: string, n: number) => ({ code: { coding: [{ code }] }, population: [pop('denominator', 8), pop('numerator', n)],
measureScore: { value: n / 8 } });
const codes = (m30.group ?? []).map(g => g.code?.coding?.[0]?.code as string);
const report = { resourceType: 'MeasureReport', id: 'M30-resultado-eeg-1', period: { start: '2025-07-01', end: '2025-12-31' },
group: codes.map((c, i) => group(c, c === 'TOTAL' ? 4 : i % 3)) } as unknown as Report;
const datos = datosValidos(datosDeReportes(m30, [report], 'semestre'), 'M30_resultado_eeg', 'semestre', ['2025-S2']);
expect(datos.filas.map(f => f['grupo'])).toEqual(codes);
expect(codes).toContain('ritmo_posterior');
const result = c1AlterationFigure(datos, { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion',
tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
const [trace] = result.figure.data as Record<string, unknown>[];
expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos',
'Gradiente anteroposterior']);
expect((trace['y'] as number[])[0]).toBe(50);
});
it('una proporción da numerador, denominador y porcentaje, y por grupo de edad los códigos de la página', () => {
// Pins down: the score becomes a percentage, the age groups `16-23`..., and an empty «Sin dato» stratum is left
// out. Fails if the fraction isn't multiplied, the codes keep FHIR's underscore or the empty stratum becomes a bar.
const total = datosValidos(datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre'),
'M21_diagnosticados_con_eeg', 'semestre');
expect(total.periodos).toEqual(['2025-S1', '2025-S2']);
expect(total.filas[0]).toMatchObject({ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, numerador: 2, denominador: 2, valor: 100, suprimido: 0 });
const porEdad = datosDeReportes(measure('M21-diagnosticados-con-eeg'), reports(fx.m21Semestres), 'semestre', { estrato: 'grupo_edad' });
expect(porEdad['valores_estrato']).toEqual(['16-23', '24-29', '30-36']);
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['16-23']).toBe('16 a 23 meses');
});
it('una exclusión del denominador llega como n_excluido', () => {
// Pins down: M24's neuropediatrics notes without F84.0 are counted apart. Fails if the exclusion is dropped.
const datos = datosDeReportes(measure('M24-confirmacion-diagnostico'), reports(fx.m24Semestres), 'semestre');
expect(datos.filas[0]).toMatchObject({ numerador: 2, denominador: 5, valor: 40, n_excluido: 1 });
});
it('una composición da todas sus categorías, también las de cero, y la página la dibuja', () => {
// Pins down: one row per category of the Measure, in its order, with zeros for the absent ones, so the C2 adapter
// accepts the partition. Fails if a category with no patients is left out (the page refuses an incomplete one).
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
expect(s1.map(f => [f['categoria'], f['n']])).toEqual([['BUENO', 2], ['MALO', 1], ['SIN_ANALIZAR', 0]]);
const m28 = datosDeReportes(measure('M28-casos-por-estado'), [reports(fx.m28Semestres)[0]], 'semestre');
const figure = c2Figure(m28, { indicador: 'M28_casos_por_estado', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
expect(figure.status).toBe('supported');
});
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
const datos = datosDeReportes(measure('M25-dias-mchat-diagnostico'), reports(fx.m25Semestres), 'semestre');
expect(datos.filas[0]).toMatchObject({ mediana: 59.5, q1: 58.75, q3: 60.25, n: 2, n_sin_evento: 4, unidad: 'dias' });
const caja = cajaDeDatos(datos as IndicadorDatos);
expect(caja.data[0]).toMatchObject({ type: 'box', median: datos.filas.filter(f => f['mediana'] !== null).map(f => f['mediana']) });
});
it('los periodos siguen al primero sin huecos y los que no han empezado se descartan', () => {
// Pins down: semesters and months counted on from the first report, and none after today. Fails if a year
// boundary is crossed wrongly or a future period is offered.
expect(periodosDesde('2024-07-01', 'semestre', 3)).toEqual(['2024-S2', '2025-S1', '2025-S2']);
expect(periodosDesde('2024-11-01', 'mes', 3)).toEqual(['2024-11', '2024-12', '2025-01']);
const today = new Date(2025, 9, 15);
expect(periodoIniciado('2025-S2', today)).toBe(true);
expect(periodoIniciado('2025-11', today)).toBe(false);
});
});
describe('Servicios FHIR de indicadores', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService, FhirIndicadoresPeriodos] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('pide los periodos elegidos de una medida a la búsqueda de MeasureReport', async () => {
// Pins down: one `Measure` list per domain, and `/MeasureReport?measure=<canonical>&periodo=...`. Fails if the
// request leaves the FHIR endpoint or loses the periods asked for.
const service = TestBed.inject(FhirIndicadoresService);
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre', ['2025-S1', '2025-S2']));
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
const request = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/M21-diagnosticados-con-eeg');
expect(request.request.params.get('periodo')).toBe('2025-S1,2025-S2');
request.flush(fx.m21Semestres);
expect((await answer).filas.length).toBe(2);
});
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
// measure computes its own periods or every period is evaluated to list them.
const periodos = TestBed.inject(FhirIndicadoresPeriodos);
periodos.today = () => new Date(2025, 11, 31);
const answer = firstValueFrom(periodos.periodos('tea', 'M28_casos_por_estado'));
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
const semestres = http.expectOne(r => r.params.get('tipo-periodo') === 'semestre');
expect(semestres.request.params.get('_count')).toBe('1');
semestres.flush({ ...fx.m28Semestres, entry: fx.m28Semestres.entry!.slice(0, 1) });
const first = reports(fx.m28Semestres)[0];
http.expectOne(r => r.params.get('tipo-periodo') === 'mes').flush({ resourceType: 'Bundle', total: 12,
entry: [{ resource: { ...first, period: { start: '2025-01-01', end: '2025-01-31' } } }] });
const found = await answer;
expect(found.filter(p => p.tipo === 'semestre').map(p => p.periodo)).toEqual(['2025-S2', '2025-S1']);
expect(found.filter(p => p.tipo === 'mes').length).toBe(12);
expect(await firstValueFrom(periodos.periodos('tea', 'M21_diagnosticados_con_eeg'))).toEqual(found);
});
});
describe('Seguimiento de TEA sobre FHIR', () => {
let http: HttpTestingController;
let service: FhirTeaSeguimientoService;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirTeaSeguimientoService] });
http = TestBed.inject(HttpTestingController);
service = TestBed.inject(FhirTeaSeguimientoService);
});
afterEach(() => http.verify());
it('la lista sale de los episodios con sus recursos incluidos y respeta filtros y página', async () => {
// Pins down: the window and cut-off as `date`, the filters as search parameters, paging as `_count`/`_offset`,
// and each row's age group, M-CHAT, ADOS-2, study EEG and alterations from the included resources. Fails if a
// filter is dropped or a column stops coming from its resource.
const answer = firstValueFrom(service.consultar({ corte: '2025-12-31', meses: 12, page: 1, page_size: 5, grupo_edad: '16-23 meses', estado_caso: 'completo' }));
const list = http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare');
expect(list.request.params.getAll('date')).toEqual(['ge2025-01-01', 'le2025-12-31']);
expect(list.request.params.get('grupo-edad')).toBe('16_23');
expect(list.request.params.get('status')).toBe('finished');
expect(list.request.params.get('_count')).toBe('5');
list.flush(fx.episodios);
http.expectOne(r => r.url === '/tea/fhir/EpisodeOfCare/$resumen-eeg').flush(fx.resumenEeg);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const response = await answer;
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
});
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect(detalle.grupo_edad).toBe('16-23 meses');
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
expect(detalle.eeg!.calidad).toBe('bueno');
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
});
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
const mapa = mapaDeElectrodos('ritmo_posterior', 'Ritmo posterior', { O1: -2.8, O2: -2.4, Pz: -1.1 });
const eje = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
expect(mapa.z[eje.indexOf(-0.75)][eje.indexOf(-0.25)]).not.toBeNull();
expect(mapa.z[eje.indexOf(0.75)][eje.indexOf(0)]).toBeNull();
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
expect(mapa.regiones[0].valor_z).toBe(-2.6);
});
});
@@ -1,325 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map, Observable, shareReplay, switchMap } from 'rxjs';
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
import { periodLabel } from './measure-report';
import {
DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo,
} from './indicadores.models';
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests';
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
// by the same rules as before.
interface Population { code?: Concept; count?: number; description?: string; criteria?: { expression?: string } }
interface Score { value?: number; unit?: string; extension?: Extension[] }
interface Stratum { value?: Concept; population?: Population[]; measureScore?: Score; component?: { code?: Concept; value?: Concept }[] }
interface Stratifier { code?: Concept[] | Concept }
interface ReportStratifier { code?: Concept[]; stratum?: Stratum[] }
interface Group { code?: Concept; population?: Population[]; measureScore?: Score; stratifier?: (Stratifier & ReportStratifier)[] }
export interface Measure extends Resource {
url?: string; version?: string; name?: string; title?: string; description?: string;
scoring?: Concept; subjectCodeableConcept?: Concept; improvementNotation?: Concept; group?: Group[];
}
export interface Report extends Resource {
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
}
interface Categoria { etiqueta: string; color: string | null; grupo: null }
const MAX_COUNT = 200;
const POPULATION_GROUP: Record<string, string> = {
'initial-population': 'poblacion', denominator: 'denominador', numerator: 'numerador',
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
};
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
// Age groups travel as `16_23`; the page names them `16-23`.
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
function count(populations: Population[] | undefined, name: string): number | null {
const found = populations?.find(p => code(p.code) === name);
return found && Number.isSafeInteger(found.count) ? found.count! : null;
}
function decimal(score: Score | undefined, name: string): number | null {
const value = extension(score, name)?.valueDecimal;
return typeof value === 'number' ? value : null;
}
const round1 = (value: number) => Math.round(value * 10) / 10;
export function categorias(measure: Measure): Record<string, Categoria> {
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
}));
}
function contrato(measure: Measure): string {
return extension(measure, 'contrato')?.valueCode ?? '';
}
// The strata a measure can be broken down by. A C2's first stratifier holds its categories, not a stratum.
function estratos(measure: Measure): string[] {
const all = (measure.group?.[0]?.stratifier ?? []).map(stratifierCode).filter((c): c is string => !!c);
return contrato(measure) === 'C2' ? all.slice(1) : all;
}
export function indicadorDeMeasure(measure: Measure): Indicador & Record<string, unknown> {
const notation = code(measure.improvementNotation);
const vistas = extensions(measure, 'vistas').map(e => e.valueCode).filter((v): v is string => !!v);
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
titulo: measure.title ?? measure.name ?? measure.id ?? '',
contrato: contrato(measure),
figuras: extensions(measure, 'figuras').map(e => e.valueString).filter((f): f is string => !!f),
tipos_periodo: extensions(measure, 'tipos-periodo').map(e => e.valueCode).filter((t): t is TipoPeriodo => t === 'semestre' || t === 'mes'),
unidad: code(measure.subjectCodeableConcept) ?? null,
sentido: notation === 'increase' ? 'mayor_mejor' : notation === 'decrease' ? 'menor_mejor' : null,
estratos: estratos(measure),
filtros: [],
...(vistas.length ? { vistas } : {}),
};
}
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
const unidad = code(measure.subjectCodeableConcept) ?? null;
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
descripcion: measure.description ?? null,
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null },
unidad,
referencias: [],
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
grupo: POPULATION_GROUP[code(p.code) ?? ''] ?? code(p.code) ?? '',
codigo: p.criteria?.expression ?? code(p.code) ?? '',
descripcion: p.description ?? '',
})),
figuras_detalle: [],
categorias: categorias(measure),
};
}
// FHIR's period end is inclusive; the page's `periodo_fin`, like `dim_periodo`, is the next day.
function nextDay(day: string): string {
const date = new Date(day + 'T00:00:00Z');
date.setUTCDate(date.getUTCDate() + 1);
return date.toISOString().slice(0, 10);
}
function reporte(report: Report, periodo: string) {
const knowledge = extension(report, 'corte-conocimiento')?.valueDateTime;
return {
periodo,
report_id: extension(report, 'reporte-id')?.valueInteger ?? null,
periodo_inicio: report.period?.start ?? null,
periodo_fin: report.period ? nextDay(report.period.end) : null,
fecha_corte: extension(report, 'corte-evento')?.valueDate ?? knowledge?.slice(0, 10) ?? null,
generado_en: report.date ?? null,
};
}
function proporcion(populations: Population[] | undefined, score: Score | undefined) {
const numerador = count(populations, 'numerator'), denominador = count(populations, 'denominator');
return {
suprimido: 0, numerador, denominador,
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
};
}
function duracion(populations: Population[] | undefined, score: Score | undefined) {
return {
suprimido: 0,
n: count(populations, 'measure-observation') ?? 0,
mediana: typeof score?.value === 'number' ? score.value : null,
q1: decimal(score, 'q1'), q3: decimal(score, 'q3'),
// The units without a value at the cut-off: FHIR's population exclusion.
n_sin_evento: count(populations, 'measure-population-exclusion') ?? 0,
n_excluido: 0,
unidad: 'dias',
};
}
function stratumValue(stratum: Stratum): string | undefined {
const value = code(stratum.value);
return value === undefined ? undefined : estratoValor(value);
}
// The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), cats = categorias(measure), estrato = scope.estrato;
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = code(g.code) ?? 'TOTAL';
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
}));
const valores = new Map<string, string>();
const filas: Record<string, unknown>[] = [];
const periodos: string[] = [];
for (const report of reports) {
if (!report.period) continue;
const periodo = periodLabel(report.period);
periodos.push(periodo);
for (const group of report.group ?? []) {
const grupo = code(group.code) ?? 'TOTAL';
if (kind === 'C2') {
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
}
const row = (populations: Population[] | undefined, score: Score | undefined) =>
kind === 'C3r' ? duracion(populations, score) : proporcion(populations, score);
if (!estrato) {
filas.push({ periodo, grupo, estrato: null, ...row(group.population, group.measureScore) });
continue;
}
const stratifier = group.stratifier?.find(s => code(s.code?.[0]) === estrato);
if (!stratifier) throw new Error('Dimensión no admitida');
for (const stratum of stratifier.stratum ?? []) {
const valor = stratumValue(stratum);
// A stratum nobody falls in, like an empty «Sin dato», isn't a bar of its own.
if (!valor || !(stratum.population ?? []).some(p => (p.count ?? 0) > 0) && valor === 'sin_dato') continue;
valores.set(valor, display(stratum.value) ?? valor);
filas.push({ periodo, grupo, estrato: valor, ...row(stratum.population, stratum.measureScore) });
}
}
}
return {
id: indicadorId(measure.id ?? ''),
titulo: measure.title ?? measure.name ?? '',
version: measure.version,
contrato: kind,
unidad: code(measure.subjectCodeableConcept) ?? '',
tipo_periodo: tipo,
periodos,
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
grupos,
categorias: cats,
grupos_de_categoria: {},
notas: [],
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
filas,
};
}
// One box per period, from each period's median and quartiles.
export function cajaDeDatos(datos: IndicadorDatos): PlotlyFigure {
const filas = datos.filas.filter(f => f['grupo'] === 'TOTAL' && f['estrato'] == null && typeof f['mediana'] === 'number');
const values = (field: string) => filas.map(f => f[field]);
return {
data: filas.length ? [{ type: 'box', name: 'Total', x: values('periodo'), q1: values('q1'), median: values('mediana'), q3: values('q3'),
lowerfence: values('q1'), upperfence: values('q3') }] : [],
layout: { title: { text: String(datos['titulo'] ?? '') }, autosize: true, margin: { l: 60, r: 24, t: 60, b: 60 },
yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
};
}
function tipoDe(periodo: string): TipoPeriodo {
return periodo.includes('-S') ? 'semestre' : 'mes';
}
// The `count` periods of `tipo` from the one starting on `start`, in order.
export function periodosDesde(start: string, tipo: TipoPeriodo, total: number): string[] {
const [year, month] = start.split('-').map(Number);
return Array.from({ length: total }, (_, i) => {
if (tipo === 'semestre') {
const n = (year * 2 + (month >= 7 ? 1 : 0)) + i;
return `${Math.floor(n / 2)}-S${n % 2 + 1}`;
}
const n = year * 12 + month - 1 + i;
return `${Math.floor(n / 12)}-${String(n % 12 + 1).padStart(2, '0')}`;
});
}
// A period that hasn't started by `today` has no data to show.
export function periodoIniciado(periodo: string, today: Date): boolean {
const current = periodOrder(tipoDe(periodo) === 'semestre'
? `${today.getFullYear()}-S${today.getMonth() < 6 ? 1 : 2}`
: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`);
return periodOrder(periodo) <= current;
}
@Injectable({ providedIn: 'root' })
export class FhirMeasures {
private readonly http = inject(HttpClient);
private readonly cache = new Map<Dominio, Observable<Measure[]>>();
all(dominio: Dominio): Observable<Measure[]> {
const domain = requireDominio(dominio);
let request = this.cache.get(domain);
if (!request) {
request = this.http.get<Bundle>(`/${domain}/fhir/Measure`).pipe(
map(bundle => resources(bundle, 'Measure') as Measure[]), shareReplay({ bufferSize: 1, refCount: false }));
this.cache.set(domain, request);
}
return request;
}
one(dominio: Dominio, indicador: string): Observable<Measure> {
return this.all(dominio).pipe(map(measures => {
const found = measures.find(m => indicadorId(m.id ?? '') === indicador);
if (!found) throw new Error('Indicador no publicado');
return found;
}));
}
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
}
}
@Injectable()
export class FhirIndicadoresService extends IndicadoresService {
private readonly measures = inject(FhirMeasures);
override catalogo(dominio: Dominio = 'tea') {
return this.measures.all(dominio).pipe(map(all => catalogoValido(all.map(indicadorDeMeasure))));
}
override metadatos(dominio: Dominio, indicador: string) {
return this.measures.one(dominio, indicador).pipe(map(m => metadatosValidos(metadatosDeMeasure(m))));
}
override datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
datosParams(tipo, periodos, scope);
if (scope.filtros?.length) throw new Error('Filtro no admitido');
let params = new HttpParams().set('_count', MAX_COUNT);
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
return this.measures.one(dominio, indicador).pipe(
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
}
override figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea');
const periodos = figuraPeriodos(selection);
if (selection.figura !== 'fig_c3r_caja') throw new Error('Figura no disponible');
const tipo = selection.tipoPeriodo ?? (periodos ? tipoDe(periodos[0]) : 'semestre');
return this.datos(dominio, selection.indicador, tipo, periodos).pipe(map(datos => figuraValida(cajaDeDatos(datos))));
}
}
// Every measure of a domain shares its periods (`dim_periodo`, whole years); one report of each type gives the first
// period and the search's total how many follow.
@Injectable()
export class FhirIndicadoresPeriodos extends IndicadoresPeriodos {
private readonly measures = inject(FhirMeasures);
private readonly queue = inject(IndicadoresRequests);
private readonly byDomain = new Map<Dominio, Observable<AvailablePeriod[]>>();
today = () => new Date();
override periodos(domain: Dominio, id: string): Observable<AvailablePeriod[]> {
const dominio = requireDominio(domain);
let request = this.byDomain.get(dominio);
if (!request) {
request = this.measures.one(dominio, id).pipe(
switchMap(measure => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'semestre').set('_count', 1))).pipe(
switchMap(semestres => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'mes').set('_count', 1))).pipe(
map(meses => [...this.listed(semestres, 'semestre'), ...this.listed(meses, 'mes')]
.sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo))))))),
shareReplay({ bufferSize: 1, refCount: false }));
this.byDomain.set(dominio, request);
}
return request;
}
private listed(bundle: Bundle, tipo: TipoPeriodo): AvailablePeriod[] {
const first = (resources(bundle, 'MeasureReport')[0] as Report | undefined)?.period;
if (!first || !bundle.total) return [];
const today = this.today();
return periodosDesde(first.start, tipo, bundle.total).filter(p => periodoIniciado(p, today)).map(periodo => ({ periodo, tipo }));
}
}
@@ -2,7 +2,6 @@ import { figureDisplayName } from './indicadores-figure-labels';
describe('UX-07A nombres de representaciones', () => {
it.each([
['fig_c1_barras_alteracion', 'Barras por alteración'],
['fig_c1_grupos', 'Grupos'],
['fig_c1_puntos', 'Puntos'],
['fig_c2_apiladas', 'Barras apiladas'],
@@ -2,7 +2,6 @@
// Exact IDs remain the option values and HTTP identities; never infer a type
// from a prefix. Unknown options keep a neutral label in publication order.
const FIGURE_LABELS: Readonly<Record<string, string>> = {
fig_c1_barras_alteracion: 'Barras por alteración',
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
fig_c1_barras_edad: 'Barras por grupo de edad',
fig_c1_dona_edad: 'Dona por grupo de edad',
@@ -58,8 +58,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
load(undefined, domain);
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
expect(sections[0].textContent).toContain(domain === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + page.domainLabels[domain]);
if (domain === 'cama') expect(sections[0].textContent).not.toContain('Filtros generales de ');
expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]);
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
expect(page.filters!.applied.selection.mode).toBe('todos');
@@ -1,142 +0,0 @@
// Covers CaMa's history tab: what it requests and when, the controls (interval, periods to show, custom
// periods), the pending panels for indicators the catalog does not publish, and error handling. Responses are
// synthetic, shaped like /cama/indicadores/<id>/periodos and /datos.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { MatDialog } from '@angular/material/dialog';
import { of } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { HISTORICO_CAMA, IndicadoresHistorico } from './indicadores-historico';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { figure?: { data: { name?: string }[] }; label?: string; }
const MESES = ['2025-01', '2025-02', '2025-03', '2025-04', '2025-05', '2025-06', '2025-07'];
const SEMESTRES = ['2024-S2', '2025-S1'];
const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
// What 18080 publishes for CaMa, including biopsias, which the history does not draw.
const CATALOGO = [item('cama_biopsias', 'C2'), item('cama_birads_456_mastografia', 'C2'), item('cama_birads_456_paciente', 'C2'),
item('cama_confirmacion_birads45', 'C1'), item('cama_dias_toma_diagnostico', 'C3r'), item('cama_eu38a', 'C3r')];
const PUBLICADOS = CATALOGO.filter(i => i.id !== 'cama_biopsias');
function datos(id: string, contrato: string, tipo: string, periodos: string[]) {
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
const filas = contrato === 'C2'
? periodos.flatMap(p => [fila(p, { categoria: 'B5', n: 7, orden: 0 }), fila(p, { categoria: 'B4', n: 5, orden: 1 })])
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 50, numerador: 5, denominador: 10, ic_bajo: 30, ic_alto: 70 }))
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' && id.includes('paciente') ? 'paciente' : 'examen', filas,
categorias: { B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, B4: { etiqueta: 'B4', color: null } } };
}
describe('Histórico de CaMa', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
const abrirDialogo = vi.fn();
function montar(catalog: Indicador[] = CATALOGO, active = false) {
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
fixture.detectChanges();
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
// Answers in waves, because the shared request queue runs four at a time.
function responder(fallo?: (r: TestRequest) => boolean) {
const vistos: string[] = [];
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
const url = r.request.url; vistos.push(url + (r.request.params.get('periodos') ? '?' + r.request.params.get('periodos') : ''));
const id = url.split('/').at(-2)!, entrada = CATALOGO.find(i => i.id === id)!;
if (fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
else {
const periodos = r.request.params.get('periodos')!.split(',');
r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos));
}
}
fixture.detectChanges();
}
return vistos;
}
const root = () => fixture.nativeElement as HTMLElement;
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
it('no pide nada hasta que la pestaña está activa, y entonces solo los indicadores de la lista que el catálogo publica', () => {
// Fails if the tab loads data while hidden, or if biopsias (not in the history) is requested.
montar();
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const vistos = responder();
const ids = new Set(vistos.map(u => u.split('/').at(-2)));
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false);
});
it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => {
montar(CATALOGO, true); responder();
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
expect(graficas()).toHaveLength(5);
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
});
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
montar(CATALOGO, true); responder();
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
});
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
montar(CATALOGO, true); responder();
const toggle = fixture.debugElement.query(By.css('mat-button-toggle-group'));
toggle.triggerEventHandler('change', { value: 'semestre' }); fixture.detectChanges();
const semestrales = responder();
expect(semestrales.length).toBeGreaterThan(0);
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
http.expectNone(() => true);
});
it('«Periodos a mostrar» ofrece pasos de cinco y «Todos»; elegir los últimos cinco recorta cada gráfica', () => {
montar(CATALOGO, true); responder();
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
});
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
montar(CATALOGO, true); responder();
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(['2025-02', '2025-05']) });
fixture.componentInstance.elegirVentana(-1); fixture.detectChanges();
expect(abrirDialogo).toHaveBeenCalledTimes(1);
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
});
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
montar(CATALOGO, true);
responder(r => r.request.url.includes('cama_eu38a/periodos'));
const panel = paneles().find(p => p.querySelector('h2')!.textContent === 'Días de la toma de la mastografía a su resultado')!;
expect(panel.querySelector('[role=alert]')).not.toBeNull();
expect(panel.textContent).not.toContain('private');
expect(graficas()).toHaveLength(4);
(panel.querySelector('[role=alert] button') as HTMLButtonElement).click(); fixture.detectChanges();
const nuevos = responder();
expect(nuevos.length).toBeGreaterThan(0);
expect(paneles().some(p => p.querySelector('[role=alert]'))).toBe(false);
expect(graficas()).toHaveLength(5);
});
it('sin ningún indicador de la lista en el catálogo no hay paneles ni consultas', () => {
montar([item('cama_biopsias', 'C2')], true);
http.expectNone(() => true);
expect(paneles()).toHaveLength(0);
});
});
@@ -1,7 +1,6 @@
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
import { sortedPeriods } from './indicadores-periodos';
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
export interface HistoricoFigura {
contrato: string;
@@ -12,8 +11,6 @@ export interface HistoricoFigura {
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
@@ -24,16 +21,19 @@ export function etiquetaPeriodo(periodo: string): string {
const [anio, resto] = periodo.split('-');
return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`;
}
// What the unit the kit publishes is called in the charts' texts.
const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
};
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'casos', eje: 'Casos' };
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
export interface HistoricoOpciones {
// Same vertical scale across small charts, so their heights compare.
yMax?: number;
pequena?: boolean;
}
// What the unit a measure publishes is called in the charts' texts.
const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
};
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
function validar(data: IndicadorDatos) {
for (const row of data.filas) {
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
@@ -42,13 +42,12 @@ function validar(data: IndicadorDatos) {
}
function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string, pequena = false) {
const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo);
const cada = pequena && periodos.length > 12 ? 6 : 3;
// A label for every month does not fit: one per quarter is still readable, with the full period on hover.
return {
autosize: true, height: pequena ? 340 : 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false },
// A label for every month does not fit: one per quarter is still readable with the full period on hover.
xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0,
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % cada === 0) },
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % (pequena && periodos.length > 12 ? 6 : 3) === 0) },
yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false },
// Shaded, because an empty space alone reads as zero. Text below the figure says the same.
shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 },
@@ -73,9 +72,8 @@ function banda(periodos: string[], bajo: (number | null)[], alto: (number | null
}
// Separate rows from what is missing or suppressed; a period is judged by its only row.
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
const delTotal = filasDelGrupo(data, 'TOTAL');
const filas = new Map(delTotal.map(row => [row['periodo'] as string, row]));
if (filas.size !== delTotal.length) throw new Error('Filas ambiguas');
const filas = new Map(data.filas.map(row => [row['periodo'] as string, row]));
if (filas.size !== data.filas.length) throw new Error('Filas ambiguas');
const suprimidos: string[] = [], sinDato: string[] = [];
const validas = periodos.map(periodo => {
const row = filas.get(periodo);
@@ -100,28 +98,29 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos casos.',
suprimidos, sinDato,
};
}
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
const periodos = validar(data), unidad = unidadDe(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const linea = c2Theme(tema).line;
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 },
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => {
const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena);
return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout;
})() },
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`,
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de las ${unidad.plural}.`,
suprimidos, sinDato,
};
}
// What each count means, for the indicators that don't count patients in the period.
// What each count means, for the indicators that don't count the unit of the period.
const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
@@ -153,7 +152,7 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
suprimidos, sinDato,
};
}
// A BI-RADS 4 without subcategory is published as «B4», with no colour.
// The kit publishes a 4 without subcategory as «B4», with no colour.
function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
const publicada = typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : '';
return publicada && publicada !== id ? publicada : id === 'B4' ? 'BI-RADS 4 (sin subcategoría)' : id;
@@ -166,25 +165,25 @@ export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: Hist
if (!figura) throw new Error('Representación no soportada');
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
}
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
// The share of cases still in process, from the case-status counts. Cases out of the protocol aren't in the base.
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const periodos = validar(data);
const n = (periodo: string, categorias: readonly string[]) => {
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
const n = (periodo: string, categoria: string) => {
const valor = data.filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria)?.['n'];
return numero(valor) ? valor : null;
};
const puntos = periodos.map(periodo => {
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
const proceso = n(periodo, 'EN_PROCESO'), completo = n(periodo, 'COMPLETO');
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
});
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
return {
contrato: 'C1',
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} casos` : ''),
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
layout: { ...layout, showlegend: false, margin: { ...(layout.margin as object), b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...(layout.yaxis as object), range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'De los casos completos o en proceso al cierre de cada periodo, el porcentaje que seguía en proceso. Los que quedaron fuera del protocolo no cuentan.',
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
};
}
@@ -33,19 +33,13 @@ describe('Pestaña Histórico', () => {
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
});
it('cacu no tiene la pestaña Histórico', () => {
// Fails if the history tab of TEA or CaMa leaks into CaCu.
it.each(['cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
// Fails if the tab leaks into a domain without enough periods for a history (TEA and CaMa have it).
abrir('cama', []);
abrir('cacu', [item('cacu_x', 'C2')]);
abrir(domain, [item(domain + '_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).toBeNull();
});
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
abrir('cama', []);
abrir('tea', [item('tea_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-analisis')).toBeNull();
});
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
const panel = () => root().querySelector('#panel-historico') as HTMLElement;
@@ -36,16 +36,6 @@ describe('Figuras de histórico', () => {
expect(suprimidos).toEqual(['feb 2024']);
expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]);
});
it('C1 con grupos adicionales dibuja la línea del total', () => {
// Pins down: a measure that publishes one group per alteration next to its total (TEA's EEG result) gets its
// history from the total's row of each period. Fails if the other groups' rows count as a second row of the
// period («Filas ambiguas»), or if two rows of the total stop being refused.
const grupos = { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior' };
const filas = base.periodos.flatMap(p => [{ ...c1(p, 40), grupo: 'TOTAL' }, { ...c1(p, 10), grupo: 'ritmo_posterior' }]);
const data: IndicadorDatos = { ...base, contrato: 'C1', grupos, filas };
expect(traza(data, 1).y).toEqual([40, 40, 40]);
expect(() => historicoFigura({ ...data, filas: [...filas, { ...c1('2024-01', 5), grupo: 'TOTAL' }] }, 'claro')).toThrow('Filas ambiguas');
});
it('C1 es una línea que no cruza huecos y su banda tampoco', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] };
const { suprimidos, figure } = historicoFigura(data, 'claro');
@@ -72,11 +62,11 @@ describe('Figuras de histórico', () => {
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
});
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
it('el porcentaje en proceso se calcula sobre completos y en proceso, sin los que quedaron fuera', () => {
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
fila('2024-01', 'COMPLETO', 10), fila('2024-01', 'EN_PROCESO', 30), fila('2024-01', 'FUERA_PROTOCOLO', 99),
fila('2024-02', 'COMPLETO', 30), fila('2024-02', 'EN_PROCESO', 10), fila('2024-02', 'FUERA_PROTOCOLO', 99)] }, 'claro');
expect(figure.data[0]['y']).toEqual([75, 25]);
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
});
@@ -173,7 +163,7 @@ describe('Pestaña Histórico', () => {
for (const { id } of items) {
const c2 = id.startsWith('M28');
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
filas: c2 ? [{ periodo: '2024-01', categoria: 'COMPLETO', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'EN_PROCESO', n: 1, orden: 1, suprimido: 0 }]
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
}
render();
@@ -17,14 +17,14 @@ import { IndicadoresService } from './indicadores.service';
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string } & (
type Panel = { item: Pick<Indicador, 'id' | 'titulo' | 'contrato'>; rango?: string } & (
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
const CASOS = 'M28_casos_por_estado';
const PERSONALIZADO = -1;
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
// CaMa's history, in the order of the mockup and with its titles. An indicator the catalog does not publish is
// drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico por categoría BI-RADS' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
@@ -50,7 +50,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
}
if (listos && TIEMPOS.includes(panel.item.id)) return [];
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de casos en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
}
return [panel];
});
@@ -104,10 +104,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
}
<p class="nota">{{ panel.figura.comoLeer }}</p>
@if (panel.figura.suprimidos.length) {
<details class="nota-pie">
<summary>Datos suprimidos</summary>
<p>Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
</details>
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
}
@@ -125,12 +122,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; }
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.nota-pie { margin-top: var(--issste-space-3); padding-top: var(--issste-space-2); border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font-size: 0.8125rem; line-height: 1.4; }
.nota-pie summary { width: fit-content; cursor: pointer; }
.nota-pie summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.nota-pie p { margin-top: var(--issste-space-2); font: inherit; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.panel.ancho { grid-column: 1 / -1; }
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
@@ -144,11 +137,8 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => this.dominio() === 'cama'
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.catalog().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
readonly tipo = computed<TipoPeriodo>(() => {
const elegido = this.elegido(), tipos = this.tipos();
@@ -168,7 +158,7 @@ export class IndicadoresHistorico {
// The periods on screen, out of those an indicator publishes.
private recortar(periodos: readonly string[]) {
const orden = cronologico(periodos), ventana = this.ventana();
if (ventana !== PERSONALIZADO) return ventana ? orden.slice(-ventana) : orden;
if (ventana !== PERSONALIZADO) return orden.slice(-ventana);
const elegidos = this.personalizados()[this.tipo()] ?? [];
return orden.filter(p => elegidos.includes(p));
}
@@ -198,8 +188,8 @@ export class IndicadoresHistorico {
const visibles = this.recortar(carga.datos.periodos);
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
})) * 1.05;
const panelDe = (item: Indicador): Panel & { datos?: IndicadorDatos } => {
if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' };
const base: (Panel & { datos?: IndicadorDatos })[] = this.elementos(tipo).map((item): Panel & { datos?: IndicadorDatos } => {
if (!item.tipos_periodo.length) return { item, estado: 'pendiente' };
const carga = cargas?.[item.id];
if (!carga) return { item, estado: 'cargando' };
if (carga.estado !== 'listo') return { item, ...carga };
@@ -213,17 +203,21 @@ export class IndicadoresHistorico {
} catch (error) {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
};
if (this.dominio() === 'cama') {
if (!this.publicados().length) return [];
return HISTORICO_CAMA.map((entrada): Panel => {
const item = this.catalog().find(i => i.id === entrada.id);
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
});
}
return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
});
return agrupar(base, tema);
});
// What the tab draws: CaMa's fixed list, with pending panels where the catalog lacks the indicator; the catalog elsewhere.
private elementos(tipo: TipoPeriodo): Indicador[] {
const catalogo = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
// Without a catalog there is nothing to say is missing.
if (this.dominio() !== 'cama' || !this.catalog().length) return catalogo;
return HISTORICO_CAMA.flatMap(({ id, titulo }) => {
const item = this.catalog().find(i => i.id === id);
if (!item) return [{ id, titulo, contrato: '', figuras: [], tipos_periodo: [] }];
return item.tipos_periodo.includes(tipo) ? [{ ...item, titulo }] : [];
});
}
constructor() {
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
@@ -231,10 +225,10 @@ export class IndicadoresHistorico {
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
});
effect(() => {
const tipo = this.tipo(), items = this.publicados();
const tipo = this.tipo(), items = this.catalog();
if (!this.active() || !items.length) return;
untracked(() => {
if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; }
if (this.catalogoCargado !== items) { this.catalogoCargado = items; this.cargas.set({}); this.solicitada = undefined; }
if (this.cargas()[tipo] || this.solicitada === tipo) return;
this.solicitada = tipo;
this.solicitudes.next({ tipo, items });
@@ -256,7 +250,7 @@ export class IndicadoresHistorico {
abrirPersonalizado() {
const tipo = this.tipo(), periodos = this.disponibles();
// Starts from what's on screen, so the user only adjusts it.
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos;
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : periodos.slice(-this.ventana());
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
.afterClosed().subscribe(resultado => {
@@ -272,6 +266,6 @@ export class IndicadoresHistorico {
const tipo = this.tipo();
this.solicitada = tipo;
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
this.solicitudes.next({ tipo, items: this.publicados() });
this.solicitudes.next({ tipo, items: this.catalog() });
}
}
@@ -16,10 +16,13 @@ import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
// rules (indicador-kpi-panel.spec.ts covers all four).
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage;
const periods = ['2026-S2', '2026-S1', '2025-S2'];
const definitions = KPI_BY_DOMAIN[domain];
const definitions = KPIS[domain];
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
// Two figures, so every domain keeps an ordinary card whose representation can change.
@@ -89,7 +92,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const ongoing = request(periods[0]);
for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) {
page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url.endsWith('/seguimiento') || r.url.includes('/fhir/'))) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.initialPeriodState()).toBe('loading');
expect(ongoing.cancelled).toBe(false);
http.expectNone(() => true);
@@ -109,7 +112,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
editor().select([periods[2]]); fixture.detectChanges();
for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url.endsWith('/seguimiento') || r.url.includes('/fhir/'))) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
expect(editor().selectedPeriods).toEqual([periods[2]]);
expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g');
@@ -224,7 +227,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const catalogs = new Map<string, typeof items>([[domain, items]]);
for (const target of ['tea', 'cacu', 'cama'] as const) {
if (target === domain) continue;
const definitions = KPI_BY_DOMAIN[target];
const definitions = KPIS[target];
const period = own.size === 1 ? '2024-S2' : '2025-S1';
own.set(target, period);
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
@@ -2,7 +2,7 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { KPI_BY_DOMAIN } from './indicadores-kpi';
import { CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN } from './indicadores-kpi';
import { AvailablePeriod } from './indicadores-periodos';
import { TipoPeriodo } from './indicadores.models';
@@ -48,7 +48,9 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
// The strip's other cards are pending until the kit publishes them, so the anchor stays the patients' count.
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_tasa_deteccion_histopatologica',
'cama_eu38a', 'cama_dias_resultado_diagnostico']);
} else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
expect(run.selected()?.periodo).toBe(periods[0]);

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