preliminary release

This commit is contained in:
Roberto Treviño Cervantes
2026-10-29 12:12:15 -06:00
parent 51517ddf61
commit e6e6fb7210
124 changed files with 5769 additions and 660 deletions
+116
View File
@@ -0,0 +1,116 @@
<div class="reportes">
<mat-toolbar class="reportes__toolbar">
<div class="reportes__title">
<span class="reportes__eyebrow">Análisis de información</span>
<h1>Bitácora de cargas</h1>
</div>
<a mat-stroked-button href="/reportes/importaciones/descarga" download="importaciones.jsonl">
<mat-icon aria-hidden="true">download</mat-icon>Descargar bitácora
</a>
</mat-toolbar>
<div class="reportes__body">
@if (error(); as mensaje) {
<p class="reportes__error" role="alert">{{ mensaje }}</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>
}
@if (estado.error) {
<p class="estado__error">{{ estado.error.tipo }}: {{ estado.error.mensaje }}</p>
}
<button mat-button type="button" (click)="recalcular(dominio.id)" [disabled]="estado.pendiente || estado.estado === 'en_curso'">
<mat-icon aria-hidden="true">refresh</mat-icon>Recalcular
</button>
</article>
}
}
</div>
</section>
<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) {
<p>No se han registrado intentos de carga o validación.</p>
} @else {
<table class="intentos">
<thead>
<tr>
<th scope="col">Fecha</th><th scope="col">Operación</th><th scope="col">Destino</th><th scope="col">Resultado</th>
<th scope="col">Leídas</th><th scope="col">Válidas</th><th scope="col">Escritas</th><th scope="col">Rechazadas</th><th scope="col"></th>
</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>
<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>
</td>
</tr>
@if (abierto() === intento.id) {
<tr class="detalle">
<td colspan="9">
@if (intento.error) {
<p class="estado__error">{{ intento.error.tipo }}: {{ intento.error.mensaje }}</p>
}
@for (fuente of intento.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(', ') }}
}
</p>
}
<table class="campos">
<thead>
<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) {
<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>
@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> }
</td>
</tr>
} @empty {
<tr><td colspan="5">No se encontraron errores ni campos vacíos.</td></tr>
}
</tbody>
</table>
</td>
</tr>
}
}
</tbody>
</table>
}
</section>
</div>
</div>
+125
View File
@@ -0,0 +1,125 @@
:host {
display: flex;
flex: 1;
min-width: 0;
}
.reportes {
display: flex;
flex: 1;
flex-direction: column;
height: calc(100dvh - var(--site-header-height));
min-width: 0;
}
.reportes__toolbar {
--mat-toolbar-container-background-color: var(--mat-sys-surface);
border-bottom: 1px solid var(--mat-sys-outline-variant);
display: flex;
gap: var(--space-3);
height: auto;
justify-content: space-between;
min-height: 68px;
padding: var(--space-2) var(--space-4);
}
.reportes__title {
display: flex;
flex-direction: column;
line-height: 1.1;
h1 {
color: var(--color-primary);
font-family: var(--font-heading);
font-size: 26px;
font-weight: 700;
margin: 0;
}
}
.reportes__eyebrow,
.reportes__hint {
color: var(--mat-sys-on-surface-variant);
font-size: 13px;
}
.reportes__body {
display: flex;
flex-direction: column;
gap: var(--space-4);
overflow-y: auto;
padding: var(--space-4);
}
.reportes__error,
.estado__error {
color: var(--mat-sys-error);
}
h2 {
font-family: var(--font-heading);
margin: 0;
}
.estado-grid {
display: grid;
gap: var(--space-3);
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
.estado {
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 8px;
padding: var(--space-3);
h3 {
font-size: 15px;
margin: 0;
}
p {
margin: var(--space-1) 0;
}
}
.estado__valor {
font-size: 18px;
font-weight: 600;
}
.estado[data-estado='error'] .estado__valor {
color: var(--mat-sys-error);
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
border-bottom: 1px solid var(--mat-sys-outline-variant);
font-size: 13px;
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
tr[data-resultado='solicitud_invalida'] td:nth-child(4),
tr[data-resultado='rechazada_por_la_base'] td:nth-child(4),
tr[data-resultado='fallida'] td:nth-child(4) {
color: var(--mat-sys-error);
}
.detalle > td {
background: var(--mat-sys-surface-container-low);
}
.chip {
background: var(--mat-sys-surface-container-high);
border-radius: 12px;
display: inline-block;
margin: 2px 4px 2px 0;
padding: 1px 8px;
}
+56
View File
@@ -0,0 +1,56 @@
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';
describe('ReportesPage', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReportesPage],
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('shows the indicator status and the aggregate attempts', () => {
const fixture = TestBed.createComponent(ReportesPage);
fixture.detectChanges();
http.expectOne('/reportes/indicadores').flush({
cacu: { estado: 'ok', pendiente: false, fin: '2026-10-29T10:00:00+00:00', duracion_s: 12 },
cama: { estado: 'error', pendiente: false, error: { tipo: 'OperationalError', mensaje: 'x' } },
tea: { estado: 'sin_correr', pendiente: true },
});
http.expectOne((r) => r.url === '/reportes/importaciones').flush({
resumen: { intentos: {}, ultimo: null },
intentos: [{
id: 'a', fecha: '2026-10-29T10:00:00+00:00', operacion: 'carga', dominio: 'cacu', resultado: 'completada',
duracion_s: 1, totales: { leidas: 10, validas: 8, insertadas: 8, rechazadas_en_validacion: 2 },
fuentes: [{
destino: 'cacu.Paciente', origen: { tipo: 'csv' },
mapeo: { requeridos_sin_mapear: [], campos_sin_mapear: [], columnas_origen: [] },
filas: {}, campos: { pac_sexo: { con_valor: 10, vacios: 0, errores: { out_of_catalog: 2 } } },
}],
}],
});
fixture.detectChanges();
const text: string = fixture.nativeElement.textContent;
expect(text).toContain('Actualizado');
expect(text).toContain('Error en el cálculo');
expect(text).toContain('En espera de cálculo');
expect(text).toContain('cacu.Paciente');
(fixture.nativeElement.querySelector('.intentos button') as HTMLButtonElement).click();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.campos').textContent).toContain('out_of_catalog: 2');
});
it('asks for a recomputation', () => {
const fixture = TestBed.createComponent(ReportesPage);
fixture.componentInstance.recalcular('tea');
http.expectOne('/reportes/indicadores/tea/recalcular').flush({ pendiente: true });
});
});
+90
View File
@@ -0,0 +1,90 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
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';
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> = {
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> = {
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.
*/
@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);
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 error = signal<string | null>(null);
ngOnInit(): void {
interval(15000)
.pipe(
startWith(0),
switchMap(() => forkJoin({ estados: this.api.indicadores(), log: this.api.importaciones() })),
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.')),
});
}
estadoTexto(estado: EstadoRecalculo): string {
return estado.pendiente && estado.estado !== 'en_curso' ? 'En espera de cálculo' : ESTADOS[estado.estado] ?? estado.estado;
}
resultadoTexto(resultado: string): string {
return RESULTADOS[resultado] ?? resultado;
}
recalcular(dominio: Dominio): void {
this.api.recalcular(dominio).subscribe({
next: () => this.estados.update((e) => (e ? { ...e, [dominio]: { ...e[dominio], pendiente: true } } : e)),
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));
}
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 })),
);
}
}
+68
View File
@@ -0,0 +1,68 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
export type Dominio = 'cacu' | 'cama' | 'tea';
export interface CampoReporte {
con_valor: number;
vacios: number;
errores?: Record<string, number>;
formatos_rechazados?: Record<string, number>;
valores_fuera_de_catalogo?: Record<string, number>;
valores_fuera_de_catalogo_poco_frecuentes?: number;
}
export interface FuenteReporte {
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>;
}
/** One line of the aggregate import log (`/reportes/importaciones`). */
export interface IntentoImportacion {
id: string;
fecha: string;
operacion: 'validacion' | 'carga';
dominio: Dominio | null;
resultado: string;
duracion_s: number;
totales: Record<string, number>;
fuentes: FuenteReporte[];
error?: { tipo: string; mensaje: string };
}
export interface ReporteImportaciones {
resumen: { intentos: Record<string, number>; ultimo: string | null };
intentos: IntentoImportacion[];
}
export interface EstadoRecalculo {
estado: 'sin_correr' | 'en_curso' | 'ok' | 'error';
pendiente: boolean;
inicio?: string;
fin?: string;
duracion_s?: number;
anios?: [number, number];
error?: { tipo: string; mensaje: string };
}
/** `/reportes/*`: the aggregate import log and the live indicator recomputation. */
@Injectable({ providedIn: 'root' })
export class ReportesApi {
private readonly http = inject(HttpClient);
importaciones(limite = 100): Observable<ReporteImportaciones> {
return this.http.get<ReporteImportaciones>('/reportes/importaciones', { params: new HttpParams().set('limite', limite) });
}
indicadores(): Observable<Record<Dominio, EstadoRecalculo>> {
return this.http.get<Record<Dominio, EstadoRecalculo>>('/reportes/indicadores');
}
recalcular(dominio: Dominio): Observable<{ pendiente: boolean }> {
return this.http.post<{ pendiente: boolean }>(`/reportes/indicadores/${dominio}/recalcular`, {});
}
}