Files
WebApp/src/app/features/indicadores/indicadores-tracking.ts
T

170 lines
11 KiB
TypeScript

import { afterNextRender, ChangeDetectorRef, 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, defer, map, of, Subject, switchMap } from 'rxjs';
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
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, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen';
@Component({
selector: 'app-indicadores-tracking',
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla],
providers: [PacienteDetalleState],
templateUrl: './indicadores-tracking.html',
styleUrl: './indicadores-tracking.scss',
})
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 teaService = inject(TeaSeguimientoService);
private readonly destroy = inject(DestroyRef);
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly injector = inject(Injector);
readonly pacienteDetalle = inject(PacienteDetalleState);
readonly fichaPacienteAbierta = output<boolean>();
/** CaMa's record opens inside its own table; this hides the section title while it does. */
readonly camaFichaAbierta = signal(false);
cambiaFichaCama(abierta: boolean) { this.camaFichaAbierta.set(abierta); this.fichaPacienteAbierta.emit(abierta); }
private controlPaciente?: HTMLElement;
private readonly requests = new Subject<SeguimientoQuery | null>();
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
private initialized = false;
private previousDomain?: Dominio;
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
message = '';
data?: SeguimientoResponse;
teaData?: TeaSeguimientoResponse;
// One open summary at a time, like an accordion.
teaAbierto?: string;
statuses: SeguimientoStatus[] = [];
private metadataLoaded = false;
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
private applied: SeguimientoQuery = { ...this.draft };
readonly latestStudy = latestStudy;
readonly gruposEdad = GRUPOS_EDAD_TEA;
readonly rangosMchat = RANGOS_MCHAT;
readonly rangosCss = RANGOS_CSS;
readonly etiquetaEstado = ESTADOS_CASO;
readonly estadosCaso = Object.entries(ESTADOS_CASO).map(([codigo, etiqueta]) => ({ codigo, etiqueta }));
// Kept from the last answer, so the filter doesn't empty while a query is running.
tiposAlteracion: { codigo: string; etiqueta: string }[] = [];
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
get response() { return this.dominio === 'tea' ? this.teaData : this.data; }
constructor() {
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' });
this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe(
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
if (!result) return;
this.changeDetector.markForCheck();
this.status = result.status; this.data = result.data; this.message = result.message;
if (result.data) {
const data = result.data;
this.statuses = data.estatus_disponibles;
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied };
if (!this.metadataLoaded) {
this.metadataLoaded = true;
this.indicators.metadatos('cacu', 'cacu_eu7').pipe(catchError(() => of(undefined)), takeUntilDestroyed(this.destroy)).subscribe(meta => {
if (meta?.categorias) this.categories = meta.categorias;
this.changeDetector.markForCheck();
});
}
}
});
this.teaRequests.pipe(switchMap(q => q ? defer(() => this.teaService.consultar(q)).pipe(
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
if (!result) return;
this.changeDetector.markForCheck();
this.status = result.status; this.teaData = result.data; this.message = result.message; this.teaAbierto = undefined;
if (result.data) {
const data = result.data;
this.tiposAlteracion = data.tipos_alteracion;
// Until the alterations are validated, the EEG filter can only tell a valid EEG from none.
this.statuses = data.resumen_eeg.validadas ? ALTERACIONES_EEG : EEG_VALIDO;
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied };
}
});
}
ngOnChanges() {
if (this.previousDomain !== this.dominio) {
// Changing domain removes the table that holds CaMa's record, so the page is told here that no record shows.
if (this.pacienteDetalle.estado().tipo !== 'cerrado' || this.camaFichaAbierta()) this.fichaPacienteAbierta.emit(false);
this.camaFichaAbierta.set(false);
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
}
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
}
private load(q: SeguimientoQuery) {
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
}
apply() { this.load({ ...this.draft, page: 1 }); }
retry() { this.load(this.applied); }
navigate(page: number) {
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
this.load({ ...this.applied, page });
}
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(paciente: SeguimientoPaciente): IdentidadPaciente { return identidadDe(paciente)!; }
// The rows of a page identify their patient by one field; an empty page keeps the legacy wording.
etiquetaIdentidad(respuesta: SeguimientoResponse) { return ETIQUETA_IDENTIDAD[respuesta.items[0] ? this.identidad(respuesta.items[0]).campo : 'id_seudonimo']; }
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return;
evento.stopPropagation();
if (evento.type === 'click' && evento.currentTarget instanceof HTMLButtonElement) {
if (evento.currentTarget.classList.contains('patient-link')) evento.preventDefault();
this.controlPaciente = evento.currentTarget;
} else if (evento.type === 'click' && evento.currentTarget instanceof HTMLTableRowElement
&& evento.target instanceof HTMLElement && !evento.target.closest('button, a, input, select, textarea')) this.controlPaciente = evento.currentTarget;
else if (evento.type === 'click' && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
else if (evento.type !== 'click') return;
this.pacienteDetalle.abrir(paciente, this.data.corte);
this.fichaPacienteAbierta.emit(true);
}
alternarTea(id: string, evento: Event) {
evento.stopPropagation();
// Row clicks that land on a control are left to that control.
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
this.teaAbierto = this.teaAbierto === id ? undefined : id;
}
volverASeguimiento() {
this.pacienteDetalle.cerrar();
this.fichaPacienteAbierta.emit(false);
const control = this.controlPaciente;
afterNextRender(() => {
if (control?.isConnected) control.focus({ preventScroll: true });
}, { injector: this.injector });
}
// The shown cytology is the patient's latest in the window. Without a Bethesda result it is either
// unsatisfactory (`cacu.calidad_insatisfactoria` in the kit) or not yet reported at the cut-off.
cytologyLabel(c: { bethesda: string | null; calidad: string | null }) {
if (c.bethesda !== null) return this.categories[c.bethesda]?.etiqueta ?? c.bethesda;
return c.calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte';
}
}