From 53a6393cb25c9e71592ff73a8b2e1c47e26fae27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Wed, 25 Nov 2026 23:20:52 -0600 Subject: [PATCH] CaMa indicators and follow-up list, model governance page --- e2e/pages.spec.ts | 22 ++++ openapi.json | 90 ++++++++++++-- src/app/api/fn/fhir/search-patient.ts | 6 +- src/app/api/fn/models/read-report-any.ts | 38 ++++++ src/app/api/fn/models/read-report-json.ts | 38 ++++++ src/app/api/functions.ts | 4 + src/app/app.html | 1 + src/app/app.routes.ts | 5 + src/app/gobernanza/figures.spec.ts | 19 +++ src/app/gobernanza/figures.ts | 144 ++++++++++++++++++++++ src/app/gobernanza/gobernanza.html | 116 +++++++++++++++++ src/app/gobernanza/gobernanza.scss | 47 +++++++ src/app/gobernanza/gobernanza.ts | 133 ++++++++++++++++++++ src/app/indicadores/follow-up.ts | 78 +++++++++++- src/app/indicadores/indicadores.ts | 20 ++- src/app/indicadores/layout.ts | 24 ++++ src/app/indicadores/measures.ts | 13 ++ src/app/indicadores/tab-seguimiento.html | 102 +++++++++++++++ src/app/indicadores/tab-seguimiento.ts | 93 ++++++++++++++ 19 files changed, 974 insertions(+), 19 deletions(-) create mode 100644 src/app/api/fn/models/read-report-any.ts create mode 100644 src/app/api/fn/models/read-report-json.ts create mode 100644 src/app/gobernanza/figures.spec.ts create mode 100644 src/app/gobernanza/figures.ts create mode 100644 src/app/gobernanza/gobernanza.html create mode 100644 src/app/gobernanza/gobernanza.scss create mode 100644 src/app/gobernanza/gobernanza.ts create mode 100644 src/app/indicadores/tab-seguimiento.html create mode 100644 src/app/indicadores/tab-seguimiento.ts diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index de21c12..6634d5f 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -53,6 +53,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie ).not.toContainText('Sin estudios'); await page.goto('/indicadores/cama'); + await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); + await page.getByRole('tab', { name: 'Seguimiento' }).click(); + await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); + await page.getByRole('option', { name: '12 meses' }).click(); + const camaRows = page.locator('table.worklist tbody tr'); + await expect(camaRows.first()).toContainText('BI-RADS'); + await page.goto('/indicadores/tea'); await expect(page.getByText('todavía no tiene indicadores')).toBeVisible(); expect(problems).toEqual([]); }); @@ -94,3 +101,18 @@ test('revision: what the messy site holds, and a decision through the page', asy await expect(page.getByText('Decisión registrada.')).toBeVisible(); expect(problems).toEqual([]); }); + +test('gobernanza: a version with its reports, its curves, and promotion refused without validation', async ({ + page, +}) => { + const problems = watch(page); + await page.goto('/gobernanza/cama'); + await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible(); + const version = page.locator('tr', { hasText: 'v1' }); + await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible(); + await version.getByRole('button', { name: 'Ver gráficas' }).click(); + await expect(page.locator('app-plot .plot svg').first()).toBeVisible(); + await version.getByRole('button', { name: 'Promover' }).click(); + await expect(page.getByText('No se promovió')).toContainText('clinical_validation'); + expect(problems.filter((p) => !p.includes('409'))).toEqual([]); +}); diff --git a/openapi.json b/openapi.json index 0b2e913..2d1b587 100644 --- a/openapi.json +++ b/openapi.json @@ -2060,6 +2060,72 @@ ] } }, + "/models/{domain}/{name}/versions/{version}/reports/{report}": { + "get": { + "description": "A version's report: the generated ones as JSON (what the governance page draws), the\nclinical validation as the file the clinical team uploaded.", + "operationId": "read_report", + "parameters": [ + { + "in": "path", + "name": "domain", + "required": true, + "schema": { + "$ref": "#/components/schemas/Domain" + } + }, + { + "in": "path", + "name": "name", + "required": true, + "schema": { + "title": "Name", + "type": "string" + } + }, + { + "in": "path", + "name": "version", + "required": true, + "schema": { + "title": "Version", + "type": "integer" + } + }, + { + "in": "path", + "name": "report", + "required": true, + "schema": { + "title": "Report", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": {}, + "application/octet-stream": {} + }, + "description": "the report as stored" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Read Report", + "tags": [ + "models" + ] + } + }, "/review/conflicts": { "get": { "description": "Rows of one person and date that disagree; reject the wrong ones.", @@ -3083,7 +3149,7 @@ }, "/{domain}/fhir/Patient": { "get": { - "description": "Patients; with `follow-up-window`, CaCu's follow-up list at the cut-off, filtered by\nstatus and in reading order, with what the list shows of each patient included.", + "description": "Patients; with `follow-up-window`, the domain's follow-up list at the cut-off,\nfiltered by status and in reading order, with what the list shows of each patient\nincluded.", "operationId": "search_patient", "parameters": [ { @@ -3111,7 +3177,7 @@ } }, { - "description": "months: whoever had a cytology sampled within them up to the cut-off", + "description": "months: the domain's follow-up list over that window up to the cut-off", "in": "query", "name": "follow-up-window", "required": false, @@ -3124,7 +3190,7 @@ "type": "null" } ], - "description": "months: whoever had a cytology sampled within them up to the cut-off", + "description": "months: the domain's follow-up list over that window up to the cut-off", "title": "Follow-Up-Window" } }, @@ -3164,13 +3230,13 @@ } }, { - "description": "one of ('-recent', '-risk-cin2', '-risk-cancer'); the list only", + "description": "-recent or -risk-", "in": "query", "name": "_sort", "required": false, "schema": { "default": "-recent", - "description": "one of ('-recent', '-risk-cin2', '-risk-cancer'); the list only", + "description": "-recent or -risk-", "title": " Sort", "type": "string" } @@ -3181,10 +3247,16 @@ "name": "risk-horizon", "required": false, "schema": { - "default": 5.0, + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], "description": "years", - "title": "Risk-Horizon", - "type": "number" + "title": "Risk-Horizon" } }, { @@ -3324,7 +3396,7 @@ }, "/{domain}/fhir/Procedure": { "get": { - "description": "Colposcopies and treatments, as the timeline infers them.", + "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments).", "operationId": "search_procedure", "parameters": [ { diff --git a/src/app/api/fn/fhir/search-patient.ts b/src/app/api/fn/fhir/search-patient.ts index 878e190..dd908e2 100644 --- a/src/app/api/fn/fhir/search-patient.ts +++ b/src/app/api/fn/fhir/search-patient.ts @@ -14,7 +14,7 @@ export interface SearchPatient$Params { '_id'?: (string | null); /** - * months: whoever had a cytology sampled within them up to the cut-off + * months: the domain's follow-up list over that window up to the cut-off */ 'follow-up-window'?: (number | null); @@ -25,14 +25,14 @@ export interface SearchPatient$Params { 'follow-up-status'?: (string | null); /** - * one of ('-recent', '-risk-cin2', '-risk-cancer'); the list only + * -recent or -risk- */ '_sort'?: string; /** * years */ - 'risk-horizon'?: number; + 'risk-horizon'?: (number | null); /** * any of ('DiagnosticReport:subject', 'RiskAssessment:subject', 'Observation:subject') diff --git a/src/app/api/fn/models/read-report-any.ts b/src/app/api/fn/models/read-report-any.ts new file mode 100644 index 0000000..db3cb90 --- /dev/null +++ b/src/app/api/fn/models/read-report-any.ts @@ -0,0 +1,38 @@ +/* eslint-disable */ +/* Code generated by ng-openapi-gen DO NOT EDIT. */ + +import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { StrictHttpResponse } from '../../strict-http-response'; +import { RequestBuilder } from '../../request-builder'; + +import { Domain } from '../../models/domain'; + +export interface ReadReport$Any$Params { + domain: Domain; + name: string; + version: number; + report: string; +} + +export function readReport$Any(http: HttpClient, rootUrl: string, params: ReadReport$Any$Params, context?: HttpContext): Observable> { + const rb = new RequestBuilder(rootUrl, readReport$Any.PATH, 'get'); + if (params) { + rb.path('domain', params.domain, {}); + rb.path('name', params.name, {}); + rb.path('version', params.version, {}); + rb.path('report', params.report, {}); + } + + return http.request( + rb.build({ responseType: 'blob', accept: 'application/octet-stream', context }) + ).pipe( + filter((r: any): r is HttpResponse => r instanceof HttpResponse), + map((r: HttpResponse) => { + return r as StrictHttpResponse; + }) + ); +} + +readReport$Any.PATH = '/models/{domain}/{name}/versions/{version}/reports/{report}'; diff --git a/src/app/api/fn/models/read-report-json.ts b/src/app/api/fn/models/read-report-json.ts new file mode 100644 index 0000000..badbc10 --- /dev/null +++ b/src/app/api/fn/models/read-report-json.ts @@ -0,0 +1,38 @@ +/* eslint-disable */ +/* Code generated by ng-openapi-gen DO NOT EDIT. */ + +import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { StrictHttpResponse } from '../../strict-http-response'; +import { RequestBuilder } from '../../request-builder'; + +import { Domain } from '../../models/domain'; + +export interface ReadReport$Json$Params { + domain: Domain; + name: string; + version: number; + report: string; +} + +export function readReport$Json(http: HttpClient, rootUrl: string, params: ReadReport$Json$Params, context?: HttpContext): Observable> { + const rb = new RequestBuilder(rootUrl, readReport$Json.PATH, 'get'); + if (params) { + rb.path('domain', params.domain, {}); + rb.path('name', params.name, {}); + rb.path('version', params.version, {}); + rb.path('report', params.report, {}); + } + + return http.request( + rb.build({ responseType: 'json', accept: 'application/json', context }) + ).pipe( + filter((r: any): r is HttpResponse => r instanceof HttpResponse), + map((r: HttpResponse) => { + return r as StrictHttpResponse; + }) + ); +} + +readReport$Json.PATH = '/models/{domain}/{name}/versions/{version}/reports/{report}'; diff --git a/src/app/api/functions.ts b/src/app/api/functions.ts index ae65159..e0af9a2 100644 --- a/src/app/api/functions.ts +++ b/src/app/api/functions.ts @@ -41,6 +41,10 @@ export type { Promote$Params as Promote$Params } from './fn/models/promote'; export { promote as promote } from './fn/models/promote'; export type { AddClinicalValidation$Params as AddClinicalValidation$Params } from './fn/models/add-clinical-validation'; export { addClinicalValidation as addClinicalValidation } from './fn/models/add-clinical-validation'; +export type { ReadReport$Json$Params as ReadReport$Json$Params } from './fn/models/read-report-json'; +export { readReport$Json as readReport$Json } from './fn/models/read-report-json'; +export type { ReadReport$Any$Params as ReadReport$Any$Params } from './fn/models/read-report-any'; +export { readReport$Any as readReport$Any } from './fn/models/read-report-any'; export type { Conflicts$Params as Conflicts$Params } from './fn/review/conflicts'; export { conflicts as conflicts } from './fn/review/conflicts'; export type { Correct$Params as Correct$Params } from './fn/review/correct'; diff --git a/src/app/app.html b/src/app/app.html index 2225e8c..4d3a5bd 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -26,6 +26,7 @@ Indicadores Conectar Revisión + Gobernanza diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 49d814c..bb8e565 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -12,5 +12,10 @@ export const routes: Routes = [ }, { path: 'conectar', loadComponent: () => import('./conectar/conectar').then((m) => m.Conectar) }, { path: 'revision', loadComponent: () => import('./revision/revision').then((m) => m.Revision) }, + { path: 'gobernanza', pathMatch: 'full', redirectTo: 'gobernanza/cacu' }, + { + path: 'gobernanza/:domain', + loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza), + }, { path: '**', redirectTo: 'indicadores/cacu' }, ]; diff --git a/src/app/gobernanza/figures.spec.ts b/src/app/gobernanza/figures.spec.ts new file mode 100644 index 0000000..ded2cf5 --- /dev/null +++ b/src/app/gobernanza/figures.spec.ts @@ -0,0 +1,19 @@ +import { interpretabilityFigures } from './figures'; + +describe('governance figures', () => { + it('draws a survival report as curves with bands and the model points', () => { + const [found] = interpretabilityFigures({ + kind: 'curves', + curves: [ + { name: 'Kaplan-Meier', months: [0, 6], survival: [1, 0.9], low: [1, 0.8], high: [1, 1] }, + ], + predicted: { name: 'Modelo', months: [6], survival: [0.92], low: [0.85], high: [0.97] }, + }); + expect(found.figure.data.length).toBe(3); // band, curve, model points + expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05); + }); + + it('draws nothing for a report it does not know', () => { + expect(interpretabilityFigures({ kind: 'other' })).toEqual([]); + }); +}); diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts new file mode 100644 index 0000000..a4e708b --- /dev/null +++ b/src/app/gobernanza/figures.ts @@ -0,0 +1,144 @@ +import type { Figure } from '../plot'; +import { PALETTE } from '../plot'; + +/** A curve with its band, as the reports give them. */ +interface Band { + x: number[]; + y: number[]; + low?: (number | null)[]; + high?: (number | null)[]; +} + +function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial[] { + const lines: Partial[] = []; + if (b.low && b.high) { + lines.push({ + x: [...b.x, ...[...b.x].reverse()], + y: [...b.high, ...[...b.low].reverse()] as number[], + fill: 'toself', + fillcolor: `${colour}33`, + line: { width: 0 }, + hoverinfo: 'skip', + showlegend: false, + type: 'scatter', + }); + } + lines.push({ + x: b.x, + y: b.y, + name, + type: 'scatter', + mode: 'lines', + line: { color: colour, dash }, + }); + return lines; +} + +/** What a model's interpretability report draws, by its kind: survival curves, the mixture's + * observed and predicted risk per subgroup, or the logistic regression's calibration. */ +export function interpretabilityFigures( + report: Record, +): { title: string; figure: Figure }[] { + switch (report['kind']) { + case 'curves': { + const data = (report['curves'] as any[]).flatMap((c, i) => + banded(c.name, { x: c.months, y: c.survival, low: c.low, high: c.high }, PALETTE[i]), + ); + const p = report['predicted']; + data.push({ + x: p.months, + y: p.survival, + error_y: { + type: 'data', + symmetric: false, + array: p.high.map((h: number, i: number) => h - p.survival[i]), + arrayminus: p.survival.map((s: number, i: number) => s - p.low[i]), + }, + name: p.name, + type: 'scatter', + mode: 'markers', + marker: { color: PALETTE[4], size: 9 }, + }); + return [ + { + title: 'Supervivencia observada y del modelo', + figure: { + data, + layout: { + xaxis: { title: { text: 'Meses desde el índice' } }, + yaxis: { title: { text: 'Supervivencia S(t)' } }, + }, + }, + }, + ]; + } + case 'subgroups': + return (report['groups'] as any[]).slice(0, 6).map((g) => ({ + title: `${Object.values(g.combination).join(' · ')} (n = ${g.n})`, + figure: { + data: [ + ...banded( + 'Observado (Turnbull)', + { + x: g.observed.years, + y: g.observed.risk, + low: g.observed.low, + high: g.observed.high, + }, + PALETTE[0], + ), + ...(g.predicted + ? banded( + 'Modelo', + { + x: g.predicted.years, + y: g.predicted.risk, + low: g.predicted.low, + high: g.predicted.high, + }, + PALETTE[4], + 'dot', + ) + : []), + ], + layout: { + xaxis: { title: { text: 'Años desde el índice' } }, + yaxis: { title: { text: 'Riesgo acumulado' } }, + }, + }, + })); + case 'coefficients': { + const bins = report['calibration']['bins'] as any[]; + return [ + { + title: `Calibración por decil de riesgo (Brier ${report['calibration']['brier'].toFixed(3)})`, + figure: { + data: [ + { + x: bins.map((b) => b.predicted), + y: bins.map((b) => b.observed), + name: 'Deciles', + type: 'scatter', + mode: 'markers', + }, + { + x: [0, 1], + y: [0, 1], + name: 'Calibración perfecta', + type: 'scatter', + mode: 'lines', + line: { dash: 'dot', color: PALETTE[6] }, + }, + ], + layout: { + xaxis: { title: { text: 'Predicho' } }, + yaxis: { title: { text: 'Observado' } }, + }, + }, + }, + ]; + } + default: + return []; + } +} diff --git a/src/app/gobernanza/gobernanza.html b/src/app/gobernanza/gobernanza.html new file mode 100644 index 0000000..f96a5d1 --- /dev/null +++ b/src/app/gobernanza/gobernanza.html @@ -0,0 +1,116 @@ +
+

Gobernanza de modelos

+ + +
+ + Datos hasta + + + + + @if (run(); as r) { + {{ r.kind }}: {{ r.status }} + } +
+ @if (message()) { +

{{ message() }}

+ } + + @if (models.isLoading()) { +

Cargando modelos…

+ } @else if (!models.value()?.length) { +

Este dominio todavía no tiene modelos entrenados.

+ } + @for (m of models.value() ?? []; track m.name) { +
+

{{ m.name }}

+ + + + + + + + + + + + + @for (v of m.versions; track v.version) { + + + + + + + + + } + +
VersiónCreadaEntrenamiento / pruebaInformesValidación clínica
+ v{{ v.version }} + @if (champion(v)) { + en producción + } + {{ v.created | date: 'yyyy-MM-dd HH:mm' }} + {{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }} + + @for (r of v.reports; track r) { + {{ + reportNames[r] ?? r + }} + } + @if (v.reports.includes('interpretability')) { + + } + + @if (!v.reports.includes('clinical_validation')) { + + } @else { + Agregada + } + + @if (!champion(v)) { + + } +
+
+ } + + @if (chosen(); as c) { +
+

Interpretabilidad · {{ c.name }} v{{ c.version }}

+ @for (f of figures(); track f.title) { +

{{ f.title }}

+ + } @empty { +

+ {{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }} +

+ } +
+ } +
diff --git a/src/app/gobernanza/gobernanza.scss b/src/app/gobernanza/gobernanza.scss new file mode 100644 index 0000000..e974ad7 --- /dev/null +++ b/src/app/gobernanza/gobernanza.scss @@ -0,0 +1,47 @@ +:host { + display: block; +} +h1 { + text-align: center; +} +.domains { + display: flex; + justify-content: center; + gap: var(--space-4); + margin-bottom: var(--space-4); +} +.domains a.active { + font-weight: 600; + text-decoration: underline; +} +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); + margin-bottom: var(--space-4); +} +.model { + margin-bottom: var(--space-4); + overflow-x: auto; +} +.num { + text-align: right; + white-space: nowrap; +} +.badge { + margin-left: var(--space-2); + padding: 2px 8px; + border-radius: 999px; + background: var(--color-primary); + color: #fff; + font-size: 12px; +} +td a { + margin-right: var(--space-3); + color: var(--color-action); +} +.empty { + padding: 48px 0; + text-align: center; +} diff --git a/src/app/gobernanza/gobernanza.ts b/src/app/gobernanza/gobernanza.ts new file mode 100644 index 0000000..6ceadff --- /dev/null +++ b/src/app/gobernanza/gobernanza.ts @@ -0,0 +1,133 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { DatePipe, DecimalPipe } from '@angular/common'; +import { Component, computed, inject, input, 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 { RouterLink } from '@angular/router'; +import { Api } from '../api/api'; +import { ApiConfiguration } from '../api/api-configuration'; +import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; +import { models } from '../api/fn/models/models'; +import { promote } from '../api/fn/models/promote'; +import { readReport$Json } from '../api/fn/models/read-report-json'; +import { score } from '../api/fn/models/score'; +import { train } from '../api/fn/models/train'; +import { versions } from '../api/fn/models/versions'; +import { domains } from '../api/fn/operations/domains'; +import { runStatus } from '../api/fn/runs/run-status'; +import type { Domain } from '../api/models/domain'; +import type { Version } from '../api/models/version'; +import { DOMAINS } from '../app'; +import { Plot } from '../plot'; +import { interpretabilityFigures } from './figures'; + +const REPORTS: Record = { + technical_validation: 'Validación técnica', + interpretability: 'Interpretabilidad', + clinical_validation: 'Validación clínica', +}; + +/** Model governance for a domain: every model's versions with their metrics and reports, + * the clinical validation the clinical team uploads, promotion (refused without the three + * reports), and the training and scoring runs. */ +@Component({ + selector: 'app-gobernanza', + imports: [ + DatePipe, + DecimalPipe, + FormsModule, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + RouterLink, + Plot, + ], + templateUrl: './gobernanza.html', + styleUrl: './gobernanza.scss', +}) +export class Gobernanza { + private readonly api = inject(Api); + private readonly root = inject(ApiConfiguration).rootUrl; + readonly domain = input.required(); + + protected readonly labels = DOMAINS as Record; + protected readonly reportNames = REPORTS; + protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); + private readonly refreshed = signal(0); + protected readonly models = resource({ + params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }), + loader: async ({ params: { domain } }) => { + const names = await this.api.invoke(models, { domain }); + return Promise.all( + names.map(async (name) => ({ + name, + versions: await this.api.invoke(versions, { domain, name }), + })), + ); + }, + }); + protected readonly chosen = signal<{ name: string; version: number } | undefined>(undefined); + protected readonly report = resource({ + params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain }, + loader: ({ params }) => + this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }), + }); + protected readonly figures = computed(() => { + const found = this.report.value(); + return found ? interpretabilityFigures(found as Record) : []; + }); + protected readonly asOf = signal(''); + protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined); + protected readonly message = signal(''); + + protected champion(v: Version): boolean { + return v.aliases.includes('champion'); + } + + protected reportUrl(name: string, version: number, report: string): string { + return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`; + } + + protected async upload(name: string, version: number, event: Event): Promise { + const file = (event.target as HTMLInputElement).files?.[0]; + if (!file) return; + await this.api.invoke(addClinicalValidation, { + domain: this.domain() as Domain, + name, + version, + // OpenAPI's binary is typed as a string; the request builder sends the File as is. + body: { file: file as unknown as string }, + }); + this.message.set(`Validación clínica agregada a ${name} v${version}.`); + this.refreshed.update((n) => n + 1); + } + + protected async promote(name: string, version: number): Promise { + try { + await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); + this.message.set(`${name} v${version} es ahora la versión en producción.`); + this.refreshed.update((n) => n + 1); + } catch (e) { + const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; + this.message.set(`No se promovió: ${detail ?? 'error'}`); + } + } + + protected async start(kind: 'train' | 'score'): Promise { + const domain = this.domain() as Domain; + const { run_id } = + kind === 'train' + ? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} }) + : await this.api.invoke(score, { domain }); + const label = kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos'; + for (;;) { + const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; + this.run.set({ kind: label, status }); + if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; + await new Promise((r) => setTimeout(r, 2000)); + } + this.refreshed.update((n) => n + 1); + } +} diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts index 249ffa7..c389271 100644 --- a/src/app/indicadores/follow-up.ts +++ b/src/app/indicadores/follow-up.ts @@ -24,14 +24,18 @@ const AGE_GROUPS: [number, number][] = [ [55, 64], ]; -export function ageGroup(birth: string | undefined, at: string): string { +export function ageGroup( + birth: string | undefined, + at: string, + groups: [number, number][] = AGE_GROUPS, +): string { if (!birth) return 'Sin dato'; const [by, bm, bd] = birth.split('-').map(Number); const [y, m, d] = at.split('-').map(Number); const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0); - const found = AGE_GROUPS.find(([lo, hi]) => lo <= age && age <= hi); + const found = groups.find(([lo, hi]) => lo <= age && age <= hi); if (found) return `${found[0]}-${found[1]}`; - return age < AGE_GROUPS[0][0] ? `<${AGE_GROUPS[0][0]}` : `${AGE_GROUPS.at(-1)![1] + 1}+`; + return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`; } /** Her current risk of an outcome at a horizon: from the latest index date any of the @@ -132,3 +136,71 @@ export function windowStart(cutoff: string, months: number): string { const day = new Date(Date.UTC(year, month, Math.min(d, last) + 1)); return day.toISOString().slice(0, 10); } + +/** One row of CaMa's follow-up list: her latest mammogram reported by the cut-off, where the + * biopsy it led to stands, and how soon she should be seen. */ +export interface CamaRow { + patient: Patient; + name?: string; + curp?: string; + status: string; + priority: string; + ageGroup: string; + mammogram: { date: string; birads?: string }; + biopsy?: { date: string; histology?: string }; +} + +const CAMA_AGE_GROUPS: [number, number][] = [ + [40, 49], + [50, 59], + [60, 69], +]; + +export function camaRows(page: Bundle, cutoff: string): CamaRow[] { + const reports = resources(page, 'DiagnosticReport'); + const observations = new Map(resources(page, 'Observation').map((o) => [o.id, o])); + const results = (r: DiagnosticReport) => + new Map( + (r.result ?? []) + .map((x) => observations.get(x.reference?.split('/')[1])) + .filter((o) => !!o) + .map((o) => [code(o!.code), o!]), + ); + const reported = (r: DiagnosticReport) => ext(r, 'report-date')?.valueDate; + return resources(page, 'Patient', 'match').map((patient) => { + const mine = reports.filter((r) => r.subject?.reference === `Patient/${patient.id}`); + const mammogram = mine + .filter((r) => code(r.code) === 'mammography' && (reported(r) ?? '9') <= cutoff) + .sort((a, b) => a.effectiveDateTime!.localeCompare(b.effectiveDateTime!)) + .at(-1); + const exam = mammogram?.effectiveDateTime ?? ''; + const biopsy = mine + .filter( + (r) => + code(r.code) === 'breast_biopsy' && + results(r).get('breast_biopsy.mammogram_exam_date')?.valueDateTime === exam && + exam <= (reported(r) ?? '') && + reported(r)! <= cutoff, + ) + .sort((a, b) => reported(a)!.localeCompare(reported(b)!)) + .at(-1); + return { + patient, + name: patient.name?.[0]?.text, + curp: patient.identifier?.find((i) => i.system === CURP)?.value, + status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', + priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '', + ageGroup: ageGroup(patient.birthDate, cutoff, CAMA_AGE_GROUPS), + mammogram: { + date: exam, + birads: mammogram + ? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept) + : undefined, + }, + biopsy: biopsy && { + date: reported(biopsy)!, + histology: code(results(biopsy).get('breast_biopsy.histology')?.valueCodeableConcept), + }, + }; + }); +} diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts index 5e8a29d..10cd4cb 100644 --- a/src/app/indicadores/indicadores.ts +++ b/src/app/indicadores/indicadores.ts @@ -6,12 +6,20 @@ import { Fhir, resources } from '../fhir'; import { TabDefiniciones } from './tab-definiciones'; import { TabIndicadores } from './tab-indicadores'; import { TabRiesgos } from './tab-riesgos'; +import { TabSeguimiento } from './tab-seguimiento'; import { TabTrazabilidad } from './tab-trazabilidad'; /** A domain's indicator page: four tabs over its FHIR measures and patients. */ @Component({ selector: 'app-indicadores', - imports: [MatTabsModule, TabIndicadores, TabTrazabilidad, TabRiesgos, TabDefiniciones], + imports: [ + MatTabsModule, + TabIndicadores, + TabTrazabilidad, + TabRiesgos, + TabSeguimiento, + TabDefiniciones, + ], template: `

{{ title() }}

@@ -34,12 +42,18 @@ import { TabTrazabilidad } from './tab-trazabilidad'; - @if (patients()) { + @if (domain() === 'cacu') { + } @else if (domain() === 'cama') { + + + + + } @@ -80,6 +94,4 @@ export class Indicadores { loader: async ({ params }) => resources(await this.fhir.all(params, 'Measure'), 'Measure'), }); - /** Patient-level analysis is served for CaCu only (so far). */ - protected readonly patients = computed(() => this.domain() === 'cacu'); } diff --git a/src/app/indicadores/layout.ts b/src/app/indicadores/layout.ts index c482046..1daad6f 100644 --- a/src/app/indicadores/layout.ts +++ b/src/app/indicadores/layout.ts @@ -44,4 +44,28 @@ export const LAYOUTS: Record = { ], anchor: 'IND1', }, + cama: { + kpis: [ + 'CAMA_BIRADS', + 'CAMA_EU38A', + 'CAMA_DIAS_TOMA_DIAGNOSTICO', + 'CAMA_CONFIRMACION_BIRADS45', + 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', + ], + route: [ + { + label: 'Resultado de mastografía', + step: 'Toma a resultado de mastografía', + fromSample: 'CAMA_EU38A', + fromStep: 'CAMA_EU38A', + }, + { + label: 'Diagnóstico', + step: 'Del resultado de mastografía al diagnóstico', + fromSample: 'CAMA_DIAS_TOMA_DIAGNOSTICO', + fromStep: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', + }, + ], + anchor: 'CAMA_BIRADS', + }, }; diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 8fe80d0..46db106 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -99,12 +99,25 @@ const LABELS: Record = { high: 'Alto', satisfactory: 'satisfactoria', unsatisfactory: 'insatisfactoria', + benign: 'Benigno', + in_situ: 'Carcinoma in situ', + invasive: 'Carcinoma invasor', + cancer: 'Diagnóstico confirmado', + pending_biopsy: 'Pendiente de biopsia', + biopsy_no_result: 'Biopsia sin resultado', + benign_biopsy: 'Biopsia benigna', + ...Object.fromEntries( + ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), + ), }; +/** A follow-up priority's label. */ +export const PRIORITY: Record = { high: 'Alta', medium: 'Media', low: 'Baja' }; export const STRATA: Record = { category: 'Categoría', age_group: 'Grupo de edad', follow_up_status: 'Estatus de seguimiento', result: 'Citología de alto grado', + birads: 'BI-RADS de la mastografía', }; export const name = (value: string) => LABELS[value] ?? value; diff --git a/src/app/indicadores/tab-seguimiento.html b/src/app/indicadores/tab-seguimiento.html new file mode 100644 index 0000000..0873cfc --- /dev/null +++ b/src/app/indicadores/tab-seguimiento.html @@ -0,0 +1,102 @@ +
+ + Fecha de corte + + + + Ventana + + @for (m of [1, 3, 6, 12]; track m) { + {{ m }} {{ m === 1 ? 'mes' : 'meses' }} + } + + + + Estatus + + Todos + @for (s of statuses; track s) { + {{ name(s) }} + } + + + + Por página + + @for (n of [20, 50, 100]; track n) { + {{ n }} + } + + +
+ +@if (error()) { + +} + +
+ + + + + + + + + + + + + @for (row of rows(); track row.patient.id) { + + + + + + + + + } @empty { + + + + } + +
PacienteGrupo de edadMastografíaBiopsiaEstatusPrioridad
+ {{ + row.name ?? row.patient.id!.slice(0, 10) + }} + @if (row.curp) { +
{{ row.curp }}
+ } +
{{ row.ageGroup }}{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }} + @if (row.biopsy; as b) { + {{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }} + } @else { + — + } + {{ name(row.status) }}{{ priority(row.priority) }}
+ {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} +
+
+ +
+ + @if (page()?.total; as total) { + {{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte + {{ applied() }} + } + + + +
diff --git a/src/app/indicadores/tab-seguimiento.ts b/src/app/indicadores/tab-seguimiento.ts new file mode 100644 index 0000000..12ab46c --- /dev/null +++ b/src/app/indicadores/tab-seguimiento.ts @@ -0,0 +1,93 @@ +import { Component, computed, inject, input, 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 { RouterLink } from '@angular/router'; +import type { Bundle } from 'fhir/r4'; +import { Fhir } from '../fhir'; +import { camaRows } from './follow-up'; +import { name, PRIORITY } from './measures'; + +const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy']; + +/** CaMa's follow-up list at a cut-off: patients whose latest mammogram in the window is + * BI-RADS 4 to 6, where their biopsy stands and how soon they should be seen. */ +@Component({ + selector: 'app-tab-seguimiento', + imports: [ + FormsModule, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule, + RouterLink, + ], + templateUrl: './tab-seguimiento.html', + styleUrl: './tab-riesgos.scss', +}) +export class TabSeguimiento { + private readonly fhir = inject(Fhir); + readonly domain = input.required(); + + protected readonly cutoff = signal(''); + protected readonly window = signal(3); + protected readonly status = signal(''); + protected readonly size = signal(20); + private readonly moved = signal(undefined); + + protected readonly statuses = STATUSES; + protected readonly name = name; + protected readonly priority = (code: string) => PRIORITY[code] ?? code; + + private readonly first = resource({ + params: () => ({ + domain: this.domain(), + 'follow-up-window': this.window(), + 'follow-up-cutoff': this.cutoff() || undefined, + 'follow-up-status': this.status() || undefined, + _count: this.size(), + }), + loader: ({ params: { domain, ...params } }) => { + this.moved.set(undefined); + return this.fhir.search(domain, 'Patient', { + ...params, + _revinclude: ['DiagnosticReport:subject'], + '_include:iterate': 'DiagnosticReport:result', + }); + }, + }); + protected readonly loading = signal(false); + protected readonly page = computed(() => this.moved() ?? this.first.value()); + protected readonly applied = computed(() => { + const self = this.page()?.link?.find((l) => l.relation === 'self')?.url; + return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : ''; + }); + protected readonly offset = computed(() => { + const self = this.page()?.link?.find((l) => l.relation === 'self')?.url; + return self ? Number(new URL(self).searchParams.get('_offset') ?? 0) : 0; + }); + protected readonly rows = computed(() => { + const page = this.page(); + const cutoff = this.applied(); + return page && cutoff ? camaRows(page, cutoff) : []; + }); + protected readonly error = computed(() => this.first.error()); + + protected has(relation: 'next' | 'previous'): boolean { + return !!this.page()?.link?.some((l) => l.relation === relation); + } + + protected async go(relation: 'next' | 'previous'): Promise { + const page = this.page(); + const next = page && this.fhir.follow(this.domain(), page, relation); + if (!next) return; + this.loading.set(true); + try { + this.moved.set(await next); + } finally { + this.loading.set(false); + } + } +}