Compare commits
3 Commits
ee75e7a2a0
...
2b0f6dfbed
| Author | SHA1 | Date | |
|---|---|---|---|
| 2b0f6dfbed | |||
| 1d43ebff3b | |||
| eb92b99a1d |
@@ -0,0 +1,18 @@
|
||||
// How the codes of the breast cohort are written for the user. Only codes whose meaning the API's own code confirms:
|
||||
// the BI-RADS categories (kit: BIRADS_4, 4A, 4B, 4C, 5, 6) and the age groups of the cohort reader (`_age_group` of
|
||||
// webapi/cama_cohort.py: under 40, each decade from 40 to 69, 70 or more, and no data when the birth date is missing
|
||||
// or later than the cut-off). Requests keep the codes; only what is shown changes.
|
||||
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)$/;
|
||||
|
||||
/** «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;
|
||||
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad };
|
||||
|
||||
/** 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,6 @@
|
||||
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 { 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 +13,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 +41,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 })),
|
||||
|
||||
@@ -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,51 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate } from './cacu-seguimiento.models';
|
||||
import { Dominio, requireDominio } from './indicadores.models';
|
||||
|
||||
// The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many
|
||||
// patients of the cohort fall in each BI-RADS category at a cut-off (`GET /<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; }
|
||||
|
||||
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,209 @@
|
||||
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('«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 } = {}): Record<string, any> {
|
||||
const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0 } = 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, 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,222 @@
|
||||
import { Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, untracked } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { isoDate } from './cacu-seguimiento.models';
|
||||
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
|
||||
import { etiquetaBirads } from './etiquetas-cohorte';
|
||||
import { AnalisisAgregado, AnalisisService, ContextoCohorte } 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.';
|
||||
|
||||
/** Today as the date input writes it, in the user's own calendar day. */
|
||||
export function hoyIso(ahora = new Date()) {
|
||||
const dos = (n: number) => String(n).padStart(2, '0');
|
||||
return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`;
|
||||
}
|
||||
|
||||
/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
|
||||
export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
|
||||
const g = agregado.grupos.find(x => x.codigo === codigo);
|
||||
return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
|
||||
}
|
||||
|
||||
/** The selection of a published group: the whole group of the cohort at the cut-off it was counted at, nothing else. */
|
||||
export function seleccionDeGrupo(agregado: AnalisisAgregado, codigo: string): SeleccionPacientes | undefined {
|
||||
const g = agregado.grupos.find(x => x.codigo === codigo);
|
||||
if (!g || motivoSinLista(agregado, codigo)) return undefined;
|
||||
return { filtros: { birads: codigo }, etiqueta: `Categoría BI-RADS: ${etiquetaBirads(codigo)}`, corte: agregado.corte, esperados: g.n,
|
||||
contexto: { cohorte: agregado.cohorte, escenario: agregado.escenario, revision: agregado.revision } };
|
||||
}
|
||||
|
||||
/** The scrolling ancestor of an element, or the document's own scroller. */
|
||||
function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
||||
for (let n = el.parentElement; n; n = n.parentElement) {
|
||||
const overflow = getComputedStyle(n).overflowY;
|
||||
if ((overflow === 'auto' || overflow === 'scroll') && n.scrollHeight > n.clientHeight) return n;
|
||||
}
|
||||
return (el.ownerDocument.scrollingElement ?? el.ownerDocument.documentElement) as HTMLElement;
|
||||
}
|
||||
|
||||
// Epidemiological analysis of the breast cohort. For now: how many patients of the cohort are in each BI-RADS category at
|
||||
// a cut-off, as a count (not an incidence or a survival estimate). A published category opens its patients in Seguimiento;
|
||||
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis',
|
||||
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
template: `
|
||||
<section class="panel" aria-labelledby="analisis-titulo">
|
||||
<h2 id="analisis-titulo">Pacientes por categoría BI-RADS</h2>
|
||||
<p class="nota">Conteo descriptivo de las pacientes de la cohorte en cada categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.</p>
|
||||
<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>
|
||||
@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) {
|
||||
<p class="contexto">Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.</p>
|
||||
@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 publicada para ver sus pacientes 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>
|
||||
}
|
||||
</section>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.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); margin-top: var(--issste-space-4); }
|
||||
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; });
|
||||
// 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,131 @@
|
||||
// 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 } 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');
|
||||
});
|
||||
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' });
|
||||
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>('#analisis-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]);
|
||||
|
||||
@@ -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» sale de la cohorte: 3 meses, sin filtros y sin citar la revisión', async () => {
|
||||
// Fails if removing the selection leaves its filters, the whole cohort or the cohort's 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({ ...base(), filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: null } }); await asentar();
|
||||
expect(root().querySelector('.seleccion')).toBeNull();
|
||||
expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined();
|
||||
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
|
||||
});
|
||||
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' }));
|
||||
});
|
||||
});
|
||||
@@ -8,17 +8,34 @@ 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, 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 };
|
||||
/** 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 +48,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,7 +89,7 @@ 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>
|
||||
@@ -107,6 +136,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,34 +148,69 @@ 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.`;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.consultas.pipe(
|
||||
switchMap((q): Observable<Resultado> => {
|
||||
if (!q) return of({ estado: 'idle', mensaje: '' });
|
||||
switchMap((c): Observable<Resultado> => {
|
||||
if (!c) return of({ estado: 'idle', mensaje: '' });
|
||||
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(
|
||||
map((data): Resultado => ({ estado: 'ready', data, mensaje: '' })),
|
||||
// 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))),
|
||||
startWith<Resultado>({ estado: 'loading', mensaje: '' }));
|
||||
}),
|
||||
@@ -149,8 +218,11 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
).subscribe(r => {
|
||||
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 +231,32 @@ 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.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined);
|
||||
}
|
||||
if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(this.applied); }
|
||||
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;
|
||||
// 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 }); }
|
||||
}
|
||||
|
||||
private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado {
|
||||
// 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.' };
|
||||
}
|
||||
@@ -179,20 +269,38 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
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;
|
||||
}
|
||||
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 analysis' cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months.
|
||||
const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto ? 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;
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, 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); }
|
||||
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;
|
||||
@@ -208,3 +316,5 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
detalles(c: SeguimientoColumna) { return c.detalles ?? []; }
|
||||
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,7 +38,7 @@
|
||||
@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>
|
||||
|
||||
@@ -7,7 +7,7 @@ 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 { IndicadoresService } from './indicadores.service';
|
||||
@@ -23,6 +23,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);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -26,7 +26,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo
|
||||
['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],
|
||||
|
||||
@@ -16,6 +16,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,10 +32,14 @@ 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 {
|
||||
/**
|
||||
* The patient summary of a follow-up row, or `null` when the row has no identifier to show. `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 pseudonymId = text(row['id_seudonimo']);
|
||||
if (!pseudonymId) return null;
|
||||
const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta;
|
||||
const days = row['dias_mastografia_diagnostico'];
|
||||
return {
|
||||
pseudonymId,
|
||||
@@ -45,6 +51,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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate } from './cacu-seguimiento.models';
|
||||
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,15 +12,20 @@ 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[];
|
||||
@@ -29,9 +35,14 @@ export interface SeguimientoTablaResponse {
|
||||
}
|
||||
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 +54,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,6 +85,7 @@ 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'])
|
||||
@@ -63,9 +95,35 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|
||||
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) {
|
||||
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 };
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SeguimientoTablaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
@@ -73,6 +131,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));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user