import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { HttpErrorResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { Dominio } from '../indicadores.models'; import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; import { downloadBlob, exportFilename } from './download-file'; import { EXPORT_LIMITS, ExportFormat, ExportInconsistent, ExportLimitExceeded, TrackingSnapshot } from './tracking-export.models'; import { fetchAllTracking, queryOf } from './tracking-export-source'; type State = 'idle' | 'working' | 'error'; const FORMAT_LABEL: Record = { xlsx: 'Excel (.xlsx)', pdf: 'PDF' }; /** * Export buttons of a follow-up list. They export the answer on screen (its cut-off, window and filters) and every * row it matches, not the visible page; a query above a format's limit is refused with a message, never truncated. */ @Component({ selector: 'app-seguimiento-exportar', imports: [DecimalPipe], template: `
@for (formato of formatos; track formato) { } @if (estado() === 'working') { }
@for (formato of formatos; track formato) { @if (total() > limits[formato]) {

{{ label[formato] }} admite hasta {{ limits[formato] | number }} registros; la consulta tiene {{ total() | number }}. Acota los filtros para exportar.

} } @if (estado() === 'working') {

{{ progressText() }}

} @if (estado() === 'error') { } @if (listo()) {

{{ listo() }}

} `, // The host takes no box of its own: the buttons sit in the title row that holds it, and each message // takes a full line below that row. styles: ` :host { display: contents; } .message { flex: 0 0 100%; margin: 0; } .hint { color: var(--issste-text-secondary); } .actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem; margin-inline-start: auto; } button { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem 1rem; min-height: 44px; box-sizing: border-box; font: inherit; cursor: pointer; } button:disabled { opacity: .5; cursor: default; } button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } `, }) export class TrackingExportBar { readonly dominio = input.required(); /** The answer on screen: its metadata says which query to export. */ readonly respuesta = input.required(); /** False while a page is being loaded, so the export never reads a query that is about to change. */ readonly habilitado = input(true); /** How the analysis named the selection this answer belongs to; it travels into the files. */ readonly seleccion = input(undefined); private readonly service = inject(SeguimientoTablaService); private subscription?: Subscription; readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf']; readonly label = FORMAT_LABEL; readonly limits = EXPORT_LIMITS; readonly estado = signal('idle'); readonly mensaje = signal(''); readonly listo = signal(''); readonly progress = signal({ fetched: 0, total: 0 }); readonly total = computed(() => this.respuesta().paginacion.total_items); readonly progressText = computed(() => { const { fetched, total } = this.progress(); return total ? `Leyendo registros: ${fetched} de ${total}…` : 'Preparando exportación…'; }); // Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it. private readonly queryKey = computed(() => { const r = this.respuesta(); return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]); }); constructor() { inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe()); // A result message belongs to the query it was made for: it goes away when another query is shown. An export still // being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one. effect(() => { this.queryKey(); untracked(() => { if (this.estado() === 'working') { this.subscription?.unsubscribe(); this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.'); } else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); } }); }); } available(formato: ExportFormat): boolean { return this.habilitado() && this.estado() !== 'working' && this.total() > 0 && this.total() <= EXPORT_LIMITS[formato]; } exportar(formato: ExportFormat) { if (!this.available(formato)) return; this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 }); this.subscription?.unsubscribe(); const clave = this.queryKey(), seleccion = this.seleccion(); this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({ next: event => { if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total }); else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave); }, error: error => this.fallar(error), }); } cancelar() { this.subscription?.unsubscribe(); this.estado.set('idle'); } private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) { try { // Each generator (and its library) downloads only when its button is used. const blob = formato === 'xlsx' ? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot) : await (await import('./tracking-pdf')).buildTrackingPdf(snapshot); // The query on screen changed while the file was being made: it is not the one that was asked for. if (clave !== this.queryKey()) return; downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato)); this.estado.set('idle'); this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`); } catch { this.fallar(new Error('generation')); } } private fallar(error: unknown) { this.estado.set('error'); const estatus = error instanceof HttpErrorResponse ? error.status : 0; this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.' : estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.' : estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.' : error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.' : 'No se pudo generar el archivo. Intenta nuevamente.'); } }