Files
WebApp/src/app/features/indicadores/indicadores-tracking.ts
T
Angel Capetillo Zavala eb92b99a1d feat(seguimiento): list opened on a group of the cohort, with its window, cut-off, cohort and revision
The follow-up list of breast cancer can now be opened on a selection that the analysis names: the
whole cohort (window 0, offered only while the selection is active), the cut-off the analysis was
computed at, the group's filter, and the cohort with its revision, which the server requires and
repeats.

- A cohort's list quotes `cohorte`, `escenario` and `revision` (not filters) on every page and in the
  export; an answer that loses a filter, changes the window or the cut-off, or is another cohort or
  revision is not drawn and cannot be exported.
- A new selection cancels the previous request; while it loads, and when it fails (403, 409, 503),
  no list of the previous query stays on screen.
- Inside the cohort the form refines the same cohort and says so; "Quitar selección" leaves it.
- "Volver al análisis" and a note when the list holds a different number of patients than the
  analysis counted.
- PDF and XLSX state the selection, the cut-off and "Toda la cohorte"; the file name tells a
  selection apart; an export in progress is cancelled, and a finished one discarded, when the query
  on screen changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 14:07:31 -06:00

128 lines
7.7 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 { IndicadoresService } from './indicadores.service';
@Component({
selector: 'app-indicadores-tracking',
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, 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 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 initialized = false;
private previousDomain?: Dominio;
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
message = '';
data?: SeguimientoResponse;
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;
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) {
// 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.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';
}
}