add bitacora page, self-hosted fonts/icons, review fixes for the install package
This commit is contained in:
@@ -10,26 +10,26 @@
|
||||
</mat-toolbar>
|
||||
|
||||
<div class="reportes__body">
|
||||
@if (error(); as mensaje) {
|
||||
<p class="reportes__error" role="alert">{{ mensaje }}</p>
|
||||
@if (error(); as message) {
|
||||
<p class="reportes__error" role="alert">{{ message }}</p>
|
||||
}
|
||||
|
||||
<section aria-labelledby="estado-title">
|
||||
<h2 id="estado-title">Indicadores</h2>
|
||||
<p class="reportes__hint">Los indicadores se recalculan automáticamente después de cada carga de información.</p>
|
||||
<div class="estado-grid">
|
||||
@for (dominio of dominios; track dominio.id) {
|
||||
@if (estados()?.[dominio.id]; as estado) {
|
||||
<article class="estado" [attr.data-estado]="estado.estado">
|
||||
<h3>{{ dominio.nombre }}</h3>
|
||||
<p class="estado__valor">{{ estadoTexto(estado) }}</p>
|
||||
@if (estado.fin) {
|
||||
<p>Último cálculo: {{ estado.fin | date: 'dd/MM/yyyy HH:mm' }} ({{ estado.duracion_s | number: '1.0-1' }} s)</p>
|
||||
@for (domain of domains; track domain.id) {
|
||||
@if (statuses()?.[domain.id]; as status) {
|
||||
<article class="estado" [attr.data-estado]="status.estado">
|
||||
<h3>{{ domain.description }}</h3>
|
||||
<p class="estado__valor">{{ statusLabel(status) }}</p>
|
||||
@if (status.fin) {
|
||||
<p>Último cálculo: {{ status.fin | date: 'dd/MM/yyyy HH:mm' }} ({{ status.duracion_s | number: '1.0-1' }} s)</p>
|
||||
}
|
||||
@if (estado.error) {
|
||||
<p class="estado__error">{{ estado.error.tipo }}: {{ estado.error.mensaje }}</p>
|
||||
@if (status.error) {
|
||||
<p class="estado__error">{{ status.error.tipo }}: {{ status.error.mensaje }}</p>
|
||||
}
|
||||
<button mat-button type="button" (click)="recalcular(dominio.id)" [disabled]="estado.pendiente || estado.estado === 'en_curso'">
|
||||
<button mat-button type="button" (click)="recompute(domain.id)" [disabled]="status.pendiente || status.estado === 'en_curso'">
|
||||
<mat-icon aria-hidden="true">refresh</mat-icon>Recalcular
|
||||
</button>
|
||||
</article>
|
||||
@@ -41,7 +41,7 @@
|
||||
<section aria-labelledby="intentos-title">
|
||||
<h2 id="intentos-title">Intentos de carga y validación</h2>
|
||||
<p class="reportes__hint">La bitácora registra únicamente conteos y formatos agregados; no almacena valores de los registros.</p>
|
||||
@if (intentos().length === 0) {
|
||||
@if (attempts().length === 0) {
|
||||
<p>No se han registrado intentos de carga o validación.</p>
|
||||
} @else {
|
||||
<table class="intentos">
|
||||
@@ -52,33 +52,33 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (intento of intentos(); track intento.id) {
|
||||
<tr [attr.data-resultado]="intento.resultado">
|
||||
<td>{{ intento.fecha | date: 'dd/MM/yyyy HH:mm' }}</td>
|
||||
<td>{{ intento.operacion === 'carga' ? 'Carga' : 'Validación' }}</td>
|
||||
<td>{{ intento.fuentes.length ? intento.fuentes[0].destino : (intento.dominio ?? '—') }}@if (intento.fuentes.length > 1) { <span> +{{ intento.fuentes.length - 1 }}</span> }</td>
|
||||
<td>{{ resultadoTexto(intento.resultado) }}</td>
|
||||
<td>{{ intento.totales['leidas'] ?? 0 }}</td>
|
||||
<td>{{ intento.totales['validas'] ?? 0 }}</td>
|
||||
<td>{{ (intento.totales['insertadas'] ?? 0) + (intento.totales['actualizadas'] ?? 0) }}</td>
|
||||
<td>{{ (intento.totales['rechazadas_en_validacion'] ?? 0) + (intento.totales['rechazadas_por_conflicto'] ?? 0) }}</td>
|
||||
@for (attempt of attempts(); track attempt.id) {
|
||||
<tr [attr.data-resultado]="attempt.resultado">
|
||||
<td>{{ attempt.fecha | date: 'dd/MM/yyyy HH:mm' }}</td>
|
||||
<td>{{ attempt.operacion === 'carga' ? 'Carga' : 'Validación' }}</td>
|
||||
<td>{{ attempt.fuentes.length ? attempt.fuentes[0].destino : (attempt.dominio ?? '—') }}@if (attempt.fuentes.length > 1) { <span> +{{ attempt.fuentes.length - 1 }}</span> }</td>
|
||||
<td>{{ outcomeLabel(attempt.resultado) }}</td>
|
||||
<td>{{ attempt.totales['leidas'] ?? 0 }}</td>
|
||||
<td>{{ attempt.totales['validas'] ?? 0 }}</td>
|
||||
<td>{{ (attempt.totales['insertadas'] ?? 0) + (attempt.totales['actualizadas'] ?? 0) }}</td>
|
||||
<td>{{ (attempt.totales['rechazadas_en_validacion'] ?? 0) + (attempt.totales['rechazadas_por_conflicto'] ?? 0) }}</td>
|
||||
<td>
|
||||
<button mat-icon-button type="button" (click)="alternar(intento.id)" [attr.aria-expanded]="abierto() === intento.id" aria-label="Ver detalle">
|
||||
<mat-icon>{{ abierto() === intento.id ? 'expand_less' : 'expand_more' }}</mat-icon>
|
||||
<button mat-icon-button type="button" (click)="toggle(attempt.id)" [attr.aria-expanded]="expanded() === attempt.id" aria-label="Ver detalle">
|
||||
<mat-icon>{{ expanded() === attempt.id ? 'expand_less' : 'expand_more' }}</mat-icon>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
@if (abierto() === intento.id) {
|
||||
@if (expanded() === attempt.id) {
|
||||
<tr class="detalle">
|
||||
<td colspan="9">
|
||||
@if (intento.error) {
|
||||
<p class="estado__error">{{ intento.error.tipo }}: {{ intento.error.mensaje }}</p>
|
||||
@if (attempt.error) {
|
||||
<p class="estado__error">{{ attempt.error.tipo }}: {{ attempt.error.mensaje }}</p>
|
||||
}
|
||||
@for (fuente of intento.fuentes; track $index) {
|
||||
@for (source of attempt.fuentes; track $index) {
|
||||
<p>
|
||||
<strong>{{ fuente.destino }}</strong> desde {{ fuente.origen.tipo }}
|
||||
@if (fuente.mapeo.requeridos_sin_mapear.length) {
|
||||
· requeridos sin mapear: {{ fuente.mapeo.requeridos_sin_mapear.join(', ') }}
|
||||
<strong>{{ source.destino }}</strong> desde {{ source.origen.tipo }}
|
||||
@if (source.mapeo.requeridos_sin_mapear.length) {
|
||||
· requeridos sin mapear: {{ source.mapeo.requeridos_sin_mapear.join(', ') }}
|
||||
}
|
||||
</p>
|
||||
}
|
||||
@@ -87,16 +87,16 @@
|
||||
<tr><th scope="col">Campo</th><th scope="col">Con valor</th><th scope="col">Vacíos</th><th scope="col">Errores</th><th scope="col">Formatos o valores rechazados</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (fila of camposConProblemas(intento); track fila.destino + fila.nombre) {
|
||||
@for (row of fieldsWithProblems(attempt); track row.target + row.name) {
|
||||
<tr>
|
||||
<td>{{ fila.nombre }}</td>
|
||||
<td>{{ fila.campo.con_valor }}</td>
|
||||
<td>{{ fila.campo.vacios }}</td>
|
||||
<td>@for (e of fila.campo.errores | keyvalue; track e.key) { <span class="chip">{{ e.key }}: {{ e.value }}</span> }</td>
|
||||
<td>{{ row.name }}</td>
|
||||
<td>{{ row.field.con_valor }}</td>
|
||||
<td>{{ row.field.vacios }}</td>
|
||||
<td>@for (e of row.field.errores | keyvalue; track e.key) { <span class="chip">{{ e.key }}: {{ e.value }}</span> }</td>
|
||||
<td>
|
||||
@for (f of fila.campo.formatos_rechazados | keyvalue; track f.key) { <span class="chip"><code>{{ f.key }}</code> ×{{ f.value }}</span> }
|
||||
@for (v of fila.campo.valores_fuera_de_catalogo | keyvalue; track v.key) { <span class="chip">{{ v.key }} ×{{ v.value }}</span> }
|
||||
@if (fila.campo.valores_fuera_de_catalogo_poco_frecuentes) { <span class="chip">otros ×{{ fila.campo.valores_fuera_de_catalogo_poco_frecuentes }}</span> }
|
||||
@for (f of row.field.formatos_rechazados | keyvalue; track f.key) { <span class="chip"><code>{{ f.key }}</code> ×{{ f.value }}</span> }
|
||||
@for (v of row.field.valores_fuera_de_catalogo | keyvalue; track v.key) { <span class="chip">{{ v.key }} ×{{ v.value }}</span> }
|
||||
@if (row.field.valores_fuera_de_catalogo_poco_frecuentes) { <span class="chip">otros ×{{ row.field.valores_fuera_de_catalogo_poco_frecuentes }}</span> }
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ReportesPage } from './reportes-page';
|
||||
import { ReportsPage } from './reportes-page';
|
||||
|
||||
describe('ReportesPage', () => {
|
||||
describe('ReportsPage', () => {
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ReportesPage],
|
||||
imports: [ReportsPage],
|
||||
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||
});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
@@ -17,7 +17,7 @@ describe('ReportesPage', () => {
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('shows the indicator status and the aggregate attempts', () => {
|
||||
const fixture = TestBed.createComponent(ReportesPage);
|
||||
const fixture = TestBed.createComponent(ReportsPage);
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/reportes/indicadores').flush({
|
||||
cacu: { estado: 'ok', pendiente: false, fin: '2026-10-29T10:00:00+00:00', duracion_s: 12 },
|
||||
@@ -48,9 +48,29 @@ describe('ReportesPage', () => {
|
||||
expect(fixture.nativeElement.querySelector('.campos').textContent).toContain('out_of_catalog: 2');
|
||||
});
|
||||
|
||||
it('keeps polling after a failed request', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const fixture = TestBed.createComponent(ReportsPage);
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/reportes/indicadores').flush('caída', { status: 502, statusText: 'Bad Gateway' });
|
||||
http.expectOne((r) => r.url === '/reportes/importaciones');
|
||||
expect(fixture.componentInstance.error()).toBeTruthy();
|
||||
|
||||
vi.advanceTimersByTime(15000);
|
||||
http.expectOne('/reportes/indicadores').flush({ cacu: { estado: 'ok', pendiente: false } });
|
||||
http.expectOne((r) => r.url === '/reportes/importaciones').flush({ resumen: { intentos: {}, ultimo: null }, intentos: [] });
|
||||
expect(fixture.componentInstance.error()).toBeNull();
|
||||
expect(fixture.componentInstance.statuses()?.cacu.estado).toBe('ok');
|
||||
fixture.destroy();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('asks for a recomputation', () => {
|
||||
const fixture = TestBed.createComponent(ReportesPage);
|
||||
fixture.componentInstance.recalcular('tea');
|
||||
const fixture = TestBed.createComponent(ReportsPage);
|
||||
fixture.componentInstance.recompute('tea');
|
||||
http.expectOne('/reportes/indicadores/tea/recalcular').flush({ pendiente: true });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,87 +4,83 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { forkJoin, interval, startWith, switchMap } from 'rxjs';
|
||||
import { apiErrorMessage } from '../connect/api/api.types';
|
||||
import { Dominio, EstadoRecalculo, IntentoImportacion, ReportesApi } from './reportes.api';
|
||||
import { EMPTY, catchError, forkJoin, interval, startWith, switchMap } from 'rxjs';
|
||||
import { Domain, apiErrorMessage } from '../connect/api/api.types';
|
||||
import { DOMAINS } from '../connect/state/connect-workspace.store';
|
||||
import { ImportAttempt, RecomputeStatus, ReportsApi } from './reportes.api';
|
||||
|
||||
const DOMINIOS: { id: Dominio; nombre: string }[] = [
|
||||
{ id: 'cacu', nombre: 'Cáncer cervicouterino' },
|
||||
{ id: 'cama', nombre: 'Cáncer de mama' },
|
||||
{ id: 'tea', nombre: 'Trastorno del espectro autista' },
|
||||
];
|
||||
|
||||
const ESTADOS: Record<string, string> = {
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
sin_correr: 'Pendiente de cálculo', en_curso: 'En proceso de cálculo', ok: 'Actualizado', error: 'Error en el cálculo',
|
||||
};
|
||||
|
||||
const RESULTADOS: Record<string, string> = {
|
||||
const OUTCOME_LABELS: Record<string, string> = {
|
||||
completada: 'Completada', solicitud_invalida: 'Solicitud inválida',
|
||||
rechazada_por_la_base: 'Rechazada por la base', fallida: 'Fallida',
|
||||
};
|
||||
|
||||
/**
|
||||
* The "Bitácora" page (route `/bitacora`): what happened to every import
|
||||
* attempt, in aggregates only, and whether each domain's indicators are up
|
||||
* to date with what was loaded. Refreshes itself every 15 seconds.
|
||||
*/
|
||||
/** The import log page (`/bitacora`): import attempts in aggregate and the indicator status per domain. */
|
||||
@Component({
|
||||
selector: 'app-reportes-page',
|
||||
imports: [DatePipe, DecimalPipe, KeyValuePipe, MatButtonModule, MatIconModule, MatToolbarModule],
|
||||
templateUrl: './reportes-page.html',
|
||||
styleUrl: './reportes-page.scss',
|
||||
})
|
||||
export class ReportesPage implements OnInit {
|
||||
private readonly api = inject(ReportesApi);
|
||||
export class ReportsPage implements OnInit {
|
||||
private readonly api = inject(ReportsApi);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly dominios = DOMINIOS;
|
||||
readonly estados = signal<Record<Dominio, EstadoRecalculo> | null>(null);
|
||||
readonly intentos = signal<IntentoImportacion[]>([]);
|
||||
readonly abierto = signal<string | null>(null);
|
||||
readonly domains = DOMAINS;
|
||||
readonly statuses = signal<Record<Domain, RecomputeStatus> | null>(null);
|
||||
readonly attempts = signal<ImportAttempt[]>([]);
|
||||
readonly expanded = signal<string | null>(null);
|
||||
readonly error = signal<string | null>(null);
|
||||
|
||||
ngOnInit(): void {
|
||||
interval(15000)
|
||||
.pipe(
|
||||
startWith(0),
|
||||
switchMap(() => forkJoin({ estados: this.api.indicadores(), log: this.api.importaciones() })),
|
||||
// Errors are handled per poll so one failed request doesn't stop the refresh.
|
||||
switchMap(() =>
|
||||
forkJoin({ statuses: this.api.indicatorStatus(), log: this.api.importLog() }).pipe(
|
||||
catchError((err) => {
|
||||
this.error.set(apiErrorMessage(err, 'No se pudo leer la bitácora.'));
|
||||
return EMPTY;
|
||||
}),
|
||||
),
|
||||
),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
)
|
||||
.subscribe({
|
||||
next: ({ estados, log }) => {
|
||||
this.estados.set(estados);
|
||||
this.intentos.set(log.intentos);
|
||||
this.error.set(null);
|
||||
},
|
||||
error: (err) => this.error.set(apiErrorMessage(err, 'No se pudo leer la bitácora.')),
|
||||
.subscribe(({ statuses, log }) => {
|
||||
this.statuses.set(statuses);
|
||||
this.attempts.set(log.intentos);
|
||||
this.error.set(null);
|
||||
});
|
||||
}
|
||||
|
||||
estadoTexto(estado: EstadoRecalculo): string {
|
||||
return estado.pendiente && estado.estado !== 'en_curso' ? 'En espera de cálculo' : ESTADOS[estado.estado] ?? estado.estado;
|
||||
statusLabel(status: RecomputeStatus): string {
|
||||
return status.pendiente && status.estado !== 'en_curso' ? 'En espera de cálculo' : STATUS_LABELS[status.estado] ?? status.estado;
|
||||
}
|
||||
|
||||
resultadoTexto(resultado: string): string {
|
||||
return RESULTADOS[resultado] ?? resultado;
|
||||
outcomeLabel(outcome: string): string {
|
||||
return OUTCOME_LABELS[outcome] ?? outcome;
|
||||
}
|
||||
|
||||
recalcular(dominio: Dominio): void {
|
||||
this.api.recalcular(dominio).subscribe({
|
||||
next: () => this.estados.update((e) => (e ? { ...e, [dominio]: { ...e[dominio], pendiente: true } } : e)),
|
||||
recompute(domain: Domain): void {
|
||||
this.api.recompute(domain).subscribe({
|
||||
next: () => this.statuses.update((s) => (s ? { ...s, [domain]: { ...s[domain], pendiente: true } } : s)),
|
||||
error: (err) => this.error.set(apiErrorMessage(err, 'No se pudo solicitar el recálculo.')),
|
||||
});
|
||||
}
|
||||
|
||||
alternar(id: string): void {
|
||||
this.abierto.update((actual) => (actual === id ? null : id));
|
||||
toggle(id: string): void {
|
||||
this.expanded.update((current) => (current === id ? null : id));
|
||||
}
|
||||
|
||||
camposConProblemas(intento: IntentoImportacion) {
|
||||
return intento.fuentes.flatMap((fuente) =>
|
||||
Object.entries(fuente.campos)
|
||||
.filter(([, campo]) => campo.errores || campo.vacios)
|
||||
.map(([nombre, campo]) => ({ destino: fuente.destino, nombre, campo })),
|
||||
fieldsWithProblems(attempt: ImportAttempt) {
|
||||
return attempt.fuentes.flatMap((source) =>
|
||||
Object.entries(source.campos)
|
||||
.filter(([, field]) => field.errores || field.vacios)
|
||||
.map(([name, field]) => ({ target: source.destino, name, field })),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Domain } from '../connect/api/api.types';
|
||||
|
||||
export type Dominio = 'cacu' | 'cama' | 'tea';
|
||||
// Field names follow the JSON the API writes to the log.
|
||||
|
||||
export interface CampoReporte {
|
||||
export interface FieldReport {
|
||||
con_valor: number;
|
||||
vacios: number;
|
||||
errores?: Record<string, number>;
|
||||
@@ -13,33 +14,33 @@ export interface CampoReporte {
|
||||
valores_fuera_de_catalogo_poco_frecuentes?: number;
|
||||
}
|
||||
|
||||
export interface FuenteReporte {
|
||||
export interface SourceReport {
|
||||
destino: string;
|
||||
origen: { tipo: string; extensiones?: string[]; archivos?: number; motor?: string | null };
|
||||
mapeo: { requeridos_sin_mapear: string[]; campos_sin_mapear: string[]; columnas_origen: string[] };
|
||||
filas: Record<string, number>;
|
||||
campos: Record<string, CampoReporte>;
|
||||
campos: Record<string, FieldReport>;
|
||||
}
|
||||
|
||||
/** One line of the aggregate import log (`/reportes/importaciones`). */
|
||||
export interface IntentoImportacion {
|
||||
/** One line of the aggregate import log. */
|
||||
export interface ImportAttempt {
|
||||
id: string;
|
||||
fecha: string;
|
||||
operacion: 'validacion' | 'carga';
|
||||
dominio: Dominio | null;
|
||||
dominio: Domain | null;
|
||||
resultado: string;
|
||||
duracion_s: number;
|
||||
totales: Record<string, number>;
|
||||
fuentes: FuenteReporte[];
|
||||
fuentes: SourceReport[];
|
||||
error?: { tipo: string; mensaje: string };
|
||||
}
|
||||
|
||||
export interface ReporteImportaciones {
|
||||
export interface ImportLog {
|
||||
resumen: { intentos: Record<string, number>; ultimo: string | null };
|
||||
intentos: IntentoImportacion[];
|
||||
intentos: ImportAttempt[];
|
||||
}
|
||||
|
||||
export interface EstadoRecalculo {
|
||||
export interface RecomputeStatus {
|
||||
estado: 'sin_correr' | 'en_curso' | 'ok' | 'error';
|
||||
pendiente: boolean;
|
||||
inicio?: string;
|
||||
@@ -49,20 +50,20 @@ export interface EstadoRecalculo {
|
||||
error?: { tipo: string; mensaje: string };
|
||||
}
|
||||
|
||||
/** `/reportes/*`: the aggregate import log and the live indicator recomputation. */
|
||||
/** `/reportes/*`: the aggregate import log and the indicator recomputation. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ReportesApi {
|
||||
export class ReportsApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
importaciones(limite = 100): Observable<ReporteImportaciones> {
|
||||
return this.http.get<ReporteImportaciones>('/reportes/importaciones', { params: new HttpParams().set('limite', limite) });
|
||||
importLog(limit = 100): Observable<ImportLog> {
|
||||
return this.http.get<ImportLog>('/reportes/importaciones', { params: new HttpParams().set('limite', limit) });
|
||||
}
|
||||
|
||||
indicadores(): Observable<Record<Dominio, EstadoRecalculo>> {
|
||||
return this.http.get<Record<Dominio, EstadoRecalculo>>('/reportes/indicadores');
|
||||
indicatorStatus(): Observable<Record<Domain, RecomputeStatus>> {
|
||||
return this.http.get<Record<Domain, RecomputeStatus>>('/reportes/indicadores');
|
||||
}
|
||||
|
||||
recalcular(dominio: Dominio): Observable<{ pendiente: boolean }> {
|
||||
return this.http.post<{ pendiente: boolean }>(`/reportes/indicadores/${dominio}/recalcular`, {});
|
||||
recompute(domain: Domain): Observable<{ pendiente: boolean }> {
|
||||
return this.http.post<{ pendiente: boolean }>(`/reportes/indicadores/${domain}/recalcular`, {});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user