diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index f3c85c8..6d679e6 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -92,7 +92,8 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow(); open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); }); - it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => { + it('tea conserva su estado pendiente sin consultas de pacientes', () => { + const dominio = 'tea'; fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true); expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible'); expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.'); diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 9fa4416..267d869 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -84,7 +84,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const ongoing = request(periods[0]); for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { page.changeSection(section); fixture.detectChanges(); - for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); + for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.initialPeriodState()).toBe('loading'); expect(ongoing.cancelled).toBe(false); http.expectNone(() => true); @@ -104,7 +104,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid editor().select([periods[2]]); fixture.detectChanges(); for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { page.changeSection(section); fixture.detectChanges(); - for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); + for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(editor().selectedPeriods).toEqual([periods[2]]); expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g'); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index af62028..c8be460 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -53,8 +53,9 @@ describe('Secciones compartidas por dominio', () => { // By id, since CaMa has one more tab. const pestana = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; pestana('seguimiento').click(); harness.detectChanges(); - if (domain === 'cacu') { - http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); + // CaCu and CaMa request their own follow-up when the tab opens; the lab WebApi has neither yet (404). + if (domain !== 'tea') { + http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); } const tracking = root.querySelector('#panel-seguimiento')!; @@ -63,6 +64,12 @@ describe('Secciones compartidas por dominio', () => { if (domain === 'cacu') { expect(tracking.querySelector('tbody')).toBeNull(); expect(tracking.querySelector('input[type=date]')).not.toBeNull(); + } else if (domain === 'cama') { + // Pending integration: the form is gone with no table, and the retry is offered. + expect(tracking.textContent).toContain('Funcionalidad pendiente de publicación'); + expect(tracking.querySelector('table')).toBeNull(); + expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull(); + expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento'); } else { expect(tracking.querySelectorAll('thead th')).toHaveLength(6); expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts new file mode 100644 index 0000000..91da255 --- /dev/null +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts @@ -0,0 +1,234 @@ +// Covers CaMa's follow-up table: when it asks, what it sends, how it draws the answer and each state (loading, +// empty, pending, error, retry). The answers are fixtures (fixtures/cama_seguimiento.json and variations of it): +// synthetic records, used by tests only; the view never reads them in normal use. +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 { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; + +const base = () => structuredClone(fixtureData) as unknown as Record; +// The server's page `n` of `tam` items, with the filters applied by it (here, none). +function pagina(n: number, tam: number, extra: Record = {}) { + const d = base(), todos = d['items'] as unknown[]; + d['items'] = todos.slice((n - 1) * tam, n * tam); + d['paginacion'] = { page: n, page_size: tam, total_items: todos.length, total_pages: Math.max(1, Math.ceil(todos.length / tam)) }; + return { ...d, ...extra }; +} + +describe('Seguimiento de CaMa (tabla)', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', 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)])); + const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); }; + // ngModel writes its values in a microtask: wait for it before reading or editing the form. + async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } + async function cargado(respuesta: Record = pagina(1, 50)) { abrir(); solicitud().flush(respuesta); await asentar(); } + const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; + const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement; + 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(); + } + // Each cell reads as its text nodes (value, then each detail) joined by one space. + const filas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => [...td.childNodes].filter(n => n.nodeType !== Node.COMMENT_NODE).map(n => (n.textContent ?? '').trim()).filter(Boolean).join(' '))); + + it('no pide nada hasta que la pestaña está activa, y entonces pide la ventana de 3 meses, página 1 de 50', async () => { + http.expectNone(() => true); + abrir(); + const r = solicitud(); + expect(r.request.method).toBe('GET'); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush(pagina(1, 50)); + }); + it('mientras carga lo dice; ya cargado dibuja la tabla con las columnas que declara la respuesta', async () => { + abrir(); fixture.detectChanges(); + expect(root().querySelector('[role=status]')?.textContent).toContain('Cargando seguimiento'); + expect(boton('Consultar').disabled).toBe(true); + solicitud().flush(pagina(1, 50)); fixture.detectChanges(); + expect(root().querySelector('[role=status]')).toBeNull(); + expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual([ + 'Identificador seudónimo', 'Grupo de edad', 'Estatus de seguimiento', 'Última mastografía', 'Resultado histopatológico', 'Días de mastografía a diagnóstico', 'Prioridad']); + expect(root().querySelector('caption')?.textContent).toBe('Resultados disponibles por paciente'); + expect(filas()).toHaveLength(27); + expect(root().textContent).toContain('Ventana consultada: 2026-07-21 al 2026-10-20.'); + }); + it('«Datos de demostración» se muestra cuando la respuesta es simulada', async () => { + await cargado(); + expect(root().querySelector('.simulation')?.textContent).toBe('Datos de demostración'); + }); + it('los detalles salen bajo su valor con su etiqueta y un valor nulo se lee «No disponible», sin línea de detalle', async () => { + await cargado(); + const todas = filas(); + const sinBiopsia = todas.find(f => f[0] === 'M-0081')!; + expect(sinBiopsia[3]).toBe('BI-RADS 4A Fecha: 2026-07-25'); + expect(sinBiopsia[4]).toBe('No disponible'); expect(sinBiopsia[5]).toBe('No disponible'); + const conBiopsia = todas.find(f => f[4].startsWith('Carcinoma invasor'))!; + expect(conBiopsia[4]).toMatch(/^Carcinoma invasor Fecha de biopsia: 20\d\d-\d\d-\d\d$/); + expect(conBiopsia[5]).toMatch(/^[0-9]+$/); + }); + it('el formulario muestra el corte que devolvió el servidor, la ventana, los cuatro filtros anunciados y el tamaño', async () => { + await cargado(); + expect((campo('Fecha de corte').querySelector('input') as HTMLInputElement).value).toBe('2026-10-20'); + expect((campo('Ventana de meses').querySelector('select') as HTMLSelectElement).selectedOptions[0].text.trim()).toBe('3 meses'); + expect([...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + const etiquetas = [...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim()); + expect(etiquetas).toEqual(['Fecha de corte', 'Ventana de meses', 'Estatus de seguimiento', 'Categoría BI-RADS', 'Grupo de edad', 'Prioridad', 'Registros por página']); + expect([...campo('Estatus de seguimiento').querySelectorAll('option')].map(o => o.text.trim())).toEqual( + ['Todos', 'Pendiente de biopsia', 'Biopsia sin resultado', 'Cáncer confirmado', 'Benigno, regresa a tamizaje', 'Información insuficiente']); + expect([...campo('Prioridad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Alta', 'Media', 'Baja']); + expect((campo('Registros por página').querySelector('input') as HTMLInputElement).value).toBe('50'); + }); + it('Consultar envía la ventana, el corte y solo los filtros elegidos, desde la página 1', async () => { + await cargado(); + await elegir('Ventana de meses', '6 meses'); await elegir('Estatus de seguimiento', 'CANCER_CONFIRMADO'); await elegir('Categoría BI-RADS', 'BIRADS_5'); + boton('Consultar').click(); fixture.detectChanges(); + const r = solicitud(); + expect(parametros(r)).toEqual({ meses: '6', page: '1', page_size: '50', corte: '2026-10-20', estatus: 'CANCER_CONFIRMADO', birads: 'BIRADS_5' }); + r.flush(pagina(1, 50, { ventana: { meses: 6, desde: '2026-04-21', hasta: '2026-10-20' }, filtros: { estatus: 'CANCER_CONFIRMADO', birads: 'BIRADS_5', grupo_edad: null, prioridad: null } })); + fixture.detectChanges(); + expect(root().textContent).toContain('Ventana consultada: 2026-04-21 al 2026-10-20.'); + }); + it('«Todos» quita el filtro: no se envía', async () => { + await cargado(); + await elegir('Prioridad', 'ALTA'); boton('Consultar').click(); fixture.detectChanges(); + solicitud().flush(pagina(1, 50, { filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: 'ALTA' } })); await asentar(); + await elegir('Prioridad', 'Todos'); boton('Consultar').click(); fixture.detectChanges(); + expect(parametros(solicitud())).not.toHaveProperty('prioridad'); + }); + + describe('paginación', () => { + it('Anterior y Siguiente piden la página vecina con los mismos filtros; en los extremos se desactivan', async () => { + await cargado(pagina(1, 10, { filtros: { estatus: null, birads: null, grupo_edad: '50-59', prioridad: null } })); + expect(root().querySelector('nav')?.textContent).toContain('Página 1 de 3, 27 registros'); + expect(boton('Anterior').disabled).toBe(true); expect(boton('Siguiente').disabled).toBe(false); + boton('Siguiente').click(); fixture.detectChanges(); + const r = solicitud(); + expect(parametros(r)).toEqual({ meses: '3', page: '2', page_size: '10', corte: '2026-10-20', grupo_edad: '50-59' }); + r.flush(pagina(2, 10)); fixture.detectChanges(); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); + expect(boton('Anterior').disabled).toBe(false); + boton('Anterior').click(); fixture.detectChanges(); + expect(solicitud().request.params.get('page')).toBe('1'); + }); + it('la última página desactiva Siguiente', async () => { + await cargado(pagina(3, 10)); + expect(boton('Siguiente').disabled).toBe(true); expect(boton('Anterior').disabled).toBe(false); + expect(filas()).toHaveLength(7); + }); + it('cambiar los filtros vuelve a la página 1', async () => { + await cargado(pagina(2, 10)); + await elegir('Prioridad', 'MEDIA'); boton('Consultar').click(); fixture.detectChanges(); + expect(solicitud().request.params.get('page')).toBe('1'); + }); + it('los botones de página no se pueden pulsar mientras se consulta', async () => { + await cargado(pagina(1, 10)); + boton('Siguiente').click(); fixture.detectChanges(); + expect(boton('Siguiente').disabled).toBe(true); expect(boton('Anterior').disabled).toBe(true); + solicitud().flush(pagina(2, 10)); + }); + it('una consulta nueva cancela la anterior y su respuesta tardía no se dibuja', async () => { + // Fails if a slow answer replaces the table of a later query. + await cargado(pagina(1, 10)); + boton('Siguiente').click(); fixture.detectChanges(); + const lenta = solicitud(); + await elegir('Prioridad', 'ALTA'); (root().querySelector('form') as HTMLFormElement).dispatchEvent(new Event('submit')); fixture.detectChanges(); + expect(lenta.cancelled).toBe(true); + const rapida = solicitud(); + rapida.flush(pagina(1, 10, { filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: 'ALTA' } })); fixture.detectChanges(); + expect(() => lenta.flush(pagina(2, 10))).toThrow(); + expect(root().querySelector('nav')?.textContent).toContain('Página 1 de 3'); + }); + }); + + describe('estados', () => { + it('sin registros para los filtros lo dice y conserva el formulario', async () => { + const vacia = pagina(1, 50); vacia['items'] = []; vacia['paginacion'] = { page: 1, page_size: 50, total_items: 0, total_pages: 1 }; + await cargado(vacia); + expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); + expect(root().querySelector('tbody td')?.getAttribute('colspan')).toBe('7'); + expect(boton('Consultar')).toBeDefined(); + }); + it('404 en la primera página: integración pendiente, sin tabla, y el reintento vuelve a pedir', async () => { + abrir(); solicitud().flush('', { status: 404, statusText: 'Not Found' }); fixture.detectChanges(); + expect(root().querySelector('[role=status]')?.textContent).toContain('El seguimiento aún no está disponible'); + expect(root().querySelector('table')).toBeNull(); expect(root().querySelector('.simulation')).toBeNull(); + boton('Reintentar seguimiento').click(); fixture.detectChanges(); + solicitud().flush(pagina(1, 50)); fixture.detectChanges(); + expect(root().querySelector('table')).not.toBeNull(); + expect(root().textContent).not.toContain('Funcionalidad pendiente de publicación'); + }); + it('404 en una página posterior es un error, no «pendiente»', async () => { + await cargado(pagina(1, 10)); + boton('Siguiente').click(); fixture.detectChanges(); + solicitud().flush('', { status: 404, statusText: 'Not Found' }); fixture.detectChanges(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('No se pudo consultar el seguimiento'); + expect(root().textContent).not.toContain('Funcionalidad pendiente'); + }); + it('400 pide revisar la fecha, la ventana y los filtros', async () => { + await cargado(); + boton('Consultar').click(); fixture.detectChanges(); + solicitud().flush({ error: 'parámetros inválidos' }, { status: 400, statusText: 'Bad Request' }); fixture.detectChanges(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha, la ventana y los filtros seleccionados'); + }); + it('un fallo del servidor muestra un mensaje fijo, nunca el cuerpo, y el reintento repite la misma consulta', async () => { + // Fails if the server's text reaches the page, or if the retry sends another query. + await cargado(); await elegir('Prioridad', 'BAJA'); boton('Consultar').click(); fixture.detectChanges(); + solicitud().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(root().querySelector('[role=alert]')?.textContent).toBe('No se pudo consultar el seguimiento. Intenta nuevamente.'); + expect(root().textContent).not.toContain('detalle interno'); + boton('Reintentar seguimiento').click(); fixture.detectChanges(); + expect(parametros(solicitud())).toMatchObject({ prioridad: 'BAJA', page: '1' }); + }); + it('una respuesta que no es de demostración o está fuera de contrato no se dibuja', async () => { + abrir(); const fuera = pagina(1, 50, { simulado: false }); + solicitud().flush(fuera); fixture.detectChanges(); + expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.'); + expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081'); + }); + it('un tamaño de página inválido no sale del navegador', async () => { + await cargado(); + const tam = campo('Registros por página').querySelector('input') as HTMLInputElement; + tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges(); + boton('Consultar').click(); fixture.detectChanges(); + http.expectNone(() => true); + expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha'); + }); + }); + + describe('listo para otra fuente', () => { + it('dibuja otras columnas, otros filtros y otros detalles sin cambios en el código', async () => { + // The view knows no column or filter by name: only the identifier is required. + abrir(); + solicitud().flush({ + simulado: true, corte: '2026-11-01', ventana: { meses: 1, desde: '2026-10-02', hasta: '2026-11-01' }, + filtros: { zona: null }, filtros_disponibles: [{ clave: 'zona', etiqueta: 'Zona', opciones: [{ codigo: 'N', etiqueta: 'Norte' }, { codigo: 'S', etiqueta: 'Sur' }] }], + columnas: [{ clave: 'id_seudonimo', etiqueta: 'Folio' }, { clave: 'evento', etiqueta: 'Último evento', detalles: [{ clave: 'evento_fecha', etiqueta: 'Ocurrió' }] }], + paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 }, + items: [{ id_seudonimo: 'X-1', evento: 'Alta', evento_fecha: '2026-10-05' }, { id_seudonimo: 'X-2', evento: null, evento_fecha: null }], + }); + await asentar(); + expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual(['Folio', 'Último evento']); + expect(filas()).toEqual([['X-1', 'Alta Ocurrió: 2026-10-05'], ['X-2', 'No disponible']]); + expect([...campo('Zona').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Norte', 'Sur']); + await elegir('Zona', 'S'); boton('Consultar').click(); fixture.detectChanges(); + expect(parametros(solicitud())).toEqual({ meses: '1', page: '1', page_size: '50', corte: '2026-11-01', zona: 'S' }); + }); + it('si la respuesta deja de anunciar un filtro, el formulario lo retira y no lo envía', async () => { + await cargado(); await elegir('Prioridad', 'ALTA'); + boton('Consultar').click(); fixture.detectChanges(); + const sin = pagina(1, 50); sin['filtros_disponibles'] = sin['filtros_disponibles'].filter((f: any) => f.clave !== 'prioridad'); delete sin['filtros']['prioridad']; + solicitud().flush(sin); fixture.detectChanges(); + expect(campo('Prioridad')).toBeUndefined(); + boton('Consultar').click(); fixture.detectChanges(); + expect(parametros(solicitud())).not.toHaveProperty('prioridad'); + }); + }); +}); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts new file mode 100644 index 0000000..5afbbb3 --- /dev/null +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -0,0 +1,167 @@ +import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; +import { Dominio } from './indicadores.models'; +import { + MESES_VENTANA, 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; } + +/** + * Follow-up list of a domain, drawn from what `GET //seguimiento` announces: the filters, the columns + * and their details come with the answer. Nothing is requested until the tab is opened. + */ +@Component({ + selector: 'app-seguimiento-tabla', + imports: [FormsModule], + template: ` + @if (data(); as respuesta) { + @if (respuesta.simulado) {

Datos de demostración

} + } +
+ + + @for (filtro of filtros(); track filtro.clave) { + + } + + +
+ @switch (estado()) { + @case ('loading') {

Cargando seguimiento…

} + @case ('pending') { +

El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.

+ + } + @case ('error') { +

{{ mensaje() }}

+ + } + } + @if (data(); as respuesta) { +

Ventana consultada: {{ respuesta.ventana.desde }} al {{ respuesta.ventana.hasta }}.

+
+ + + @for (c of respuesta.columnas; track c.clave) { } + + @for (item of respuesta.items; track item['id_seudonimo']) { + + @for (c of respuesta.columnas; track c.clave) { + + } + + } @empty { } + +
Resultados disponibles por paciente
{{ c.etiqueta }}
{{ texto(item[c.clave]) }}@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { {{ d.etiqueta }}: {{ texto(item[d.clave]) }} } }
No hay registros para los filtros aplicados.
+
+ + } + `, + styles: ` + :host { display: block; min-width: 0; } + p { color: var(--issste-text-secondary); } + form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; } + label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; } + input, select, button { 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%; } + button { cursor: pointer; } button:disabled { opacity: .5; cursor: default; } + input:focus-visible, select:focus-visible, button:focus-visible, .tracking-table:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } + .simulation { padding: 1rem; border: 2px solid var(--issste-accent); font-weight: 700; color: var(--issste-text); } + .tracking-table { overflow-x: auto; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + table { width: 100%; min-width: 60rem; border-collapse: collapse; background: var(--issste-surface); } + caption { text-align: start; padding: 1rem; } + th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px solid var(--issste-border); } + th { background: var(--issste-background); font-weight: 600; } + small { display: block; margin-top: .35rem; } + nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; } + `, +}) +export class IndicadoresSeguimientoTabla implements OnChanges { + @Input({ required: true }) dominio!: Dominio; + @Input() active = false; + private readonly service = inject(SeguimientoTablaService); + private readonly consultas = new Subject(); + readonly ventanas = MESES_VENTANA; + readonly tamanoMaximo = PAGE_SIZE_MAX; + readonly estado = signal('idle'); + readonly mensaje = signal(''); + readonly data = signal(undefined); + readonly filtros = signal([]); + 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 iniciado = false; + private previo?: Dominio; + + constructor() { + this.consultas.pipe( + switchMap((q): Observable => { + if (!q) return of({ estado: 'idle', mensaje: '' }); + let peticion: Observable; + // An invalid query never leaves the browser; it reads like the server's own 400. + try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); } + return peticion.pipe( + map((data): Resultado => ({ estado: 'ready', data, mensaje: '' })), + catchError(error => of(this.fallo(error, q))), + startWith({ estado: 'loading', mensaje: '' })); + }), + takeUntilDestroyed(inject(DestroyRef)), + ).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); + }); + } + + ngOnChanges() { + if (this.previo !== this.dominio) { + 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 }; + } + if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(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.' }; + 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.' }; + } + // The answer says which filters exist and what was applied: the form follows it. + private recibir(data: SeguimientoTablaResponse) { + this.data.set(data); this.filtros.set(data.filtros_disponibles); + const claves = new Set(data.filtros_disponibles.map(f => f.clave)); + this.draft = { ...this.draft, corte: data.corte, filtros: Object.fromEntries(Object.entries(this.draft.filtros).filter(([k]) => claves.has(k))) }; + this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size, + filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) }; + this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size; + } + aplicar() { + const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record; + const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros }; + this.applied = q; + this.consultas.next(q); + } + ir(page: number) { if (page >= 1) this.consultas.next(this.applied = { ...this.applied, page }); } + reintentar() { this.consultas.next(this.applied); } + detalles(c: SeguimientoColumna) { return c.detalles ?? []; } + texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); } +} diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 82e4f1d..9ed5fd5 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -5,7 +5,9 @@ }

Seguimiento de {{ domainLabel }}

-@if (dominio !== 'cacu') { +@if (dominio === 'cama') { + +} @else if (dominio !== 'cacu') {

El seguimiento aún no está disponible.

diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 0610727..80898ba 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -7,13 +7,14 @@ 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 { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'; import { Dominio } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; @Component({ selector: 'app-indicadores-tracking', - imports: [FormsModule, MatButtonModule, PacienteDetalleComponent], + imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, IndicadoresSeguimientoTabla], providers: [PacienteDetalleState], templateUrl: './indicadores-tracking.html', styleUrl: './indicadores-tracking.scss',