import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { catchError, combineLatest, of, Subscription, timeout, TimeoutError } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { IndicadoresService } from './indicadores.service'; import { httpMessage } from './indicadores-http'; import { cajaTexto, CLAVES, Clave, FIGURA_C3R, figuraTiempos, hayCajas, ModeloTiempos, modeloTiempos, ParTiempos, TiemposIncompatibles } from './indicadores-tiempos-pareados'; @Component({ selector: 'app-indicador-tiempos-pareados', imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicador-tiempos-pareados.html', styleUrl: './indicador-tiempos-pareados.scss', }) export class IndicadorTiemposPareados implements OnChanges, OnDestroy { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) par!: ParTiempos; // The card's indicator (diagnosis). Its partner (lab result) is hidden from the // catalog and requested directly by id, for data and metadata. @Input({ required: true }) indicador!: Indicador; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; @Input() metadata?: IndicadorMetadatos; readonly metadataRequested = output(); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); readonly claves = CLAVES; readonly cajaTexto = cajaTexto; message = ''; model?: ModeloTiempos; figure?: PlotlyFigure; helpOpen = false; partnerMetadata?: IndicadorMetadatos; private readonly snapshots = inject(IndicadoresSnapshots); private readonly service = inject(IndicadoresService); private readonly changeDetector = inject(ChangeDetectorRef); private subscription?: Subscription; private metadataSubscription?: Subscription; private key = ''; private loaded = false; get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } // TODO: mover al kit (como_leer de la vista coordinada de tiempos). get caveat() { return `Las dos cajas no cuentan exactamente a las mismas ${this.par.estudios}: cada indicador tiene su propio horizonte ` + 'y la segunda solo incluye las que llegaron a diagnóstico. La diferencia entre las medianas no es el tiempo del tramo intermedio.'; } /** "Cómo leer": only what the kit publishes for each C3r figure, plus the caveat above. */ get readingGuide() { const fuentes: Record = { reporte: this.partnerMetadata, diagnostico: this.metadata }; return CLAVES.flatMap(clave => { const detail = fuentes[clave]?.figuras_detalle?.find(item => item.figura === FIGURA_C3R); const descripcion = detail?.descripcion?.trim() ?? ''; const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); return descripcion || como_leer.length ? [{ clave, nombre: this.par.etiquetas[clave], descripcion, como_leer }] : []; }); } get metadataPending() { return !this.metadata || !this.partnerMetadata; } toggleHelp() { this.helpOpen = !this.helpOpen; if (!this.helpOpen) return; if (!this.metadata) this.metadataRequested.emit(); if (!this.partnerMetadata) { this.metadataSubscription?.unsubscribe(); this.metadataSubscription = this.service.metadatos(this.dominio, this.par.reporte).pipe(catchError(() => of(undefined))) .subscribe(value => { this.partnerMetadata = value; this.changeDetector.markForCheck(); }); } } ngOnChanges(changes: SimpleChanges) { const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([ this.par.reporte, this.par.diagnostico, this.indicador.contrato, this.indicador.tipos_periodo]); if (changes['dominio'] || changes['par']) { this.partnerMetadata = undefined; this.metadataSubscription?.unsubscribe(); } if (key !== this.key) { this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.model = undefined; this.figure = undefined; if (!this.visible) { this.status.set('deferred'); return; } this.load(); } else if (this.visible && !this.loaded) this.load(); else if (this.model && changes['tema']) this.draw(); } retry() { if (this.visible) this.load(); } private load() { this.subscription?.unsubscribe(); this.loaded = true; this.model = undefined; this.figure = undefined; if (this.indicador.id !== this.par.diagnostico || this.indicador.contrato !== 'C3r') { this.message = 'El catálogo no publica el indicador de tiempo necesario para esta vista.'; this.status.set('incompatible'); return; } // The partner shares the diagnosis periodicity; its response is validated by id, contract and period. const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); if (!compatibility.compatible) { this.message = compatibility.reason; this.status.set('incompatible'); return; } const key = this.key; const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; this.status.set('loading'); this.subscription = combineLatest([ this.snapshots.datos(this.dominio, this.par.reporte, this.applied.tipo, periods), this.snapshots.datos(this.dominio, this.par.diagnostico, this.applied.tipo, periods, this.indicador.version), ]).pipe(timeout({ first: 40000 })).subscribe({ next: ([reporte, diagnostico]) => { if (key !== this.key) return; try { this.model = modeloTiempos(this.par, { reporte, diagnostico }, this.applied.tipo, periods); this.draw(); this.status.set(hayCajas(this.model) ? 'ready' : 'empty'); } catch (error) { this.failure(error); } }, error: error => { if (key === this.key) this.failure(error); }, }); } private failure(error: unknown) { this.model = undefined; this.figure = undefined; this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' : error instanceof TiemposIncompatibles ? error.message : httpMessage(error); this.status.set(error instanceof TiemposIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) ? 'incompatible' : 'error'); this.changeDetector.markForCheck(); } private draw() { if (!this.model) return; this.figure = figuraTiempos(this.model, this.par, this.tema); this.changeDetector.markForCheck(); } ngOnDestroy() { this.subscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); } }