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 { Loading } from '../loading'; import { schema } from '../api/fn/ingest/schema'; import { unrecognised } from '../api/fn/review/unrecognised'; 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', ]; /** Identity fields as linkage names them (core.schema.Identity). */ const IDENTITY_TITLES: Record = { record_number: 'Expediente', curp: 'CURP', nss: 'NSS', full_name: 'Nombre', }; /** The platform's hold reasons (English in its logs) as the reviewer reads them. */ const REASONS: [RegExp, (m: RegExpExecArray) => string][] = [ [/^Field required$/, () => 'falta el dato'], [ /^Input should be (.+)$/, (m) => `valor fuera del catálogo (se espera ${m[1].replace(/ or /g, ' o ')})`, ], [/^not found in the document as quoted$/, () => 'no está en el documento tal como se citó'], [/^Value error, a date is not a record number$/, () => 'una fecha no es un expediente'], [ /^records of this person disagree on birth date or sex$/, () => 'sus registros no coinciden en fecha de nacimiento o sexo', ], [ /^no name, birth date or record number was read$/, () => 'no se leyó nombre, fecha de nacimiento ni expediente', ], [/^no identity linked to this record$/, () => 'ninguna identidad vinculada a este registro'], [/^nothing found$/, () => 'no se encontró nada en el documento'], [ /^no LLM answering and no patterns set$/, () => 'sin modelo de lenguaje disponible ni patrones configurados', ], ]; /** 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: [ Loading, 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), }); /** Documents the chosen pipeline's routes don't recognise (its `otherwise` routes). */ protected readonly unrecognised = resource({ params: () => this.pipeline(), loader: ({ params }) => params ? this.api.invoke(unrecognised, { pipeline: params }) : Promise.resolve([] as Row[]), }); /** A row's fields but its route and preview, as `name: value`. */ protected details(row: Row): string { return Object.entries(row) .filter(([k, v]) => !['route', 'preview'].includes(k) && v !== null && v !== '') .map(([k, v]) => `${k}: ${v}`) .join(' · '); } 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 ?? ''); } /** The platform's field titles (the catalog's), by entity: what the page calls a field. */ protected readonly titles = resource({ loader: async () => { const found = (await this.api.invoke(schema)) as Record; return Object.fromEntries( Object.entries((found['entities'] ?? {}) as Record).map(([e, s]) => [ e, Object.fromEntries( Object.entries((s['properties'] ?? {}) as Record).map(([f, p]) => [ f, p['title'] as string, ]), ), ]), ) as Record>; }, }); protected title(field: string): string { return this.titles.value()?.[this.entity()]?.[field] ?? field; } /** A hold's reasons as the reviewer reads them (the platform logs them in English). */ protected said(row: Row): string { const found = row['_held']; const all = Array.isArray(found) ? (found as string[]) : [String(found ?? '')]; return all.map((r) => this.spanish(r)).join('; '); } /** Why linkage proposes two records as one person, in the reviewer's words. */ protected candidateReason(reason: unknown): string { const text = String(reason ?? ''); const typo = /^(\w+) one typo apart$/.exec(text); if (typo) return `${IDENTITY_TITLES[typo[1]] ?? typo[1]} a una letra de distancia`; return text === 'same birth date' ? 'misma fecha de nacimiento' : text; } private spanish(reason: string): string { const field = /^(\w+): (.*)$/.exec(reason); const [name, message] = field ? [this.title(field[1]) + ': ', field[2]] : ['', reason]; for (const [pattern, text] of REASONS) { const m = pattern.exec(message); if (m) return name + text(m); } return reason; } 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(); } }