import { HttpErrorResponse } from '@angular/common/http'; import { DecimalPipe, KeyValuePipe } from '@angular/common'; import { Component, computed, inject, linkedSignal, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatTabsModule } from '@angular/material/tabs'; import { Api } from '../api/api'; import { pipeline as getPipeline } from '../api/fn/ingest/pipeline'; import { pipelines } from '../api/fn/ingest/pipelines'; import { startRun } from '../api/fn/ingest/start-run'; import { conflicts } from '../api/fn/review/conflicts'; import { correct } from '../api/fn/review/correct'; import { decidePersons } from '../api/fn/review/decide-persons'; import { held } from '../api/fn/review/held'; import { persons } from '../api/fn/review/persons'; import { reject } from '../api/fn/review/reject'; import { runStatus } from '../api/fn/runs/run-status'; import type { Correction } from '../api/models/correction'; import type { Rejection } from '../api/models/rejection'; type Entity = Rejection['entity']; type Row = Record; const ENTITIES: Record = { cervical_cytology: 'Citología cervical', cervical_biopsy: 'Biopsia cervical', clinical_note: 'Nota médica', death: 'Defunción', identity: 'Identidad', mammography: 'Mastografía', breast_biopsy: 'Biopsia de mama', breast_treatment: 'Tratamiento de cáncer de mama', breast_recurrence: 'Recurrencia de cáncer de mama', mchat: 'M-CHAT', ados2: 'ADOS-2', eeg: 'Electroencefalograma', }; const IDENTITY_FIELDS: Correction['field'][] = [ 'record_number', 'full_name', 'curp', 'nss', 'birth_date', 'sex', ]; /** Bookkeeping columns, not values a reviewer judges. */ const HIDDEN = [ '_pipeline', '_target', '_record', '_held', '_raw', '_quotes', '_index', 'rows_merged', 'known_at', ]; /** /revision: what ingestion held for a person to decide. Every decision is logged and * applied on the pipeline's next run. */ @Component({ selector: 'app-revision', imports: [ DecimalPipe, KeyValuePipe, FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatTabsModule, ], templateUrl: './revision.html', styleUrl: './revision.scss', }) export class Revision { private readonly api = inject(Api); protected readonly entities = Object.entries(ENTITIES) as [Entity, string][]; protected readonly fields = IDENTITY_FIELDS; protected readonly entity = signal('cervical_cytology'); protected readonly held = resource({ params: () => this.entity(), loader: ({ params }) => this.api.invoke(held, { entity: params }), }); protected readonly conflicts = resource({ params: () => this.entity(), loader: ({ params }) => this.api.invoke(conflicts, { entity: params }), }); /** The pipeline and link node whose persons are reviewed. */ protected readonly pipelines = resource({ loader: () => this.api.invoke(pipelines) }); /** The chosen pipeline; the first one until the reviewer picks another. */ protected readonly pipeline = linkedSignal( () => this.pipelines.value()?.[0]?.['pipeline_id'], ); protected readonly links = resource({ params: () => this.pipeline(), loader: async ({ params }) => { if (!params) return []; const saved = await this.api.invoke(getPipeline, { pipeline_id: params }); return saved.pipeline.nodes.filter((n) => n.kind === 'link').map((n) => n.id); }, }); protected readonly node = signal(undefined); protected readonly link = computed(() => this.node() ?? this.links.value()?.[0]); protected readonly persons = resource({ params: () => ({ pipeline: this.pipeline(), node: this.link() }), loader: ({ params }) => params.pipeline && params.node ? this.api.invoke(persons, { pipeline: params.pipeline, node: params.node }) : Promise.resolve({ to_settle: [], torn: [] } as Record), }); protected readonly message = signal(''); protected readonly decided = signal(new Set()); protected readonly run = signal(''); protected readonly entityLabel = ENTITIES; protected values(row: Row): Row { const raw = (row['_raw'] as Row | undefined) ?? row; return Object.fromEntries( Object.entries(raw).filter(([k]) => !HIDDEN.includes(k) && !k.startsWith('_dlt')), ); } protected reasons(row: Row): string { const found = row['_held']; return Array.isArray(found) ? found.join('; ') : String(found ?? ''); } protected text(value: unknown): string { return typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value ?? '—'); } protected candidates(entry: Row): Row[] { return (entry['candidates'] as Row[]) ?? []; } protected records(entry: Row): Row[] { return (entry['records'] as Row[]) ?? []; } private async done(key: string, call: Promise, what: string): Promise { try { await call; this.decided.update((s) => new Set(s).add(key)); this.message.set(`${what} Se aplica en la siguiente ejecución.`); } catch (e) { this.message.set( e instanceof HttpErrorResponse ? JSON.stringify(e.error?.detail ?? e.message) : String(e), ); } } protected rejectRow(entity: Entity, record: string, reason: string): Promise { return this.done( record, this.api.invoke(reject, { body: { entity, record, reason } }), 'Registro rechazado.', ); } protected decide(person: string, candidate: string, same: boolean): Promise { const body = { person, candidate, same }; return this.done( `${person}|${candidate}`, this.api.invoke(decidePersons, { body }), 'Decisión registrada.', ); } protected fix(record: string, field: Correction['field'], value: string): Promise { return this.done( `${record}|${field}`, this.api.invoke(correct, { body: { record, field, value } }), 'Corrección registrada.', ); } /** Runs the pipeline so the decisions apply, then reloads what is left. */ protected async apply(): Promise { const id = this.pipeline(); if (!id) return; const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} }); let status = 'STARTING'; while (!['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) { this.run.set(status); await new Promise((r) => setTimeout(r, 2000)); status = (await this.api.invoke(runStatus, { run_id }))['status']; } this.run.set(status); this.decided.set(new Set()); this.held.reload(); this.conflicts.reload(); this.persons.reload(); } }