Compare commits

...

19 Commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Implications: domain switching now depends on the App shell; a page embedded
elsewhere has no way to change domain by itself. Specs that asserted the
in-page links now assert their absence, and app.spec covers the menu.
2026-11-09 18:10:58 -06:00
rockdrigo 39974b8533 feat(cama): TEA tabs, follow-up list from announced columns and histopathology donut by BI-RADS category 2026-11-09 17:55:34 -06:00
56 changed files with 1073 additions and 304 deletions
+19 -6
View File
@@ -4,12 +4,25 @@
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
}
</nav>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
[attr.aria-label]="'Dominio actual: ' + domainLabels[domain] + '. Cambiar dominio'">
{{ domainLabels[domain] }} <span aria-hidden="true">▾</span>
</button>
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
@for (option of otherDomains(); track option) {
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ domainLabels[option] }}</a>
}
</mat-menu>
} @else {
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
}
</nav>
}
</div>
</header>
+25
View File
@@ -29,6 +29,31 @@
width: clamp(180px, 16vw, 200px);
}
.platform-title {
color: var(--color-text);
font-family: var(--issste-font-heading);
font-size: 1.25rem;
font-weight: 500;
line-height: 1.15;
margin-inline-start: var(--issste-space-4);
margin-inline-end: auto;
overflow-wrap: anywhere;
}
.domain-selector {
flex: 0 0 auto;
background-color: var(--issste-accent);
color: var(--issste-text);
font-weight: 700;
white-space: nowrap;
}
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
@media (max-width: 599px) {
.platform-title { font-size: 1.125rem; min-width: 0; }
}
.site-header__nav {
align-items: center;
display: flex;
+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();
+13 -1
View File
@@ -1,10 +1,13 @@
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { filter, map } from 'rxjs';
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
@Component({
imports: [RouterLink, RouterOutlet],
imports: [RouterLink, RouterOutlet, MatButtonModule, MatMenuModule],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
@@ -13,6 +16,15 @@ export class App {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
protected readonly title = 'Plataforma de Indicadores';
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
private readonly url = toSignal(this.router.events.pipe(
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
// On an indicators page the header names its domain and switches to the others.
protected readonly activeDomain = computed(() =>
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
private readonly leafRouteData = toSignal(
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
@@ -1,4 +1,6 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number;
// Filters a list announces in `filtros_disponibles`, by key.
filtros?: Record<string, string>; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
export interface SeguimientoPaciente {
id_seudonimo: string;
@@ -91,13 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
});
it.each(['cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
});
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
const service=TestBed.inject(CacuSeguimientoService);
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
@@ -15,15 +15,18 @@ import { filterCompatibility } from './indicadores-memory';
import { DonutSelection } from './indicadores-donut-drilldown';
import { IndicadoresService } from './indicadores.service';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { vistaConfirmacion } from './indicadores-confirmacion-citologia';
import { parTiempos } from './indicadores-tiempos-pareados';
import { parConteos } from './indicadores-conteos-pareados';
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
@Component({
selector: 'app-indicador-catalog-card',
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos || !!conteos' },
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados],
template: `
<mat-card>
<header>
@@ -46,6 +49,10 @@ import { parTiempos } from './indicadores-tiempos-pareados';
<div #visibilityRegion class="confirmacion-region">
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (conteos; as par) {
<div #visibilityRegion class="conteos-region">
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (tiempos; as par) {
<div #visibilityRegion class="tiempos-region">
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
@@ -91,7 +98,7 @@ import { parTiempos } from './indicadores-tiempos-pareados';
}
.card-identity { min-width: 0; }
h2, p { overflow-wrap: anywhere; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
min-width: 48px; min-height: 48px; color: var(--issste-text); }
.pin-toggle mat-icon { flex-shrink: 0; }
@@ -120,10 +127,12 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
});
}
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); }
get isConfirmacion() { return !!vistaConfirmacion(this.dominio, this.indicador); }
// Connected time pairs replace the diagnosis card with one coordinated box plot.
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
// Exams and patients of the same finding, drawn together on the exams' card.
get conteos() { return parConteos(this.dominio, this.indicador.id); }
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
private updateNumeric() {
@@ -1,4 +1,4 @@
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
<section class="confirmacion" [attr.aria-label]="'Confirmación histopatológica, ' + vista.textos.filas.toLowerCase()">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
@@ -16,7 +16,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 +30,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 +50,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 +60,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; }
@@ -8,12 +8,9 @@ import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './in
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { 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',
@@ -48,14 +45,18 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
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 +66,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 +85,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 +94,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 +117,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 +127,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 +135,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();
}
@@ -0,0 +1,53 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
@case ('empty') { <p role="status">No hay periodos publicados por los dos conteos.</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' && model; as m) {
@if (pages.length > 1) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ m.periodo }}, {{ periodIndex + 1 }} de {{ pages.length }}</span>
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === pages.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
<div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
@if (total) {
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section>
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por ' + par.unidades.pacientes.slice(0, -1) + ', ' + m.periodo" />
</section>
</div>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ texto(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
</table>
</div>
</details>
}
</section>
@@ -0,0 +1,22 @@
:host { display: block; min-width: 0; }
.conteos { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
.applied-summary, .note { color: var(--issste-text-secondary); }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
.periods button:disabled { opacity: .5; cursor: default; }
// The two figures share the card in equal halves; one above the other on a narrow card.
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
app-plotly-chart { --plot-height: 400px; }
summary { cursor: pointer; padding-block: .75rem; }
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.table-scroll { overflow: auto; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@@ -0,0 +1,117 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { TitleCasePipe } from '@angular/common';
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
@Component({
selector: 'app-indicador-conteos-pareados',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe],
templateUrl: './indicador-conteos-pareados.html',
styleUrl: './indicador-conteos-pareados.scss',
})
export class IndicadorConteosPareados implements OnChanges, OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) par!: ParConteos;
// The card's indicator (the exams); its partner (the patients) has no card and is requested by id.
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
periodIndex = 0;
pages: ModeloConteos[] = [];
donutFigure?: PlotlyFigure;
barsFigure?: PlotlyFigure;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
helpOpen = false;
// "Cómo leer": what the kit publishes for the exams' two figures.
get readingGuide() {
const figuras = [['fig_c2_donas', 'Dona por categoría'], ['fig_c2_barras', 'Pacientes y ' + this.par.unidades.examenes]] as const;
return figuras.flatMap(([figura, nombre]) => {
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
}
retry() { if (this.visible) this.load(); }
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.';
this.status.set('incompatible'); return;
}
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version),
this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods),
]).pipe(timeout({ first: 40000 })).subscribe({
next: ([examenes, pacientes]) => {
if (key !== this.key) return;
try {
this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo);
// The most recent period first; navigation goes back.
this.periodIndex = Math.max(0, this.pages.length - 1);
this.draw(); this.status.set(this.model ? 'ready' : 'empty');
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.clear();
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof ConteosIncompatibles ? error.message : httpMessage(error);
this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
this.changeDetector.markForCheck();
}
changePeriod(step: number) {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.draw();
}
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -1,4 +1,4 @@
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
<section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
@@ -16,24 +16,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 +48,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 { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
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,6 +42,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private key = '';
private loaded = false;
private pages: Modelo[] = [];
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
get sinDatoNote() {
@@ -51,6 +51,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
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 +71,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 +102,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 +114,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 +155,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; }
@@ -104,7 +104,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; }
@@ -13,20 +13,21 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
}
@if (temporalReference) { <p>{{ temporalReference }}</p> }
<p class="kpi-state" role="status">{{ state }}</p>
<!-- A card with its value says nothing more about its state; any other state is the message. -->
@if (state !== 'Disponible') { <p class="kpi-state" role="status">{{ state }}</p> }
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</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: 1.25rem; line-height: 1.3; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
h3, p { overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; }
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.value { font: var(--mat-sys-headline-medium); }
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; }
`,
})
@@ -52,6 +52,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();
@@ -104,8 +116,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', () => {
@@ -175,24 +188,23 @@ describe('KPI integración con autoridad global', () => {
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
http.expectNone(r => r.url.endsWith('/datos'));
});
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
for (const domain of ['cacu', 'cama'] as const) {
load(domain);
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
req.forEach((r, i) => r.flush({ ...response(i, domain), 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 : 3);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '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)']);
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', 'Disponible', 'Disponible']);
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '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)']);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.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 cards say only their own line; the kit notes are the figure footer.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(domain !== 'cacu');
// 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', () => {
@@ -212,7 +224,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);
@@ -224,7 +236,7 @@ describe('KPI integración con autoridad global', () => {
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
const 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,11 +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 === 'cacu' ? [] : result().notes ?? []" />
[loading]="result().loading ?? false" [notes]="dominio !== 'tea' ? [] : result().notes ?? []" />
@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; }',
// 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;
@@ -14,9 +14,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') {
@@ -43,10 +45,5 @@
</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>
@@ -1,19 +1,19 @@
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
@use '@angular/material' as mat;
// One compact row, like the Seguimiento form: the two selectors, Aplicar and the pending notice.
:host { display: block; min-width: 0; @include mat.theme((density: -4)); }
section { min-width: 0; }
.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; }
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
.apply-button { min-height: 40px; }
@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%; }
}
@@ -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,38 @@ 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 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.grados.map(g => escapar(g.etiqueta)), text: rotulos(exterior, m.grados.map(g => g.etiqueta), true),
textfont: { size: 11 }, customdata: custom(exterior),
marker: { colors: m.grados.map(g => rgba(g.color, sel.categoria && g.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 400, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
@@ -0,0 +1,45 @@
import { IndicadorDatos } from './indicadores.models';
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, PARES_CONTEOS, parConteos, razon, totalExamenes } from './indicadores-conteos-pareados';
// Covers the paired counts of cáncer de mama: mammograms by BI-RADS (donut) and each patient BI-RADS next to its
// mammograms (bars). Fixtures: two one-period answers built below, with the categories the API publishes.
const par = PARES_CONTEOS[0];
const filas = (n: Record<string, number | null>) => Object.entries(n).map(([categoria, v]) =>
({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: v, suprimido: v === null ? 1 : 0 }));
const examenes = (n: Record<string, number | null> = { B4A: 30, B4B: 18, B4C: 12, B5: 1016, B6: 972, SIN_DATO: 20 }) => ({
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
categorias: Object.fromEntries(Object.keys(n).map(k => [k, { etiqueta: k === 'SIN_DATO' ? 'Sin dato' : 'BI-RADS ' + k.slice(1), color: '#C26A2B' }])),
filas: filas(n) }) as unknown as IndicadorDatos;
const pacientes = () => ({ id: 'cama_birads_456_paciente', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'],
categorias: { BIRADS_4: { etiqueta: 'BI-RADS 4' }, BIRADS_5: { etiqueta: 'BI-RADS 5' }, BIRADS_6: { etiqueta: 'BI-RADS 6' } },
filas: filas({ BIRADS_4: 15, BIRADS_5: 254, BIRADS_6: 243 }) }) as unknown as IndicadorDatos;
describe('Conteos por mastografía y por paciente', () => {
it('la tarjeta de mastografías los dibuja y la de pacientes no tiene tarjeta propia', () => {
// Fails if the pair is found on the wrong card, or the patients still get a card of their own.
expect(parConteos('cama', 'cama_birads_456_mastografia')).toBe(par);
expect(parConteos('cama', 'cama_birads_456_paciente')).toBeUndefined();
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true);
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false);
});
it('suma 4A, 4B y 4C en el BI-RADS 4 de la paciente y deja «Sin dato» fuera de la dona', () => {
// Fails if subcategories don't add up to their patient category, or uncategorised exams enter the donut.
const [m] = modelosConteos(par, examenes(), pacientes(), 'semestre');
expect(m.filas.map(f => [f.id, f.pacientes, f.examenes])).toEqual([['BIRADS_4', 15, 60], ['BIRADS_5', 254, 1016], ['BIRADS_6', 243, 972]]);
expect(razon(m.filas[0])).toBe(4);
expect(totalExamenes(m)).toBe(2048); expect(m.sinDato).toBe(20);
expect(donaConteos(m, par, 'claro').data[0]['values']).toEqual([30, 18, 12, 1016, 972]);
expect(barrasConteos(m, par, 'claro').data.map(t => t['x'])).toEqual([[15, 254, 243], [60, 1016, 972]]);
});
it('una celda suprimida no se vuelve cero', () => {
// Fails if a suppressed exam count is drawn as zero or its category's sum and ratio are still computed.
const [m] = modelosConteos(par, examenes({ B4A: null, B4B: 18, B4C: 12, B5: 1016, B6: 972 }), pacientes(), 'semestre');
expect(totalExamenes(m)).toBeNull(); expect(m.filas[0].examenes).toBeNull(); expect(razon(m.filas[0])).toBeNull();
expect(donaConteos(m, par, 'claro').data).toEqual([]);
});
it('rechaza respuestas de otro indicador o intervalo', () => {
// Fails if the view accepts data that isn't the pair it draws.
expect(() => modelosConteos(par, pacientes(), pacientes(), 'semestre')).toThrow(ConteosIncompatibles);
expect(() => modelosConteos(par, examenes(), pacientes(), 'mes')).toThrow(ConteosIncompatibles);
});
});
@@ -0,0 +1,102 @@
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber } from './indicadores-format';
// Two C2 counts of the same finding, one per exam and one per patient: the exams' composition as a donut, and
// each patient category next to its exams, so the bars say how many exams each patient has.
export interface ParConteos {
dominio: Dominio;
examenes: string;
pacientes: string;
// Exam category -> patient category it adds to (BI-RADS 4A, 4B and 4C are a patient's BI-RADS 4).
grupoDe: Readonly<Record<string, string>>;
unidades: { examenes: string; pacientes: string; porPaciente: string };
}
export const PARES_CONTEOS: readonly ParConteos[] = [
{ dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente',
grupoDe: { B4A: 'BIRADS_4', B4B: 'BIRADS_4', B4C: 'BIRADS_4', B5: 'BIRADS_5', B6: 'BIRADS_6' },
unidades: { examenes: 'mastografías', pacientes: 'pacientes', porPaciente: 'por paciente' } },
];
// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own.
export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id);
export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) =>
PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes));
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
export interface ModeloConteos { periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[]; notas: string[]; }
export class ConteosIncompatibles extends Error {}
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const fail = (message: string): never => { throw new ConteosIncompatibles(message); };
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const miles = (v: number) => v.toLocaleString('es-MX');
// A suppressed or unpublished cell is unknown, never zero.
function cuenta(filas: Record<string, unknown>[], periodo: string, categoria: string): number | null {
const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria);
return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null;
}
const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce<number>((s, v) => s + v!, 0);
/** One model per period both responses publish, in chronological order. */
export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] {
for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) {
if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) {
fail('Los datos no corresponden a los conteos por mastografía y por paciente.');
}
}
const catExamenes = examenes['categorias'] as Record<string, unknown>, catPacientes = pacientes['categorias'] as Record<string, unknown>;
const etiqueta = (cat: Record<string, unknown>, id: string) => registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : id;
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : '#8A9199';
const ids = Object.keys(par.grupoDe).filter(id => Object.hasOwn(catExamenes, id));
const filasIds = [...new Set(Object.values(par.grupoDe))];
if (!ids.length || filasIds.some(id => !Object.hasOwn(catPacientes, id))) fail('Las categorías de mastografías y pacientes no coinciden.');
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
return periodos.map(periodo => {
const cats = ids.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) }));
return {
periodo, examenes: cats, sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
filas: filasIds.map(id => ({ id, etiqueta: etiqueta(catPacientes, id), pacientes: cuenta(filasP, periodo, id),
examenes: sumar(cats.filter(c => par.grupoDe[c.id] === id).map(c => c.n)) })),
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
};
});
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
export const razon = (f: FilaConteo) => f.pacientes && f.examenes !== null ? f.examenes / f.pacientes : null;
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const total = totalExamenes(m);
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
}
/** Per patient category: patients next to their exams, and how many exams each patient has. */
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
const traza = (clave: 'pacientes' | 'examenes', nombre: string, color: string) => ({
type: 'bar', orientation: 'h', name: nombre, y, x: m.filas.map(f => f[clave]), marker: { color },
text: m.filas.map(f => f[clave] === null ? 'Sin dato' : miles(f[clave]!)), textposition: 'outside', cliponaxis: false,
hovertemplate: `%{y}: %{x} ${nombre}<extra></extra>` });
const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0));
return { data: [traza('pacientes', par.unidades.pacientes, '#7A8794'), traza('examenes', par.unidades.examenes, '#C26A2B')],
layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 96, r: 150, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false },
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true },
annotations: m.filas.map((f, i) => {
const r = razon(f);
return { x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: y[i], yref: 'y', showarrow: false, align: 'left', font: { size: 12, color: p.text },
text: r === null ? 'Sin razón' : `<b>≈ ${r.toLocaleString('es-MX', { maximumFractionDigits: 1 })}</b> ${par.unidades.porPaciente}` };
}) }, config: { displayModeBar: false } };
}
@@ -1,6 +1,6 @@
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { font-size: 1.5rem; margin-top: 0; }
h2 { font-size: 1.25rem; font-weight: 500; margin-top: 0; }
h3 { font-size: 1.25rem; }
h4 { font-size: 1rem; margin-bottom: .5rem; }
section + section { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); }
@@ -19,7 +19,7 @@ export class IndicadoresDefinitions {
@Input() loading = false;
@Input() error = '';
readonly retry = output<void>();
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION;
@@ -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,
@@ -126,12 +126,12 @@ describe('Pestaña Histórico', () => {
it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => {
abrir();
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
fixture.componentInstance.tipo.set('semestre'); render();
fixture.componentInstance.elegido.set('semestre'); render();
const semestre = http.expectOne(r => r.url === datosUrl);
expect(semestre.request.params.get('periodos')).toBe('2024-S1');
semestre.flush(datos('semestre', ['2024-S1'])); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)');
fixture.componentInstance.tipo.set('mes'); render();
fixture.componentInstance.elegido.set('mes'); render();
fixture.componentRef.setInput('tema', 'oscuro'); render();
http.expectNone(() => true);
});
@@ -147,11 +147,11 @@ describe('Pestaña Histórico', () => {
c.elegirVentana(5); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)');
http.expectNone(() => true);
c.tipo.set('semestre'); render();
c.elegido.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render();
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']);
c.tipo.set('mes'); render();
c.elegido.set('mes'); render();
expect(c.ventana()).toBe(5);
http.expectNone(() => true);
});
@@ -191,10 +191,10 @@ describe('Pestaña Histórico', () => {
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)');
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)');
// The other granularity keeps its own choice.
c.tipo.set('semestre'); render();
c.elegido.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render();
c.tipo.set('mes'); render();
c.elegido.set('mes'); render();
expect(c.ventana()).toBe(-1);
http.expectNone(() => true);
});
@@ -51,9 +51,9 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
template: `
<div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="tipo.set($event.value)">
<mat-button-toggle value="mes">Mensual</mat-button-toggle>
<mat-button-toggle value="semestre">Semestral</mat-button-toggle>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
@@ -123,7 +123,13 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
readonly tipo = signal<TipoPeriodo>('mes');
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.catalog().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
readonly tipo = computed<TipoPeriodo>(() => {
const elegido = this.elegido(), tipos = this.tipos();
return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes';
});
// How many of the latest periods to show, per granularity; 0 shows them all.
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
@@ -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 === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.initialPeriodState()).toBe('loading');
expect(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 === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
expect(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'] }));
@@ -48,7 +48,8 @@ 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_confirmacion_birads45', 'cama_dias_toma_diagnostico']);
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_tasa_deteccion_histopatologica',
'cama_eu38a', 'cama_dias_resultado_diagnostico']);
} else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
expect(run.selected()?.periodo).toBe(periods[0]);
@@ -129,7 +129,15 @@ const DATOS_2025_S2: Record<string, IndicadorDatos> = {
describe('KPI de CaMa con respuestas reales de WebApi', () => {
const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 };
const result = (index: number) => kpiResult(DATOS_2025_S2[KPI_BY_DOMAIN.cama[index].id], KPI_BY_DOMAIN.cama[index], 'cama', applied);
// The card of each real answer; confirmación and tamizaje a diagnóstico are no longer cards, so theirs is
// built from the answer, to keep checking the C1 and C3r rules on real data.
const ids = Object.keys(DATOS_2025_S2);
const result = (index: number) => {
const data = DATOS_2025_S2[ids[index]];
const definition = KPI_BY_DOMAIN.cama.find(d => d.id === ids[index])
?? { id: data.id, title: data.id, contrato: data.contrato as 'C1' | 'C3r', unit: '' };
return kpiResult(data, definition, 'cama', applied);
};
it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => {
expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 }));
@@ -5,7 +5,9 @@ const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit'
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 };
// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI.
const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0],
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] };
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]],
// One card of each contract, in the C2, C1, C3r order the tests index by.
cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
}
@@ -67,3 +69,4 @@ it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
.toBe('Selección no consolidable');
});
@@ -37,8 +37,10 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
],
cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
{ id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
{ id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.` },
{ id: 'cama_eu38a', title: 'Tiempo de tamizaje a resultado', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
],
};
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
@@ -48,6 +50,11 @@ const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => strin
cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`,
cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`,
};
const C2_INFO: Record<Dominio, string> = {
tea: 'Conteo de pacientes únicos en el periodo.',
cacu: 'Pacientes con citología tomada en el periodo.',
cama: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
};
const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = {
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
@@ -88,7 +95,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
if (!rows.every(row => count(row['n']))) return empty;
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
if (!count(value)) return empty;
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: C2_INFO[domain] };
}
if (definition.contrato === 'C1') {
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
@@ -44,8 +44,8 @@ describe('UX-04 navegación Angular', () => {
const harness = await setup();
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
load(domain, harness); harness.detectChanges();
// Our shell keeps the domain nav on the page itself, see indicadores-page.html.
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(3);
// Domain switching lives in the App header (app.spec.ts); the page must not add a second one.
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(0);
http.expectNone(() => true);
});
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
@@ -10,14 +10,6 @@
}
</header>
@if (!fichaPacienteAbierta()) {
<!-- Upstream moved domain switching into its own app shell's header (a
dropdown in app.ts/app.html); our shell is shared with other workspace
sections (Conectar, Gobernanza) so it stays here instead, same as before. -->
<nav aria-label="Dominios de indicadores" class="domain-nav">
@for (domain of dominios; track domain) {
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainNavLabels[domain] }}</a>
}
</nav>
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
@for (section of sections; track section.id) {
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
@@ -31,7 +23,7 @@
@if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
<p class="section-description">{{ dominio === 'tea' ? 'Se aplica a las figuras y los indicadores destacados.' : 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' }}</p>
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" />
@@ -56,7 +48,7 @@
@if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@let resumen = teaResumenPeriodo;
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
<h2 id="kpi-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
@@ -74,7 +66,7 @@
<section class="graphic-section" aria-labelledby="graphic-section-title">
<div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
<h2 id="graphic-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
@if (!catalogLoading() && !catalogError() && catalog().length) {
<p class="catalog-count" role="status">{{ catalogOrder().length }} indicadores publicados</p>
}
@@ -127,7 +119,7 @@
</section>
</div>
@if (dominio === 'tea') {
@if (conHistorico) {
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
</section>
@@ -4,43 +4,17 @@
// The workspace shell clips overflow, so the page scrolls itself.
:host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); }
.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
h1 { font: var(--mat-sys-headline-large); font-family: var(--issste-font-heading); font-weight: 700; margin: .65rem 0; }
h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
// Kept here (not moved to our app shell, see the template comment above the
// nav) -- same rules as before upstream relocated its own copy into app.scss.
.domain-nav {
display: flex;
flex-wrap: wrap;
gap: var(--issste-space-2);
padding: var(--issste-space-2);
justify-content: center;
margin: var(--issste-space-4) 0;
border-radius: var(--issste-radius);
}
.domain-nav a {
flex: 0 1 6rem;
max-width: 10rem;
color: var(--issste-text);
border: 1px solid var(--issste-border);
background: var(--issste-surface);
min-height: 44px;
border-radius: var(--issste-radius);
}
.domain-nav a[aria-current='page'] {
background: var(--issste-accent);
font-weight: 700;
text-decoration: none;
}
@media (max-width: 550px) {
.domain-nav { gap: var(--issste-space-2); padding-inline: 0; }
}
.state { padding: 1.25rem; margin: 0; }
.section-title { font-family: var(--issste-font-heading); font-size: 1.5rem; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
.kpi-section, .graphic-section { min-width: 0; }
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
// Every card of a row of cards is as tall as the tallest one.
.kpi-grid { grid-auto-rows: 1fr; }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
.catalog-grid { align-items: stretch; }
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
@@ -57,10 +31,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 550px) {
h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); }
h1 { font-size: 1.5rem; }
}
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
.global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
.global-filters .section-title { font-size: 1rem; }
.global-filters .section-description { margin: var(--issste-space-1) 0 var(--issste-space-2); font: var(--mat-sys-body-small); }
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
@@ -69,6 +45,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
align-items: stretch;
}
// Cáncer de mama's four cards: one size, four in a row on wide screens and two by two below.
@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
@@ -136,13 +136,9 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
http.expectNone(() => true);
});
it('UX-06B mantiene una sola navegación entre dominios, sin duplicar botones', () => {
// Our shell has no domain selector of its own (unlike upstream's App),
// so the page keeps exactly the one it always had -- not duplicated.
// (Needs a render pass first: unlike upstream's trivial "absent" check,
// confirming presence requires the template to have actually painted.)
// The App header owns the domain menu (app.spec.ts); fails if the page brings back its own links.
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(1);
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav a')).toHaveLength(3);
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(0);
expect(cards()).toHaveLength(0);
// Constructing the page legitimately initializes its domain catalog.
const catalogRequest = http.expectOne('/tea/indicadores');
@@ -1,7 +1,7 @@
import { DOCUMENT } from '@angular/common';
import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -11,7 +11,9 @@ import { MatIconModule } from '@angular/material/icon';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { esSocioConteos } from './indicadores-conteos-pareados';
import { IndicadoresService } from './indicadores.service';
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
import { IndicadorPeriodFilters } from './indicador-period-filters';
@@ -35,17 +37,20 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// Only TEA has enough periods for its history to say anything.
const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
// Domains with enough periods for their history to say anything.
const CON_HISTORICO: readonly Dominio[] = ['tea', 'cama'];
const MIN_BUSQUEDA = 5;
const HISTORICO_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
@Component({
selector: 'app-indicadores-page',
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections() { return this.dominio === 'tea' ? TEA_SECTIONS : SECTIONS; }
get sections() { return this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
get conHistorico() { return CON_HISTORICO.includes(this.dominio); }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
setFichaPacienteAbierta(open: boolean) {
@@ -265,14 +270,12 @@ export class IndicadoresPage {
private readonly memory = inject(IndicadoresMemory);
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute, { optional: true });
readonly dominios = DOMINIOS;
dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
// At the start of the header line.
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino' };
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
// Short form for the domain-switcher buttons (our shell's own nav, see the
// template comment above it) -- `domainLabels`/`domainTitles` are prose-length.
readonly domainNavLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
@@ -306,13 +309,17 @@ export class IndicadoresPage {
readonly catalog = signal<Indicador[]>([]);
// Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null);
readonly searchVisible = computed(() => this.catalogOrder().length >= 2);
// With a few indicators every card is in view; the selector only pays off from MIN_BUSQUEDA on.
readonly searchVisible = computed(() => this.catalogOrder().length >= MIN_BUSQUEDA);
// Stable presentation priority; pins still take precedence in the grid.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
// The interactive views go first.
// A paired partner is drawn on its pair's card, not on one of its own.
const ids = catalog.map(item => item.id);
const resumen = catalog.filter(item => (!item.vistas || item.vistas.includes('resumen')) && !esSocioConteos(this.dominio, item.id, ids));
const primero = (item: Indicador) => !!vistaEscenario(this.dominio, item);
return [...resumen.filter(primero), ...resumen.filter(item => !primero(item))];
});
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
readonly selectionSummary = computed(() => {
@@ -9,6 +9,9 @@ import { IndicadorPeriodFilters } from './indicador-period-filters';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { Dominio, IndicadorDatos } from './indicadores.models';
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
// rules (indicador-kpi-panel.spec.ts covers all four).
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
describe('P0.1 selección publicada y último periodo por KPI', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
beforeEach(() => {
@@ -21,12 +24,12 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) });
function catalog(domain: Dominio) {
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
http.expectOne('/' + domain + '/indicadores').flush(KPIS[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
fixture.detectChanges();
return http.match(r => r.url.endsWith('/periodos'));
}
function load(domain: Dominio, periods: string[][]) {
catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i])));
catalog(domain).forEach((r, i) => r.flush(payload(KPIS[domain][i].id, periods[i])));
fixture.detectChanges();
}
// Regression assertions below target the original KPI contracts. The added lab
@@ -43,7 +46,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
const d = KPI_BY_DOMAIN[domain][index];
const d = KPIS[domain][index];
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{
periodo: period, grupo: d.contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0,
@@ -56,7 +59,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
if (!requests.length) return resolved;
resolved.push(...requests);
requests.forEach(r => {
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
const index = KPIS[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed));
});
fixture.detectChanges();
@@ -64,11 +67,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
}
it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => {
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]);
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos'));
const anchor = http.expectOne(r => r.url.endsWith('/' + KPIS[domain][0].id + '/datos'));
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
const requests = flushDatos(domain);
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1'));
expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1'));
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPIS[domain].slice(1).map(() => '2026-S1'));
expect(panels().map(p => p.temporalReference)).toEqual(KPIS[domain].map(() => '2026-S1'));
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]);
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
@@ -112,7 +115,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => {
const requests = catalog('cacu');
requests[0].flush('private', { status: 503, statusText: 'Unavailable' });
requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2'])));
requests.slice(1).forEach((r, i) => r.flush(payload(KPIS.cacu[i + 1].id, ['2025-S2'])));
fixture.detectChanges(); flushDatos('cacu');
expect(fixture.componentInstance.initialPeriodState()).toBe('error');
expect(panels()).toHaveLength(0);
@@ -130,7 +133,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const outgoing = catalog('cacu'); const incoming = catalog('cama');
expect(outgoing.every(r => r.cancelled)).toBe(true);
expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow();
incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1'])));
incoming.forEach((r, i) => r.flush(payload(KPIS.cama[i].id, ['2025-S1'])));
fixture.detectChanges(); const requests = flushDatos('cama');
expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true);
expect(editor().options).toEqual(['2025-S1']);
@@ -45,9 +45,10 @@ describe('Selección de indicadores gráficos', () => {
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: catálogo de %i', count => {
it.each([0, 1, 4, 5, 6])('muestra el selector desde cinco indicadores: catálogo de %i', count => {
// Fails if the selector shows for a handful of cards, or stops showing for a long catalog.
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
expect(!!select()).toBe(count >= 5); expect(cards()).toHaveLength(count);
http.expectNone(() => true);
});
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
@@ -37,15 +37,13 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea'
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' || domain === 'cama'
? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
// Upstream moved domain selection to its own App shell; ours keeps it on
// the page itself (see indicadores-page.html), since our shell is shared
// with other workspace sections.
expect(root.querySelector('nav.domain-nav')).not.toBeNull();
// The App header switches domains (see app.html); the page has no switcher of its own.
expect(root.querySelector('nav.domain-nav')).toBeNull();
for (const tab of tabs) {
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
expect(panel.getAttribute('aria-labelledby')).toBe(tab.id);
@@ -53,25 +51,14 @@ describe('Secciones compartidas por dominio', () => {
}
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
tab('seguimiento').click(); harness.detectChanges();
if (domain === 'cacu' || domain === 'tea') {
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
}
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
if (domain === 'cacu') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else if (domain === 'tea') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else {
expect(tracking.querySelectorAll('thead th')).toHaveLength(6);
expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1);
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
}
// Every domain queries its list; until it is published there is no table, only the form.
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
tab('datos').click(); harness.detectChanges();
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
tab('resumen').click(); harness.detectChanges();
@@ -6,7 +6,7 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
return item.contrato === 'C2' && Array.isArray(item.filtros)
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
? (['grupo_edad', 'estatus_seguimiento', 'birads'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
}
@@ -5,24 +5,23 @@
}
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
<h2>Seguimiento de {{ domainLabel }}</h2>
@if (dominio !== 'cacu' && dominio !== 'tea') {
<p>El seguimiento aún no está disponible.</p>
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
<table>
<thead><tr><th scope="col">Paciente / identificación</th><th scope="col">Proceso o etapa</th><th scope="col">Estado</th><th scope="col">Fecha de referencia</th><th scope="col">Responsable</th><th scope="col">Acciones</th></tr></thead>
<tbody><tr><td colspan="6">No hay registros de seguimiento disponibles.</td></tr></tbody>
</table>
</div>
} @else {
<form (ngSubmit)="apply()">
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
</select></label>
@if (propio) {
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
</select></label>
}
@for (f of filtrosTabla; track f.clave) {
<label>{{ f.etiqueta }} <select [name]="'filtro-' + f.clave" [attr.name]="'filtro-' + f.clave" [(ngModel)]="filtrosDraft[f.clave]">
<option [ngValue]="undefined">Todos</option>
@for (o of f.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
</select></label>
}
@if (dominio === 'tea') {
<label>Grupo de edad <select name="grupo_edad" [(ngModel)]="draft.grupo_edad">
<option [ngValue]="undefined">Todos</option>
@@ -92,6 +91,22 @@
</tbody>
</table>
</div>
} @else if (tablaData; as response) {
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr>@for (c of response.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
<tbody>
@for (item of response.items; track item['id_seudonimo']) {
<tr [attr.data-paciente]="item['id_seudonimo']">
@for (c of response.columnas; track c.clave) {
<td>{{ valorTabla(item[c.clave]) }}@for (d of detallesTabla(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ valorTabla(item[d.clave]) }}</small> } }</td>
}
</tr>
} @empty { <tr><td [attr.colspan]="response.columnas.length">No hay registros para los filtros aplicados.</td></tr> }
</tbody>
</table>
</div>
} @else if (data; as response) {
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<table>
@@ -117,5 +132,4 @@
<button type="button" [disabled]="response.paginacion.page >= response.paginacion.total_pages" (click)="navigate(response.paginacion.page + 1)">Siguiente</button>
</nav>
}
}
</div>
@@ -1,6 +1,6 @@
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { font-size: 1.5rem; margin-top: 0; }
h2 { font-size: 1.25rem; font-weight: 500; margin-top: 0; }
p { color: var(--issste-text-secondary); }
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
@@ -31,7 +31,7 @@ tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issst
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: var(--issste-radius); border: 1px solid var(--issste-border); font-weight: 600; }
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
tbody tr.tea-row { cursor: pointer; transition: background-color 120ms ease; }
tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
@@ -12,6 +12,7 @@ import { Dominio } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen';
import { SeguimientoColumna, SeguimientoFiltro, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor } from './seguimiento-tabla.service';
@Component({
selector: 'app-indicadores-tracking',
@@ -27,6 +28,7 @@ export class IndicadoresTracking implements OnChanges {
private readonly service = inject(CacuSeguimientoService);
private readonly indicators = inject(IndicadoresService);
private readonly teaService = inject(TeaSeguimientoService);
private readonly tablaService = inject(SeguimientoTablaService);
private readonly destroy = inject(DestroyRef);
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly injector = inject(Injector);
@@ -35,18 +37,22 @@ export class IndicadoresTracking implements OnChanges {
private controlPaciente?: HTMLElement;
private readonly requests = new Subject<SeguimientoQuery | null>();
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
private readonly tablaRequests = new Subject<{ dominio: Dominio; q: SeguimientoQuery } | null>();
private initialized = false;
private previousDomain?: Dominio;
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
message = '';
data?: SeguimientoResponse;
teaData?: TeaSeguimientoResponse;
// Domains whose list announces its own filters and columns.
tablaData?: SeguimientoTablaResponse;
filtrosTabla: SeguimientoFiltro[] = [];
// One open summary at a time, like an accordion.
teaAbierto?: string;
statuses: SeguimientoStatus[] = [];
private metadataLoaded = false;
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50, filtros: {} };
private applied: SeguimientoQuery = { ...this.draft };
readonly latestStudy = latestStudy;
readonly gruposEdad = GRUPOS_EDAD_TEA;
@@ -57,7 +63,8 @@ export class IndicadoresTracking implements OnChanges {
// Kept from the last answer, so the filter doesn't empty while a query is running.
tiposAlteracion: { codigo: string; etiqueta: string }[] = [];
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
get response() { return this.dominio === 'tea' ? this.teaData : this.data; }
get response() { return this.dominio === 'tea' ? this.teaData : this.dominio === 'cacu' ? this.data : this.tablaData; }
get propio() { return this.dominio === 'cacu' || this.dominio === 'tea'; }
constructor() {
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
@@ -93,24 +100,43 @@ export class IndicadoresTracking implements OnChanges {
this.draft = { ...this.applied };
}
});
this.tablaRequests.pipe(switchMap(r => r ? defer(() => this.tablaService.consultar(r.dominio, r.q)).pipe(
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, r.q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
if (!result) return;
this.changeDetector.markForCheck();
this.status = result.status; this.tablaData = result.data; this.message = result.message;
if (result.data) {
const data = result.data;
this.filtrosTabla = data.filtros_disponibles;
const filtros = Object.fromEntries(Object.entries(data.filtros).filter((e): e is [string, string] => e[1] !== null));
this.applied = { corte: data.corte, meses: data.ventana.meses, filtros, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied, filtros: { ...filtros } };
}
});
}
ngOnChanges() {
if (this.previousDomain !== this.dominio) {
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.tablaRequests.next(null);
this.data = undefined; this.teaData = undefined; this.tablaData = undefined; this.filtrosTabla = [];
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50, filtros: {} }; this.applied = { ...this.draft };
}
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
if (!this.propio && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
}
private load(q: SeguimientoQuery) {
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.tablaData = undefined; this.applied = { ...q };
if (this.dominio === 'tea') this.teaRequests.next(q);
else if (this.dominio === 'cacu') this.requests.next(q);
else this.tablaRequests.next({ dominio: this.dominio, q });
}
apply() { this.load({ ...this.draft, page: 1 }); }
apply() { this.load({ ...this.draft, filtros: Object.fromEntries(Object.entries(this.draft.filtros ?? {}).filter(([, v]) => v)), page: 1 }); }
valorTabla(v: SeguimientoValor | undefined) { return v === null || v === undefined || v === '' ? 'No disponible' : typeof v === 'number' ? v.toLocaleString('es-MX') : v; }
detallesTabla(c: SeguimientoColumna) { return c.detalles ?? []; }
get filtrosDraft() { return this.draft.filtros ??= {}; }
retry() { this.load(this.applied); }
navigate(page: number) {
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
@@ -18,8 +18,13 @@ export interface Indicador {
filtros?: IndicadorFiltro[];
// Tabs that show it; without this field, all of them.
vistas?: string[];
// Interactive donut and bars by one stratum, like CaCu's EU7.
escenario?: VistaEscenario;
}
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado';
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads'];
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
@@ -1,7 +1,7 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
import { DatosScope, DIMENSIONES_ESTRATO, DimensionEstrato, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -20,7 +20,9 @@ export class IndicadoresService {
&& new Set(item['figuras']).size === item['figuras'].length
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length
&& (item['escenario'] === undefined || record(item['escenario']) && typeof item['escenario']['etiqueta'] === 'string'
&& DIMENSIONES_ESTRATO.includes(item['escenario']['estrato'] as DimensionEstrato)))) {
throw new Error('Respuesta de catálogo inválida');
}
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
@@ -66,7 +68,7 @@ export class IndicadoresService {
}
let params = new HttpParams();
if (scope.estrato) {
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
if (!DIMENSIONES_ESTRATO.includes(scope.estrato)) throw new Error('Dimensión no admitida');
params = params.set('estrato', scope.estrato);
}
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
@@ -0,0 +1,56 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
import { Dominio, requireDominio } from './indicadores.models';
// Follow-up list whose filters and columns come with the answer, so a domain needs no code of its own.
export type SeguimientoValor = string | number | null;
// `detalles` are shown under the value, each with its label (for example the date of a result).
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[] }
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoStatus[] }
export interface SeguimientoTablaResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
filtros: Record<string, string | null>;
filtros_disponibles: SeguimientoFiltro[];
columnas: SeguimientoColumna[];
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
items: Record<string, SeguimientoValor>[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const valor = (v: unknown) => v === null || typeof v === 'string' || typeof v === 'number' && Number.isFinite(v);
// Keys travel as query parameters, so they are restricted to what can't collide with the shared ones.
const clave = (v: unknown) => text(v) && /^[a-z][a-z0-9_]*$/.test(v) && !['meses', 'page', 'page_size', 'corte'].includes(v);
const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiqueta']);
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
// Same rule as CaCu and TEA: demonstration records only.
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'], available = v['filtros_disponibles'], columns = v['columnas'];
if (!isoDate(v['corte']) || !record(window) || ![1, 3, 6, 12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !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(available) || !available.every(f => record(f) && clave(f['clave']) && text(f['etiqueta']) && Array.isArray(f['opciones']) && f['opciones'].every(opcion))
|| new Set(available.map(f => f['clave'])).size !== available.length
|| !record(filters) || !Object.entries(filters).every(([k, f]) => f === null || typeof f === 'string' && available.some(a => a['clave'] === k))
|| !Array.isArray(columns) || !columns.length || !columns.every(c => record(c) && text(c['clave']) && text(c['etiqueta'])
&& (c['detalles'] === undefined || Array.isArray(c['detalles']) && c['detalles'].every(d => record(d) && text(d['clave']) && text(d['etiqueta']))))
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number)
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor)))
throw new Error('Respuesta de seguimiento inválida');
return v as unknown as SeguimientoTablaResponse;
}
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {
private readonly http = inject(HttpClient);
consultar(dominio: Dominio, query: SeguimientoQuery) {
if (!validSeguimientoQuery(query) || !Object.keys(query.filtros ?? {}).every(clave)) throw new Error('Parámetros de seguimiento inválidos');
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
if (query.corte) params = params.set('corte', query.corte);
for (const [k, v] of Object.entries(query.filtros ?? {})) if (v) params = params.set(k, v);
return this.http.get<unknown>(`/${requireDominio(dominio)}/seguimiento`, { params }).pipe(map(seguimientoTablaResponse));
}
}
@@ -0,0 +1,90 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import eu7 from './fixtures/eu7-c2-ejemplos.json';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { modelo, vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadoresTracking } from './indicadores-tracking';
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
// Covers what lets a domain reuse CaCu's views without code of its own: the interactive donut and bars
// chosen by the catalog's `escenario`, and the follow-up list whose filters and columns come in the answer.
// Fixtures: `eu7-c2-ejemplos.json` (CaCu's EU7 answers, relabelled here as another stratum) and `lista`,
// a two-patient CaMa list built below.
// Two CaMa patients, one without a biopsy, with the filters and columns the list announces.
const lista = () => ({
simulado: true, corte: '2026-10-20', ventana: { meses: 3, desde: '2026-07-21', hasta: '2026-10-20' },
filtros: { birads: null }, filtros_disponibles: [{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: [{ codigo: 'BIRADS_5', etiqueta: 'BI-RADS 5' }] }],
columnas: [{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' },
{ clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] },
{ clave: 'biopsia', etiqueta: 'Resultado histopatológico' }],
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
items: [{ id_seudonimo: 'M-0001', birads: 'BI-RADS 5', mastografia_fecha: '2026-09-01', biopsia: 'Carcinoma invasor' },
{ id_seudonimo: 'M-0002', birads: 'BI-RADS 4A', mastografia_fecha: '2026-08-15', biopsia: null }],
});
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();
});
});
describe('Seguimiento con filtros y columnas anunciados', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresTracking); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama');
fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const text = () => fixture.nativeElement.textContent as string;
it('pinta las columnas, los detalles y los valores ausentes de la respuesta', () => {
// Fails if CaMa stops querying its own list or the table stops following `columnas`.
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista()); fixture.detectChanges();
const headers = Array.from(fixture.nativeElement.querySelectorAll('thead th')).map(e => (e as HTMLElement).textContent?.trim());
expect(headers).toEqual(['Identificador seudónimo', 'Última mastografía', 'Resultado histopatológico']);
expect(text()).toContain('Fecha: 2026-09-01');
expect(fixture.nativeElement.querySelectorAll('tbody tr')[1].textContent).toContain('No disponible');
});
it('envía cada filtro anunciado con su clave y sin los vacíos', () => {
// Fails if the announced filters stop reaching the query, or an empty choice is sent as a value.
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista()); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('select[name="filtro-birads"]')).not.toBeNull();
expect(fixture.nativeElement.querySelector('select[name="estatus"]')).toBeNull();
fixture.componentInstance.filtrosDraft['birads'] = 'BIRADS_5'; fixture.componentInstance.apply();
let req = http.expectOne(r => r.url === '/cama/seguimiento');
expect(req.request.params.get('birads')).toBe('BIRADS_5');
req.flush({ ...lista(), filtros: { birads: 'BIRADS_5' } });
fixture.componentInstance.filtrosDraft['birads'] = ''; fixture.componentInstance.apply();
req = http.expectOne(r => r.url === '/cama/seguimiento');
expect(req.request.params.has('birads')).toBe(false);
req.flush(lista());
});
it('sin lista publicada queda pendiente', () => {
// Fails if a 404 on the first page is shown as an error instead of a list not yet published.
http.expectOne(r => r.url === '/cama/seguimiento').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(text()).toContain('Funcionalidad pendiente de publicación');
});
it('solo admite datos de demostración y respuestas coherentes', () => {
// Fails if the validation stops guarding the table from real records or from filters it didn't announce.
expect(() => seguimientoTablaResponse({ ...lista(), simulado: false })).toThrow();
expect(() => seguimientoTablaResponse({ ...lista(), filtros: { edad: '40-49' } })).toThrow();
expect(() => seguimientoTablaResponse({ ...lista(), filtros_disponibles: [{ clave: 'page', etiqueta: 'X', opciones: [] }] })).toThrow();
expect(() => seguimientoTablaResponse({ ...lista(), items: [{ birads: 'BI-RADS 5' }] })).toThrow();
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista());
});
});
@@ -25,7 +25,7 @@ button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outl
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
dd[data-calidad=aceptable] { color: #B26A00; }
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
.bar { grid-column: 1 / -1; height: .375rem; border-radius: var(--issste-radius); background: var(--issste-border); overflow: hidden; }
.bar span { display: block; height: 100%; background: var(--issste-text); }
details { margin-top: .5rem; }
summary { cursor: pointer; font-weight: 600; font-size: .9rem; min-height: 44px; display: flex; align-items: center; gap: .5rem; list-style: none; }
@@ -44,7 +44,7 @@ dt { color: var(--issste-text-secondary); } dd { margin: 0; text-align: end; fon
.regiones li { padding: .1rem 0; }
.regiones li span:last-child { float: inline-end; font-variant-numeric: tabular-nums; }
.regiones .destacada { font-weight: 700; }
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: 999px;
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: var(--issste-radius);
font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; }
.sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; }
.metricas, .efectos { margin: 0; padding: 0; list-style: none; }
+9 -2
View File
@@ -10,7 +10,7 @@
--color-border: #e3e7df;
--color-step: #f0f3e8;
--font-body: 'Roboto', sans-serif;
--font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif;
--font-heading: 'Roboto', 'Helvetica Neue', Arial, sans-serif;
--site-header-height: 72px;
/* Spacing scale on a 4px grid. Use these for padding, margins and gaps
@@ -42,7 +42,7 @@
--issste-space-3: var(--space-3);
--issste-space-4: var(--space-4);
--issste-space-6: var(--space-6);
--issste-radius: var(--mat-sys-corner-medium);
--issste-radius: 4px;
}
html {
@@ -60,6 +60,13 @@ html {
density: 0,
)
);
// Institutional shapes: square corners with a slight rounding, including buttons (no pills).
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
--mat-sys-corner-full: 4px;
}
body {