diff --git a/src/app/features/indicadores/indicadores-analisis-figuras.ts b/src/app/features/indicadores/indicadores-analisis-figuras.ts
new file mode 100644
index 0000000..50e5d03
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-analisis-figuras.ts
@@ -0,0 +1,40 @@
+import { PlotlyFigure, Tema } from './indicadores.models';
+import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
+import { AnalisisAgregado } from './indicadores-analisis.service';
+
+/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». */
+export const etiquetaBirads = (codigo: string) => /^BIRADS_/.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
+const miles = (v: number) => v.toLocaleString('es-MX');
+
+/** The code of the published bar that was clicked, from its `customdata`; a suppressed bar or an empty click gives nothing. */
+export function grupoDelClic(evento: unknown, agregado: AnalisisAgregado | undefined): string | undefined {
+ const punto = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0];
+ const codigo = punto?.customdata;
+ return typeof codigo === 'string' && agregado?.grupos.some(g => g.codigo === codigo && !g.suprimido) ? codigo : undefined;
+}
+
+/**
+ * Patients per BI-RADS category. A suppressed category is drawn as an empty grey bar that says it is not published,
+ * never as a zero; each bar carries its code, so a click can only change the filters of the list, never read rows.
+ */
+export function gruposFigura(d: AnalisisAgregado, tema: Tema): PlotlyFigure {
+ const p = c2Theme(tema), s = C2_PALETTE.states;
+ return {
+ data: [{
+ type: 'bar', x: d.grupos.map(g => etiquetaBirads(g.codigo)), y: d.grupos.map(g => g.suprimido ? 0 : g.n),
+ customdata: d.grupos.map(g => g.codigo),
+ marker: { color: d.grupos.map(g => g.suprimido ? s.noData : C2_PALETTE.series[0]) },
+ text: d.grupos.map(g => g.suprimido ? 'No publicado' : miles(g.n!)), textposition: 'outside', cliponaxis: false,
+ hovertemplate: d.grupos.map(g => g.suprimido
+ ? `${etiquetaBirads(g.codigo)} Menos de ${d.umbral_supresion} pacientes: no se publica`
+ : `${etiquetaBirads(g.codigo)} ${miles(g.n!)} pacientes`),
+ }],
+ layout: {
+ autosize: true, height: 360, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
+ margin: { t: 32, l: 56, r: 16, b: 56 }, showlegend: false,
+ xaxis: { title: { text: 'Categoría BI-RADS' }, fixedrange: true, automargin: true },
+ yaxis: { title: { text: 'Pacientes' }, gridcolor: p.grid, zeroline: false, fixedrange: true, rangemode: 'tozero' },
+ },
+ config: { displayModeBar: false },
+ };
+}
diff --git a/src/app/features/indicadores/indicadores-analisis.service.ts b/src/app/features/indicadores/indicadores-analisis.service.ts
new file mode 100644
index 0000000..3a25e35
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-analisis.service.ts
@@ -0,0 +1,51 @@
+import { inject, Injectable } from '@angular/core';
+import { HttpClient, HttpParams } from '@angular/common/http';
+import { map } from 'rxjs';
+import { isoDate } from './cacu-seguimiento.models';
+import { Dominio, requireDominio } from './indicadores.models';
+
+// The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many
+// patients of the cohort fall in each BI-RADS category at a cut-off (`GET //analisis/indicadores?corte=`).
+// It is a descriptive count, not an incidence or a survival estimate, and it never carries patient rows. The answer
+// names the cohort, the scenario and a `revision` of the cohort that the patients' list must quote back: a list asked
+// for with another revision is refused, so a group opened from this count is always the group that was counted.
+export interface GrupoAnalisis { codigo: string; n: number | null; suprimido: boolean; }
+export interface AnalisisAgregado {
+ simulado: true; cohorte: string; revision: string; escenario: string; corte: string; umbral_supresion: number;
+ unidad: string; denominador: string; grupos: GrupoAnalisis[];
+}
+/** What a patients' list must quote back to open a group of the aggregate. */
+export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; }
+
+const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v);
+const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
+// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
+const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
+function sinFilasDePaciente(v: unknown): boolean {
+ if (Array.isArray(v)) return v.every(sinFilasDePaciente);
+ if (!record(v)) return true;
+ return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
+}
+
+/** Validates the aggregate before anything is drawn: aggregates only, and nothing published under the threshold. */
+export function analisisAgregado(v: unknown): AnalisisAgregado {
+ const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
+ if (!record(v) || v['simulado'] !== true) return invalido();
+ const umbral = v['umbral_supresion'], grupos = v['grupos'];
+ if (!sinFilasDePaciente(v) || !text(v['cohorte']) || !text(v['escenario']) || !isoDate(v['corte']) || !text(v['unidad']) || !text(v['denominador'])
+ || !text(v['revision']) || !/^[0-9a-f]{64}$/.test(v['revision']) || typeof umbral !== 'number' || !Number.isFinite(umbral) || umbral < 1
+ || !Array.isArray(grupos) || !grupos.length
+ || !grupos.every(g => record(g) && text(g['codigo']) && typeof g['suprimido'] === 'boolean'
+ && (g['suprimido'] ? g['n'] === null : typeof g['n'] === 'number' && Number.isInteger(g['n']) && g['n'] >= umbral))
+ || new Set(grupos.map(g => (g as GrupoAnalisis).codigo)).size !== grupos.length) return invalido();
+ return v as unknown as AnalisisAgregado;
+}
+
+@Injectable({ providedIn: 'root' })
+export class AnalisisService {
+ private readonly http = inject(HttpClient);
+ agregado(dominio: Dominio, corte: string) {
+ if (!isoDate(corte)) throw new Error('Fecha de corte inválida');
+ return this.http.get(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
+ }
+}
diff --git a/src/app/features/indicadores/indicadores-analisis.spec.ts b/src/app/features/indicadores/indicadores-analisis.spec.ts
new file mode 100644
index 0000000..c4464c9
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-analisis.spec.ts
@@ -0,0 +1,200 @@
+import { Component, output } from '@angular/core';
+import { TestBed } from '@angular/core/testing';
+import { provideHttpClient } from '@angular/common/http';
+import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
+import { PlotlyChart } from '../../shared/plotly/plotly-chart';
+import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
+import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
+import { analisisAgregado } from './indicadores-analisis.service';
+import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
+
+// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
+// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
+// sends to Seguimiento, and the tab's requests and states. The fixtures are in indicadores-analisis.testing.ts.
+
+describe('Respuesta del análisis', () => {
+ it('admite el agregado de la cohorte, con la extensión de grupos y el arreglo de indicadores vacío', () => {
+ // Fails if the real answer (with the fields the prototype leaves empty) stops being accepted.
+ expect(analisisAgregado(agregadoJson()).grupos).toHaveLength(6);
+ });
+ it('rechaza lo que no es un agregado: filas de paciente, un grupo suprimido con conteo o un grupo publicado bajo el umbral', () => {
+ // Fails if a guard stops rejecting patient rows at any depth, or a count that should be hidden.
+ expect(() => analisisAgregado({ ...agregadoJson(), simulado: false })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), pacientes: [] })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false, items: [{ id_seudonimo: 'M-1' }] }] })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_4', n: 3, suprimido: true }] })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 4, suprimido: false }] })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_5', n: 7, suprimido: false }] })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), revision: 'abc' })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), corte: '2026-13-40' })).toThrow();
+ expect(() => analisisAgregado({ ...agregadoJson(), grupos: [] })).toThrow();
+ });
+});
+
+describe('Figura del análisis', () => {
+ it('dibuja una barra por categoría con sus pacientes y la suprimida vacía, gris y sin cifra', () => {
+ // Fails if a suppressed category is drawn as a zero count, or loses its explanation.
+ const fig = gruposFigura(agregado(), 'claro');
+ const barra = fig.data[0];
+ expect(barra['x']).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
+ expect(barra['y']).toEqual([0, 0, 0, 0, 6, 0]);
+ expect((barra['text'] as string[]).filter(t => t === 'No publicado')).toHaveLength(5);
+ expect((barra['hovertemplate'] as string[])[0]).toContain('Menos de 5 pacientes: no se publica');
+ expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
+ });
+ it('un clic solo da el código de una barra publicada', () => {
+ // Fails if a click on a suppressed or unknown bar could open its list.
+ expect(grupoDelClic({ points: [{ customdata: 'BIRADS_5' }] }, agregado())).toBe('BIRADS_5');
+ expect(grupoDelClic({ points: [{ customdata: 'BIRADS_4' }] }, agregado())).toBeUndefined();
+ expect(grupoDelClic({ points: [{ customdata: 'OTRO' }] }, agregado())).toBeUndefined();
+ expect(grupoDelClic({ points: [{}] }, agregado())).toBeUndefined();
+ expect(grupoDelClic(undefined, agregado())).toBeUndefined();
+ });
+ it('escribe los códigos como en la clínica', () => {
+ expect(etiquetaBirads('BIRADS_4A')).toBe('BI-RADS 4A');
+ expect(etiquetaBirads('OTRO')).toBe('OTRO');
+ });
+});
+
+describe('Selección que va a Seguimiento', () => {
+ it('un grupo publicado lleva su filtro, el corte, el nombre, cuántas pacientes cuenta y la cohorte con su revisión', () => {
+ // Fails if the list is opened without the cohort's revision, at another cut-off, or on another group.
+ expect(seleccionDeGrupo(agregado(), 'BIRADS_5')).toEqual({
+ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 6, contexto: CONTEXTO });
+ });
+ it('un grupo suprimido o desconocido no abre nada y dice por qué', () => {
+ // Fails if the list of a group the answer hid could be opened.
+ expect(motivoSinLista(agregado(), 'BIRADS_4')).toBe(MOTIVO_GRUPO_SUPRIMIDO);
+ expect(seleccionDeGrupo(agregado(), 'BIRADS_4')).toBeUndefined();
+ expect(seleccionDeGrupo(agregado(), 'OTRO')).toBeUndefined();
+ expect(motivoSinLista(agregado(), 'BIRADS_5')).toBeUndefined();
+ });
+ it('hoy se escribe como la fecha de un campo de fecha, en el día del usuario', () => {
+ expect(hoyIso(new Date(2026, 10, 3, 23, 59))).toBe('2026-11-03');
+ });
+});
+
+@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
+class ChartStub { readonly plotClick = output(); }
+
+describe('Pestaña Análisis epidemiológico', () => {
+ let fixture: ReturnType>, http: HttpTestingController;
+ beforeEach(() => {
+ TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
+ TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
+ fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
+ fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
+ });
+ afterEach(() => { fixture.destroy(); http.verify(); });
+ const root = () => fixture.nativeElement as HTMLElement;
+ const text = () => root().textContent as string;
+ const pedido = (corte = hoyIso()) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte);
+ const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
+ const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
+ // The date goes in as the user would type it; ngModel writes its value in a microtask.
+ async function escribirCorte(valor: string) {
+ // A form control is registered in a microtask after its first render: it is only ready to be typed into after that.
+ fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
+ const c = root().querySelector('input[name="corte"]') as HTMLInputElement;
+ c.value = valor; c.dispatchEvent(new Event('input', { bubbles: true })); c.dispatchEvent(new Event('change', { bubbles: true }));
+ fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
+ expect(c.value, 'el campo conserva lo escrito').toBe(valor === '2026-02-31' ? '' : valor);
+ }
+
+ it('no pide nada hasta abrirse; luego pide el agregado al corte de hoy y lo dibuja con su tabla', () => {
+ // Fails if the tab loads while hidden, or its first request stops carrying a cut-off.
+ fixture.detectChanges();
+ http.expectNone(() => true);
+ abrir();
+ expect(text()).toContain('Pacientes por categoría BI-RADS');
+ pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
+ expect(text()).toContain('No estima incidencia, recurrencia ni supervivencia.');
+ const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
+ expect(filas.map(f => f.querySelector('th')!.textContent!.trim())).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
+ expect(filas.map(f => f.children[1].textContent!.trim())).toEqual(['No publicado', 'No publicado', 'No publicado', 'No publicado', '6', 'No publicado']);
+ });
+ it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => {
+ // Fails if a slow answer replaces the aggregate of a later cut-off.
+ abrir();
+ const primera = pedido(); primera.flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ await escribirCorte('2026-09-01');
+ expect(fixture.componentInstance.corte).toBe('2026-09-01');
+ boton('Consultar')!.click(); fixture.detectChanges();
+ const lenta = pedido('2026-09-01');
+ // The button is disabled while a query runs, so the later query comes from the code (a retry, a programmatic refresh).
+ expect(boton('Consultar')!.disabled).toBe(true);
+ await escribirCorte('2026-08-01'); fixture.componentInstance.consultar(); fixture.detectChanges();
+ expect(lenta.cancelled).toBe(true);
+ pedido('2026-08-01').flush(agregadoJson({ corte: '2026-08-01' })); fixture.detectChanges();
+ expect(text()).toContain('Fecha de corte: 2026-08-01.');
+ });
+ it('una fecha que no es de calendario no sale del navegador', async () => {
+ // Fails if an invalid cut-off is sent to the server.
+ abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ await escribirCorte('2026-02-31'); boton('Consultar')!.click(); fixture.detectChanges();
+ http.expectNone(() => true);
+ expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte');
+ });
+ it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => {
+ // Fails if the table offers the patients of a hidden group.
+ abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
+ expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
+ expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
+ expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
+ });
+ it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
+ // Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
+ const emitidas: SeleccionPacientes[] = [];
+ fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
+ abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ (root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement).click();
+ fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_5' }] });
+ fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_4' }] });
+ expect(emitidas).toHaveLength(2);
+ expect(emitidas[0]).toEqual(emitidas[1]);
+ expect(emitidas[0]).toMatchObject({ filtros: { birads: 'BIRADS_5' }, corte: hoyIso(), esperados: 6, contexto: { ...CONTEXTO } });
+ });
+ it('al volver restaura el foco en el control de origen y no repite ninguna consulta', () => {
+ // Fails if coming back from Seguimiento loses the focus or the answer already loaded.
+ fixture.componentInstance.verPacientes.subscribe(() => undefined);
+ abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ const origen = root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement;
+ origen.focus(); origen.click();
+ (document.activeElement as HTMLElement | null)?.blur();
+ fixture.componentInstance.restaurar();
+ http.expectNone(() => true);
+ expect(document.activeElement).toBe(origen);
+ expect(fixture.componentInstance.datos()?.grupos).toHaveLength(6);
+ });
+
+ it('sin endpoint publicado queda pendiente, sin mostrarse como un error', () => {
+ // Fails if a 404 is shown as a broken page instead of a feature not yet published.
+ abrir(); pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
+ expect(text()).toContain('Funcionalidad pendiente de publicación');
+ expect(root().querySelector('[role=alert]')).toBeNull();
+ });
+ it('con la cohorte no disponible (503) lo dice y deja reintentar; el reintento repite la misma consulta', () => {
+ // Fails if a cohort that is not configured is hidden, or the retry asks for another date.
+ abrir(); pedido().flush({ error: 'Cohorte no disponible' }, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
+ expect(text()).toContain('La cohorte no está disponible en este momento.');
+ boton('Reintentar consulta')!.click(); fixture.detectChanges();
+ pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
+ expect(root().querySelector('tbody')).not.toBeNull();
+ });
+ it('un error del servicio se muestra con su reintento y con el mensaje fijo, nunca con el cuerpo', () => {
+ // Fails if a real failure is swallowed or the server's own text reaches the page.
+ abrir(); pedido().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges();
+ expect(root().querySelector('[role=alert]')?.textContent).toContain('El servicio encontró un error interno');
+ expect(text()).not.toContain('detalle interno');
+ expect(boton('Reintentar consulta')).toBeDefined();
+ });
+ it('una respuesta fuera de contrato no se dibuja', () => {
+ // Fails if an answer with patient rows or counts under the threshold reaches the page.
+ abrir(); pedido().flush({ ...agregadoJson({ corte: hoyIso() }), pacientes: [{ id_seudonimo: 'M-0001' }] }); fixture.detectChanges();
+ expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
+ expect(root().querySelector('tbody')).toBeNull();
+ expect(text()).not.toContain('M-0001');
+ });
+});
diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts
new file mode 100644
index 0000000..edde907
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-analisis.ts
@@ -0,0 +1,216 @@
+import { Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, untracked } from '@angular/core';
+import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
+import { HttpErrorResponse } from '@angular/common/http';
+import { FormsModule } from '@angular/forms';
+import { MatButtonModule } from '@angular/material/button';
+import { MatProgressBarModule } from '@angular/material/progress-bar';
+import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
+import { PlotlyChart } from '../../shared/plotly/plotly-chart';
+import { isoDate } from './cacu-seguimiento.models';
+import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
+import { AnalisisAgregado, AnalisisService, ContextoCohorte } from './indicadores-analisis.service';
+import { Dominio, Tema } from './indicadores.models';
+
+type Carga = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
+
+/**
+ * The patients behind a group of the aggregate, for the page to open them in Seguimiento: the list's filters, how to
+ * name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
+ * patients the analysis counts there.
+ */
+export interface SeleccionPacientes { filtros: Record; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
+
+export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
+
+/** Today as the date input writes it, in the user's own calendar day. */
+export function hoyIso(ahora = new Date()) {
+ const dos = (n: number) => String(n).padStart(2, '0');
+ return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`;
+}
+
+/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
+export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
+ const g = agregado.grupos.find(x => x.codigo === codigo);
+ return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
+}
+
+/** The selection of a published group: the whole group of the cohort at the cut-off it was counted at, nothing else. */
+export function seleccionDeGrupo(agregado: AnalisisAgregado, codigo: string): SeleccionPacientes | undefined {
+ const g = agregado.grupos.find(x => x.codigo === codigo);
+ if (!g || motivoSinLista(agregado, codigo)) return undefined;
+ return { filtros: { birads: codigo }, etiqueta: `Categoría BI-RADS: ${etiquetaBirads(codigo)}`, corte: agregado.corte, esperados: g.n,
+ contexto: { cohorte: agregado.cohorte, escenario: agregado.escenario, revision: agregado.revision } };
+}
+
+/** The scrolling ancestor of an element, or the document's own scroller. */
+function contenedorDeScroll(el: HTMLElement): HTMLElement {
+ for (let n = el.parentElement; n; n = n.parentElement) {
+ const overflow = getComputedStyle(n).overflowY;
+ if ((overflow === 'auto' || overflow === 'scroll') && n.scrollHeight > n.clientHeight) return n;
+ }
+ return (el.ownerDocument.scrollingElement ?? el.ownerDocument.documentElement) as HTMLElement;
+}
+
+// Epidemiological analysis of the breast cohort. For now: how many patients of the cohort are in each BI-RADS category at
+// a cut-off, as a count (not an incidence or a survival estimate). A published category opens its patients in Seguimiento;
+// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
+@Component({
+ selector: 'app-indicadores-analisis',
+ imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart],
+ template: `
+
+
Pacientes por categoría BI-RADS
+
Conteo descriptivo de las pacientes de la cohorte en cada categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.