feat(seguimiento): list opened on a group of the cohort, with its window, cut-off, cohort and revision
The follow-up list of breast cancer can now be opened on a selection that the analysis names: the whole cohort (window 0, offered only while the selection is active), the cut-off the analysis was computed at, the group's filter, and the cohort with its revision, which the server requires and repeats. - A cohort's list quotes `cohorte`, `escenario` and `revision` (not filters) on every page and in the export; an answer that loses a filter, changes the window or the cut-off, or is another cohort or revision is not drawn and cannot be exported. - A new selection cancels the previous request; while it loads, and when it fails (403, 409, 503), no list of the previous query stays on screen. - Inside the cohort the form refines the same cohort and says so; "Quitar selección" leaves it. - "Volver al análisis" and a note when the list holds a different number of patients than the analysis counted. - PDF and XLSX state the selection, the cut-off and "Toda la cohorte"; the file name tells a selection apart; an export in progress is cancelled, and a finished one discarded, when the query on screen changes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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,20 @@
|
||||
// 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,
|
||||
});
|
||||
/** 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 @@
|
||||
// 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('avisa cuando la lista no tiene tantos pacientes como contó el análisis, y calla cuando coinciden', async () => {
|
||||
// Fails if a difference between the analysis' count and the list goes unsaid.
|
||||
abrirCon(seleccion(1, { esperados: 30 }));
|
||||
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
|
||||
expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección; la lista muestra 27.');
|
||||
fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges();
|
||||
solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar();
|
||||
expect(root().querySelector('.diferencia')).toBeNull();
|
||||
});
|
||||
|
||||
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'" [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="status">{{ 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,65 @@ 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. */
|
||||
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; la lista muestra ${total}.`;
|
||||
}
|
||||
|
||||
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 +214,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 +227,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,14 +265,32 @@ 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.
|
||||
@@ -208,3 +312,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);
|
||||
|
||||
@@ -11,15 +11,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 +34,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 +53,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 +84,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'])
|
||||
@@ -73,6 +104,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