import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { 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 { filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { httpMessage } from './indicadores-http'; import { Celda } from './indicadores-confirmacion-citologia'; import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA, lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama'; // Figures of the kit whose "Cómo leer" describes this coordinated view. const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const; /** * CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the * result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service * for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`. */ @Component({ selector: 'app-indicador-histopatologia-cama', imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicador-histopatologia-cama.html', styleUrl: './indicador-confirmacion-citologia.scss', }) export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { @Input({ required: true }) dominio!: Dominio; @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'); message = ''; selection?: SeleccionHistopatologia; periods: string[] = []; periodIndex = 0; model?: ModeloHistopatologia; donutFigure?: PlotlyFigure; ratesFigure?: PlotlyFigure; helpOpen = false; private helpPinned = false; private readonly snapshots = inject(IndicadoresSnapshots); private readonly changeDetector = inject(ChangeDetectorRef); private subscription?: Subscription; private key = ''; private loaded = false; private pages: ModeloHistopatologia[] = []; // The rates figure has a phone-width variant; it is redrawn when the window crosses that width. private readonly estrecho = typeof matchMedia === 'function' ? matchMedia('(max-width: 600px)') : undefined; private readonly alCambiarAncho = () => this.draw(); constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); } get intervalLabel() { return this.applied?.tipo === 'mes' ? 'Intervalo mensual' : 'Intervalo semestral'; } get contextPeriod() { return this.model?.periodo ?? this.periods[this.periodIndex] ?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : ''); } get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; } readonly estadoTasa = estadoTasa; cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); } get readingGuide() { const details = this.metadata?.figuras_detalle ?? []; return FIGURAS.flatMap(([figura, nombre]) => { const detail = details.find(item => item.figura === figura); const descripcion = detail?.descripcion?.trim() ?? ''; const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; }); } toggleHelp() { if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; } this.helpPinned = true; this.showHelp(); } showHelp() { if (this.helpOpen) return; this.helpOpen = true; this.metadataRequested.emit(); } hideHelp() { if (!this.helpPinned) this.helpOpen = false; } onHelpFocusOut(event: FocusEvent) { const next = event.relatedTarget; if (next instanceof Node && (event.currentTarget as Node).contains(next)) return; this.helpPinned = false; this.helpOpen = false; } ngOnChanges(changes: SimpleChanges) { const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS }) + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]); if (key !== this.key) { this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear(); 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 clear() { this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined; this.donutFigure = undefined; this.ratesFigure = undefined; } private load() { this.subscription?.unsubscribe(); this.loaded = true; this.clear(); const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) { this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.'; 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 = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({ next: datos => { if (key !== this.key) return; try { this.periods = periodosHistopatologia(datos, this.applied.tipo, periods); this.pages = this.periods.map(p => modeloHistopatologia(datos, p)); // The most recent period first; navigation goes back. this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod(); } catch (error) { this.failure(error); } }, error: error => { if (key === this.key) this.failure(error); }, }); } private failure(error: unknown) { this.clear(); this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' : error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error); this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) ? 'incompatible' : 'error'); this.changeDetector.markForCheck(); } private activatePeriod() { this.model = this.pages[this.periodIndex]; this.selection = this.model ? seleccionBase(this.model) : undefined; this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty'); } changePeriod(step: number) { if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; this.periodIndex += step; this.activatePeriod(); } select(trace: string, index = 0) { if (!this.model || !this.selection || this.status() !== 'ready') return; this.selection = clicHistopatologia(this.model, this.selection, trace, index); this.draw(); } plotClicked(event: unknown) { const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); } private draw() { if (!this.model || !this.selection) return; this.donutFigure = donaHistopatologia(this.model, this.selection, this.tema); this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches); this.changeDetector.markForCheck(); } ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); } }