211 lines
13 KiB
TypeScript
211 lines
13 KiB
TypeScript
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<string, string | undefined>; }
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
@Component({
|
|
selector: 'app-seguimiento-tabla',
|
|
imports: [FormsModule, TrackingExportBar, CamaPatientCard],
|
|
template: `
|
|
@if (ficha(); as patient) {
|
|
<app-cama-patient-card [summary]="patient" (back)="cerrarFicha()" />
|
|
}
|
|
<div [hidden]="!!ficha()">
|
|
<div class="title-row">
|
|
<h2>Seguimiento de {{ domainLabel }}</h2>
|
|
@if (data(); as respuesta) {
|
|
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready'" />
|
|
}
|
|
</div>
|
|
<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> }
|
|
</select></label>
|
|
@for (filtro of filtros(); track filtro.clave) {
|
|
<label>{{ filtro.etiqueta }} <select [name]="'filtro-' + filtro.clave" [(ngModel)]="draft.filtros[filtro.clave]">
|
|
<option [ngValue]="undefined">Todos</option>
|
|
@for (o of filtro.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
|
</select></label>
|
|
}
|
|
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" /></label>
|
|
<button type="submit" [disabled]="estado() === 'loading'">Consultar</button>
|
|
</form>
|
|
@switch (estado()) {
|
|
@case ('loading') { <p role="status">Cargando seguimiento…</p> }
|
|
@case ('pending') {
|
|
<p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p>
|
|
<button type="button" (click)="reintentar()">Reintentar seguimiento</button>
|
|
}
|
|
@case ('error') {
|
|
<p role="alert">{{ mensaje() }}</p>
|
|
<button type="button" (click)="reintentar()">Reintentar seguimiento</button>
|
|
}
|
|
}
|
|
@if (data(); as respuesta) {
|
|
<p>Ventana consultada: {{ respuesta.ventana.desde }} al {{ respuesta.ventana.hasta }}.</p>
|
|
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
|
<table>
|
|
<caption>Resultados disponibles por paciente</caption>
|
|
<thead><tr>@for (c of respuesta.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
|
|
<tbody>
|
|
@for (item of respuesta.items; track item['id_seudonimo']) {
|
|
<tr tabindex="-1" [attr.data-paciente]="item['id_seudonimo']" (click)="abrirFicha(item, $event)">
|
|
@for (c of respuesta.columnas; track c.clave) {
|
|
<td>@if (c.clave === 'id_seudonimo') { <button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item['id_seudonimo']" (click)="abrirFicha(item, $event)">{{ texto(item[c.clave]) }}</button> } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
|
|
}
|
|
</tr>
|
|
} @empty { <tr><td [attr.colspan]="respuesta.columnas.length">No hay registros para los filtros aplicados.</td></tr> }
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
<nav aria-label="Paginación de seguimiento">
|
|
<button type="button" [disabled]="respuesta.paginacion.page <= 1 || estado() === 'loading'" (click)="ir(respuesta.paginacion.page - 1)">Anterior</button>
|
|
<span>Página {{ respuesta.paginacion.page }} de {{ respuesta.paginacion.total_pages }}, {{ respuesta.paginacion.total_items }} registros</span>
|
|
<button type="button" [disabled]="respuesta.paginacion.page >= respuesta.paginacion.total_pages || estado() === 'loading'" (click)="ir(respuesta.paginacion.page + 1)">Siguiente</button>
|
|
</nav>
|
|
}
|
|
</div>
|
|
`,
|
|
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<boolean>();
|
|
readonly ficha = signal<CamaPatientSummary | undefined>(undefined);
|
|
private controlFicha?: HTMLElement;
|
|
private readonly consultas = new Subject<SeguimientoTablaQuery | null>();
|
|
readonly ventanas = MESES_VENTANA;
|
|
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
|
readonly estado = signal<Estado>('idle');
|
|
readonly mensaje = signal('');
|
|
readonly data = signal<SeguimientoTablaResponse | 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 iniciado = false;
|
|
private previo?: Dominio;
|
|
|
|
constructor() {
|
|
this.consultas.pipe(
|
|
switchMap((q): Observable<Resultado> => {
|
|
if (!q) return of({ estado: 'idle', mensaje: '' });
|
|
let peticion: Observable<SeguimientoTablaResponse>;
|
|
// An invalid query never leaves the browser; it reads like the server's own 400.
|
|
try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); }
|
|
return peticion.pipe(
|
|
map((data): Resultado => ({ estado: 'ready', data, mensaje: '' })),
|
|
catchError(error => of(this.fallo(error, q))),
|
|
startWith<Resultado>({ estado: 'loading', mensaje: '' }));
|
|
}),
|
|
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<string, string>;
|
|
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<string, SeguimientoValor>, evento: Event) {
|
|
const origen = evento.target instanceof HTMLElement ? evento.target : null;
|
|
// A click on the row opens the record unless it landed on another control; the id button always does.
|
|
if (evento.currentTarget instanceof HTMLTableRowElement && origen?.closest('button, a, input, select, textarea')) return;
|
|
const corte = this.data()?.corte;
|
|
const resumen = corte ? toCamaPatientSummary(item, corte) : null;
|
|
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); }
|
|
}
|