import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Injector, Input, OnChanges, output } 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 { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'; import { Dominio } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service'; import { TeaPacienteResumen } from './tea-paciente-resumen'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; @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 heatmap cell of the analysis, for its follow-up list. @Input() seleccion?: SeleccionSeguimiento; 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(); private controlPaciente?: HTMLElement; private readonly requests = new Subject(); private readonly teaRequests = new Subject(); 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 = {}; draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50, filtros: {} }; 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.dominio === 'cacu' ? this.data : undefined; } // CaMa's list announces its own filters and columns and is drawn by IndicadoresSeguimientoTabla. get propio() { return this.dominio === 'cacu' || this.dominio === 'tea'; } 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; 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) { if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(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, filtros: {} }; 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 (!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 }; if (this.dominio === 'tea') this.teaRequests.next(q); else if (this.dominio === 'cacu') this.requests.next(q); } apply() { this.load({ ...this.draft, filtros: Object.fromEntries(Object.entries(this.draft.filtros ?? {}).filter(([, v]) => v)), 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 }); } 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'; } }