import { afterNextRender, Component, DestroyRef, inject, Injector, Input, OnChanges, output, 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 { 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, } 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, TrackingExportBar, CamaPatientCard], template: ` @if (ficha(); as patient) { }

Seguimiento de {{ domainLabel }}

@if (data(); as respuesta) { }
@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 }}
@if (c.clave === 'id_seudonimo') { } @else { {{ 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); } .title-row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem 1rem; margin-bottom: 1rem; } .title-row h2 { margin: 0; margin-inline-end: auto; } 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; } .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; } tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; } tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); } .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; } `, }) export class IndicadoresSeguimientoTabla implements OnChanges { @Input({ required: true }) dominio!: Dominio; @Input() active = false; /** Domain name for the section title, which sits in the same row as the export buttons. */ @Input() domainLabel = ''; 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(); readonly ficha = signal(undefined); private controlFicha?: HTMLElement; 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) { 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 }; } 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); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. if (evento.currentTarget instanceof HTMLTableRowElement && origen?.closest('button, a, input, select, textarea')) return; const corte = this.data()?.corte; const resumen = corte ? toCamaPatientSummary(item, corte) : null; if (!resumen || this.estado() !== 'ready') return; evento.stopPropagation(); this.controlFicha = evento.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined; this.ficha.set(resumen); this.fichaAbierta.emit(true); } cerrarFicha() { this.ficha.set(undefined); this.fichaAbierta.emit(false); const control = this.controlFicha; afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector }); } detalles(c: SeguimientoColumna) { return c.detalles ?? []; } texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); } }