Compare commits

..

16 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 7580319fc8 fix(cama): single vertical scroll in Análisis epidemiológico
The visually-hidden labels are absolutely positioned and had no positioned ancestor in the view, so they were laid out against the document and, with the table far down the page, gave the document its own vertical scroll next to the one of the page container. The view is now their containing block.
2026-11-14 07:56:33 -06:00
Angel Capetillo Zavala 7a2f0f42a9 feat(cama): Análisis epidemiológico frame with category cards, cut-off bar and the BI-RADS count 2026-11-14 00:14:53 -06:00
Angel Capetillo Zavala 01d6e71f07 Accept 64-bit patient identifiers 2026-11-13 18:23:45 -06:00
Angel Capetillo Zavala 3b246b4f1f Identify follow-up patients by pac_id
Rows name their patient with pac_id (a decimal string) or the legacy
id_seudonimo. pac_id wins; an invalid pac_id is never replaced by the
legacy field, and a page that repeats a patient or mixes both fields is
not drawn or exported. The table, patient record, PDF and spreadsheet
follow the announced identifier column and label. CaCu requests risk
only with a pac_id.
2026-11-13 18:19:27 -06:00
Angel Capetillo Zavala caf5f954b7 Proxy patient routes without the cohort access token 2026-11-13 18:19:26 -06:00
edgar edb868f372 Patient record reads its risk from GET /cacu/pacientes/<pac_id>/riesgo, by the id the follow-up list shows 2026-11-13 17:29:54 -06:00
Angel Capetillo Zavala 2e0938628c Merge commit '0acee49de2098b2f9d06607f7d374091a5f4b764' into dashboard-test
# Conflicts:
#	src/app/features/indicadores/etiquetas-cohorte.ts
#	src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts
2026-11-13 15:45:55 -06:00
Angel Capetillo Zavala 3783505dbd Use the regular window for breast follow-up 2026-11-13 15:44:01 -06:00
Angel Capetillo Zavala 0acee49de2 fix(cama): regular follow-up opens on the 3-month window and adopts the cohort the server returns
The follow-up list asks for the regular window without quoting a revision; when the answer
names a cohort the next pages and the files quote it. A new cut-off or a revision that changed
under the list is asked for again without the old revision (once, then reported). Leaving the
analysis' selection returns to the regular window. A server that does not answer from the cohort
keeps the plain list.

Histopathology codes are written with the catalog labels (Benigno, Carcinoma in situ, Carcinoma
invasor, Desconocido); other values stay as they arrive.
2026-11-13 15:43:02 -06:00
Angel Capetillo Zavala 18e9260705 Keep breast follow-up on the selected cohort 2026-11-13 15:32:39 -06:00
Angel Capetillo Zavala 3f4cf2217f Merge commit '7971a49dcda5f9759f6cf4693c1c725153172edb' into dashboard-test 2026-11-13 15:23:06 -06:00
Angel Capetillo Zavala 7971a49dcd feat(cama): regular follow-up read from the cohort, with the revision refreshed on a new cut-off
The follow-up tab of breast cancer now reads the cohort the analysis publishes: it asks for the
cohort's revision at today's cut-off and lists the whole cohort quoting it. Where the server does
not publish the cohort (404 or 503 on its aggregate) the plain follow-up list is read.

- Another cut-off in the form asks for that cut-off's revision before the list; a revision that
  changes under the list (409) is asked for again once and the same query repeated, and a conflict
  that persists is reported.
- "Quitar selección" returns to the whole cohort instead of another source.
- An empty whole cohort says "Sin pacientes para el corte seleccionado"; filters and windows keep
  the text of the filters.
- Filters, cut-off, page and rows are kept while a record is opened and closed.
- Page specs that open CaMa follow-up answer the aggregate first.
2026-11-13 15:18:11 -06:00
Angel Capetillo Zavala c06cce20df Pass synthetic cohort access through the server proxy 2026-11-13 15:17:14 -06:00
Angel Capetillo Zavala 2b0f6dfbed feat(cama): readable BI-RADS and age labels, the biopsy report date, and no export of a list that does not match its group
Contract review against WebApi 1d5f1e0 (webapi/cama_analysis.py, cama_cohort.py, docs/cama-cohort-api.md).

- The cohort's list is rewritten once on arrival so the table, the record and the PDF/XLSX show
  "BI-RADS 5" and "50 a 59 años" (also "Menores de 40 años", "70 años o más", "Sin dato"); the codes
  stay in `<clave>_codigo` and in the filter options, which are what the requests send. Only codes
  whose meaning the API's own code confirms are labelled; biopsy grades are left as they arrive.
- The record calls the biopsy date what the list calls it ("Fecha de reporte"): in the cohort it is
  the date of the biopsy report, which can be known while its result is not.
- With the same cohort revision, cut-off and filter the aggregate and the list are counted from the
  same rows, so a different total breaks the contract: the list shows an alert and its PDF/XLSX
  buttons are disabled.
- When no category is published the analysis says so and keeps "No publicado": the answer cannot
  tell an empty cohort from categories under the threshold.
- Tests: the chosen cut-off reaches the aggregate, the list, the record and every page of the file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:29:45 -06:00
Angel Capetillo Zavala 1d43ebff3b feat(indicadores): Análisis epidemiológico tab for breast cancer, and the way back from Seguimiento
A CaMa-only tab between Histórico and Seguimiento shows how many patients of the cohort fall in
each BI-RADS category at a cut-off (GET /cama/analisis/indicadores?corte=), as the cohort API
publishes it. It is a descriptive count, not an incidence or a survival estimate.

- Loading, pending (404), unavailable (503), error and out-of-contract states; the answer is
  validated as an aggregate (no patient rows, nothing published under the threshold).
- A suppressed category is drawn grey and says why; only a published category opens its patients
  in Seguimiento ("Ver pacientes" or a click on its bar).
- The page keeps the selection while the user moves between tabs, clears it on a domain change, and
  "Volver al análisis" returns to the analysis as it was, with the scroll and the focus on the
  control that opened the list, and no new request.
- Tables and figure scroll inside their own region at phone width. CaCu and TEA keep their three
  sections. Curves, the heatmap and the cohort diagnostics of the prototype wait for an API.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:34 -06:00
Angel Capetillo Zavala eb92b99a1d feat(seguimiento): list opened on a group of the cohort, with its window, cut-off, cohort and revision
The follow-up list of breast cancer can now be opened on a selection that the analysis names: the
whole cohort (window 0, offered only while the selection is active), the cut-off the analysis was
computed at, the group's filter, and the cohort with its revision, which the server requires and
repeats.

- A cohort's list quotes `cohorte`, `escenario` and `revision` (not filters) on every page and in the
  export; an answer that loses a filter, changes the window or the cut-off, or is another cohort or
  revision is not drawn and cannot be exported.
- A new selection cancels the previous request; while it loads, and when it fails (403, 409, 503),
  no list of the previous query stays on screen.
- Inside the cohort the form refines the same cohort and says so; "Quitar selección" leaves it.
- "Volver al análisis" and a note when the list holds a different number of patients than the
  analysis counted.
- PDF and XLSX state the selection, the cut-off and "Toda la cohorte"; the file name tells a
  selection apart; an export in progress is cancelled, and a finished one discarded, when the query
  on screen changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:31 -06:00
52 changed files with 2276 additions and 178 deletions
@@ -1,7 +1,9 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
export interface SeguimientoPaciente {
id_seudonimo: string;
pac_id?: string;
id_seudonimo?: string;
grupo_edad: string;
estatus: SeguimientoStatus;
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
@@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
import { identidadDe, identidadesDe } from './paciente-identidad';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
@@ -19,12 +20,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
const c = item['ultima_citologia'], h = item['ultimo_vph'];
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
})) throw new Error('Respuesta de seguimiento inválida');
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
return v as unknown as SeguimientoResponse;
}
@Injectable({ providedIn: 'root' })
@@ -0,0 +1,20 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
};
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
const HISTOLOGIA: Readonly<Record<string, string>> = {
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
};
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
@@ -4,7 +4,7 @@ const pad = (n: number) => String(n).padStart(2, '0');
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
* patient identifier, because file names end up in download lists, backups and mail attachments.
*/
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
}
@@ -1,5 +1,6 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { Dominio } from '../indicadores.models';
import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
@@ -54,6 +55,8 @@ export class TrackingExportBar {
readonly respuesta = input.required<SeguimientoTablaResponse>();
/** False while a page is being loaded, so the export never reads a query that is about to change. */
readonly habilitado = input(true);
/** How the analysis named the selection this answer belongs to; it travels into the files. */
readonly seleccion = input<string | undefined>(undefined);
private readonly service = inject(SeguimientoTablaService);
private subscription?: Subscription;
@@ -73,13 +76,22 @@ export class TrackingExportBar {
// Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it.
private readonly queryKey = computed(() => {
const r = this.respuesta();
return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items]);
return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]);
});
constructor() {
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
// A result message belongs to the query it was made for: it goes away when another query is shown.
effect(() => { this.queryKey(); untracked(() => { if (this.estado() !== 'working') { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); } }); });
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
effect(() => {
this.queryKey();
untracked(() => {
if (this.estado() === 'working') {
this.subscription?.unsubscribe();
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
});
});
}
available(formato: ExportFormat): boolean {
@@ -90,10 +102,11 @@ export class TrackingExportBar {
if (!this.available(formato)) return;
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
this.subscription?.unsubscribe();
const clave = this.queryKey(), seleccion = this.seleccion();
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
next: event => {
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
else void this.generar(formato, event.snapshot);
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
},
error: error => this.fallar(error),
});
@@ -104,13 +117,15 @@ export class TrackingExportBar {
this.estado.set('idle');
}
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot) {
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
try {
// Each generator (and its library) downloads only when its button is used.
const blob = formato === 'xlsx'
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
downloadBlob(blob, exportFilename('seguimiento-cancer-de-mama', snapshot.corte, formato));
// The query on screen changed while the file was being made: it is not the one that was asked for.
if (clave !== this.queryKey()) return;
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
this.estado.set('idle');
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
} catch {
@@ -120,7 +135,10 @@ export class TrackingExportBar {
private fallar(error: unknown) {
this.estado.set('error');
this.mensaje.set(error instanceof ExportLimitExceeded ? 'La consulta excede el límite de este formato. Acota los filtros.'
const estatus = error instanceof HttpErrorResponse ? error.status : 0;
this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.'
: estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.'
: estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.'
: error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.'
: 'No se pudo generar el archivo. Intenta nuevamente.');
}
@@ -0,0 +1,157 @@
// Covers the files of a list opened from the analysis: they state the selection, the cut-off and «Toda la cohorte», and
// hold exactly the patients the table holds, over several pages; and an export never outlives the query it was made for.
// Fixture: fixtures/cama_seguimiento.json, whose rows are repeated to make a list of several pages.
import { TestBed } from '@angular/core/testing';
import { Observable, of, Subject } from 'rxjs';
import { strFromU8, unzipSync } from 'fflate';
import fixtureData from '../fixtures/cama_seguimiento.json';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service';
import { TrackingExportBar } from './tracking-export-bar';
import { CONTEXTO } from '../indicadores-analisis.testing';
import { fetchAllTracking, queryOf } from './tracking-export-source';
import { TrackingSnapshot } from './tracking-export.models';
import { trackingDocument } from './tracking-pdf';
import { buildTrackingXlsx } from './tracking-xlsx';
const ETIQUETA = 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 5';
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
// A cohort of `n` patients, M-0001 onwards, served in the pages that were asked for, with the filters it applied.
function cohorte(n: number) {
const plantilla = (base()['items'] as Record<string, unknown>[])[0];
const todos = Array.from({ length: n }, (_, i) => ({ ...plantilla, id_seudonimo: `M-${String(i + 1).padStart(4, '0')}` }));
return (q: SeguimientoTablaQuery): SeguimientoTablaResponse => seguimientoTablaResponse({
...base(), ventana: { meses: q.meses, desde: '2025-01-01', hasta: '2026-10-20' }, corte: q.corte ?? '2026-10-20',
filtros: { ...base()['filtros'], ...q.filtros }, ...(q.contexto ?? {}),
paginacion: { page: q.page, page_size: q.page_size, total_items: n, total_pages: Math.ceil(n / q.page_size) },
items: todos.slice((q.page - 1) * q.page_size, q.page * q.page_size),
});
}
const consulta = (extra: Partial<SeguimientoTablaQuery> = {}): SeguimientoTablaQuery =>
({ corte: '2026-10-20', meses: 0, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO, ...extra });
const textos = (nodo: unknown, salida: string[] = []): string[] => {
if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida));
return salida;
};
describe('Archivos de una selección del análisis', () => {
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery) => of(cohorte(450)(q)) } as unknown as SeguimientoTablaService;
it('el PDF y el XLSX dicen la selección, el corte y «Toda la cohorte», y traen los mismos pacientes que la tabla en todas sus páginas', async () => {
// Fails if a file loses the selection, calls the whole cohort «0 meses», or its patients differ from the table's pages.
const q = consulta();
// The table, page by page (50 per page), as the user would walk it.
const filasTabla: string[] = [];
for (let p = 1; p <= 9; p++) filasTabla.push(...cohorte(450)({ ...q, page: p }).items.map(i => String(i['id_seudonimo'])));
let snapshot!: TrackingSnapshot;
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({
next: e => { if (e.kind === 'done') snapshot = { ...e.snapshot, seleccion: ETIQUETA }; }, error: fallo, complete: ok }));
expect(snapshot.items.map(i => String(i['id_seudonimo']))).toEqual(filasTabla);
expect(new Set(filasTabla).size).toBe(450);
const pdf = textos(trackingDocument(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)), 'data:image/png;base64,AAAA'));
expect(pdf).toContain('Selección del análisis'); expect(pdf).toContain(ETIQUETA);
expect(pdf).toContain('Fecha de corte'); expect(pdf).toContain('2026-10-20');
expect(pdf).toContain('Toda la cohorte, al 2026-10-20');
expect(pdf.some(t => /0 meses/.test(t))).toBe(false);
expect(pdf.filter(t => /^M-\d{4}$/.test(t))).toEqual(filasTabla);
const PROHIBIDO = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|mock|valor cl[ií]nico/i;
expect(pdf.filter(t => PROHIBIDO.test(t))).toEqual([]);
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)))).arrayBuffer()));
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']);
expect(cadenas).toContain(ETIQUETA); expect(cadenas).toContain('Selección del análisis'); expect(cadenas).toContain('Toda la cohorte, al 2026-10-20');
expect(cadenas).not.toMatch(/0 meses/);
expect(cadenas.replace(/<[^>]+>/g, ' ')).not.toMatch(PROHIBIDO);
expect([...cadenas.matchAll(/M-\d{4}/g)].map(m => m[0]).filter((v, i, a) => a.indexOf(v) === i)).toEqual(filasTabla);
});
it('sin una selección los archivos no llevan esa línea y conservan la ventana de meses', async () => {
// Fails if a plain list gets a selection line, or a window of months stops being written as dates and months.
const q = consulta({ meses: 3, filtros: {} });
let snapshot!: TrackingSnapshot;
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = e.snapshot; }, error: fallo, complete: ok }));
const pdf = textos(trackingDocument(snapshot, new Date(), 'data:image/png;base64,AAAA'));
expect(pdf).not.toContain('Selección del análisis');
expect(pdf).toContain('2025-01-01 al 2026-10-20 (3 meses)');
});
it('la consulta de una respuesta conserva la cohorte y su revisión, y todas las páginas del archivo la citan', async () => {
// Fails if the export reads a cohort's list without quoting its revision (the server refuses it) or from another one.
const respuesta = cohorte(450)(consulta());
expect(queryOf(respuesta)).toMatchObject({ corte: '2026-10-20', meses: 0, page: 1, page_size: 200, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
const pedidas: SeguimientoTablaQuery[] = [];
const espia = { consultar: (_d: string, q: SeguimientoTablaQuery) => { pedidas.push(q); return of(cohorte(450)(q)); } } as unknown as SeguimientoTablaService;
await new Promise<void>((ok, fallo) => fetchAllTracking(espia, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
expect(pedidas.map(q => q.page).sort()).toEqual([1, 2, 3]);
expect(pedidas.every(q => q.contexto?.revision === CONTEXTO.revision && q.contexto?.cohorte === CONTEXTO.cohorte && q.meses === 0)).toBe(true);
// A plain list quotes no cohort.
expect(queryOf(seguimientoTablaResponse(base())).contexto).toBeUndefined();
});
it('una página posterior de otra revisión hace fallar la lectura', async () => {
// Fails if a file mixes pages of two revisions of the cohort.
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, contexto: { ...CONTEXTO, revision: 'f'.repeat(64) } }) : cohorte(450)(q));
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
expect(error).toBeInstanceOf(Error);
});
it('una página posterior que pierde un filtro hace fallar la lectura: no se exporta un subconjunto de otra consulta', async () => {
// Fails if a file mixes the pages of the selection with a page of another population.
const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, filtros: {} }) : cohorte(450)(q));
const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService;
const error = await new Promise<unknown>(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) }));
expect(error).toBeInstanceOf(Error);
});
});
describe('Exportación: la consulta cambia mientras se exporta', () => {
let respuestas: (q: SeguimientoTablaQuery) => Observable<SeguimientoTablaResponse>, descargas: string[];
let fixture: ReturnType<typeof TestBed.createComponent<TrackingExportBar>>;
beforeEach(() => {
descargas = [];
respuestas = q => of(cohorte(27)(q));
TestBed.configureTestingModule({ providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } }] });
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
});
afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); });
const montar = (r: SeguimientoTablaResponse, seleccion?: string) => {
fixture = TestBed.createComponent(TrackingExportBar);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('respuesta', r);
fixture.componentRef.setInput('seleccion', seleccion); fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
};
const excel = (root: HTMLElement) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes('Excel')) as HTMLButtonElement;
const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } };
it('un archivo de una selección se llama como tal y no lleva a ningún paciente en el nombre', async () => {
// Fails if the file of a selection is told apart from a plain list by nothing, or names a patient.
const root = montar(cohorte(27)(consulta()), ETIQUETA);
excel(root).click(); await esperar();
expect(descargas).toHaveLength(1);
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/);
expect(descargas[0]).not.toMatch(/M-\d|cama/i);
});
it('si la consulta en pantalla cambia mientras se lee, se cancela y no se descarga nada', async () => {
// Fails if a list read for the old selection is downloaded as the one now on screen.
const lenta = new Subject<SeguimientoTablaResponse>();
respuestas = () => lenta;
const root = montar(cohorte(27)(consulta()), ETIQUETA);
excel(root).click(); fixture.detectChanges();
expect(root.textContent).toContain('Preparando exportación');
fixture.componentRef.setInput('respuesta', cohorte(27)(consulta({ filtros: { birads: 'BIRADS_6' } })));
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
lenta.next(cohorte(27)(consulta()));
await esperar();
expect(descargas).toEqual([]);
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió; se canceló la exportación');
expect(excel(root).disabled).toBe(false);
});
it('si cambia mientras se genera el archivo, tampoco se descarga', async () => {
// Fails if a file finished after the selection changed still reaches the downloads.
const root = montar(cohorte(27)(consulta()), ETIQUETA);
excel(root).click();
fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges();
await esperar();
expect(descargas).toEqual([]);
expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió');
});
});
@@ -1,6 +1,7 @@
import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs';
import { Dominio } from '../indicadores.models';
import { PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
import { identidadesDe } from '../paciente-identidad';
import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models';
const CONCURRENCY = 3;
@@ -13,17 +14,14 @@ export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQue
page: 1,
page_size: PAGE_SIZE_MAX,
filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])),
// A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server.
contexto: contextoDe(response),
};
}
// The server must report having applied the window and the filters that were asked for; otherwise the file would
// hold rows of another query under the title of this one.
function sameQuery(query: SeguimientoTablaQuery, answer: SeguimientoTablaResponse): boolean {
const entries = (filters: Record<string, string | null | undefined>) =>
JSON.stringify(Object.entries(filters).filter(([, v]) => !!v).sort(([a], [b]) => a.localeCompare(b)));
return answer.ventana.meses === query.meses && (!query.corte || answer.corte === query.corte)
&& entries(query.filtros ?? {}) === entries(answer.filtros);
}
const sameQuery = consultaAplicada;
/**
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
@@ -44,7 +42,7 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi
mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY),
tap(({ page, answer }) => {
if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages
|| answer.corte !== first.corte) throw new ExportInconsistent('The list changed while it was being read');
|| answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read');
collected.set(page, answer.items);
}),
map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })),
@@ -53,8 +51,8 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi
startWith<TrackingExportEvent>({ kind: 'progress', fetched: first.items.length, total }),
concatWith(defer(() => {
const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows);
const ids = new Set(items.map(item => item['id_seudonimo']));
if (items.length !== total || ids.size !== total) throw new ExportInconsistent('The pages do not add up to the announced total');
// Every row has the identity the table shows, and no patient (or episode) appears on two pages.
if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total');
return of<TrackingExportEvent>({
kind: 'done',
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
@@ -1,4 +1,4 @@
import { SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service';
import { etiquetaVentana, SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service';
/** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */
export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const;
@@ -8,6 +8,8 @@ export type TrackingRow = Record<string, SeguimientoValor>;
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
export interface TrackingSnapshot {
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
seleccion?: string;
corte: string;
ventana: SeguimientoTablaResponse['ventana'];
filtros: SeguimientoTablaResponse['filtros'];
@@ -16,6 +18,12 @@ export interface TrackingSnapshot {
items: TrackingRow[];
}
/** The window as the files state it: the whole cohort up to the cut-off, or the dates and months of the window. */
export function ventanaConsultada(snapshot: Pick<TrackingSnapshot, 'ventana'>): string {
const { meses, desde, hasta } = snapshot.ventana;
return meses === 0 ? `Toda la cohorte, al ${hasta}` : `${desde} al ${hasta} (${etiquetaVentana(meses)})`;
}
export type TrackingExportEvent =
| { kind: 'progress'; fetched: number; total: number }
| { kind: 'done'; snapshot: TrackingSnapshot };
@@ -1,7 +1,7 @@
import { renderPdf, PdfDefinition } from './pdf-engine';
import { COLORS, institutionalDocument, loadLogo } from './pdf-template';
import { displayText, exportColumns } from './tracking-export-table';
import { TrackingSnapshot } from './tracking-export.models';
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
export const TRACKING_TITLE = 'Cáncer de mama';
@@ -11,8 +11,9 @@ const zebra = { ...rule, fillColor: (row: number) => (row === 0 ? undefined : ro
/** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */
function parameters(snapshot: TrackingSnapshot) {
const rows: unknown[][] = [
...(snapshot.seleccion ? [['Selección del análisis', snapshot.seleccion]] : []),
['Fecha de corte', snapshot.corte],
['Ventana consultada', `${snapshot.ventana.desde} al ${snapshot.ventana.hasta} (${snapshot.ventana.meses} ${snapshot.ventana.meses === 1 ? 'mes' : 'meses'})`],
['Ventana consultada', ventanaConsultada(snapshot)],
...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']),
['Registros', String(snapshot.items.length)],
];
@@ -1,7 +1,7 @@
import type { Feature, SheetData } from 'write-excel-file/browser';
import { neutralizeFormula } from './cell-sanitizer';
import { flatTable } from './tracking-export-table';
import { TrackingSnapshot } from './tracking-export.models';
import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models';
export const DATA_SHEET = 'Seguimiento';
export const PARAMETERS_SHEET = 'Parámetros';
@@ -49,8 +49,9 @@ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData
return [
[header('Parámetro'), header('Valor')],
row('Reporte', 'Cáncer de mama'),
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
row('Fecha de corte', snapshot.corte),
row('Ventana consultada', `${snapshot.ventana.desde} al ${snapshot.ventana.hasta} (${snapshot.ventana.meses} ${snapshot.ventana.meses === 1 ? 'mes' : 'meses'})`),
row('Ventana consultada', ventanaConsultada(snapshot)),
...filters,
row('Total de registros', snapshot.items.length),
row('Generado', generatedAt(now)),
@@ -0,0 +1,40 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { AnalisisAgregado } from './indicadores-analisis.service';
import { etiquetaBirads } from './etiquetas-cohorte';
export { etiquetaBirads };
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
? `<b>${etiquetaBirads(g.codigo)}</b><br>Menos de ${d.umbral_supresion} pacientes: no se publica<extra></extra>`
: `<b>${etiquetaBirads(g.codigo)}</b><br>${miles(g.n!)} pacientes<extra></extra>`),
}],
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 },
};
}
@@ -0,0 +1,57 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { Dominio, requireDominio } from './indicadores.models';
// The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many
// patients of the cohort fall in each BI-RADS category at a cut-off (`GET /<dominio>/analisis/indicadores?corte=`).
// It is a descriptive count, not an incidence or a survival estimate, and it never carries patient rows. The answer
// names the cohort, the scenario and a `revision` of the cohort that the patients' list must quote back: a list asked
// for with another revision is refused, so a group opened from this count is always the group that was counted.
export interface GrupoAnalisis { codigo: string; n: number | null; suprimido: boolean; }
export interface AnalisisAgregado {
simulado: true; cohorte: string; revision: string; escenario: string; corte: string; umbral_supresion: number;
unidad: string; denominador: string; grupos: GrupoAnalisis[];
}
/** What a patients' list must quote back to open a group of the aggregate. */
export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; }
/** 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())}`;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
// 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<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
}
}
@@ -0,0 +1,235 @@
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<unknown>(); }
describe('Pestaña Análisis epidemiológico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, 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('encabeza la vista y deriva las dos tarjetas de los estados de los grupos, sin sumar pacientes', () => {
// Fails if the cards count patients instead of categories, appear before an answer, or the heading and denominator are lost.
abrir();
expect(root().querySelector('h2')!.textContent).toBe('Análisis epidemiológico');
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const tarjetas = Array.from(root().querySelectorAll('app-indicador-kpi-card')) as HTMLElement[];
expect(tarjetas.map(t => t.querySelector('h3')!.textContent)).toEqual(['Categorías publicadas', 'Categorías no publicadas']);
expect(tarjetas.map(t => t.querySelector('.value')!.textContent!.trim())).toEqual(['1', '5']);
expect(tarjetas[0].textContent).toContain('de 6 categorías BI-RADS');
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('abrir la lista en Seguimiento');
});
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
// Fails if the cards stay on screen without an answer with categories.
abrir();
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
expect(Array.from(root().querySelectorAll('app-indicador-kpi-card .value')).map(v => v.textContent!.trim())).toEqual(['0', '6']);
fixture.componentInstance.consultar(); fixture.detectChanges();
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(root().querySelector('app-indicador-kpi-card')).toBeNull();
});
it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => {
// Fails if a slow answer replaces the aggregate of a later cut-off.
abrir();
const primera = pedido(); primera.flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
await escribirCorte('2026-09-01');
expect(fixture.componentInstance.corte).toBe('2026-09-01');
boton('Consultar')!.click(); fixture.detectChanges();
const lenta = pedido('2026-09-01');
// The button is disabled while a query runs, so the later query comes from the code (a retry, a programmatic refresh).
expect(boton('Consultar')!.disabled).toBe(true);
await escribirCorte('2026-08-01'); fixture.componentInstance.consultar(); fixture.detectChanges();
expect(lenta.cancelled).toBe(true);
pedido('2026-08-01').flush(agregadoJson({ corte: '2026-08-01' })); fixture.detectChanges();
expect(text()).toContain('Fecha de corte: 2026-08-01.');
});
it('una fecha que no es de calendario no sale del navegador', async () => {
// Fails if an invalid cut-off is sent to the server.
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
await escribirCorte('2026-02-31'); boton('Consultar')!.click(); fixture.detectChanges();
http.expectNone(() => true);
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte');
});
it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => {
// Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost.
abrir();
const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true }));
pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges();
expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.');
expect(text()).not.toContain('Sin pacientes');
expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true);
});
it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => {
// Fails if the table offers the patients of a hidden group.
abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges();
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
});
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
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');
});
});
@@ -0,0 +1,47 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
export const CORTE = '2026-10-20';
export const CONTEXTO = { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: REVISION };
/** One published category (BI-RADS 5, six patients) and five suppressed ones. */
export const agregado = (extra: Partial<AnalisisAgregado> = {}): AnalisisAgregado => ({
simulado: true, ...CONTEXTO, corte: CORTE, umbral_supresion: 5, unidad: 'paciente',
denominador: 'pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
grupos: [
{ codigo: 'BIRADS_4', n: null, suprimido: true }, { codigo: 'BIRADS_4A', n: null, suprimido: true }, { codigo: 'BIRADS_4B', n: null, suprimido: true },
{ codigo: 'BIRADS_4C', n: null, suprimido: true }, { codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_6', n: null, suprimido: true },
],
...extra,
});
/**
* The answer of the cohort's list as the API sends it: only the two filters it announces, with the code as their label,
* the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown),
* and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off.
*/
export function listaCohorte(o: { corte?: string; filtros?: Record<string, string>; page?: number; size?: number; n?: number; meses?: number; revision?: string } = {}): Record<string, any> {
const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0, revision = REVISION } = o;
const todos = Array.from({ length: n }, (_, i) => ({
id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01',
biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null,
}));
const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c }));
return {
simulado: true, ...CONTEXTO, revision, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha',
filtros: { birads: null, grupo_edad: null, ...filtros },
filtros_disponibles: [
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) },
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: opciones(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']) }],
columnas: [
{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
{ clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] },
{ clave: 'biopsia', etiqueta: 'Resultado histopatológico', detalles: [{ clave: 'biopsia_fecha', etiqueta: 'Fecha de reporte' }] }],
paginacion: { page, page_size: size, total_items: n, total_pages: Math.max(1, Math.ceil(n / size)) },
items: todos.slice((page - 1) * size, page * size),
};
}
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
@@ -0,0 +1,240 @@
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 { IndicadorKpiCard } from './indicador-kpi-card';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service';
import { Dominio, Tema } from './indicadores.models';
type Carga<T> = { 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<string, string>; 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.';
export { hoyIso };
/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
const g = agregado.grupos.find(x => x.codigo === codigo);
return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
}
/** The 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, IndicadorKpiCard],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
<p class="nota">Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.</p>
@if (datos(); as d) {
<p class="contexto">Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.</p>
<div class="tarjetas">
<app-indicador-kpi-card title="Categorías publicadas" [value]="publicadas()" state="Disponible" [quietWhenAvailable]="true"
[additionalInfo]="'de ' + d.grupos.length + ' categorías BI-RADS.'" />
<app-indicador-kpi-card title="Categorías no publicadas" [value]="d.grupos.length - publicadas()" state="Disponible" [quietWhenAvailable]="true"
[additionalInfo]="'Con menos de ' + d.umbral_supresion + ' pacientes: su conteo y su lista no se publican.'" />
</div>
}
<form class="controles" (ngSubmit)="consultar()">
<label>Fecha de corte <input name="corte" type="date" required [(ngModel)]="corte" [max]="hoy" /></label>
<button type="submit" mat-stroked-button [disabled]="carga().estado === 'cargando'">Consultar</button>
</form>
<article class="panel" aria-labelledby="birads-titulo">
<h3 id="birads-titulo">Pacientes por categoría BI-RADS</h3>
@switch (carga().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Consultando el análisis" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') {
<p role="status">La cohorte no está disponible en este momento.</p>
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
}
@case ('error') {
<div role="alert"><p>{{ $any(carga()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
}
}
@if (datos(); as d) {
@if (todasSuprimidas()) {
<p class="nota">Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.</p>
}
<p class="aviso" role="status">{{ aviso() }}</p>
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
label="Pacientes por categoría BI-RADS" />
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
<table>
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<tbody>
@for (g of d.grupos; track g.codigo) {
<tr [attr.data-grupo]="g.codigo">
<th scope="row">{{ etiqueta(g.codigo) }}</th>
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
</tr>
}
</tbody>
</table>
</div>
}
</article>
</section>
`,
styles: `
:host { display: block; min-width: 0; }
/* Positioned so the absolutely placed visually-hidden labels belong to this view: otherwise they are laid out against the document and give it a vertical scroll of its own. */
.analisis { position: relative; display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.analisis > * { margin: 0; }
/* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */
:host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2, h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-4); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; }
input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
/* The live region stays in the page, so what is written into it is announced; empty, it takes no room. */
.aviso { padding: var(--issste-space-2) var(--issste-space-3); border-left: 4px solid var(--issste-accent); font: var(--mat-sys-body-medium); }
.aviso:empty { padding: 0; border: 0; margin: 0; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
.tabla-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
td:nth-child(2) { font-variant-numeric: tabular-nums; }
td:last-child { min-width: 11rem; }
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@media (max-width: 600px) { .panel { padding: var(--issste-space-4); } .controles label, .controles input { width: 100%; } }
`,
})
export class IndicadoresAnalisis {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The patients of a group, for the page to open them in Seguimiento.
readonly verPacientes = output<SeleccionPacientes>();
readonly miles = (v: number) => v.toLocaleString('es-MX');
readonly etiqueta = etiquetaBirads;
readonly motivo = MOTIVO_GRUPO_SUPRIMIDO;
readonly hoy = hoyIso();
private readonly service = inject(AnalisisService);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly pedidos = new Subject<string>();
private abierto = false;
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; });
// How many categories the answer publishes; the rest are suppressed. Counts categories only, never patients.
readonly publicadas = computed(() => this.datos()?.grupos.filter(g => !g.suprimido).length ?? 0);
// The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published.
readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido));
readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; });
constructor() {
const destroy = inject(DestroyRef);
const cargar = (corte: string): Observable<Carga<AnalisisAgregado>> => {
let fuente: Observable<AnalisisAgregado>;
try { fuente = this.service.agregado(this.dominio(), corte); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); }
return fuente.pipe(
map((datos): Carga<AnalisisAgregado> => ({ estado: 'listo', datos })),
catchError(error => of(this.fallo(error))),
startWith<Carga<AnalisisAgregado>>({ estado: 'cargando' }));
};
this.pedidos.pipe(switchMap(cargar), takeUntilDestroyed(destroy)).subscribe(c => { this.aviso.set(''); this.carga.set(c); });
effect(() => {
if (!this.active() || this.abierto) return;
untracked(() => { this.abierto = true; this.consultar(); });
});
}
private fallo(error: unknown): Carga<AnalisisAgregado> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la fecha de corte. Revisa la fecha.' };
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
}
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
}
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.pedidos.next(this.corte);
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
// A click on a published bar is the same as its «Ver pacientes» button; a suppressed bar does nothing.
clicGrupo(evento: unknown) {
const codigo = grupoDelClic(evento, this.datos());
if (!codigo) return;
const fila = Array.from(this.host.nativeElement.querySelectorAll<HTMLElement>('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo);
this.verGrupo(codigo, fila?.querySelector<HTMLElement>('button.ver') ?? this.host.nativeElement.querySelector<HTMLElement>('.plot-viewport'));
}
// The patients of a published group: the page opens them in Seguimiento. Where the user was is kept for the way back.
verGrupo(codigo: string, origen?: EventTarget | null) {
const d = this.datos();
if (!d) return;
this.aviso.set(motivoSinLista(d, codigo) ?? '');
const seleccion = seleccionDeGrupo(d, codigo);
if (!seleccion) return;
const el = origen instanceof HTMLElement ? origen : null;
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
if (!r) return;
if (r.area.isConnected) r.area.scrollTop = r.arriba;
(r.origen?.isConnected ? r.origen : this.host.nativeElement.querySelector<HTMLElement>('input[name="corte"]'))?.focus({ preventScroll: true });
this.retorno = undefined;
}
}
@@ -0,0 +1,136 @@
// Covers how the breast cohort is written for the user (BI-RADS and age groups), that the requests keep the codes, that
// the cut-off the user chose reaches the list, the record and the files, and what the record says of a biopsy whose
// report date is known while its result is not. Fixture: listaCohorte() in indicadores-analisis.testing.ts.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { strFromU8, unzipSync } from 'fflate';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
import { fetchAllTracking, queryOf } from './export/tracking-export-source';
import { trackingDocument } from './export/tracking-pdf';
import { buildTrackingXlsx } from './export/tracking-xlsx';
const CORTE_ELEGIDO = '2026-09-01';
const textos = (nodo: unknown, salida: string[] = []): string[] => {
if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida));
return salida;
};
describe('Etiquetas de la cohorte', () => {
it('escribe las categorías BI-RADS y los grupos de edad como en la clínica, y deja lo demás como llegó', () => {
// Fails if a confirmed code is shown raw, or a code whose meaning is not confirmed is invented.
expect(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'].map(etiquetaBirads)).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO'].map(etiquetaEdad)).toEqual(
['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(etiquetaBirads('BIRADS_7')).toBe('BIRADS_7'); expect(etiquetaEdad('OTRO')).toBe('OTRO');
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
});
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
const r = seguimientoTablaResponse(listaCohorte());
expect(r.filtros_disponibles[0].opciones.map(o => [o.codigo, o.etiqueta]).slice(0, 2)).toEqual([['BIRADS_4', 'BI-RADS 4'], ['BIRADS_4A', 'BI-RADS 4A']]);
expect(r.filtros_disponibles[1].opciones.map(o => o.etiqueta)).toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(r.items[0]).toMatchObject({ birads: 'BI-RADS 5', birads_codigo: 'BIRADS_5', grupo_edad: '50 a 59 años', grupo_edad_codigo: '50-59' });
const histo = listaCohorte();
(histo['items'] as Record<string, unknown>[])[0]['biopsia'] = 'CARCINOMA_INVASOR';
expect(seguimientoTablaResponse(histo).items[0]).toMatchObject({ biopsia: 'Carcinoma invasor', biopsia_codigo: 'CARCINOMA_INVASOR' });
expect(r.filtros).toEqual({ birads: null, grupo_edad: null });
const plana = listaCohorte(); delete plana['cohorte'];
expect(seguimientoTablaResponse(plana).items[0]).toMatchObject({ birads: 'BIRADS_5', grupo_edad: '50-59' });
});
});
describe('La lista de la cohorte con etiquetas legibles y el corte elegido', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('active', false);
fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const seleccion = (esperados = 6): SeleccionSeguimiento => ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE_ELEGIDO, esperados, contexto: CONTEXTO, id: 1 });
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const celdas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent!.replace(/\s+/g, ' ').trim()));
it('muestra BI-RADS y grupos de edad legibles en las filas y en los filtros, pero la petición sigue enviando los códigos', async () => {
// Fails if the user reads codes, or a filter chosen by its label is sent as text instead of its code.
fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion()); fixture.detectChanges();
let r = solicitud();
expect(parametros(r)).toMatchObject({ corte: CORTE_ELEGIDO, birads: 'BIRADS_5', meses: '0', ...CONTEXTO });
r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await asentar();
expect(celdas()[1].slice(1, 3)).toEqual(['60 a 69 años', 'BI-RADS 5 Fecha: 2025-02-01']);
expect(root().textContent).not.toMatch(/BIRADS_5|60-69/);
expect([...campo('Grupo de edad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
const s = campo('Grupo de edad').querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === '60 a 69 años')!.value;
s.dispatchEvent(new Event('change')); await asentar();
[...root().querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); fixture.detectChanges();
r = solicitud();
expect(parametros(r)).toMatchObject({ grupo_edad: '60-69', birads: 'BIRADS_5', corte: CORTE_ELEGIDO });
r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5', grupo_edad: '60-69' } }));
});
it('el corte elegido en el análisis llega a la lista, a la ficha y a todas las páginas de la exportación', async () => {
// Fails if the list, the record or a page of the file is read at another cut-off than the one the user chose.
fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion(450)); fixture.detectChanges();
solicitud().flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); await asentar();
// The record, opened from the row that was clicked.
(root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar();
expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE_ELEGIDO}.`);
// The files: every page asks for the same cut-off, and the answer must give it back.
const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 }));
const pedidas: SeguimientoTablaQuery[] = [];
const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> => {
pedidas.push(q); return of(seguimientoTablaResponse(listaCohorte({ corte: q.corte, filtros: q.filtros as Record<string, string>, page: q.page, size: q.page_size, n: 450 }))); } } as unknown as SeguimientoTablaService;
expect(queryOf(respuesta)).toMatchObject({ corte: CORTE_ELEGIDO, meses: 0, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO });
await new Promise<void>((ok, fallo) => fetchAllTracking(servicio, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok }));
expect(pedidas.map(q => q.corte)).toEqual([CORTE_ELEGIDO, CORTE_ELEGIDO, CORTE_ELEGIDO]);
});
});
describe('Ficha y archivos de una fila con biopsia reportada y resultado desconocido', () => {
const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO }));
const fila = (i: number) => respuesta.items[i];
const NOW = new Date(Date.UTC(2026, 10, 13, 18, 0));
it('la ficha dice «Fecha de reporte», conserva «No disponible» para el resultado, el estatus y la prioridad, y escribe BI-RADS y edad legibles', () => {
// Fails if the date of a biopsy report is called the date of the biopsy, or an unknown result is filled in.
const resumen = toCamaPatientSummary(fila(2), CORTE_ELEGIDO, respuesta.columnas)!;
expect(resumen).toMatchObject({ birads: 'BI-RADS 5', ageGroup: '50 a 59 años', histopathology: null, biopsyDate: '2025-02-15', biopsyDateLabel: 'Fecha de reporte', status: null, priority: null });
TestBed.configureTestingModule({ providers: [provideHttpClient()] });
const card = TestBed.createComponent(CamaPatientCard);
card.componentRef.setInput('summary', resumen); card.detectChanges();
const t = (card.nativeElement.textContent as string).replace(/\s+/g, ' ');
expect(t).toContain('Resultado: No disponible'); expect(t).toContain('Fecha de reporte: 2025-02-15');
expect(t).toContain('Categoría BI-RADS: BI-RADS 5'); expect(t).toContain('50 a 59 años');
expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).toMatch(/Prioridad\s*No disponible/); expect(t).toMatch(/Días de mastografía a diagnóstico\s*No disponible/);
expect(t).not.toContain('Fecha de biopsia');
const pdf = textos(camaPatientDocument(resumen, NOW, 'data:image/png;base64,AAAA'));
expect(pdf).toContain('Fecha de reporte'); expect(pdf).not.toContain('Fecha de biopsia');
// A list whose columns do not rename the date keeps the record's own wording.
expect(toCamaPatientSummary(fila(2), CORTE_ELEGIDO)!.biopsyDateLabel).toBeUndefined();
});
it('los archivos escriben las etiquetas, no los códigos, y la fila con fecha de reporte sin resultado sale con la celda vacía', async () => {
// Fails if a file carries codes the user cannot read, or invents a result for a report whose result is unknown.
const snapshot = { corte: respuesta.corte, ventana: respuesta.ventana, filtros: respuesta.filtros, filtros_disponibles: respuesta.filtros_disponibles, columnas: respuesta.columnas, items: respuesta.items, seleccion: 'Categoría BI-RADS: BI-RADS 5' };
const pdf = textos(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA'));
expect(pdf).toContain('BI-RADS 5'); expect(pdf).toContain('50 a 59 años'); expect(pdf.some(t => /BIRADS_|50-59/.test(t))).toBe(false);
expect(pdf).toContain('Fecha de reporte: 2025-02-15');
const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer()));
const cadenas = strFromU8(hojas['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|');
expect(cadenas).toContain('|BI-RADS 5|'); expect(cadenas).toContain('|60 a 69 años|'); expect(cadenas).not.toMatch(/BIRADS_|\|50-59\|/);
expect(cadenas).toContain('Resultado histopatológico: Fecha de reporte');
});
});
@@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => {
http.match(() => true);
}
it('CaMa: Resumen, Histórico, Seguimiento y Datos y definiciones, en ese orden', () => {
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
});
it.each(['tea', 'cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
@@ -144,8 +144,15 @@
</section>
}
@if (conAnalisis) {
<section id="panel-analisis" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-analisis" tabindex="0" [hidden]="activeSection() !== 'analisis'">
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" (verPacientes)="verPacientes($event)" />
</section>
}
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
[seleccion]="seleccionSeguimiento()" (volverAlAnalisis)="volverAlAnalisis()"
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
</section>
@@ -28,11 +28,13 @@ import { httpMessage } from './indicadores-http';
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
@@ -40,19 +42,36 @@ const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
{ id: 'datos', label: 'Datos y definiciones' },
];
const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]];
// The epidemiological analysis is CaMa's: between its history and its follow-up list.
const SECCIONES_CON_ANALISIS: readonly { id: DashboardSection; label: string }[] = [
SECCIONES_CON_HISTORICO[0], SECCIONES_CON_HISTORICO[1], { id: 'analisis', label: 'Análisis epidemiológico' }, SECCIONES_CON_HISTORICO[2], SECCIONES_CON_HISTORICO[3]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico, IndicadoresAnalisis],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
// The history tab is CaMa's; the other domains keep their three sections.
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
// The history and the analysis tabs are CaMa's; the other domains keep their three sections.
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conAnalisis ? SECCIONES_CON_ANALISIS : this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
get conHistorico() { return this.dominio === 'cama'; }
get conAnalisis() { return this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
private readonly analisis = viewChild(IndicadoresAnalisis);
// The patients of a curve or a heatmap cell, opened in Seguimiento; the id makes a repeated click apply again.
// It belongs to the domain it was made in and stays while the user moves between the tabs.
readonly seleccionSeguimiento = signal<SeleccionSeguimiento | undefined>(undefined);
verPacientes(seleccion: SeleccionPacientes) {
this.seleccionSeguimiento.set({ ...seleccion, id: (this.seleccionSeguimiento()?.id ?? 0) + 1 });
this.changeSection('seguimiento');
}
// Back to the analysis: the part, the scroll and the focus where the user left them.
volverAlAnalisis() {
this.changeSection('analisis');
afterNextRender(() => this.analisis()?.restaurar(), { injector: this.injector });
}
setFichaPacienteAbierta(open: boolean) {
this.fichaPacienteAbierta.set(open);
if (open) this.closeGraphicNavigation(false, false);
@@ -538,6 +557,7 @@ export class IndicadoresPage {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.closeGraphicNavigation(false, false);
this.activeSection.set('resumen');
this.seleccionSeguimiento.set(undefined);
this.searchQuery.set('');
this.filtersEdited();
this.filters = undefined;
@@ -0,0 +1,178 @@
// Covers the journey of breast cancer on the page: Análisis → «Ver pacientes» → Seguimiento on the group → record →
// «Volver al análisis», with the analysis as it was and the focus on the control that opened the list; the selection going
// with the domain; CaCu and TEA keeping their three sections; and the wording of every screen of the journey.
// Fixtures: indicadores-analisis.testing.ts (the aggregate) and fixtures/cama_seguimiento.json (the list).
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 { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from '../../app.routes';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import fixtureData from './fixtures/cama_seguimiento.json';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis';
import { IndicadorFigureCard } from './indicador-figure-card';
import { agregadoJson, CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { readonly plotClick = output<unknown>(); }
const catalogoCama: Indicador[] = [{ id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras'], tipos_periodo: ['mes'] }];
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
// What the cohort's list answers to the group BI-RADS 5: the whole cohort, the cut-off asked for, the filter applied and the cohort quoted back.
const cohorte = (corte: string) => ({ ...base(), ...CONTEXTO, corte, ventana: { meses: 0, desde: '2025-01-01', hasta: corte },
filtros: { ...base()['filtros'], birads: 'BIRADS_5' } });
// Nothing a user can read or a screen reader announces refers to tests, simulation, a development environment or the mock.
const PROHIBIDO = /mock|demostraci|simulad|sint[eé]tic|ficticio|entorno|\bdev\b/i;
function legible(root: HTMLElement): string[] {
const textos = [root.textContent ?? ''];
root.querySelectorAll('[aria-label], [title], [alt]').forEach(el => ['aria-label', 'title', 'alt'].forEach(a => { const v = el.getAttribute(a); if (v) textos.push(v); }));
return textos;
}
describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () => {
let http: HttpTestingController;
const corte = hoyIso();
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
async function entrar() {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage);
http.expectOne('/cama/indicadores').flush(catalogoCama); harness.detectChanges();
const root = harness.routeNativeElement!;
const tab = (id: string) => root.querySelector<HTMLButtonElement>('#tab-' + id)!;
const panel = (id: string) => root.querySelector<HTMLElement>('#panel-' + id)!;
const asentar = async () => { harness.detectChanges(); await harness.fixture.whenStable(); harness.detectChanges(); };
return { harness, page, root, tab, panel, asentar };
}
async function abrirAnalisis(e: Awaited<ReturnType<typeof entrar>>) {
e.tab('analisis').click(); e.harness.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte).flush(agregadoJson({ corte })); await e.asentar();
}
const lista = () => http.expectOne(q => q.url === '/cama/seguimiento');
const parametros = (r: ReturnType<typeof lista>) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
it('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => {
// Fails if any step of the journey drops the selection, repeats a request, loses the focus or the answer already loaded.
const e = await entrar();
await abrirAnalisis(e);
const origen = e.root.querySelector<HTMLButtonElement>('#birads-titulo ~ .tabla-scroll tr[data-grupo="BIRADS_5"] button.ver')!;
origen.focus(); origen.click(); e.harness.detectChanges();
// Seguimiento on the whole cohort of the group, at the analysis' cut-off, quoting its cohort and revision.
expect(e.page.activeSection()).toBe('seguimiento');
const r = lista();
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte, ...CONTEXTO, birads: 'BIRADS_5' });
r.flush(cohorte(corte)); await e.asentar();
expect(e.panel('seguimiento').hidden).toBe(false); expect(e.panel('analisis').hidden).toBe(true);
expect(e.panel('seguimiento').textContent).toContain('Categoría BI-RADS: BI-RADS 5');
expect(e.panel('seguimiento').textContent).toContain('Toda la cohorte');
expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección y la lista muestra 27. No coinciden');
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
// The record opens over the list and gives it back.
e.root.querySelector<HTMLButtonElement>('.patient-link')!.click(); await e.asentar();
expect(e.root.querySelector('#dashboard-title')?.textContent).toBe('Ficha del paciente');
expect(e.root.querySelector('.section-tabs')).toBeNull();
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
[...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar();
expect(e.root.querySelector('.section-tabs')).not.toBeNull();
expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5');
// Back to the analysis: same answer, no new request, the focus where the user left it.
[...e.panel('seguimiento').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Volver al análisis')!.click(); await e.asentar();
expect(e.page.activeSection()).toBe('analisis');
expect(e.tab('analisis').getAttribute('aria-selected')).toBe('true');
expect(e.panel('analisis').hidden).toBe(false);
http.expectNone(q => q.url.startsWith('/cama/analisis'));
expect(e.panel('analisis').querySelectorAll('tbody tr')).toHaveLength(6);
expect(document.activeElement).toBe(origen);
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
// Seguimiento keeps the selection for the user who goes back to its tab.
e.tab('seguimiento').click(); await e.asentar();
http.expectNone(q => q.url === '/cama/seguimiento');
expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5');
});
it('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => {
// Fails if any step of the journey is read at another cut-off than the chosen one, or the file does not say it.
const ELEGIDO = '2026-09-01';
const descargas: string[] = [];
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test'); vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
const e = await entrar();
await abrirAnalisis(e);
const entrada = e.root.querySelector<HTMLInputElement>('#panel-analisis input[name="corte"]')!;
entrada.value = ELEGIDO; entrada.dispatchEvent(new Event('input')); await e.asentar();
[...e.panel('analisis').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); e.harness.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === ELEGIDO).flush(agregadoJson({ corte: ELEGIDO })); await e.asentar();
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ corte: ELEGIDO, meses: '0', birads: 'BIRADS_5', ...CONTEXTO });
r.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await e.asentar();
expect(e.panel('seguimiento').textContent).toContain(`corte ${ELEGIDO}`);
// The record.
e.root.querySelector<HTMLButtonElement>('.patient-link')!.click(); await e.asentar();
expect(e.root.querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${ELEGIDO}.`);
[...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar();
// The file: the pages are read at the same cut-off, and the file says so.
[...e.panel('seguimiento').querySelectorAll('app-seguimiento-exportar button')].find(b => b.textContent!.includes('Excel'))!.dispatchEvent(new Event('click'));
const pagina = http.expectOne(q => q.url === '/cama/seguimiento');
expect(parametros(pagina)).toMatchObject({ corte: ELEGIDO, page_size: '200', meses: '0', birads: 'BIRADS_5', ...CONTEXTO });
pagina.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' }, size: 200 }));
for (let i = 0; i < 30 && !descargas.length; i++) { await new Promise(res => setTimeout(res, 20)); e.harness.detectChanges(); }
expect(descargas).toHaveLength(1);
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-09-01_/);
});
it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => {
// Fails if a stale revision shows rows, or the way back to the analysis is lost with the error.
const e = await entrar();
await abrirAnalisis(e);
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
lista().flush({ error: 'La cohorte cambió; actualiza el análisis' }, { status: 409, statusText: 'Conflict' }); await e.asentar();
expect(e.panel('seguimiento').querySelector('[role="alert"]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis');
expect(e.panel('seguimiento').querySelector('table')).toBeNull();
expect(e.panel('seguimiento').querySelector('app-seguimiento-exportar')).toBeNull();
[...e.panel('seguimiento').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Volver al análisis')!.click(); await e.asentar();
expect(e.panel('analisis').querySelectorAll('tbody tr')).toHaveLength(6);
});
it('al cambiar de dominio la selección se limpia; CaCu y TEA no tienen Análisis y conservan sus tres secciones', async () => {
// Fails if a selection survives into another domain, or the analysis tab leaks into CaCu or TEA.
const e = await entrar();
await abrirAnalisis(e);
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
lista().flush(cohorte(corte)); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeDefined();
for (const dominio of ['cacu', 'tea'] as const) {
e.page.changeDominio(dominio); e.harness.detectChanges();
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(e.root.querySelector('#panel-analisis')).toBeNull();
}
e.page.changeDominio('cama'); e.harness.detectChanges();
http.expectOne('/cama/indicadores').flush(catalogoCama); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(e.root.querySelector('.seleccion')).toBeNull();
});
it('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => {
// Fails if the missing endpoint is hidden or shown as a broken page, or the wording leaks the environment.
const e = await entrar();
e.tab('analisis').click(); e.harness.detectChanges();
http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); await e.asentar();
expect(e.panel('analisis').textContent).toContain('Funcionalidad pendiente de publicación');
expect(e.panel('analisis').querySelector('[role="alert"]')).toBeNull();
expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]);
});
});
@@ -37,8 +37,8 @@ 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"]'));
// CaMa also has Histórico, between Resumen and Seguimiento.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
// CaMa also has Histórico and Análisis epidemiológico, between Resumen and Seguimiento; CaCu and TEA keep their three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
@@ -60,13 +60,12 @@ describe('Secciones compartidas por dominio', () => {
}
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : '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 === 'cama') {
// Pending integration: the form is gone with no table, and the retry is offered.
expect(tracking.textContent).toContain('Funcionalidad pendiente de publicación');
// An unavailable cohort has no table and offers a retry.
expect(tracking.querySelector('table')).toBeNull();
expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull();
expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento');
@@ -0,0 +1,162 @@
// Covers the habitual access to Seguimiento of breast cancer: the list opens on the regular window and, when the server
// answers from the cohort, adopts the cohort and its revision for the next pages and the files; a cut-off or a changed
// revision is asked for without the old revision; and the filters, the cut-off, the page and the rows are kept while the
// record is opened and closed. Fixtures: indicadores-analisis.testing.ts (listaCohorte) and fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import fixtureData from './fixtures/cama_seguimiento.json';
import { CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
const OTRA = 'a'.repeat(64);
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
describe('Seguimiento de CaMa: acceso habitual', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama');
fixture.componentRef.setInput('active', false); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const lista = () => http.expectOne(r => r.url === '/cama/seguimiento');
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim());
async function escribir(nombre: string, valor: string) {
const c = root().querySelector(`input[name="${nombre}"]`) as HTMLInputElement; c.value = valor; c.dispatchEvent(new Event('input')); await asentar();
}
async function elegir(etiqueta: string, valor: string) {
const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar();
}
// The list opens on the regular window of 3 months and the cohort answers with its revision.
async function abierta(extra: Parameters<typeof listaCohorte>[0] = {}) {
abrir(); lista().flush(listaCohorte({ meses: 3, n: 27, ...extra })); await asentar();
}
it.each([404, 503])('informa que la cohorte no está disponible ante %s y no cambia de fuente', async status => {
// Fails if an unavailable source is reported as an empty list or another source is queried.
abrir(); lista().flush({ error: 'x' }, { status, statusText: 'Unavailable' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible');
http.expectNone(r => r.url === '/cama/seguimiento');
});
it('abre en la ventana habitual de 3 meses sin citar ninguna revisión, y adopta la cohorte que el servidor devuelve', async () => {
// Fails if the habitual access asks for another window, or needs a revision it cannot have yet, or shows an analysis banner.
http.expectNone(() => true);
abrir();
const r = lista();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush(listaCohorte({ meses: 3, n: 27, size: 10 })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
expect(root().textContent).toContain('Ventana consultada: 2025-02-01 al 2026-10-20.');
// The next page quotes the cohort the first answer named, with the same window and cut-off.
boton('Siguiente')!.click(); fixture.detectChanges();
const p2 = lista();
expect(parametros(p2)).toEqual({ meses: '3', page: '2', page_size: '10', corte: CORTE, ...CONTEXTO });
p2.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2 })); await asentar();
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
});
it('«Toda la cohorte» pide la ventana 0 citando la cohorte', async () => {
// Fails if the whole cohort is asked for without the revision the server requires for it.
await abierta();
await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO });
r.flush(listaCohorte({ meses: 0, n: 43 })); await asentar();
expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.');
expect(root().querySelector('nav')?.textContent).toContain('43 registros');
});
it('un servidor sin cohorte responde la lista de siempre: sin «Toda la cohorte» y sin citar nada', async () => {
// Fails if a deployment without the cohort provider loses its follow-up list or is sent parameters it does not know.
abrir(); lista().flush(base()); await asentar();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
boton('Consultar')!.click(); fixture.detectChanges();
expect(parametros(lista())).not.toHaveProperty('revision');
});
it('si el usuario cambia el corte, la consulta no cita la revisión del corte anterior y adopta la nueva', async () => {
// Fails if a list at another cut-off is asked for with the revision of the previous one.
await abierta();
await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ corte: '2026-09-01', meses: '3' });
expect(parametros(r)).not.toHaveProperty('revision');
r.flush(listaCohorte({ meses: 3, n: 27, corte: '2026-09-01', revision: OTRA })); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
expect(parametros(lista())).toMatchObject({ corte: '2026-09-01', revision: OTRA });
});
it('si la cohorte cambia bajo la lista (409), repite la misma consulta una vez sin la revisión vieja; un segundo 409 sí se dice', async () => {
// Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops.
await abierta({ size: 10 });
boton('Siguiente')!.click(); fixture.detectChanges();
lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ page: '2', meses: '3' });
expect(parametros(r)).not.toHaveProperty('revision');
r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, revision: OTRA })); await asentar();
expect(root().querySelector('[role=alert]')).toBeNull();
// A conflict that persists is reported, not retried forever.
boton('Consultar')!.click(); fixture.detectChanges();
lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges();
lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis');
expect(root().querySelector('table')).toBeNull();
});
it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => {
// Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow window as an empty cohort.
await abierta({ n: 0 });
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 0 })); await asentar();
expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.');
expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true);
await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar();
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
});
it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => {
// Fails if opening the record resets the form, the page or the rows the user was reading.
await abierta({ size: 10 });
await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 3, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar();
boton('Siguiente')!.click(); fixture.detectChanges();
const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: CORTE, ...CONTEXTO });
r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar();
const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim());
(root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar();
expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE}.`);
([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar();
http.expectNone(() => true);
expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes);
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement;
expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años');
expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(CORTE);
});
it('con una selección del análisis, «Quitar selección» regresa a la lista habitual: 3 meses, sin filtros ni revisión citada', async () => {
// Fails if leaving the selection keeps its filter, its window or the old revision.
await abierta();
fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 43, contexto: { ...CONTEXTO, revision: REVISION }, id: 1 });
fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 43, filtros: { birads: 'BIRADS_5' } })); await asentar();
expect(root().querySelector('.seleccion')).not.toBeNull();
boton('Quitar selección')!.click(); fixture.detectChanges();
const r = lista(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE });
r.flush(listaCohorte({ meses: 3, n: 27 })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
});
it('la biopsia se escribe con las etiquetas del catálogo y un valor desconocido queda como llegó', async () => {
// Fails if a source code is remapped to a diagnosis the catalog does not name, or the code is lost.
abrir();
const r = listaCohorte({ meses: 3, n: 4 }); const v = ['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'OTRO_VALOR']; r['items'].forEach((i: any, k: number) => { i['biopsia'] = v[k]; });
lista().flush(r); await asentar();
expect([...root().querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.replace(/\s+/g, ' ').trim().split(' Fecha')[0])).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'OTRO_VALOR']);
});
});
@@ -0,0 +1,226 @@
// Covers the follow-up list when the epidemiological analysis opens it on a group of the cohort: what it asks for (whole
// cohort, the analysis' cut-off, the group's filter and the cohort with its revision), what the user reads, how the
// selection is kept, refined and removed, and that a list which does not belong to the selection on screen is never
// drawn. Fixture: fixtures/cama_seguimiento.json shaped like the cohort's list (two filters, the cohort quoted back).
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import fixtureData from './fixtures/cama_seguimiento.json';
import { CONTEXTO, CORTE } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
const NULOS = { birads: null, grupo_edad: null };
const OPCIONES = { birads: ['BIRADS_4', 'BIRADS_5', 'BIRADS_6'], grupo_edad: ['40-49', '50-59', '60-69'] };
// The cohort's answer: only the two filters it announces, the cohort quoted back, window 0 and the filters it applied.
function cohorte(filtros: Record<string, string>, pagina = 1, tam = 50, extra: Record<string, any> = {}) {
const d = base(), todos = d['items'] as unknown[];
d['items'] = todos.slice((pagina - 1) * tam, pagina * tam);
d['paginacion'] = { page: pagina, page_size: tam, total_items: todos.length, total_pages: Math.max(1, Math.ceil(todos.length / tam)) };
d['corte'] = CORTE; d['ventana'] = { meses: 0, desde: '2025-01-01', hasta: CORTE };
d['filtros'] = { ...NULOS, ...filtros };
d['filtros_disponibles'] = [
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: OPCIONES.birads.map(c => ({ codigo: c, etiqueta: c })) },
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: OPCIONES.grupo_edad.map(c => ({ codigo: c, etiqueta: c })) }];
return { ...d, ...CONTEXTO, ...extra };
}
const seleccion = (id: number, extra: Partial<SeleccionSeguimiento> = {}): SeleccionSeguimiento =>
({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id, ...extra });
const PARAMS = { meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO, birads: 'BIRADS_5' };
describe('Seguimiento de CaMa abierto desde el análisis', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama');
fixture.componentRef.setInput('active', false); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = (dominio = 'cama') => http.expectOne(r => r.url === `/${dominio}/seguimiento`);
const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const abrirCon = (sel: SeleccionSeguimiento) => { fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', sel); fixture.detectChanges(); };
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
async function elegir(etiqueta: string, valor: string) {
const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor || o.value.endsWith(valor))!.value;
s.dispatchEvent(new Event('change')); await asentar();
}
const banner = () => root().querySelector('.seleccion')?.textContent?.replace(/\s+/g, ' ').trim();
const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim());
const exportar = () => root().querySelector('app-seguimiento-exportar');
it('pide toda la cohorte con el corte del análisis, el filtro del grupo y la cohorte con su revisión, y lo dice con su etiqueta y un camino de regreso', async () => {
// Fails if the list opens on another window, cut-off, group or cohort revision, or hides where it came from.
http.expectNone(() => true);
abrirCon(seleccion(1));
const r = solicitud();
expect(parametros(r)).toEqual(PARAMS);
r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico: Categoría BI-RADS: BI-RADS 5. Toda la cohorte, corte 2026-10-20.');
expect(boton('Volver al análisis')).toBeDefined(); expect(boton('Quitar selección')).toBeDefined();
expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.');
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
expect(fixture.componentInstance.etiquetaDatos()).toBe('Categoría BI-RADS: BI-RADS 5');
expect(exportar()).not.toBeNull();
});
it('sin una selección la ventana no ofrece «Toda la cohorte» y la consulta no cita ninguna cohorte', async () => {
// Fails if the whole cohort becomes a plain window of the list, or a plain query quotes a revision.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const r = solicitud();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush({ ...base() }); await asentar();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
expect(root().querySelector('.seleccion')).toBeNull();
});
it('si la lista no tiene tantos pacientes como contó el análisis para la misma selección y revisión, lo avisa y no deja exportarla; si coinciden, calla y exporta', async () => {
// Fails if a list that breaks the contract can be exported as if it were the group that was counted.
abrirCon(seleccion(1, { esperados: 30 }));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(root().querySelector('.diferencia')?.getAttribute('role')).toBe('alert');
expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección y la lista muestra 27. No coinciden, por lo que este resultado no se puede exportar.');
expect([...exportar()!.querySelectorAll('button')].every(b => b.disabled)).toBe(true);
expect(root().querySelector('table')).not.toBeNull();
fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges();
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(root().querySelector('.diferencia')).toBeNull();
expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true);
});
it('una respuesta que pierde el filtro, cambia la ventana o el corte, o no es la cohorte ni la revisión pedidas no se dibuja ni se puede exportar', async () => {
// Fails if rows of another population or of another revision are shown (or exported) under the name of the analysis' group.
for (const [mal, respuesta] of [
['pierde el filtro', cohorte({})],
['cambia la ventana', cohorte({ birads: 'BIRADS_5' }, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })],
['cambia el corte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { corte: '2026-09-01' })],
['otra revisión', cohorte({ birads: 'BIRADS_5' }, 1, 50, { revision: 'f'.repeat(64) })],
['otra cohorte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { cohorte: 'otra' })],
['sin cohorte', (() => { const d: Record<string, any> = cohorte({ birads: 'BIRADS_5' }); delete d['revision']; return d; })()],
] as const) {
fixture.componentRef.setInput('active', true);
fixture.componentRef.setInput('seleccion', seleccion(mal.length * 7 + mal.charCodeAt(1)));
fixture.detectChanges();
solicitud().flush(respuesta); await asentar();
expect(root().querySelector('[role=alert]')?.textContent, mal).toContain('no corresponde a la selección consultada');
expect(root().querySelector('table'), mal).toBeNull();
expect(exportar(), mal).toBeNull();
expect(root().textContent, mal).not.toContain('M-0081');
}
});
it('403, 409 y 503 dicen qué pasó, no dejan ninguna lista a la vista y no exponen el cuerpo del servidor', async () => {
// Fails if a refused list is explained with the server's text, or the previous rows stay under the failed selection.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
for (const [status, texto] of [[403, 'no hay acceso, o la selección tiene muy pocos pacientes'], [409, 'La cohorte cambió desde que se calculó el análisis'],
[503, 'La cohorte no está disponible en este momento']] as const) {
const c = root().querySelector('input[name="corte"]') as HTMLInputElement;
c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
const r = solicitud();
expect(r.request.params.get('corte'), String(status)).toBe(c.value);
r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar();
const alerta = root().querySelector('[role=alert]')?.textContent;
expect(alerta, String(status)).toContain(texto);
expect(alerta, String(status)).not.toContain('detalle interno');
expect(root().querySelector('table'), String(status)).toBeNull();
expect(exportar(), String(status)).toBeNull();
}
});
it('una selección nueva cancela la anterior: su respuesta tardía no se dibuja y mientras carga no queda la lista anterior', async () => {
// Fails if a slow answer replaces the list of a later selection, or the old rows stay under the new banner.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(root().querySelector('table')).not.toBeNull();
fixture.componentRef.setInput('seleccion', seleccion(2, { filtros: { birads: 'BIRADS_6' }, etiqueta: 'Categoría BI-RADS: BI-RADS 6' })); fixture.detectChanges();
const r2 = solicitud();
expect(root().querySelector('table')).toBeNull();
expect(root().textContent).toContain('Cargando seguimiento');
fixture.componentRef.setInput('seleccion', seleccion(3, { filtros: { birads: 'BIRADS_4' }, etiqueta: 'Categoría BI-RADS: BI-RADS 4' })); fixture.detectChanges();
const r3 = solicitud();
expect(r2.cancelled).toBe(true);
expect(() => r2.flush(cohorte({ birads: 'BIRADS_6' }))).toThrow();
r3.flush(cohorte({ birads: 'BIRADS_4' })); await asentar();
expect(banner()).toContain('BI-RADS 4');
expect(banner()).not.toContain('BI-RADS 6');
expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 4');
});
it('al paginar conserva la selección, el corte, el filtro y la cohorte, y el nombre sigue a las filas', async () => {
// Fails if a later page is asked without the group's filter or the cohort's revision, or loses the name of the selection.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' }, 1, 10)); await asentar();
boton('Siguiente')!.click(); fixture.detectChanges();
const r = solicitud();
expect(parametros(r)).toEqual({ ...PARAMS, page: '2', page_size: '10' });
r.flush(cohorte({ birads: 'BIRADS_5' }, 2, 10)); await asentar();
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 5');
expect(banner()).toContain('BI-RADS 5');
});
it('la selección sobrevive a salir de la pestaña y volver, sin pedir otra vez; «Volver al análisis» avisa a la página', async () => {
// Fails if coming back to the tab repeats the request, drops the selection or the way back stops working.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
let volvio = 0; fixture.componentInstance.volverAlAnalisis.subscribe(() => volvio++);
fixture.componentRef.setInput('active', false); fixture.detectChanges();
fixture.componentRef.setInput('active', true); fixture.detectChanges();
http.expectNone(() => true);
expect(banner()).toContain('BI-RADS 5');
expect(root().querySelector('table')).not.toBeNull();
boton('Volver al análisis')!.click();
expect(volvio).toBe(1);
expect(banner()).toContain('BI-RADS 5');
});
it('«Consultar» sin cambios repite la misma selección; con otro filtro refina la misma cohorte, citando su revisión, y lo dice', async () => {
// Fails if the banner keeps naming a group after the user narrowed the list, or a refinement leaves the cohort.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
let r = solicitud();
expect(parametros(r)).toEqual(PARAMS);
r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico');
await elegir('Grupo de edad', '50-59'); boton('Consultar')!.click(); fixture.detectChanges();
r = solicitud();
expect(parametros(r)).toEqual({ ...PARAMS, grupo_edad: '50-59' });
r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' })); await asentar();
expect(banner()).toContain('Pacientes de la cohorte del análisis epidemiológico, corte 2026-10-20. Los filtros y la ventana son los de esta consulta.');
expect(banner()).not.toContain('selección del análisis');
expect(exportar()).not.toBeNull();
expect(fixture.componentInstance.etiquetaDatos()).toBe('Cohorte del análisis epidemiológico');
expect(root().querySelector('.diferencia')).toBeNull();
expect(ventanas()).toContain('Toda la cohorte');
});
it('«Quitar selección» vuelve a la lista habitual: 3 meses, sin filtros ni nombre, y sin citar la revisión anterior', async () => {
// Fails if removing the selection leaves its filter, the whole-cohort window or the old revision behind.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
boton('Quitar selección')!.click(); fixture.detectChanges();
const r = solicitud();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE });
r.flush(cohorte({}, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined();
expect(exportar()).not.toBeNull();
});
it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => {
// Fails if a selection (or its cohort) made in one domain survives into another.
abrirCon(seleccion(1));
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
fixture.componentRef.setInput('seleccion', undefined); fixture.componentRef.setInput('dominio', 'cacu'); fixture.detectChanges();
expect(root().querySelector('.seleccion')).toBeNull();
expect(root().querySelector('table')).toBeNull();
const r = solicitud('cacu');
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush('', { status: 404, statusText: 'Not Found' });
});
it('una selección que llega con la pestaña inactiva espera a que se abra', async () => {
// Fails if the list is asked for while its tab is hidden.
fixture.componentRef.setInput('seleccion', seleccion(1)); fixture.detectChanges();
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
solicitud().flush(cohorte({ birads: 'BIRADS_5' }));
});
});
@@ -4,21 +4,39 @@ import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { Dominio } from './indicadores.models';
import { columnaEnlace, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { TrackingExportBar } from './export/tracking-export-bar';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import {
MESES_VENTANA, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse,
SeguimientoTablaService, SeguimientoValor,
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor,
} from './seguimiento-tabla.service';
type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error';
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string };
interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; filtros: Record<string, string | undefined>; }
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string; estatus?: number };
/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */
type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string };
// What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the
// list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click.
export interface SeleccionSeguimiento {
filtros: Record<string, string>; etiqueta: string; corte?: string; esperados?: number | null; contexto?: ContextoLista; id: number;
}
const ETIQUETA_COHORTE = 'Cohorte del análisis epidemiológico';
/** The answer does not apply the cut-off, window or filters that were asked for: it is neither shown nor exported. */
export class SeguimientoNoCoincide extends Error {}
interface Borrador { corte?: string; meses: MesesVentana; page_size: number; filtros: Record<string, string | undefined>; }
const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string, string | undefined>) => {
const f = (x: Record<string, string | undefined>) => JSON.stringify(Object.entries(x).filter(([, v]) => !!v).sort(([k], [l]) => k.localeCompare(l)));
return f(a) === f(b);
};
/**
* Follow-up list of a domain, drawn from what `GET /<dominio>/seguimiento` announces: the filters, the columns
* and their details come with the answer. Nothing is requested until the tab is opened.
* and their details come with the answer. Nothing is requested until the tab is opened. The analysis can open it
* on a selection (a published group, whole cohort); the list keeps it until it is removed or the domain changes.
*/
@Component({
selector: 'app-seguimiento-tabla',
@@ -31,13 +49,25 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
<div class="title-row">
<h2>Seguimiento de {{ domainLabel }}</h2>
@if (data(); as respuesta) {
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready'" />
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
}
</div>
@if (seleccionMostrada(); as sel) {
<div class="seleccion" role="status">
@if (seleccionExacta()) {
<span>Pacientes de la selección del análisis epidemiológico: <strong>{{ sel }}</strong>. {{ etiquetaVentana(0) }}@if (corteSeleccion()) {, corte {{ corteSeleccion() }}}.</span>
} @else {
<span>Pacientes de la cohorte del análisis epidemiológico@if (corteSeleccion()) {, corte {{ corteSeleccion() }}}. Los filtros y la ventana son los de esta consulta.</span>
}
<button type="button" class="volver" (click)="volverAlAnalisis.emit()">Volver al análisis</button>
<button type="button" (click)="quitarSeleccion()">Quitar selección</button>
</div>
@if (diferencia(); as d) { <p class="diferencia" role="alert">{{ d }}</p> }
}
<form (ngSubmit)="aplicar()">
<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 ventanas; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
@for (m of ventanas(); track m) { <option [ngValue]="m">{{ etiquetaVentana(m) }}</option> }
</select></label>
@for (filtro of filtros(); track filtro.clave) {
<label>{{ filtro.etiqueta }} <select [name]="'filtro-' + filtro.clave" [(ngModel)]="draft.filtros[filtro.clave]">
@@ -60,19 +90,19 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
}
}
@if (data(); as respuesta) {
<p>Ventana consultada: {{ respuesta.ventana.desde }} al {{ respuesta.ventana.hasta }}.</p>
<p>Ventana consultada: {{ respuesta.ventana.meses === 0 ? etiquetaVentana(0) + ', al ' + respuesta.ventana.hasta : respuesta.ventana.desde + ' al ' + respuesta.ventana.hasta }}.</p>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr>@for (c of respuesta.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
<tbody>
@for (item of respuesta.items; track item['id_seudonimo']) {
<tr tabindex="-1" [attr.data-paciente]="item['id_seudonimo']" (click)="abrirFicha(item, $event)">
@for (item of respuesta.items; track identidad(item).id) {
<tr tabindex="-1" [attr.data-paciente]="identidad(item).id" (click)="abrirFicha(item, $event)">
@for (c of respuesta.columnas; track c.clave) {
<td>@if (c.clave === 'id_seudonimo') { <button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item['id_seudonimo']" (click)="abrirFicha(item, $event)">{{ texto(item[c.clave]) }}</button> } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
<td>@if (c.clave === claveEnlace(respuesta, item)) { <button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirFicha(item, $event)">{{ texto(item[c.clave]) }}</button> } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
}
</tr>
} @empty { <tr><td [attr.colspan]="respuesta.columnas.length">No hay registros para los filtros aplicados.</td></tr> }
} @empty { <tr><td [attr.colspan]="respuesta.columnas.length">{{ textoVacio(respuesta) }}</td></tr> }
</tbody>
</table>
</div>
@@ -107,6 +137,11 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
.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; }
.seleccion { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-bottom: 1rem; padding: .5rem .75rem;
border-left: 4px solid var(--issste-accent); background: var(--issste-surface); color: var(--issste-text); }
.seleccion span { overflow-wrap: anywhere; min-width: 0; }
.diferencia { margin: 0 0 1rem; overflow-wrap: anywhere; }
@media (max-width: 600px) { .title-row { gap: .5rem; } form label, form input, form select { width: 100%; } }
`,
})
export class IndicadoresSeguimientoTabla implements OnChanges {
@@ -114,43 +149,97 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
@Input() active = false;
/** Domain name for the section title, which sits in the same row as the export buttons. */
@Input() domainLabel = '';
// The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again.
@Input() seleccion?: SeleccionSeguimiento;
private readonly service = inject(SeguimientoTablaService);
private readonly injector = inject(Injector);
/** Tells the page that an individual record replaced the list, so it can retitle itself. */
readonly fichaAbierta = output<boolean>();
/** The way back to the analysis the selection came from. */
readonly volverAlAnalisis = output<void>();
readonly ficha = signal<CamaPatientSummary | undefined>(undefined);
private controlFicha?: HTMLElement;
private readonly consultas = new Subject<SeguimientoTablaQuery | null>();
readonly ventanas = MESES_VENTANA;
private readonly consultas = new Subject<Consulta | null>();
readonly etiquetaVentana = etiquetaVentana;
readonly tamanoMaximo = PAGE_SIZE_MAX;
readonly estado = signal<Estado>('idle');
readonly mensaje = signal('');
readonly data = signal<SeguimientoTablaResponse | undefined>(undefined);
/** The name of the selection the list on screen was asked for; it is set with the answer, never ahead of it. */
readonly etiquetaDatos = signal<string | undefined>(undefined);
/** The selection of the query now applied (what the banner says). */
readonly seleccionMostrada = signal<string | undefined>(undefined);
/** Whether the list is still exactly the analysis' group (its filters, whole cohort, its cut-off) and not a refinement of the cohort. */
readonly seleccionExacta = signal(false);
readonly corteSeleccion = signal<string | undefined>(undefined);
readonly filtros = signal<SeguimientoTablaResponse['filtros_disponibles']>([]);
draft: Borrador = { meses: 3, page_size: 50, filtros: {} };
// The last query that was sent: the pages and the retry go from it, not from what is being edited.
private applied: SeguimientoTablaQuery = { meses: 3, page: 1, page_size: 50 };
private appliedEtiqueta?: string;
private activa?: SeleccionSeguimiento;
/** The cohort the list is read from while the analysis' selection is active; every query quotes it. */
private contextoActivo?: ContextoLista;
private seleccionAplicada?: number;
private iniciado = false;
private previo?: Dominio;
/** «Toda la cohorte» is offered while the analysis' cohort is active (or the form still holds it), never as a plain window. */
ventanas() { return this.contextoActivo || this.draft.meses === 0 ? MESES_VENTANA : MESES_VENTANA.filter(m => m !== 0); }
/**
* What the list says when it does not hold as many patients as the analysis counted for the selection. With the same
* cohort revision, cut-off and filter the server counts both from the same rows, so a difference breaks the contract:
* the list stays visible, but it is not exported as if it were the group that was counted.
*/
diferencia() {
const esperados = this.activa?.esperados, total = this.data()?.paginacion.total_items;
if (!this.seleccionExacta() || this.estado() !== 'ready' || esperados == null || total === undefined || esperados === total) return undefined;
return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`;
}
// The cut-off of the cohort's revision: another cut-off is another cohort at that date, so its revision is not quoted.
private contextoCorte?: string;
// A cohort that changed under a plain list is read again once, without the old revision, before it is reported.
private reintentoHecho = false;
/** The list of one query, as the server answers it (without the loading state). */
private lista(c: Consulta): Observable<Resultado> {
const { q, etiqueta } = c;
let peticion: Observable<SeguimientoTablaResponse>;
// An invalid query never leaves the browser; it reads like the server's own 400.
try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); }
return peticion.pipe(
// A selection names its patients: an answer that does not apply its window, cut-off and every filter is dropped,
// because its rows would pass for the analysis' group. A plain query shows what the answer says it applied.
map((data): Resultado => {
if ((etiqueta || q.contexto) && !consultaAplicada(q, data)) throw new SeguimientoNoCoincide('La respuesta no corresponde a la consulta');
return { estado: 'ready', data, mensaje: '', etiqueta };
}),
catchError(error => of(this.fallo(error, q))));
}
constructor() {
this.consultas.pipe(
switchMap((q): Observable<Resultado> => {
if (!q) return of({ estado: 'idle', mensaje: '' });
let peticion: Observable<SeguimientoTablaResponse>;
// An invalid query never leaves the browser; it reads like the server's own 400.
try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); }
return peticion.pipe(
map((data): Resultado => ({ estado: 'ready', data, mensaje: '' })),
catchError(error => of(this.fallo(error, q))),
startWith<Resultado>({ estado: 'loading', mensaje: '' }));
switchMap((c): Observable<Resultado> => {
if (!c) return of({ estado: 'idle', mensaje: '' });
return this.lista(c).pipe(startWith<Resultado>({ estado: 'loading', mensaje: '' }));
}),
takeUntilDestroyed(inject(DestroyRef)),
).subscribe(r => {
// The cohort changed under a plain list: the same query is asked again, once, without the old revision, before the user hears of it.
if (r.estatus === 409 && !this.activa && this.contextoActivo && !this.reintentoHecho) {
this.reintentoHecho = true;
this.consultas.next({ q: { ...this.applied, contexto: undefined }, etiqueta: this.appliedEtiqueta });
return;
}
if (r.estado === 'ready') this.reintentoHecho = false;
this.estado.set(r.estado);
this.mensaje.set(r.mensaje);
if (r.estado === 'idle') { this.data.set(undefined); this.filtros.set([]); }
if (r.data) this.recibir(r.data);
if (r.estado === 'idle') { this.data.set(undefined); this.etiquetaDatos.set(undefined); this.filtros.set([]); }
// In the analysis' cohort a query that fails (or whose answer does not match) leaves no list on screen: the rows
// of the previous query would pass for the one the banner names.
if ((r.estado === 'error' || r.estado === 'pending') && (this.contextoActivo || r.mensaje === MENSAJE_NO_COINCIDE)) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
if (r.data) { this.recibir(r.data); this.etiquetaDatos.set(r.etiqueta); }
});
}
@@ -159,14 +248,41 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); }
this.previo = this.dominio; this.iniciado = false; this.consultas.next(null);
this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 };
// The selection belongs to the domain it was made in.
this.appliedEtiqueta = undefined; this.activa = undefined; this.contextoActivo = undefined; this.seleccionAplicada = undefined;
this.contextoCorte = undefined; this.reintentoHecho = false;
this.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined);
}
const sel = this.seleccion;
if (this.active && sel && sel.id !== this.seleccionAplicada) {
this.seleccionAplicada = sel.id; this.iniciado = true; this.activa = sel; this.contextoActivo = sel.contexto; this.contextoCorte = sel.corte;
this.reintentoHecho = false;
// Whatever was on screen belongs to another query: it goes before the selection is asked for.
this.data.set(undefined); this.etiquetaDatos.set(undefined);
if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); }
this.draft = { ...this.draft, meses: 0, corte: sel.corte ?? this.draft.corte, filtros: { ...sel.filtros } };
this.aplicar(sel.etiqueta);
return;
}
if (this.active && !this.iniciado) {
this.iniciado = true;
this.consultas.next({ q: this.applied });
}
if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(this.applied); }
}
private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado {
return { ...this.falloBase(error, q), estatus: error instanceof HttpErrorResponse ? error.status : undefined };
}
private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado {
if (error instanceof HttpErrorResponse && error.status === 404 && this.dominio === 'cama') return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' };
// A first page that does not exist yet is the list's own pending state; a later page that fails is an error.
if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' };
if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' };
// A cohort's list: the group was too small to publish or access was not granted; the cohort changed after the count; or it is not configured.
if (error instanceof HttpErrorResponse && error.status === 403) return { estado: 'error', mensaje: 'Esta lista no está disponible: no hay acceso, o la selección tiene muy pocos pacientes para publicarse.' };
if (error instanceof HttpErrorResponse && error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió desde que se calculó el análisis. Vuelve al análisis, consúltalo de nuevo y abre otra vez el grupo.' };
if (error instanceof HttpErrorResponse && error.status === 503) return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' };
if (error instanceof SeguimientoNoCoincide) return { estado: 'error', mensaje: MENSAJE_NO_COINCIDE };
if (error instanceof SeguimientoInvalido) return { estado: 'error', mensaje: 'La respuesta del servicio no tiene el formato esperado.' };
return { estado: 'error', mensaje: 'No se pudo consultar el seguimiento. Intenta nuevamente.' };
}
@@ -178,21 +294,47 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size,
filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) };
this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size;
// A list read from the cohort says which one (and its revision): the next pages and the files quote it.
this.contextoActivo = contextoDe(data); this.contextoCorte = data.corte;
this.applied = { ...this.applied, contexto: this.contextoActivo };
}
aplicar() {
// The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort
// included; anything else is the user's own query, with a window of months.
aplicar(seleccion?: string) {
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros };
const activa = this.activa, contexto = this.contextoActivo;
const exacta = !!seleccion || (!!activa && this.draft.meses === 0 && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte));
// In the cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months.
// The banner names the analysis' selection, or the cohort of the analysis once the user has refined it.
const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto && activa ? ETIQUETA_COHORTE : undefined);
if (!contexto && this.draft.meses === 0) this.draft = { ...this.draft, meses: 3 };
this.seleccionMostrada.set(etiqueta);
this.seleccionExacta.set(!!etiqueta && exacta);
this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined);
this.appliedEtiqueta = etiqueta;
// Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one.
const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte;
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros,
contexto: otroCorte ? undefined : contexto };
// A new query of the cohort starts from nothing on screen: what was there belongs to the previous one.
if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
this.applied = q;
this.consultas.next(q);
this.consultas.next({ q, etiqueta });
}
ir(page: number) { if (page >= 1) this.consultas.next(this.applied = { ...this.applied, page }); }
reintentar() { this.consultas.next(this.applied); }
// Leaving the analysis' selection returns to the habitual list: the regular window, no filters, the cohort's new revision.
quitarSeleccion() {
this.draft = { ...this.draft, meses: 3, filtros: {} };
this.activa = undefined; this.contextoActivo = undefined;
this.aplicar();
}
ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); }
reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta }); }
abrirFicha(item: Record<string, SeguimientoValor>, evento: Event) {
const origen = evento.target instanceof HTMLElement ? evento.target : null;
// A click on the row opens the record unless it landed on another control; the id button always does.
if (evento.currentTarget instanceof HTMLTableRowElement && origen?.closest('button, a, input, select, textarea')) return;
const corte = this.data()?.corte;
const resumen = corte ? toCamaPatientSummary(item, corte) : null;
const resumen = corte ? toCamaPatientSummary(item, corte, this.data()?.columnas) : null;
if (!resumen || this.estado() !== 'ready') return;
evento.stopPropagation();
this.controlFicha = evento.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined;
@@ -205,6 +347,16 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
const control = this.controlFicha;
afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector });
}
// The cohort answers an empty page only for a whole cohort without filters that has no patient at the cut-off.
textoVacio(r: SeguimientoTablaResponse) {
const sinFiltros = Object.values(r.filtros).every(v => !v);
return r.cohorte && r.ventana.meses === 0 && sinFiltros ? 'Sin pacientes para el corte seleccionado.' : 'No hay registros para los filtros aplicados.';
}
detalles(c: SeguimientoColumna) { return c.detalles ?? []; }
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(item: Record<string, SeguimientoValor>): IdentidadPaciente { return identidadDe(item)!; }
claveEnlace(r: SeguimientoTablaResponse, item: Record<string, SeguimientoValor>) { return columnaEnlace(r.columnas, this.identidad(item).campo); }
texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); }
}
const MENSAJE_NO_COINCIDE = 'La respuesta del servicio no corresponde a la selección consultada, por lo que no se muestra. Intenta nuevamente.';
@@ -6,7 +6,8 @@
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
@if (dominio !== 'cama') { <h2>Seguimiento de {{ domainLabel }}</h2> }
@if (dominio === 'cama') {
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" (fichaAbierta)="cambiaFichaCama($event)" />
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
(volverAlAnalisis)="volverAlAnalisis.emit()" />
} @else if (dominio !== 'cacu') {
<p>El seguimiento aún no está disponible.</p>
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
@@ -37,14 +38,14 @@
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
@if (data; as response) {
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
<tbody>
@for (item of response.items; track item.id_seudonimo) {
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="item.id_seudonimo">
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirPaciente(item, $event)">{{ item.id_seudonimo }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
@for (item of response.items; track identidad(item).id) {
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
@@ -7,9 +7,10 @@ import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimient
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { MatButtonModule } from '@angular/material/button';
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service';
@Component({
@@ -23,6 +24,10 @@ export class IndicadoresTracking implements OnChanges {
@Input({ required: true }) domainLabel = '';
@Input() dominio: Dominio = 'tea';
@Input() active = false;
/** CaMa: the patients of a curve or a cell of the analysis, for its follow-up list. */
@Input() seleccion?: SeleccionSeguimiento;
/** CaMa: the way back to the analysis the selection came from. */
readonly volverAlAnalisis = output<void>();
private readonly service = inject(CacuSeguimientoService);
private readonly indicators = inject(IndicadoresService);
private readonly destroy = inject(DestroyRef);
@@ -93,6 +98,10 @@ export class IndicadoresTracking implements OnChanges {
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
this.load({ ...this.applied, page });
}
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(paciente: SeguimientoPaciente): IdentidadPaciente { return identidadDe(paciente)!; }
// The rows of a page identify their patient by one field; an empty page keeps the legacy wording.
etiquetaIdentidad(respuesta: SeguimientoResponse) { return ETIQUETA_IDENTIDAD[respuesta.items[0] ? this.identidad(respuesta.items[0]).campo : 'id_seudonimo']; }
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return;
evento.stopPropagation();
@@ -6,10 +6,10 @@
@if (failed()) { <p class="toolbar-message" role="alert">No se pudo generar el PDF. Intenta nuevamente.</p> }
</div>
<header>
<h2 #title tabindex="-1">Paciente {{ p.pseudonymId }}</h2>
<h2 #title tabindex="-1">Paciente {{ p.patientId }}</h2>
<p>Fecha de corte: {{ p.cutoff }}.</p>
<dl class="summary">
<div><dt>Identificador seudónimo</dt><dd>{{ p.pseudonymId }}</dd></div>
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
@@ -29,7 +29,7 @@
<mat-card-header><h3 id="histopatologia-title">Histopatología</h3></mat-card-header>
<mat-card-content>
<ul>
<li><strong>Resultado histopatológico</strong><span>Resultado: {{ p.histopathology ?? notAvailable }}</span><span>Fecha de biopsia: {{ p.biopsyDate ?? notAvailable }}</span></li>
<li><strong>Resultado histopatológico</strong><span>Resultado: {{ p.histopathology ?? notAvailable }}</span><span>{{ p.biopsyDateLabel ?? 'Fecha de biopsia' }}: {{ p.biopsyDate ?? notAvailable }}</span></li>
</ul>
</mat-card-content>
</mat-card>
@@ -16,7 +16,7 @@ describe('Ficha CaMa: resumen', () => {
it('reads every field the follow-up row carries', () => {
const row = complete();
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
pseudonymId: row['id_seudonimo'], cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
});
@@ -102,7 +102,7 @@ describe('Ficha CaMa: componente', () => {
for (let i = 0; i < 100 && !downloads.length; i++) await new Promise(r => setTimeout(r, 50));
expect(downloads).toHaveLength(1);
expect(downloads[0]).toMatch(/^ficha-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.pdf$/);
expect(downloads[0]).not.toContain(summary.pseudonymId);
expect(downloads[0]).not.toContain(summary.patientId);
vi.restoreAllMocks();
}, 30000);
@@ -35,7 +35,7 @@ describe('Ficha CaMa: PDF individual', () => {
it('prints each field of the record under its label', () => {
const p = complete();
const found = texts(definition(p)['content']);
for (const t of [`Paciente ${p.pseudonymId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia', 'Días de mastografía a diagnóstico']) expect(found).toContain(t);
});
@@ -16,17 +16,17 @@ const section = (title: string, rows: [string, string | number | null][]) => [
/** The document definition of one patient's record. Exported so its content can be checked without rendering. */
export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo?: string): PdfDefinition {
return institutionalDocument({ title: PATIENT_TITLE, logo, now, orientation: 'portrait' }, [
{ text: `Paciente ${patient.pseudonymId}`, style: 'h1' },
{ text: `Paciente ${patient.patientId}`, style: 'h1' },
{ text: `Fecha de corte: ${patient.cutoff}`, style: 'muted' },
...section('Resumen', [
['Identificador seudónimo', patient.pseudonymId],
[patient.idLabel, patient.patientId],
['Grupo de edad', patient.ageGroup],
['Estatus de seguimiento', patient.status],
['Prioridad', patient.priority],
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
]),
...section('Mastografía', [['Categoría BI-RADS', patient.birads], ['Fecha de la mastografía', patient.mammographyDate]]),
...section('Histopatología', [['Resultado histopatológico', patient.histopathology], ['Fecha de biopsia', patient.biopsyDate]]),
...section('Histopatología', [['Resultado histopatológico', patient.histopathology], [patient.biopsyDateLabel ?? 'Fecha de biopsia', patient.biopsyDate]]),
...section('Pronóstico y recomendaciones', [
...PROGNOSIS_PLACEHOLDERS.map(p => [p.label, PROGNOSIS_UNAVAILABLE] as [string, string]),
['Recomendaciones', RECOMMENDATIONS_UNAVAILABLE],
@@ -1,13 +1,17 @@
import { TrackingRow } from '../../export/tracking-export.models';
import { CampoIdentidad, ETIQUETA_IDENTIDAD, identidadDe } from '../../paciente-identidad';
export const NOT_AVAILABLE = 'No disponible';
/**
* What the CaMa follow-up list says about one patient, read from the row that was clicked. `pseudonymId` is the
* synthetic `M-…` identifier of the list; it is not a platform identifier and is never sent anywhere.
* What the CaMa follow-up list says about one patient, read from the row that was clicked. `patientId` is the
* identifier the row carries (`idField` says which field); the record only shows it.
*/
export interface CamaPatientSummary {
pseudonymId: string;
patientId: string;
idField: CampoIdentidad;
/** What the identifier is called on screen and in the file. */
idLabel: string;
cutoff: string;
ageGroup: string | null;
status: string | null;
@@ -16,6 +20,8 @@ export interface CamaPatientSummary {
mammographyDate: string | null;
histopathology: string | null;
biopsyDate: string | null;
/** What the list calls that date: the cohort's list gives the date of the biopsy report, which can be known before its result is. */
biopsyDateLabel?: string;
daysMammographyToDiagnosis: number | null;
}
@@ -30,13 +36,19 @@ export const RECOMMENDATIONS_UNAVAILABLE = 'Recomendaciones no disponibles.';
const text = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : null);
/** The patient summary of a follow-up row, or `null` when the row has no identifier to show. */
export function toCamaPatientSummary(row: TrackingRow, cutoff: string): CamaPatientSummary | null {
const pseudonymId = text(row['id_seudonimo']);
if (!pseudonymId) return null;
/**
* The patient summary of a follow-up row, or `null` when the row has no identity that can be trusted. `columnas` are the ones the
* list announced: the label it gives to the biopsy date is kept, so the record says the same as the list.
*/
export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: readonly { clave: string; detalles?: readonly { clave: string; etiqueta: string }[] }[] = []): CamaPatientSummary | null {
const identity = identidadDe(row);
if (!identity) return null;
const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta;
const days = row['dias_mastografia_diagnostico'];
return {
pseudonymId,
patientId: identity.id,
idField: identity.campo,
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
cutoff,
ageGroup: text(row['grupo_edad']),
status: text(row['estatus']),
@@ -45,6 +57,7 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string): CamaPati
mammographyDate: text(row['mastografia_fecha']),
histopathology: text(row['biopsia']),
biopsyDate: text(row['biopsia_fecha']),
...(etiquetaFecha ? { biopsyDateLabel: etiquetaFecha } : {}),
daysMammographyToDiagnosis: typeof days === 'number' && Number.isFinite(days) ? days : null,
};
}
@@ -1,10 +1,10 @@
@if (estado.tipo !== 'cerrado') {
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
<header>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.id_seudonimo }}</h2>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.identidad.id }}</h2>
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
<dl class="summary">
<div><dt>Identificador seudónimo</dt><dd>{{ estado.resumen.id_seudonimo }}</dd></div>
<div><dt>{{ etiquetaIdentidad }}</dt><dd>{{ estado.resumen.identidad.id }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
@@ -79,7 +79,7 @@
</mat-card>
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
<mat-card-content><app-paciente-riesgo-tabla /></mat-card-content>
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
</mat-card>
</div>
}
@@ -1,8 +1,9 @@
import { Observable } from 'rxjs';
import { IdentidadPaciente } from '../paciente-identidad';
/** Snapshot of the received row, independent of the Seguimiento transport contract. */
export interface PacienteResumen {
id_seudonimo: string;
identidad: IdentidadPaciente;
grupoEdad: string | null;
estatus: string | null;
corte: string;
@@ -27,7 +28,8 @@ export interface PacienteDetalle {
}
export interface PacienteDetalleProvider {
obtener(idSeudonimo: string): Observable<PacienteDetalle | null>;
/** `id` is the patient identifier of the row; a patient the provider does not know is `null`. */
obtener(id: string): Observable<PacienteDetalle | null>;
}
export type PacienteDetalleEstado =
@@ -5,9 +5,9 @@ import { PacienteDetalleProvider } from './paciente-detalle.models';
@Injectable({ providedIn: 'root' })
export class PacienteDetalleMockProvider implements PacienteDetalleProvider {
obtener(idSeudonimo: string) {
obtener(id: string) {
return defer(() => {
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo);
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === id);
// Each read owns its data; consumers cannot mutate another selection or the fixtures.
return of(detalle ? structuredClone(detalle) : null);
});
@@ -3,6 +3,7 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Subject, of, throwError } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
@@ -10,9 +11,9 @@ import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.mod
import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
describe('Proveedor de detalle sintético', () => {
it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => {
@@ -59,7 +60,7 @@ describe('Estado de selección del paciente', () => {
const estado = state.estado();
expect(estado.tipo).toBe('no-disponible');
if (estado.tipo !== 'cerrado') {
expect(estado.resumen.id_seudonimo).toBe('001');
expect(estado.resumen.identidad.id).toBe('001');
expect(estado.resumen.vph?.resultado).toBe('NEGATIVO');
expect(estado.resumen.vph?.genotipo16y18).toBeNull();
expect(estado.resumen.diasTomaDiagnostico).toBe(0);
@@ -108,7 +109,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
let root: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
fixture = TestBed.createComponent(IndicadoresTracking);
root = fixture.nativeElement;
http = TestBed.inject(HttpTestingController);
@@ -166,7 +168,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
fixture.detectChanges();
const estado = fixture.componentInstance.pacienteDetalle.estado();
expect(estado.tipo).toBe('disponible');
if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo);
if (estado.tipo === 'disponible') expect(estado.resumen.identidad.id).toBe(pacientes[1].id_seudonimo);
volver();
expect(row).toBe(document.activeElement);
http.expectNone(() => true);
@@ -238,20 +240,15 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
http.expectNone(() => true);
});
it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => {
// Fails if a row that only has id_seudonimo asks the risk route (which takes a pac_id) or leaves no «no disponible» state.
it('una ficha de un renglón con solo id_seudonimo no consulta el riesgo y lo declara no disponible', () => {
const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
const obtener = vi.spyOn(provider, 'obtener');
try {
const detail = abrir();
const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Información simulada');
expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
expect(obtener).toHaveBeenCalledExactlyOnceWith();
volver();
const otra = abrir(1);
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
const tarjeta = abrir().querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(tarjeta.querySelector('table')).toBeNull();
expect(obtener).not.toHaveBeenCalled();
http.expectNone(() => true);
} finally { obtener.mockRestore(); }
});
@@ -2,6 +2,7 @@ import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core'
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, catchError, defer, map, of, switchMap } from 'rxjs';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { identidadDe } from '../paciente-identidad';
import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models';
import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider';
import { AltaRegistroTemporal } from './paciente-registro.models';
@@ -17,14 +18,14 @@ export class PacienteDetalleState {
readonly estado = this.actual.asReadonly();
readonly registrosTemporales = computed(() => {
const estado = this.actual();
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo);
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.identidad.id);
});
constructor() {
this.seleccion.pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.identidad.id)).pipe(
map(detalle => {
if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) {
if (detalle && (detalle.id_seudonimo !== resumen.identidad.id || detalle.origen !== 'sintetico')) {
throw new Error('Detalle incompatible con la selección');
}
return detalle
@@ -38,8 +39,10 @@ export class PacienteDetalleState {
}
abrir(paciente: SeguimientoPaciente, corte: string) {
const identidad = identidadDe(paciente);
if (!identidad) return;
const resumen: PacienteResumen = {
id_seudonimo: paciente.id_seudonimo,
identidad,
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
estatus: paciente.estatus.etiqueta,
corte,
@@ -65,7 +68,7 @@ export class PacienteDetalleState {
agregarRegistro(alta: AltaRegistroTemporal) {
const estado = this.actual();
if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false;
return this.sesion.agregar(alta.id_seudonimo, alta.registro);
if (estado.tipo === 'cerrado' || estado.resumen.identidad.id !== alta.paciente.id) return false;
return this.sesion.agregar(alta.paciente.id, alta.registro);
}
}
@@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente } from '../paciente-identidad';
import { PacienteDetalleEstado } from './paciente-detalle.models';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
@@ -31,19 +32,22 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
ngOnDestroy() { this.dialogoActivo?.close(); }
get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; }
/** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */
get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; }
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
abrirRegistro(tipo: TipoRegistroTemporal) {
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
const id_seudonimo = this.estado.resumen.id_seudonimo;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; id_seudonimo: string }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
const paciente = this.estado.resumen.identidad;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, paciente }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false,
});
this.dialogoActivo = ref;
ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => {
this.dialogoActivo = undefined;
if (registro) this.registroAgregado.emit({ id_seudonimo, registro });
if (registro) this.registroAgregado.emit({ paciente, registro });
});
}
etiquetaCitologia(resultado: string | null, calidad: string | null) {
@@ -1,7 +1,7 @@
<h2 mat-dialog-title>{{ titulo }}</h2>
<form [formGroup]="form" (ngSubmit)="agregar()">
<mat-dialog-content>
<p>Paciente {{ data.id_seudonimo }}</p>
<p>Paciente {{ data.paciente.id }}</p>
<div class="fields">
<mat-form-field appearance="outline">
<mat-label>{{ etiquetaTipo }}</mat-label>
@@ -1,4 +1,5 @@
import { Component, DestroyRef, inject } from '@angular/core';
import { IdentidadPaciente } from '../paciente-identidad';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -10,7 +11,7 @@ import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO,
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; }
export interface RegistroDialogData { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente; }
const opcionValida = (catalogo: Readonly<Record<string, string>>): ValidatorFn =>
control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true };
@@ -7,17 +7,21 @@ import { MatSelectHarness } from '@angular/material/select/testing';
import { MatInputHarness } from '@angular/material/input/testing';
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
import { MatDialog } from '@angular/material/dialog';
import { firstValueFrom } from 'rxjs';
import { firstValueFrom, of } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
import { TipoRegistroTemporal } from './paciente-registro.models';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
@@ -31,7 +35,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
let dialog: MatDialog;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
http = TestBed.inject(HttpTestingController);
dialog = TestBed.inject(MatDialog);
montarTracking();
@@ -130,7 +135,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo);
expect(almacenado.paciente).toBe(pacientes[0].id_seudonimo);
expect(almacenado.origen).toBe('sesion-demostracion');
expect(almacenado.fecha).toBe('2026-10-26');
http.expectNone(() => true);
@@ -274,7 +279,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
const a = primero.get(PacienteDetalleState);
const b = segundo.get(PacienteDetalleState);
a.abrir(pacientes[0], fixtureData.corte);
expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
expect(a.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
a.cerrar();
expect(a.registrosTemporales()).toEqual([]);
primero.destroy();
@@ -282,7 +287,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
expect(b.registrosTemporales()).toHaveLength(1);
b.abrir(pacientes[1], fixtureData.corte);
expect(b.registrosTemporales()).toEqual([]);
expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
expect(b.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
} finally {
if (!primero.destroyed) primero.destroy();
segundo.destroy();
@@ -1,3 +1,4 @@
import { IdentidadPaciente } from '../paciente-identidad';
import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos';
type ResultadoDemo = {
@@ -14,11 +15,12 @@ export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo'];
/** Independiente del resumen recibido y del historial inicial del proveedor. */
export type RegistroTemporal = Readonly<NuevoRegistroTemporal & {
id: number;
id_seudonimo: string;
/** Identifier of the patient the record was added to. */
paciente: string;
origen: 'sesion-demostracion';
}>;
export interface AltaRegistroTemporal {
id_seudonimo: string;
paciente: IdentidadPaciente;
registro: NuevoRegistroTemporal;
}
@@ -5,6 +5,7 @@ import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
describe('Fecha de calendario de registros temporales', () => {
it('acepta días reales, incluyendo años bisiestos y límites de año', () => {
@@ -35,7 +36,7 @@ describe.each(casos)('Formulario de $tipo', caso => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, paciente: identidadDe({ id_seudonimo: '001' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -82,7 +83,7 @@ describe('Resultados dependientes del estudio', () => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', paciente: identidadDe({ id_seudonimo: 'A' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
const fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -132,7 +133,7 @@ describe('Memoria de registros temporales', () => {
const sesion = TestBed.inject(PacienteRegistrosSesion);
for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true);
expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']);
expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true);
expect(sesion.paraPaciente('001').every(r => r.paciente === '001' && r.origen === 'sesion-demostracion')).toBe(true);
for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]);
sesion.agregar('toString', casos[0].registro);
expect(sesion.paraPaciente('toString')).toHaveLength(1);
@@ -11,21 +11,21 @@ export class PacienteRegistrosSesion {
private readonly registros = signal<ReadonlyMap<string, readonly RegistroTemporal[]>>(new Map());
private siguienteId = 0;
paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] {
return this.registros().get(idSeudonimo) ?? SIN_REGISTROS;
paraPaciente(id: string): readonly RegistroTemporal[] {
return this.registros().get(id) ?? SIN_REGISTROS;
}
agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean {
if (!idSeudonimo || !nuevo) return false;
agregar(id: string, nuevo: NuevoRegistroTemporal): boolean {
if (!id || !nuevo) return false;
const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion
: nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio;
const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : '');
if (!validado) return false;
const registro: RegistroTemporal = Object.freeze({
...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion',
...validado, id: ++this.siguienteId, paciente: id, origen: 'sesion-demostracion',
});
this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([
...(actual.get(idSeudonimo) ?? []), registro,
this.registros.update(actual => new Map(actual).set(id, Object.freeze([
...(actual.get(id) ?? []), registro,
])));
return true;
}
@@ -4,7 +4,6 @@
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@case ('no-disponible') {
<p role="status">Riesgo individual no disponible para esta paciente.</p>
<p class="availability">La consulta de riesgo individual aún no está habilitada.</p>
}
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
@@ -1,4 +1,4 @@
import { Component, inject } from '@angular/core';
import { Component, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@@ -11,6 +11,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
styleUrl: './paciente-riesgo-tabla.scss',
})
export class PacienteRiesgoTabla {
readonly estado = inject(PacienteRiesgoState).estado;
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>();
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
constructor() {
effect(() => this.state.pacId.set(this.pacId()));
}
}
@@ -40,9 +40,9 @@ export interface RiesgoPacienteCacu {
riesgo: LoteRiesgoCacu | null;
}
/** Deliberately no patient argument until secure identity resolution is authorized. */
/** `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(): Observable<unknown>;
obtener(pacId: string): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -1,8 +1,16 @@
import { InjectionToken } from '@angular/core';
import { of } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
},
});
@@ -12,6 +12,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
fixture.componentRef.setInput('pacId', '42');
fixture.detectChanges();
fixture.detectChanges();
return fixture;
}
@@ -20,14 +22,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify();
});
it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
const f = setup(), root: HTMLElement = f.nativeElement;
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
f.detectChanges();
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('aún no está habilitada');
expect(root.textContent).toContain('Recomendaciones no disponibles');
expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/);
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull());
});
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
@@ -35,7 +38,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith();
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
expect(root.querySelectorAll('thead th')).toHaveLength(4);
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
@@ -134,7 +137,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
expect(otra.nativeElement.querySelector('table')).toBeNull();
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
@@ -1,16 +1,23 @@
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of } from 'rxjs';
import { Injectable, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' };
@Injectable()
export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
// `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
), { initialValue: CARGANDO });
}
@@ -0,0 +1,216 @@
// Covers how a follow-up row identifies its patient (`pac_id`, or the legacy `id_seudonimo`): the rule itself, the CaMa
// table and record, the files built from the same rows, and CaCu's risk request. Fixtures: fixtures/cama_seguimiento.json
// (27 synthetic rows) rewritten to carry `pac_id`, and fixtures/cacu_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { lastValueFrom, Observable, of, toArray } from 'rxjs';
import camaData from './fixtures/cama_seguimiento.json';
import cacuData from './fixtures/cacu_seguimiento.json';
import { ExportInconsistent } from './export/tracking-export.models';
import { fetchAllTracking } from './export/tracking-export-source';
import { flatTable } from './export/tracking-export-table';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresTracking } from './indicadores-tracking';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-detalle/paciente-riesgo.provider';
import { columnaEnlace, identidadDe, identidadesDe } from './paciente-identidad';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
describe('Identidad de un renglón', () => {
// Fails if `pac_id` stops winning over the legacy field, or stops being kept as the text the server sent.
it('uses pac_id when the row has it, and the legacy id_seudonimo otherwise', () => {
expect(identidadDe({ pac_id: '42', id_seudonimo: 'P-X' })).toEqual({ campo: 'pac_id', id: '42' });
expect(identidadDe({ id_seudonimo: 'P-X' })).toEqual({ campo: 'id_seudonimo', id: 'P-X' });
expect(identidadDe({ pac_id: null, id_seudonimo: 'P-X' })?.campo).toBe('id_seudonimo');
});
// Fails if a number, a padded value or a pseudonym in `pac_id` is accepted, or if an invalid pac_id falls back to the pseudonym.
it('refuses a pac_id that is not a plain decimal string, without falling back to id_seudonimo', () => {
for (const malo of [42, '042', '-1', '4 2', '1e3', '', 'P-X', '12345678901234567890', {}]) expect(identidadDe({ pac_id: malo, id_seudonimo: 'P-X' })).toBeNull();
expect(identidadDe({ pac_id: '0' })?.id).toBe('0');
expect(identidadDe({ pac_id: '9223372036854775807' })?.id).toBe('9223372036854775807');
});
// Fails if a row with no identifier opens a record for nobody.
it('has no identity without an identifier', () => {
expect(identidadDe({})).toBeNull();
expect(identidadDe({ id_seudonimo: '' })).toBeNull();
expect(identidadDe({ id_seudonimo: 7 })).toBeNull();
});
// Fails if a page that repeats a patient, or identifies rows by different fields, can be shown.
it('refuses a page with a repeated patient or with mixed identifier fields', () => {
expect(identidadesDe([{ pac_id: '7' }, { pac_id: '8' }])).toHaveLength(2);
expect(identidadesDe([{ pac_id: '7' }, { pac_id: '7' }])).toBeNull();
expect(identidadesDe([{ pac_id: '7' }, { id_seudonimo: 'P-8' }])).toBeNull();
expect(identidadesDe([])).toEqual([]);
});
// Fails if the link moves to a column that is not the identifier when the answer announces it.
it('puts the link on the identifier column of the row, else on any identifier column, else on the first', () => {
expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }, { clave: 'pac_id' }], 'pac_id')).toBe('pac_id');
expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }], 'pac_id')).toBe('id_seudonimo');
expect(columnaEnlace([{ clave: 'a' }, { clave: 'b' }], 'pac_id')).toBe('a');
});
});
/** The CaMa fixture with `pac_id` (1..n) instead of the pseudonym. */
function conPacId(): Record<string, any> {
const d = structuredClone(camaData) as unknown as Record<string, any>;
d['columnas'][0] = { clave: 'pac_id', etiqueta: 'Identificador de paciente' };
d['items'] = (d['items'] as Record<string, any>[]).map((item, i) => {
const { id_seudonimo: _, ...rest } = item;
return { pac_id: String(i + 1), ...rest };
});
return d;
}
describe('Tabla de seguimiento con pac_id', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];
// Fails if the header or the link stop following the column the answer announces for the identifier.
it('shows the announced pac_id column and links each row by it', () => {
cargar(conPacId());
expect([...root().querySelectorAll('thead th')][0].textContent!.trim()).toBe('Identificador de paciente');
expect(enlaces().slice(0, 3).map(b => b.textContent!.trim())).toEqual(['1', '2', '3']);
expect(enlaces()[0].getAttribute('aria-label')).toBe('Ver ficha del paciente 1');
expect(root().querySelector('tbody tr')?.getAttribute('data-paciente')).toBe('1');
});
// Fails if the row that was used opens the record of another row, shows the legacy label, or the focus does not go
// back to the control that was used.
it('opens the record of the row that was used and returns focus to it', async () => {
const datos = conPacId(), items = datos['items'] as Record<string, any>[];
cargar(datos);
for (const indice of [2, 0]) {
enlaces()[indice].click(); fixture.detectChanges();
const ficha = root().querySelector('app-cama-patient-card')!;
expect(ficha.querySelector('h2')!.textContent!.trim()).toBe(`Paciente ${items[indice]['pac_id']}`);
expect(ficha.textContent).toContain(items[indice]['birads']);
expect(ficha.textContent).toContain('Identificador de paciente');
expect(ficha.textContent).not.toContain('Identificador seudónimo');
ficha.querySelector<HTMLButtonElement>('.back-button')!.click(); fixture.detectChanges();
await fixture.whenStable(); fixture.detectChanges();
expect(document.activeElement).toBe(enlaces()[indice]);
}
});
// Fails if a page that repeats a patient, or mixes pac_id with the legacy field, is drawn: its rows would open the same record.
it('does not draw an answer whose rows cannot be told apart or identify patients by different fields', () => {
const repetida = conPacId(); repetida['items'][1]['pac_id'] = repetida['items'][0]['pac_id'];
cargar(repetida);
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
expect(enlaces()).toHaveLength(0);
});
// Fails if a numeric pac_id is accepted: the contract is a decimal string.
it('does not draw an answer whose pac_id is a number', () => {
const numerica = conPacId(); numerica['items'][0]['pac_id'] = 1;
cargar(numerica);
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
});
// Fails if the legacy contract stops working while the server still sends only id_seudonimo.
it('still draws and opens a row that only has id_seudonimo', () => {
cargar(structuredClone(camaData) as unknown as Record<string, any>);
enlaces()[0].click(); fixture.detectChanges();
expect(root().querySelector('app-cama-patient-card h2')!.textContent).toContain('Paciente ' + (camaData.items[0] as any).id_seudonimo);
expect(root().querySelector('app-cama-patient-card')!.textContent).toContain('Identificador seudónimo');
});
});
describe('Archivos con pac_id', () => {
// A server over `todas`, `tam` rows a page.
function servidor(todas: Record<string, any>[], tam: number) {
return {
consultar(_d: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> {
const d = conPacId(); d['items'] = todas.slice((q.page - 1) * tam, q.page * tam);
d['paginacion'] = { page: q.page, page_size: tam, total_items: todas.length, total_pages: Math.ceil(todas.length / tam) };
return of(seguimientoTablaResponse(d));
},
} as unknown as SeguimientoTablaService;
}
const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5 };
// Fails if the file holds other rows, or the same rows in another order, than the pages of the table.
it('hands the files the same rows in the same order as the pages of the table', async () => {
const todas = conPacId()['items'] as Record<string, any>[];
const salida = await lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()));
const hecho = salida.at(-1)!;
expect(hecho.kind).toBe('done');
if (hecho.kind !== 'done') return;
expect(hecho.snapshot.items.map(i => i['pac_id'])).toEqual(todas.map(i => i['pac_id']));
const plana = flatTable(hecho.snapshot);
expect(plana.columns[0]).toMatchObject({ key: 'pac_id', label: 'Identificador de paciente' });
expect(plana.rows.map(f => f[0])).toEqual(todas.map(i => i['pac_id']));
});
// Fails if a patient that appears on two pages is exported twice as if it were two patients.
it('refuses a list in which the same patient is on two pages', async () => {
const todas = conPacId()['items'] as Record<string, any>[];
todas[7] = { ...todas[7], pac_id: todas[0]['pac_id'] };
await expect(lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()))).rejects.toBeInstanceOf(ExportInconsistent);
});
});
describe('Riesgo de CaCu por pac_id', () => {
let http: HttpTestingController;
const solicitudes: string[] = [];
function montar(items: Record<string, any>[]) {
solicitudes.length = 0;
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: (id: string) => { solicitudes.push(id); return of(null); } } }] });
const fixture = TestBed.createComponent(IndicadoresTracking);
http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('domainLabel', 'CaCu'); fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...structuredClone(cacuData), items });
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
fixture.detectChanges();
return fixture;
}
const filas = () => (structuredClone(cacuData) as unknown as { items: Record<string, any>[] }).items;
const primerEncabezado = (f: ReturnType<typeof montar>) => [...f.nativeElement.querySelectorAll('thead th')][0].textContent.trim();
const abrirSegunda = (f: ReturnType<typeof montar>) => { (f.nativeElement.querySelectorAll('tbody button.patient-link')[1] as HTMLButtonElement).click(); f.detectChanges(); };
afterEach(() => http.verify());
// Fails if the record asks for the risk with something other than the row's pac_id, or shows the legacy label for it.
it('requests the risk with the pac_id of the row and labels the identifier as the patient identifier', () => {
const items = filas().slice(0, 2).map(({ id_seudonimo: _, ...r }, i) => ({ pac_id: String(40 + i), ...r }));
const fixture = montar(items);
expect(primerEncabezado(fixture)).toBe('Identificador de paciente');
abrirSegunda(fixture);
expect(solicitudes).toEqual(['41']);
expect(fixture.nativeElement.querySelector('app-paciente-detalle h2').textContent).toContain('Paciente 41');
fixture.destroy();
});
// Fails if the migration alias wins over pac_id: a hash kept in id_seudonimo must never reach the risk route.
it('prefers pac_id over the legacy alias that rows carry during the migration', () => {
const items = filas().slice(0, 2).map((r, i) => ({ ...r, pac_id: String(40 + i) }));
const fixture = montar(items);
expect(primerEncabezado(fixture)).toBe('Identificador de paciente');
abrirSegunda(fixture);
expect(solicitudes).toEqual(['41']);
fixture.destroy();
});
// Fails if a legacy value is sent to the risk route, which only accepts a pac_id.
it('does not request the risk of a row that only has id_seudonimo', () => {
const fixture = montar(filas().slice(0, 2));
expect(primerEncabezado(fixture)).toBe('Identificador seudónimo');
abrirSegunda(fixture);
expect(solicitudes).toEqual([]);
expect(fixture.nativeElement.querySelector('app-paciente-riesgo-tabla').textContent).toContain('Riesgo individual no disponible');
fixture.destroy();
});
});
@@ -0,0 +1,54 @@
// How a follow-up row says who its patient is: `pac_id`, or the legacy `id_seudonimo` that servers may still send.
/** The fields that can identify a patient on a row, in order of precedence. */
export const CAMPOS_IDENTIDAD = ['pac_id', 'id_seudonimo'] as const;
export type CampoIdentidad = typeof CAMPOS_IDENTIDAD[number];
export interface IdentidadPaciente {
/** The field the identifier came from: `pac_id` wins over the legacy `id_seudonimo`. */
campo: CampoIdentidad;
/** The identifier as sent, scoped to the domain it was read in. `pac_id` is a decimal string. */
id: string;
}
/** What the row's identifier is called on screen and in the files, by the field it comes from. */
export const ETIQUETA_IDENTIDAD: Readonly<Record<CampoIdentidad, string>> = {
pac_id: 'Identificador de paciente',
id_seudonimo: 'Identificador seudónimo',
};
// No leading zeros and no sign: the value is compared and sent as text, so it has one spelling.
const PAC_ID = /^(0|[1-9][0-9]{0,18})$/;
/** The fields of a row that matter here; a typed row or a plain record both fit. */
export interface FilaConIdentidad { readonly pac_id?: unknown; readonly id_seudonimo?: unknown }
const texto = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
/**
* The identity of a row, or `null` when it has none that can be trusted: a `pac_id` that is not a decimal string
* (a number is refused, not converted) or no identifier at all. A present `pac_id` is never replaced by
* `id_seudonimo` when it is invalid.
*/
export function identidadDe(fila: FilaConIdentidad): IdentidadPaciente | null {
const pacId = fila.pac_id;
if (pacId !== undefined && pacId !== null) return typeof pacId === 'string' && PAC_ID.test(pacId) ? { campo: 'pac_id', id: pacId } : null;
return texto(fila.id_seudonimo) ? { campo: 'id_seudonimo', id: fila.id_seudonimo } : null;
}
/**
* The identities of a page of rows, or `null` when the page cannot be shown: a row without identity, rows that do not
* identify their patient by the same field, or two rows of the same patient (they would open the same record).
*/
export function identidadesDe(filas: readonly FilaConIdentidad[]): IdentidadPaciente[] | null {
const identidades = filas.map(identidadDe);
if (identidades.some(i => i === null)) return null;
const validas = identidades as IdentidadPaciente[];
if (validas.some(i => i.campo !== validas[0].campo)) return null;
return new Set(validas.map(i => i.id)).size === validas.length ? validas : null;
}
/** The column that holds the link to the record: the one of the row's own field, else any identifier column, else the first. */
export function columnaEnlace(columnas: readonly { clave: string }[], campo: CampoIdentidad): string | undefined {
return columnas.find(c => c.clave === campo)?.clave
?? columnas.find(c => (CAMPOS_IDENTIDAD as readonly string[]).includes(c.clave))?.clave
?? columnas[0]?.clave;
}
@@ -2,6 +2,8 @@ import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { Dominio, requireDominio } from './indicadores.models';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
@@ -11,27 +13,37 @@ export interface SeguimientoOpcion { codigo: string; etiqueta: string; }
// `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: SeguimientoOpcion[]; }
// What a list of a cohort quotes back so that it opens the cohort that was counted: the cohort, its scenario and the
// revision of its rows. They are not filters; the answer repeats them, and a list that does not is not the one asked for.
export interface ContextoLista { cohorte: string; escenario: string; revision: string; }
export const CLAVES_CONTEXTO = ['cohorte', 'escenario', 'revision'] as const;
export interface SeguimientoTablaQuery {
corte?: string; meses: 1 | 3 | 6 | 12; page: number; page_size: number;
corte?: string; meses: MesesVentana; page: number; page_size: number;
// The filters the list announces in `filtros_disponibles`, by key; an empty value is no filter.
filtros?: Record<string, string | undefined>;
contexto?: ContextoLista;
}
export interface SeguimientoTablaResponse {
export interface SeguimientoTablaResponse extends Partial<ContextoLista> {
simulado: true;
corte: string;
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
ventana: { meses: MesesVentana; desde: string; hasta: string };
filtros: Record<string, string | null>;
filtros_disponibles: SeguimientoFiltro[];
columnas: SeguimientoColumna[];
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
// Every item names its patient (`pac_id`, or the legacy `id_seudonimo`); the rest are the columns' keys and their details.
items: Record<string, SeguimientoValor>[];
}
export class SeguimientoInvalido extends Error {}
export const MESES_VENTANA = [1, 3, 6, 12] as const;
// 0 is the whole list, without a time window: what a curve or a heatmap cell of the analysis opens. The list offers
// it only while such a selection is active.
export const MESES_VENTANA = [1, 3, 6, 12, 0] as const;
export type MesesVentana = typeof MESES_VENTANA[number];
/** What the window is called on screen and in the files: the whole cohort or a number of months. */
export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`;
export const PAGE_SIZE_MAX = 200;
const RESERVADAS = ['meses', 'page', 'page_size', 'corte'];
const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
@@ -43,7 +55,27 @@ const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiquet
export function validQuery(q: SeguimientoTablaQuery) {
return (!q.corte || isoDate(q.corte)) && (MESES_VENTANA as readonly number[]).includes(q.meses) && integer(q.page, 1)
&& integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX && Object.keys(q.filtros ?? {}).every(clave);
&& integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX && Object.keys(q.filtros ?? {}).every(clave)
// A cohort's list needs a cut-off: the revision belongs to it.
&& (!q.contexto || (!!q.corte && CLAVES_CONTEXTO.every(k => text(q.contexto![k]))));
}
/**
* Whether an answer says it applied the window and the filters that were asked for (and the cut-off, when one was
* asked, and the cohort, scenario and revision of a cohort's list). A list or a file must not show rows of another
* query under the title of this one.
*/
export function consultaAplicada(query: SeguimientoTablaQuery, answer: SeguimientoTablaResponse): boolean {
const entries = (filters: Record<string, string | null | undefined>) =>
JSON.stringify(Object.entries(filters).filter(([, v]) => !!v).sort(([a], [b]) => a.localeCompare(b)));
return answer.ventana.meses === query.meses && (!query.corte || answer.corte === query.corte)
&& entries(query.filtros ?? {}) === entries(answer.filtros)
&& (!query.contexto || CLAVES_CONTEXTO.every(k => answer[k] === query.contexto![k]));
}
/** The cohort an answer belongs to, when it names one: what the next pages and the files must quote back. */
export function contextoDe(answer: SeguimientoTablaResponse): ContextoLista | undefined {
return answer.cohorte && answer.escenario && answer.revision ? { cohorte: answer.cohorte, escenario: answer.escenario, revision: answer.revision } : undefined;
}
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
@@ -54,18 +86,45 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
&& Array.isArray(f['opciones']) && f['opciones'].every(opcion)) && new Set(available.map(f => (f as Record<string, unknown>)['clave'])).size === available.length;
const columnasOk = Array.isArray(columns) && columns.length > 0 && 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'])))));
if (CLAVES_CONTEXTO.some(k => v[k] !== undefined && !text(v[k]))) throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
if (!isoDate(v['corte']) || !record(window) || !(MESES_VENTANA as readonly number[]).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'] > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|| !filtrosOk || !columnasOk
|| !record(filters) || !Object.entries(filters).every(([k, f]) => (f === null || typeof f === 'string') && (available as Record<string, unknown>[]).some(a => a['clave'] === k))
|| !Array.isArray(v['items']) || v['items'].length > p['page_size']
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
}
return v as unknown as SeguimientoTablaResponse;
const respuesta = v as unknown as SeguimientoTablaResponse;
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
}
/**
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays
* in `<clave>_codigo` and in the filters' options, which are what the requests send.
*/
export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
const claves = Object.keys(ETIQUETADAS);
return {
...r,
filtros_disponibles: r.filtros_disponibles.map(f => claves.includes(f.clave)
? { ...f, opciones: f.opciones.map(o => o.etiqueta === o.codigo ? { ...o, etiqueta: etiquetaDeFiltro(f.clave, o.codigo) } : o) } : f),
items: r.items.map(item => {
const nuevo = { ...item };
for (const k of claves) {
const valor = item[k];
if (typeof valor !== 'string' || etiquetaDeFiltro(k, valor) === valor) continue;
if (nuevo[k + '_codigo'] === undefined) nuevo[k + '_codigo'] = valor;
nuevo[k] = etiquetaDeFiltro(k, valor);
}
return nuevo;
}),
};
}
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {
private readonly http = inject(HttpClient);
@@ -73,6 +132,7 @@ export class SeguimientoTablaService {
if (!validQuery(query)) throw new SeguimientoInvalido('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);
if (query.contexto) for (const k of CLAVES_CONTEXTO) params = params.set(k, query.contexto[k]);
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));
}