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'; @Component({ selector: 'app-indicadores-tracking', imports: [FormsModule, MatButtonModule, PacienteDetalleComponent], 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; private readonly service = inject(CacuSeguimientoService); private readonly indicators = inject(IndicadoresService); 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 initialized = false; private previousDomain?: Dominio; status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle'; message = ''; data?: SeguimientoResponse; statuses: SeguimientoStatus[] = []; private metadataLoaded = false; categories: Record = {}; draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 }; private applied: SeguimientoQuery = { ...this.draft }; readonly latestStudy = latestStudy; get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); } constructor() { this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe( map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => 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.' }))) : 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(); }); } } }); } 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.data = 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); } } private load(q: SeguimientoQuery) { if (this.dominio !== 'cacu') 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.applied = { ...q }; this.requests.next(q); } apply() { this.load({ ...this.draft, page: 1 }); } retry() { this.load(this.applied); } navigate(page: number) { if (!this.data || page < 1 || page > this.data.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); } 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'; } }