eb92b99a1d
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>
146 lines
7.7 KiB
TypeScript
146 lines
7.7 KiB
TypeScript
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<ExportFormat, string> = { 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: `
|
|
<div class="actions" role="group" aria-label="Exportar resultados"
|
|
[attr.title]="'Se exportan los ' + (total() | number) + ' registros de la consulta mostrada, no solo la página visible.'">
|
|
@for (formato of formatos; track formato) {
|
|
<button type="button" [disabled]="!available(formato)" (click)="exportar(formato)">Exportar {{ label[formato] }}</button>
|
|
}
|
|
@if (estado() === 'working') { <button type="button" (click)="cancelar()">Cancelar</button> }
|
|
</div>
|
|
@for (formato of formatos; track formato) {
|
|
@if (total() > limits[formato]) {
|
|
<p class="message hint">{{ label[formato] }} admite hasta {{ limits[formato] | number }} registros; la consulta tiene {{ total() | number }}. Acota los filtros para exportar.</p>
|
|
}
|
|
}
|
|
@if (estado() === 'working') { <p class="message" role="status">{{ progressText() }}</p> }
|
|
@if (estado() === 'error') { <p class="message" role="alert">{{ mensaje() }}</p> }
|
|
@if (listo()) { <p class="message" role="status">{{ listo() }}</p> }
|
|
`,
|
|
// 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<Dominio>();
|
|
/** The answer on screen: its metadata says which query to export. */
|
|
readonly respuesta = input.required<SeguimientoTablaResponse>();
|
|
/** 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<string | undefined>(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<State>('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.');
|
|
}
|
|
}
|