CaMa indicators and follow-up list, model governance page

This commit is contained in:
Roberto Treviño
2026-11-25 23:20:52 -06:00
parent 9b02641804
commit 53a6393cb2
19 changed files with 974 additions and 19 deletions
+22
View File
@@ -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([]);
});
+81 -9
View File
@@ -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-<outcome>",
"in": "query",
"name": "_sort",
"required": false,
"schema": {
"default": "-recent",
"description": "one of ('-recent', '-risk-cin2', '-risk-cancer'); the list only",
"description": "-recent or -risk-<outcome>",
"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": [
{
+3 -3
View File
@@ -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-<outcome>
*/
'_sort'?: string;
/**
* years
*/
'risk-horizon'?: number;
'risk-horizon'?: (number | null);
/**
* any of ('DiagnosticReport:subject', 'RiskAssessment:subject', 'Observation:subject')
+38
View File
@@ -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<StrictHttpResponse<any>> {
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<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
readReport$Any.PATH = '/models/{domain}/{name}/versions/{version}/reports/{report}';
+38
View File
@@ -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<StrictHttpResponse<any>> {
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<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
readReport$Json.PATH = '/models/{domain}/{name}/versions/{version}/reports/{report}';
+4
View File
@@ -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';
+1
View File
@@ -26,6 +26,7 @@
<a routerLink="/indicadores/cacu" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
<a routerLink="/gobernanza" routerLinkActive="active">Gobernanza</a>
</nav>
</header>
+5
View File
@@ -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' },
];
+19
View File
@@ -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([]);
});
});
+144
View File
@@ -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<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
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<string, any>,
): { 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 [];
}
}
+116
View File
@@ -0,0 +1,116 @@
<section class="page">
<h1>Gobernanza de modelos</h1>
<nav class="domains" aria-label="Dominios">
@for (d of domains.value() ?? []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Datos hasta</mat-label>
<input
matInput
type="date"
[ngModel]="asOf()"
(ngModelChange)="asOf.set($event)"
name="asOf"
/>
</mat-form-field>
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button>
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button>
@if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span>
}
</form>
@if (message()) {
<p class="muted" role="status">{{ message() }}</p>
}
@if (models.isLoading()) {
<p class="muted">Cargando modelos…</p>
} @else if (!models.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
}
@for (m of models.value() ?? []; track m.name) {
<div class="card model">
<h2>{{ m.name }}</h2>
<table class="plain">
<thead>
<tr>
<th>Versión</th>
<th>Creada</th>
<th>Entrenamiento / prueba</th>
<th>Informes</th>
<th>Validación clínica</th>
<th></th>
</tr>
</thead>
<tbody>
@for (v of m.versions; track v.version) {
<tr>
<td>
v{{ v.version }}
@if (champion(v)) {
<span class="badge">en producción</span>
}
</td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num">
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td>
@for (r of v.reports; track r) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
reportNames[r] ?? r
}}</a>
}
@if (v.reports.includes('interpretability')) {
<button
mat-button
type="button"
(click)="chosen.set({ name: m.name, version: v.version })"
>
Ver gráficas
</button>
}
</td>
<td>
@if (!v.reports.includes('clinical_validation')) {
<input
type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
(change)="upload(m.name, v.version, $event)"
/>
} @else {
Agregada
}
</td>
<td>
@if (!champion(v)) {
<button mat-stroked-button type="button" (click)="promote(m.name, v.version)">
Promover
</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
@if (chosen(); as c) {
<div class="card">
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" />
} @empty {
<p class="muted">
{{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }}
</p>
}
</div>
}
</section>
+47
View File
@@ -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;
}
+133
View File
@@ -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<string, string> = {
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<string>();
protected readonly labels = DOMAINS as Record<string, string>;
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<string, unknown>) : [];
});
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<void> {
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<void> {
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<void> {
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);
}
}
+75 -3
View File
@@ -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<DiagnosticReport>(page, 'DiagnosticReport');
const observations = new Map(resources<Observation>(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<Patient>(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),
},
};
});
}
+16 -4
View File
@@ -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: `
<section class="page">
<h1>{{ title() }}</h1>
@@ -34,12 +42,18 @@ import { TabTrazabilidad } from './tab-trazabilidad';
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
</ng-template>
</mat-tab>
@if (patients()) {
@if (domain() === 'cacu') {
<mat-tab label="Análisis de riesgos">
<ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" />
</ng-template>
</mat-tab>
} @else if (domain() === 'cama') {
<mat-tab label="Seguimiento">
<ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" />
</ng-template>
</mat-tab>
}
<mat-tab label="Datos y definiciones">
<ng-template matTabContent>
@@ -80,6 +94,4 @@ export class Indicadores {
loader: async ({ params }) =>
resources<Measure>(await this.fhir.all(params, 'Measure'), 'Measure'),
});
/** Patient-level analysis is served for CaCu only (so far). */
protected readonly patients = computed(() => this.domain() === 'cacu');
}
+24
View File
@@ -44,4 +44,28 @@ export const LAYOUTS: Record<string, Layout> = {
],
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',
},
};
+13
View File
@@ -99,12 +99,25 @@ const LABELS: Record<string, string> = {
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<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
export const STRATA: Record<string, string> = {
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;
+102
View File
@@ -0,0 +1,102 @@
<form class="filters card" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
matInput
type="date"
[ngModel]="cutoff() || applied()"
(ngModelChange)="cutoff.set($event)"
name="cutoff"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@for (m of [1, 3, 6, 12]; track m) {
<mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option>
@for (s of statuses; track s) {
<mat-option [value]="s">{{ name(s) }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label>
<mat-select [value]="size()" (selectionChange)="size.set($event.value)">
@for (n of [20, 50, 100]; track n) {
<mat-option [value]="n">{{ n }}</mat-option>
}
</mat-select>
</mat-form-field>
</form>
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
}
<div class="table-wrap card">
<table class="plain worklist">
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Mastografía</th>
<th>Biopsia</th>
<th>Estatus</th>
<th>Prioridad</th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
row.name ?? row.patient.id!.slice(0, 10)
}}</a>
@if (row.curp) {
<div class="muted curp">{{ row.curp }}</div>
}
</td>
<td>{{ row.ageGroup }}</td>
<td>{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }}</td>
<td>
@if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }}
} @else {
—
}
</td>
<td>{{ name(row.status) }}</td>
<td>{{ priority(row.priority) }}</td>
</tr>
} @empty {
<tr>
<td colspan="6" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte
{{ applied() }}
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
Anterior
</button>
<button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()">
Siguiente
</button>
</div>
+93
View File
@@ -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<string>();
protected readonly cutoff = signal<string>('');
protected readonly window = signal(3);
protected readonly status = signal<string>('');
protected readonly size = signal(20);
private readonly moved = signal<Bundle | undefined>(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<void> {
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);
}
}
}