Compare commits

...

18 Commits

Author SHA1 Message Date
Roberto Treviño ac1d8fc4fa Records show the server's names for coded results; risk lists say empty only once loaded 2026-11-29 06:43:10 -06:00
Roberto Treviño d09e8c59ed Proxy waits up to two minutes for the API 2026-11-29 01:32:09 -06:00
Roberto Treviño 4a8e2e22bd Name breast recurrences in Revisión 2026-11-29 01:06:40 -06:00
Roberto Treviño 1655d464e1 Regenerate the API client for breast recurrences 2026-11-28 23:05:21 -06:00
Roberto Treviño e275782198 Recurrence scenarios leave Gobernanza: the record draws them 2026-11-28 21:30:01 -06:00
Roberto Treviño 133092f8c8 Record: Relación con el ADOS-2 and Análisis de recurrencia; Gobernanza draws the association 2026-11-28 21:28:42 -06:00
Roberto Treviño 6ea54d6e6d Trazabilidad, Datos y definiciones and the risk lists as the old app: declared panels, old labels and order; page tests against the capture 2026-11-28 17:24:29 -06:00
Roberto Treviño cbec0d431e Governance figures spec: scenarios are drawn by the record 2026-11-28 17:16:25 -06:00
Roberto Treviño fd19fdaefa TEA record: Zonas más afectadas (head map and zones by deviation); survival scenarios leave Gobernanza 2026-11-28 17:15:43 -06:00
Roberto Treviño 20e26b847a Wizard page test waits for the cancelled dialog to close before saving 2026-11-28 16:05:21 -06:00
Roberto Treviño 37444a25a1 TEA record: ADOS-2 by item, EEG quality and its alterations against the age norm; page tests follow the cards' and dialog's words 2026-11-28 13:29:23 -06:00
Roberto Treviño cb0403affb TEA Análisis de Riesgo as the old page: its filters, the EEG summary of the filtered children and their list; the domain's full name; reports that fail to load can be retried 2026-11-28 10:47:22 -06:00
Roberto Treviño aeb2d4ec84 TEA Indicadores as the old page: the period summary in words, the three timeliness boxes, counts and age-group figures; tab named Resumen 2026-11-28 10:26:24 -06:00
Roberto Treviño 3e096dd03f CaMa Indicadores as the old page: its cards, timeliness boxes with pending ones, BI-RADS 4–6 donuts, malignancy by BI-RADS and the biopsy donut, the confirmation card; page definitions apart from figure builders 2026-11-28 10:09:30 -06:00
Roberto Treviño 9a15ac6fcb CaCu Indicadores as the old page: its cards and words, the route, cytology and biopsy donuts, results by clinical scenario, confirmation rates; the page test compares with the capture; the guard injects before it waits 2026-11-28 10:03:31 -06:00
Roberto Treviño 198aae59da Conectar dialog by kind of source; plain-language canvas; login page and guard; loading indicators as the old app; survival curves of her clinical scenarios in the CaMa record 2026-11-28 09:30:00 -06:00
Roberto Treviño cc22840c3c Client for otherwise routes and unrecognised documents 2026-11-27 19:17:49 -06:00
Roberto Treviño 672091d19a Client for extract fields taken from columns 2026-11-27 16:25:01 -06:00
98 changed files with 7700 additions and 356 deletions
+175 -8
View File
@@ -1,3 +1,4 @@
import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test';
/** Every page loads from the API with no failed request and no console error. */
@@ -9,6 +10,32 @@ function watch(page: Page): string[] {
return problems;
}
// The pages show only to someone signed in (the API itself answers everyone).
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
});
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
await page.goto('/conectar');
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page).toHaveURL(/\/conectar$/);
await page.getByRole('button', { name: 'Cuenta' }).click();
await page.getByRole('menuitem', { name: 'Salir' }).click();
await expect(page).toHaveURL(/\/login/);
await page.close();
});
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page,
}) => {
@@ -24,7 +51,10 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population',
).count;
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(String(count));
// the card says it as the old one did: "<n> pacientes"
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
`${count.toLocaleString('es-MX')} pacientes`,
);
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
@@ -54,13 +84,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).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.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
expect(problems).toEqual([]);
});
@@ -71,13 +101,13 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible();
await page.getByText('Fuente · Patients').click();
await expect(page.locator('formly-form')).toBeVisible();
await page.getByText('Fuente de datos · Patients').click();
await expect(page.locator('formly-form')).toBeVisible(); // drawn by hand: its raw form
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Mapear · cytology', { exact: true }).click();
await expect(page.getByText('Códigos del sitio')).toBeVisible();
await page.getByText('Traducir códigos · cytology', { exact: true }).click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect
.poll(() =>
page
@@ -90,7 +120,9 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
expect(problems).toEqual([]);
});
test('revision: what the hospital source holds, and a decision through the page', async ({ page }) => {
test('revision: what the hospital source holds, and a decision through the page', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click();
@@ -116,3 +148,138 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
await expect(page.getByText('No se promovió')).toContainText('clinical_validation');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
});
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
page,
}) => {
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
const problems = watch(page);
await page.goto('/conectar');
await page.getByLabel('Nueva canalización').fill('asistente');
await page.getByLabel('Nueva canalización').press('Enter');
await page.getByRole('button', { name: 'Fuente de datos' }).click();
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
await page.locator('[data-type="sqlserver"]').click();
await page.locator('[data-field="host"]').fill(site.hostname);
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
await page.locator('mat-select[data-field="table"]').click();
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.getByText('Fuente de datos · Resultados')).toBeVisible();
// A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it');
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
await page.getByRole('button', { name: 'Cancelar' }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
expect(problems).toEqual([]);
});
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
* opportunity section on, in order, and the kind of each plot (its traces' types). */
function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const old = captured(domain);
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ server {
root /usr/share/nginx/html;
location /api/ {
proxy_pass http://api:8000/;
proxy_read_timeout 30s;
proxy_read_timeout 120s;
}
location / {
try_files $uri $uri/ /index.html;
+1922 -57
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
/* 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 { Login } from '../../models/login';
export interface AuthCookieLogin$Params {
body: Login
}
export function authCookieLogin(http: HttpClient, rootUrl: string, params: AuthCookieLogin$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, authCookieLogin.PATH, 'post');
if (params) {
rb.body(params.body, 'application/x-www-form-urlencoded');
}
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>;
})
);
}
authCookieLogin.PATH = '/auth/login';
+29
View File
@@ -0,0 +1,29 @@
/* 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';
export interface AuthCookieLogout$Params {
}
export function authCookieLogout(http: HttpClient, rootUrl: string, params?: AuthCookieLogout$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, authCookieLogout.PATH, 'post');
if (params) {
}
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>;
})
);
}
authCookieLogout.PATH = '/auth/logout';
+32
View File
@@ -0,0 +1,32 @@
/* 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 { Browsed } from '../../models/browsed';
export interface Browse$Params {
path?: (string | null);
}
export function browse(http: HttpClient, rootUrl: string, params?: Browse$Params, context?: HttpContext): Observable<StrictHttpResponse<Browsed>> {
const rb = new RequestBuilder(rootUrl, browse.PATH, 'get');
if (params) {
rb.query('path', params.path, {});
}
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<Browsed>;
})
);
}
browse.PATH = '/ingest/sources/browse';
+34
View File
@@ -0,0 +1,34 @@
/* 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 { SignIn } from '../../models/sign-in';
export interface OauthStart$Params {
provider: string;
origin: string;
}
export function oauthStart(http: HttpClient, rootUrl: string, params: OauthStart$Params, context?: HttpContext): Observable<StrictHttpResponse<SignIn>> {
const rb = new RequestBuilder(rootUrl, oauthStart.PATH, 'get');
if (params) {
rb.path('provider', params.provider, {});
rb.query('origin', params.origin, {});
}
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<SignIn>;
})
);
}
oauthStart.PATH = '/ingest/sources/oauth/{provider}/start';
+30
View File
@@ -0,0 +1,30 @@
/* 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 { Catalog } from '../../models/catalog';
export interface SourceTypes$Params {
}
export function sourceTypes(http: HttpClient, rootUrl: string, params?: SourceTypes$Params, context?: HttpContext): Observable<StrictHttpResponse<Catalog>> {
const rb = new RequestBuilder(rootUrl, sourceTypes.PATH, 'get');
if (params) {
}
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<Catalog>;
})
);
}
sourceTypes.PATH = '/ingest/sources/types';
+35
View File
@@ -0,0 +1,35 @@
/* 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 { Answers } from '../../models/answers';
import { Tested } from '../../models/tested';
export interface TestSource$Params {
limit?: number;
body: Answers
}
export function testSource(http: HttpClient, rootUrl: string, params: TestSource$Params, context?: HttpContext): Observable<StrictHttpResponse<Tested>> {
const rb = new RequestBuilder(rootUrl, testSource.PATH, 'post');
if (params) {
rb.query('limit', params.limit, {});
rb.body(params.body, 'application/json');
}
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<Tested>;
})
);
}
testSource.PATH = '/ingest/sources/test';
+3 -6
View File
@@ -8,14 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { BodyUpload } from '../../models/body-upload';
import { Uploaded } from '../../models/uploaded';
export interface Upload$Params {
body: BodyUpload
}
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<Uploaded>> {
const rb = new RequestBuilder(rootUrl, upload.PATH, 'post');
if (params) {
rb.body(params.body, 'multipart/form-data');
@@ -26,9 +25,7 @@ export function upload(http: HttpClient, rootUrl: string, params: Upload$Params,
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
return r as StrictHttpResponse<Uploaded>;
})
);
}
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+35
View File
@@ -0,0 +1,35 @@
/* 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';
export interface Unrecognised$Params {
pipeline: string;
}
export function unrecognised(http: HttpClient, rootUrl: string, params: Unrecognised$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
[key: string]: any;
}>>> {
const rb = new RequestBuilder(rootUrl, unrecognised.PATH, 'get');
if (params) {
rb.query('pipeline', params.pipeline, {});
}
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<Array<{
[key: string]: any;
}>>;
})
);
}
unrecognised.PATH = '/review/unrecognised';
+33
View File
@@ -0,0 +1,33 @@
/* 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 { UserCreate } from '../../models/user-create';
import { UserRead } from '../../models/user-read';
export interface RegisterRegister$Params {
body: UserCreate
}
export function registerRegister(http: HttpClient, rootUrl: string, params: RegisterRegister$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, registerRegister.PATH, 'post');
if (params) {
rb.body(params.body, 'application/json');
}
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<UserRead>;
})
);
}
registerRegister.PATH = '/users/register';
@@ -0,0 +1,30 @@
/* 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 { UserRead } from '../../models/user-read';
export interface UsersCurrentUser$Params {
}
export function usersCurrentUser(http: HttpClient, rootUrl: string, params?: UsersCurrentUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersCurrentUser.PATH, 'get');
if (params) {
}
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<UserRead>;
})
);
}
usersCurrentUser.PATH = '/users/me';
+31
View File
@@ -0,0 +1,31 @@
/* 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';
export interface UsersDeleteUser$Params {
id: string;
}
export function usersDeleteUser(http: HttpClient, rootUrl: string, params: UsersDeleteUser$Params, context?: HttpContext): Observable<StrictHttpResponse<void>> {
const rb = new RequestBuilder(rootUrl, usersDeleteUser.PATH, 'delete');
if (params) {
rb.path('id', params.id, {});
}
return http.request(
rb.build({ responseType: 'text', accept: '*/*', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return (r as HttpResponse<any>).clone({ body: undefined }) as StrictHttpResponse<void>;
})
);
}
usersDeleteUser.PATH = '/users/{id}';
@@ -0,0 +1,33 @@
/* 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 { UserRead } from '../../models/user-read';
import { UserUpdate } from '../../models/user-update';
export interface UsersPatchCurrentUser$Params {
body: UserUpdate
}
export function usersPatchCurrentUser(http: HttpClient, rootUrl: string, params: UsersPatchCurrentUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersPatchCurrentUser.PATH, 'patch');
if (params) {
rb.body(params.body, 'application/json');
}
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<UserRead>;
})
);
}
usersPatchCurrentUser.PATH = '/users/me';
+35
View File
@@ -0,0 +1,35 @@
/* 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 { UserRead } from '../../models/user-read';
import { UserUpdate } from '../../models/user-update';
export interface UsersPatchUser$Params {
id: string;
body: UserUpdate
}
export function usersPatchUser(http: HttpClient, rootUrl: string, params: UsersPatchUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersPatchUser.PATH, 'patch');
if (params) {
rb.path('id', params.id, {});
rb.body(params.body, 'application/json');
}
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<UserRead>;
})
);
}
usersPatchUser.PATH = '/users/{id}';
+32
View File
@@ -0,0 +1,32 @@
/* 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 { UserRead } from '../../models/user-read';
export interface UsersUser$Params {
id: string;
}
export function usersUser(http: HttpClient, rootUrl: string, params: UsersUser$Params, context?: HttpContext): Observable<StrictHttpResponse<UserRead>> {
const rb = new RequestBuilder(rootUrl, usersUser.PATH, 'get');
if (params) {
rb.path('id', params.id, {});
}
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<UserRead>;
})
);
}
usersUser.PATH = '/users/{id}';
+26
View File
@@ -1,6 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth/auth-cookie-login';
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
@@ -23,10 +27,18 @@ export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
export { startRun as startRun } from './fn/ingest/start-run';
export type { Schema$Params as Schema$Params } from './fn/ingest/schema';
export { schema as schema } from './fn/ingest/schema';
export type { Browse$Params as Browse$Params } from './fn/ingest/browse';
export { browse as browse } from './fn/ingest/browse';
export type { OauthStart$Params as OauthStart$Params } from './fn/ingest/oauth-start';
export { oauthStart as oauthStart } from './fn/ingest/oauth-start';
export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
export { sourcePreview as sourcePreview } from './fn/ingest/source-preview';
export type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
export { sourceResources as sourceResources } from './fn/ingest/source-resources';
export type { TestSource$Params as TestSource$Params } from './fn/ingest/test-source';
export { testSource as testSource } from './fn/ingest/test-source';
export type { SourceTypes$Params as SourceTypes$Params } from './fn/ingest/source-types';
export { sourceTypes as sourceTypes } from './fn/ingest/source-types';
export type { Upload$Params as Upload$Params } from './fn/ingest/upload';
export { upload as upload } from './fn/ingest/upload';
export type { Models$Params as Models$Params } from './fn/models/models';
@@ -59,12 +71,26 @@ export type { DecidePersons$Params as DecidePersons$Params } from './fn/review/d
export { decidePersons as decidePersons } from './fn/review/decide-persons';
export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject';
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies';
export type { Study$Params as Study$Params } from './fn/eeg/study';
export { study as study } from './fn/eeg/study';
export type { UsersCurrentUser$Params as UsersCurrentUser$Params } from './fn/users/users-current-user';
export { usersCurrentUser as usersCurrentUser } from './fn/users/users-current-user';
export type { UsersPatchCurrentUser$Params as UsersPatchCurrentUser$Params } from './fn/users/users-patch-current-user';
export { usersPatchCurrentUser as usersPatchCurrentUser } from './fn/users/users-patch-current-user';
export type { RegisterRegister$Params as RegisterRegister$Params } from './fn/users/register-register';
export { registerRegister as registerRegister } from './fn/users/register-register';
export type { UsersUser$Params as UsersUser$Params } from './fn/users/users-user';
export { usersUser as usersUser } from './fn/users/users-user';
export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/users/users-delete-user';
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
+21
View File
@@ -2,30 +2,51 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Analysis } from './models/analysis';
export type { Answers } from './models/answers';
export type { BodyAddClinicalValidation } from './models/body-add-clinical-validation';
export type { BodyUpload } from './models/body-upload';
export type { Browsed } from './models/browsed';
export type { Catalog } from './models/catalog';
export type { Condition } from './models/condition';
export type { Correction } from './models/correction';
export type { Domain } from './models/domain';
export type { Entry } from './models/entry';
export type { ErrorModel } from './models/error-model';
export type { Extract } from './models/extract';
export type { Fhir } from './models/fhir';
export type { FieldSpec } from './models/field-spec';
export type { Group } from './models/group';
export type { Guided } from './models/guided';
export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join';
export type { Link } from './models/link';
export type { Listing } from './models/listing';
export type { Login } from './models/login';
export type { Map } from './models/map';
export type { Metric } from './models/metric';
export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
export type { Position } from './models/position';
export type { Provider } from './models/provider';
export type { Read } from './models/read';
export type { Rejection } from './models/rejection';
export type { Relation } from './models/relation';
export type { Route } from './models/route';
export type { RunRequest } from './models/run-request';
export type { SavedPipeline } from './models/saved-pipeline';
export type { SignIn } from './models/sign-in';
export type { Site } from './models/site';
export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type';
export type { Study } from './models/study';
export type { Target } from './models/target';
export type { Tested } from './models/tested';
export type { Training } from './models/training';
export type { Uploaded } from './models/uploaded';
export type { UserCreate } from './models/user-create';
export type { UserRead } from './models/user-read';
export type { UserUpdate } from './models/user-update';
export type { ValidationError } from './models/validation-error';
export type { Version } from './models/version';
+2
View File
@@ -2,10 +2,12 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Metric } from '../models/metric';
import { Relation } from '../models/relation';
export interface Analysis {
age_months: (number | null);
id: string;
level: (string | null);
metrics: Array<Metric>;
relation?: Array<Relation>;
valid: (boolean | null);
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Answers {
answers?: {
[key: string]: any;
};
node?: (string | null);
pipeline?: (string | null);
type: string;
}
+2 -1
View File
@@ -2,5 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUpload {
file: string;
files: Array<string>;
folder?: (string | null);
}
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Entry } from '../models/entry';
export interface Browsed {
entries: Array<Entry>;
parent: (string | null);
path: (string | null);
}
+19
View File
@@ -0,0 +1,19 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Group } from '../models/group';
import { Option } from '../models/option';
import { Provider } from '../models/provider';
import { SourceType } from '../models/source-type';
export interface Catalog {
formats: Array<Option>;
groups: {
[key: string]: Group;
};
providers: {
[key: string]: Provider;
};
types: {
[key: string]: SourceType;
};
}
+8
View File
@@ -2,7 +2,15 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Condition {
/**
* Por ejemplo «text», el texto leído del documento.
*/
column: string;
op: 'equals' | 'contains' | 'matches' | 'present';
/**
* Lo que se busca; por ejemplo «citología».
*/
value?: string;
}
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
+9
View File
@@ -0,0 +1,9 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Entry {
kind: 'folder' | 'file';
name: string;
path: string;
size?: (number | null);
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface ErrorModel {
detail: (string | {
[key: string]: string;
});
}
+24 -1
View File
@@ -13,17 +13,40 @@ import { Position } from '../models/position';
*/
export interface Extract {
column: (string | Array<string>);
/**
* Dato → columna, sin leer el texto.
*/
columns?: {
[key: string]: string;
};
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
/**
* Para el modelo de lenguaje.
*/
hints?: string;
id: string;
inputs?: Array<string>;
kind?: 'extract';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
method?: 'auto' | 'llm' | 'patterns';
/**
* Dato → expresión con un grupo ( ).
*/
patterns?: {
[key: string]: string;
};
+5 -1
View File
@@ -11,10 +11,14 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'fhir';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+15
View File
@@ -0,0 +1,15 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Option } from '../models/option';
export interface FieldSpec {
advanced?: boolean;
default?: any;
help?: string;
label: string;
options?: Array<Option>;
placeholder?: string;
provider?: (string | null);
required?: boolean;
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format';
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Group {
description: string;
title: string;
}
+14
View File
@@ -0,0 +1,14 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* How the Conectar dialog drew a source: its type (core.sources) and the answers given.
* The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none.
*/
export interface Guided {
answers?: {
[key: string]: any;
};
type: string;
}
+8
View File
@@ -11,7 +11,15 @@ export interface Join {
id: string;
inputs?: Array<string>;
kind?: 'join';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
/**
* Pares [columna izquierda, derecha].
*/
on: Array<[string, string]>;
position?: (Position | null);
}
+12
View File
@@ -16,8 +16,20 @@ export interface Link {
id: string;
inputs?: Array<string>;
kind?: 'link';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Parecidos por encima de esto los ve un revisor.
*/
review?: number;
/**
* Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).
*/
rules?: Array<string>;
}
+15
View File
@@ -0,0 +1,15 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* What "Probar conexión" shows: a database's tables (the resources of `source`, built
* from `args`), or the first rows the type's own node reads (files, records).
*/
export interface Listing {
args?: {
[key: string]: any;
};
kind: 'tables' | 'rows';
source?: (string | null);
}
+11
View File
@@ -0,0 +1,11 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Login {
client_id?: (string | null);
client_secret?: (string | null);
grant_type?: (string | null);
password: string;
scope?: string;
username: string;
}
+20
View File
@@ -8,18 +8,38 @@ import { Position } from '../models/position';
* (core.concept_map), and its date formats.
*/
export interface Map {
/**
* La tabla de códigos del sitio.
*/
concept_map?: (string | null);
/**
* Dato de la plataforma → columna del sitio.
*/
fields: {
[key: string]: string;
};
/**
* Por ejemplo %d/%m/%Y.
*/
formats?: {
[key: string]: string;
};
id: string;
inputs?: Array<string>;
kind?: 'map';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Un dato igual para todas las filas.
*/
values?: {
[key: string]: string;
};
+6
View File
@@ -1,10 +1,16 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric {
code: string;
electrodes?: Array<Site>;
median?: (number | null);
model: (string | null);
outside: (number | null);
p5?: (number | null);
p95?: (number | null);
value: number;
z: (number | null);
zones?: Array<Site>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Option {
label: string;
value: any;
}
+17
View File
@@ -0,0 +1,17 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* A sign-in button's OAuth 2.0 provider (authorization code flow).
*/
export interface Provider {
authorize_params?: {
[key: string]: string;
};
authorize_url: string;
env: string;
scope: string;
title: string;
token_url: string;
}
+8
View File
@@ -7,10 +7,18 @@ import { Position } from '../models/position';
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
*/
export interface Read {
/**
* Donde la entrada trae cada documento.
*/
column: string;
id: string;
inputs?: Array<string>;
kind?: 'read';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
+25
View File
@@ -0,0 +1,25 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
+13 -2
View File
@@ -5,13 +5,24 @@ import { Condition } from '../models/condition';
import { Position } from '../models/position';
/**
* Only the rows where every condition holds (e.g. reports titled "Citología").
* Only the rows where every condition holds (e.g. reports titled "Citología"). An
* `otherwise` route takes the rows of its input that none of the other routes on that
* input take (documents nobody recognises, for a reviewer), then its own conditions.
*/
export interface Route {
id: string;
inputs?: Array<string>;
kind?: 'route';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
/**
* Recoge lo que nadie reconoce, para revisarlo.
*/
otherwise?: boolean;
position?: (Position | null);
when: Array<Condition>;
when?: Array<Condition>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface SignIn {
state: string;
url: string;
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Site {
site: string;
value: number;
z: (number | null);
}
+22
View File
@@ -0,0 +1,22 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { FieldSpec } from '../models/field-spec';
import { Listing } from '../models/listing';
export interface SourceType {
args?: {
[key: string]: any;
};
description: string;
fields: {
[key: string]: FieldSpec;
};
group: string;
icon: string;
listing?: (Listing | null);
primary_key?: Array<string>;
resource?: (string | null);
source: string;
then?: (string | null);
title: string;
}
+26
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Guided } from '../models/guided';
import { Position } from '../models/position';
/**
@@ -8,16 +9,41 @@ import { Position } from '../models/position';
* own primary key or `primary_key`; replaced whole when it has none.
*/
export interface Source {
/**
* Los de la fuente dlt.
*/
args?: {
[key: string]: any;
};
guided?: (Guided | null);
id: string;
inputs?: Array<string>;
kind?: 'source';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
/**
* Columnas que identifican una fila.
*/
primary_key?: Array<string>;
/**
* Cuál, si la fuente ofrece varios (una tabla).
*/
resource?: (string | null);
/**
* Módulo:función de la fuente dlt.
*/
source: string;
/**
* Transformador dlt para los archivos.
*/
then?: (string | null);
}
+9 -1
View File
@@ -8,10 +8,18 @@ import { Position } from '../models/position';
* one `link` node among the inputs. Rule breaks are held for review.
*/
export interface Target {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
/**
* En qué estudio de la plataforma se guarda.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'target';
/**
* Cómo se ve en el diagrama.
*/
label?: string;
position?: (Position | null);
}
+12
View File
@@ -0,0 +1,12 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Tested {
detail?: (string | null);
message: string;
ok: boolean;
rows?: Array<{
[key: string]: any;
}>;
tables?: Array<string>;
}
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Uploaded {
bucket_url: string;
files: Array<string>;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserCreate {
domains?: Array<Domain>;
email: string;
is_active?: (boolean | null);
is_superuser?: (boolean | null);
is_verified?: (boolean | null);
name?: string;
password: string;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserRead {
domains?: Array<Domain>;
email: string;
id: string;
is_active?: boolean;
is_superuser?: boolean;
is_verified?: boolean;
name?: string;
}
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from '../models/domain';
export interface UserUpdate {
domains?: (Array<Domain> | null);
email?: (string | null);
is_active?: (boolean | null);
is_superuser?: (boolean | null);
is_verified?: (boolean | null);
name?: (string | null);
password?: (string | null);
}
+17 -6
View File
@@ -22,12 +22,23 @@
} @else {
<span class="title"></span>
}
<nav class="sections" aria-label="Secciones">
<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>
@if (!onLogin()) {
<nav class="sections" aria-label="Secciones">
<a [routerLink]="home()" 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>
@if (auth.user(); as u) {
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
<mat-icon>account_circle</mat-icon> {{ u.name || u.email }}
</button>
<mat-menu #account="matMenu">
<span class="who" mat-menu-item disabled>{{ u.email }}</span>
<button mat-menu-item (click)="logout()"><mat-icon>logout</mat-icon> Salir</button>
</mat-menu>
}
}
</header>
<main class="main">
+32 -15
View File
@@ -1,21 +1,38 @@
import { Routes } from '@angular/router';
import { domainAllowed, signedIn } from './auth/auth';
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{ path: 'login', loadComponent: () => import('./auth/login').then((m) => m.Login) },
{
path: 'indicadores/:domain',
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
path: '',
canActivateChild: [signedIn],
children: [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{
path: 'indicadores/:domain',
canActivate: [domainAllowed],
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
},
{
path: 'indicadores/:domain/pacientes/:id',
canActivate: [domainAllowed],
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
},
{
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',
canActivate: [domainAllowed],
loadComponent: () => import('./gobernanza/gobernanza').then((m) => m.Gobernanza),
},
{ path: '**', redirectTo: 'indicadores/cacu' },
],
},
{
path: 'indicadores/:domain/pacientes/:id',
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
},
{ 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' },
];
+5
View File
@@ -72,3 +72,8 @@
display: none;
}
}
.user {
color: var(--color-text-secondary);
font-weight: 600;
}
+15 -2
View File
@@ -8,11 +8,12 @@ import { filter, map } from 'rxjs';
import { Api } from './api/api';
import { domains } from './api/fn/operations/domains';
import { Domain } from './api/models/domain';
import { Auth } from './auth/auth';
export const DOMAINS: Record<Domain, string> = {
cacu: 'Cáncer cervicouterino',
cama: 'Cáncer de mama',
tea: 'TEA',
tea: 'Trastorno del espectro autista',
};
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
@@ -32,6 +33,7 @@ export const DOMAINS: Record<Domain, string> = {
export class App {
private readonly api = inject(Api);
private readonly router = inject(Router);
protected readonly auth = inject(Auth);
protected readonly labels = DOMAINS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly url = toSignal(
@@ -46,6 +48,17 @@ export class App {
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined,
);
protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain()),
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
);
/** The sign-in page shows only the brand. */
protected readonly onLogin = computed(() => this.url().startsWith('/login'));
/** Where "Indicadores" goes: the first domain this user may see. */
protected readonly home = computed(
() => `/indicadores/${this.auth.user()?.domains[0] ?? 'cacu'}`,
);
protected async logout(): Promise<void> {
await this.auth.logout();
await this.router.navigateByUrl('/login');
}
}
+82
View File
@@ -0,0 +1,82 @@
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Injectable, computed, inject, signal } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import type { Domain } from '../api/models/domain';
/** Who is signed in, and the domains the app shows them. */
export interface User {
id: string;
email: string;
name: string;
is_superuser: boolean;
domains: Domain[];
}
/** The web app's sign-in (the API's fastapi-users, a session cookie). It decides only what
* the app shows: the API answers without a session. */
@Injectable({ providedIn: 'root' })
export class Auth {
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
/** undefined: not asked yet; null: nobody signed in. */
private readonly current = signal<User | null | undefined>(undefined);
readonly user = this.current.asReadonly();
readonly signedIn = computed(() => !!this.current());
/** Whether the signed-in user may see the domain (an administrator sees every one). */
canSee(domain: string): boolean {
const u = this.current();
return !!u && (u.is_superuser || u.domains.includes(domain as Domain));
}
async load(): Promise<User | null> {
try {
this.current.set(await firstValueFrom(this.http.get<User>(`${this.root}/users/me`)));
} catch {
this.current.set(null);
}
return this.current() ?? null;
}
/** Signs in; a wrong user or password comes back as words for the form. */
async login(email: string, password: string): Promise<string | null> {
const body = new HttpParams().set('username', email.trim()).set('password', password);
try {
await firstValueFrom(this.http.post(`${this.root}/auth/login`, body));
} catch (e) {
if (e instanceof HttpErrorResponse && e.status === 400) {
return 'Usuario o contraseña incorrectos.';
}
return 'No hay conexión con la plataforma. Intente de nuevo.';
}
await this.load();
return null;
}
async logout(): Promise<void> {
try {
await firstValueFrom(this.http.post(`${this.root}/auth/logout`, null));
} finally {
this.current.set(null);
}
}
}
/** Pages show only to someone signed in; the others go to the sign-in page and come back. */
export const signedIn: CanActivateFn = async (_route, state) => {
const auth = inject(Auth);
const router = inject(Router); // before any await: inject works only in the guard's first turn
const user = auth.user() === undefined ? await auth.load() : auth.user();
return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
};
/** A domain's pages show only to whom may see it. */
export const domainAllowed: CanActivateFn = (route) => {
const auth = inject(Auth);
const domain = route.paramMap.get('domain');
if (!domain || auth.canSee(domain)) return true;
const first = auth.user()?.domains[0];
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
};
+49
View File
@@ -0,0 +1,49 @@
<section class="login" aria-labelledby="login-title">
<div class="box">
<img class="logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
<h1 class="title" id="login-title">Inicio de sesión</h1>
<form class="form" (ngSubmit)="enter()" novalidate>
<mat-form-field appearance="outline" class="field" subscriptSizing="dynamic">
<input
matInput
name="email"
[(ngModel)]="email"
placeholder="Usuario"
aria-label="Usuario"
autocomplete="username"
autocapitalize="none"
spellcheck="false"
/>
</mat-form-field>
<mat-form-field appearance="outline" class="field" subscriptSizing="dynamic">
<input
matInput
name="password"
[(ngModel)]="password"
[type]="show() ? 'text' : 'password'"
placeholder="Contraseña"
aria-label="Contraseña"
autocomplete="current-password"
/>
<button
mat-icon-button
matSuffix
type="button"
class="eye"
(click)="show.set(!show())"
[attr.aria-label]="show() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="show()"
>
<mat-icon>{{ show() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</mat-form-field>
@if (error(); as message) {
<p class="error" role="alert">{{ message }}</p>
}
<button type="submit" class="enter" [disabled]="!email.trim() || !password || sending()">
{{ sending() ? 'Ingresando…' : 'Ingresar' }}
</button>
</form>
<p class="legal">©{{ year }} Todos los derechos reservados.</p>
</div>
</section>
+141
View File
@@ -0,0 +1,141 @@
:host {
display: flex;
flex: 1;
min-width: 0;
--login-background: #f8f9fa;
--login-border: #e9ecef;
}
.login {
align-items: center;
display: flex;
flex: 1;
justify-content: center;
padding: 72px 24px 56px;
}
.box {
display: flex;
flex-direction: column;
gap: 16px;
max-width: 340px;
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it. */
.logo {
align-self: center;
animation: logo-in 600ms ease-out both;
display: block;
width: 260px;
}
@keyframes logo-in {
from {
opacity: 0;
transform: translateY(-8px);
}
}
@media (prefers-reduced-motion: reduce) {
.logo {
animation: none;
}
}
/* The title between two rules. */
.title {
align-items: center;
color: var(--color-text);
display: flex;
font-family: var(--font-heading);
font-size: 1.375rem;
font-weight: 600;
gap: 16px;
margin: 0 0 8px;
white-space: nowrap;
&::before,
&::after {
background: var(--color-border);
content: '';
flex: 1;
height: 1px;
}
}
.form {
display: flex;
flex-direction: column;
gap: 12px;
}
.field {
--mat-form-field-container-height: 44px;
--mat-form-field-container-vertical-padding: 12px;
width: 100%;
}
.eye {
color: var(--color-text-secondary);
}
.error {
color: var(--mat-sys-error);
font-size: 0.875rem;
margin: -4px 0 0;
}
/* One column with the fields; its border turns to the action color once the form is complete. */
.enter {
align-items: center;
background: var(--login-background);
border: 1px solid var(--login-border);
border-radius: 10px;
color: var(--color-text-secondary);
cursor: default;
display: flex;
font: inherit;
font-size: 0.9375rem;
font-weight: 500;
justify-content: center;
margin-top: 8px;
min-height: 46px;
transition:
background-color 260ms ease,
border-color 260ms ease,
color 260ms ease;
width: 100%;
&:not(:disabled) {
border-color: var(--color-action);
color: var(--color-text);
cursor: pointer;
}
&:hover:not(:disabled) {
background: var(--color-action-hover);
}
&:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
}
.legal {
color: var(--color-text-secondary);
font-size: 0.8125rem;
margin: 16px 0 0;
text-align: center;
}
@media (max-width: 600px) {
.login {
padding: 48px 16px;
}
.logo {
width: 208px;
}
}
+42
View File
@@ -0,0 +1,42 @@
import { Component, inject, input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { Router } from '@angular/router';
import { Auth } from './auth';
/** "Inicio de sesión": the brand, two fields and one button. */
@Component({
selector: 'app-login',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
templateUrl: './login.html',
styleUrl: './login.scss',
})
export class Login {
private readonly auth = inject(Auth);
private readonly router = inject(Router);
/** Where to go once signed in (the page that asked for it). */
readonly next = input<string>('');
protected email = '';
protected password = '';
protected readonly show = signal(false);
protected readonly sending = signal(false);
protected readonly error = signal('');
protected readonly year = new Date().getFullYear();
protected async enter(): Promise<void> {
if (!this.email.trim() || !this.password || this.sending()) return;
this.sending.set(true);
this.error.set('');
const problem = await this.auth.login(this.email, this.password);
this.sending.set(false);
if (problem) {
this.error.set(problem);
return;
}
const first = this.auth.user()?.domains[0] ?? 'cacu';
await this.router.navigateByUrl(this.next() || `/indicadores/${first}`);
}
}
+33 -7
View File
@@ -29,7 +29,9 @@
</span>
@if (pipelineId()) {
@for (k of kinds; track k[0]) {
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
<button mat-stroked-button (click)="add(k[0])" [matTooltip]="help[k[0]]">
<mat-icon>add</mat-icon>{{ k[1] }}
</button>
}
<span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button>
@@ -70,6 +72,7 @@
<mat-icon>delete</mat-icon>
</button>
</div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
@@ -86,12 +89,35 @@
} @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
@if (guided(d); as g) {
<div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)">
Avanzado (para personal técnico)
</mat-slide-toggle>
} @else if (d.kind === 'source') {
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con ayuda
</button>
}
@if (!guided(d) || advanced()) {
@if (guided(d)) {
<p class="muted">Si cambia algo aquí, la fuente deja de editarse con ayuda.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
}
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
+31
View File
@@ -109,3 +109,34 @@ h2 {
width: auto;
}
}
.help {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.source-summary {
align-items: center;
background: var(--color-background, #f7f8f6);
border: 1px solid var(--color-border);
border-radius: 8px;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
justify-content: space-between;
margin-bottom: var(--space-2);
padding: var(--space-2);
p {
align-items: center;
display: flex;
font-weight: 500;
gap: 6px;
margin: 0;
}
p mat-icon {
color: var(--color-success, #2e7d32);
}
}
+77 -10
View File
@@ -6,7 +6,10 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatDialog } from '@angular/material/dialog';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material';
@@ -24,6 +27,7 @@ import type { Pipeline } from '../api/models/pipeline';
import type { Source } from '../api/models/source';
import { ConceptMapEditor } from './concept-map-editor';
import { FORMLY_TYPES, nodeSchema } from './schema-form';
import { SourceDialog, SourceDialogData, SourceDialogResult } from './source-dialog';
type Doc = Pipeline['nodes'][number];
type Kind = NonNullable<Doc['kind']>;
@@ -47,16 +51,29 @@ function canvasNode(id: string, point: { x: number; y: number }, label: string):
};
}
/** Each step's name and what it does, in the operator's words (the canvas and its panel). */
export const KINDS: Record<Kind, string> = {
source: 'Fuente',
read: 'Leer',
route: 'Filtrar',
map: 'Mapear',
extract: 'Extraer',
fhir: 'FHIR',
join: 'Unir',
link: 'Vincular',
target: 'Destino',
source: 'Fuente de datos',
read: 'Leer documentos',
route: 'Separar por tipo',
map: 'Traducir códigos',
extract: 'Sacar datos',
fhir: 'Leer FHIR',
join: 'Juntar',
link: 'Identificar a la persona',
target: 'Guardar en la plataforma',
};
export const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Saca el texto de cada documento (PDF, Word, escaneos con OCR).',
route:
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Toma de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee paquetes FHIR que un sistema envió y saca de ellos los estudios.',
join: 'Junta dos entradas que hablan de lo mismo; por ejemplo, un resultado con su orden.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.',
};
const ID = /^[a-z][a-z0-9_]*$/;
@@ -73,7 +90,9 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule,
MatInputModule,
MatListModule,
MatSlideToggleModule,
MatTableModule,
MatTooltipModule,
Vflow,
ConceptMapEditor,
],
@@ -85,7 +104,11 @@ const ID = /^[a-z][a-z0-9_]*$/;
export class Conectar {
private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema);
private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP;
/** The raw form of a source drawn with the dialog ("Avanzado"). */
protected readonly advanced = signal(false);
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -158,10 +181,47 @@ export class Conectar {
}
protected add(kind: Kind): void {
if (kind === 'source') {
void this.connectSource();
return;
}
this.place(kind, {});
}
/** "Fuente de datos": the dialog walks the operator through it; editing reopens it. */
protected async connectSource(id?: string): Promise<void> {
const doc = id ? (this.docs().find((d) => d.id === id) as Source | undefined) : undefined;
const data: SourceDialogData = {
pipeline: this.pipelineId(),
node: doc?.id,
guided: doc?.guided ?? null,
label: doc?.label ?? '',
};
const ref = this.dialog.open<SourceDialog, SourceDialogData, SourceDialogResult>(SourceDialog, {
data,
width: '760px',
maxWidth: '96vw',
maxHeight: '92vh',
autoFocus: false,
});
const result = await new Promise<SourceDialogResult | undefined>((done) =>
ref.afterClosed().subscribe(done),
);
if (!result) return;
if (doc) {
this.update(doc.id, (d) => ({ ...d, guided: result.guided, label: result.label }) as Doc);
this.select(doc.id);
} else {
this.place('source', { guided: result.guided, label: result.label });
}
this.message.set('Fuente lista. Guarde la canalización para conservarla.');
}
private place(kind: Kind, fields: Record<string, unknown>): void {
let n = 1;
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
const id = `${kind}_${n}`;
const doc = { id, kind, inputs: [] } as unknown as Doc;
const doc = { id, kind, inputs: [], ...fields } as unknown as Doc;
this.docs.update((ds) => [...ds, doc]);
this.nodes.update((ns) => [
...ns,
@@ -204,6 +264,12 @@ export class Conectar {
);
this.form = new UntypedFormGroup({});
this.preview.set(undefined);
this.advanced.set(false);
}
/** A source the dialog drew (its answers make its dlt fields). */
protected guided(d: Doc): Source['guided'] {
return d.kind === 'source' ? ((d as Source).guided ?? undefined) : undefined;
}
/** The form's values into the selected node. */
@@ -213,6 +279,7 @@ export class Conectar {
const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
);
if (this.advanced()) delete values['guided']; // drawn by hand from here on
this.update(
id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
+369
View File
@@ -0,0 +1,369 @@
@if (!type()) {
<h2 mat-dialog-title>¿Dónde están los datos?</h2>
<mat-dialog-content>
@if (catalog.isLoading()) {
<div class="loading" role="status">
<mat-spinner diameter="32" /> <span>Cargando opciones…</span>
</div>
}
@for (g of groups(); track g.id) {
<section class="group">
<h3>{{ g.title }}</h3>
<p class="hint">{{ g.description }}</p>
<div class="types">
@for (t of g.types; track t.id) {
<button type="button" class="type" (click)="pick(t.id)" [attr.data-type]="t.id">
<mat-icon>{{ icon(t.icon) }}</mat-icon>
<span class="type-title">{{ t.title }}</span>
<span class="type-text">{{ t.description }}</span>
</button>
}
</div>
</section>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Cancelar</button>
</mat-dialog-actions>
} @else {
<h2 mat-dialog-title class="with-icon">
<mat-icon>{{ icon(type()!.icon) }}</mat-icon> {{ type()!.title }}
</h2>
<mat-dialog-content>
<p class="hint">{{ type()!.description }}</p>
<ng-template #field let-name let-f="f">
@switch (f.type === 'server_file' ? 'folder' : f.type) {
@case ('password') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[type]="showPassword()[name] ? 'text' : 'password'"
[ngModel]="isMasked(name) ? '' : text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="isMasked(name) ? 'Guardada (escriba para cambiarla)' : f.placeholder"
[attr.data-field]="name"
autocomplete="off"
/>
<button
mat-icon-button
matSuffix
type="button"
(click)="togglePassword(name)"
[attr.aria-label]="showPassword()[name] ? 'Ocultar' : 'Mostrar'"
>
<mat-icon>{{ showPassword()[name] ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('number') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
type="number"
[ngModel]="text(name)"
(ngModelChange)="setNumber(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('select') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select [ngModel]="value(name)" (ngModelChange)="set(name, $event)">
@for (o of f.options; track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('format') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
>
@for (o of formats(); track o.value) {
<mat-option [value]="o.value">{{ o.label }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@case ('table') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
@if (tables().length) {
<mat-select
[ngModel]="value(name)"
(ngModelChange)="set(name, $event); test()"
[attr.data-field]="name"
>
@for (t of tables(); track t) {
<mat-option [value]="t">{{ t }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
}
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
@case ('folder') {
<div class="picker">
<mat-form-field appearance="outline" class="grow">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
<button mat-stroked-button type="button" (click)="openFolder(name, text(name) || null)">
<mat-icon>folder_open</mat-icon> Examinar…
</button>
</div>
@if (browsing(); as b) {
@if (b.field === name) {
<div class="browser" role="group" aria-label="Carpetas del servidor">
<div class="browser-head">
@if (b.at.path) {
<button
mat-icon-button
type="button"
(click)="openFolder(name, b.at.parent)"
aria-label="Subir"
>
<mat-icon>arrow_upward</mat-icon>
</button>
<code>{{ b.at.path }}</code>
} @else {
<span class="hint">Carpetas habilitadas en el servidor</span>
}
</div>
<ul>
@for (e of b.at.entries; track e.path) {
<li>
@if (e.kind === 'folder') {
<button type="button" class="entry" (click)="openFolder(name, e.path)">
<mat-icon>folder</mat-icon> {{ e.name }}
</button>
} @else if (browsingFiles()) {
<button type="button" class="entry" (click)="chooseFile(e.path)">
<mat-icon>description</mat-icon> {{ e.name }}
</button>
} @else {
<span class="entry file"
><mat-icon>description</mat-icon> {{ e.name }}</span
>
}
</li>
} @empty {
<li class="hint">Vacía.</li>
}
</ul>
<div class="browser-actions">
<button mat-button type="button" (click)="browsing.set(undefined)">Cerrar</button>
@if (!browsingFiles()) {
<button
mat-flat-button
type="button"
[disabled]="!b.at.path"
(click)="chooseFolder()"
>
Elegir esta carpeta
</button>
}
</div>
</div>
}
}
}
@case ('upload') {
<div
class="drop"
(dragover)="$event.preventDefault()"
(drop)="dropped(name, $event)"
[attr.data-field]="name"
>
<mat-icon>cloud_upload</mat-icon>
<p>Arrastre aquí los archivos, o</p>
<div class="drop-buttons">
<button mat-stroked-button type="button" (click)="files.click()">
Elegir archivos
</button>
<button mat-stroked-button type="button" (click)="folder.click()">
Elegir una carpeta
</button>
</div>
<input #files type="file" multiple hidden (change)="upload(name, files.files)" />
<input
#folder
type="file"
webkitdirectory
hidden
(change)="upload(name, folder.files)"
/>
@if (uploading(); as u) {
@if (u.field === name) {
<mat-progress-bar mode="determinate" [value]="u.percent" />
<span class="hint">Subiendo… {{ u.percent }} %</span>
}
}
@if (uploaded()[name]?.length) {
<p class="ok">
<mat-icon>check_circle</mat-icon> {{ uploaded()[name].length }} archivos subidos
</p>
} @else if (text(name)) {
<p class="ok"><mat-icon>check_circle</mat-icon> Archivos ya subidos</p>
}
</div>
}
@case ('oauth') {
<div class="signin">
@if (account(name); as who) {
<p class="ok"><mat-icon>check_circle</mat-icon> Conectado como {{ who }}</p>
<button mat-button type="button" (click)="signIn(name, f.provider)">
Usar otra cuenta
</button>
} @else {
<button mat-flat-button type="button" (click)="signIn(name, f.provider)">
<mat-icon>login</mat-icon>
Iniciar sesión con {{ catalog.value()?.providers?.[f.provider]?.title }}
</button>
}
@if (f.help) {
<p class="hint">{{ f.help }}</p>
}
</div>
}
@default {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<input
matInput
[ngModel]="text(name)"
(ngModelChange)="set(name, $event)"
[placeholder]="f.placeholder"
[attr.data-field]="name"
/>
@if (f.help) {
<mat-hint>{{ f.help }}</mat-hint>
}
</mat-form-field>
}
}
</ng-template>
<div class="fields">
@for (e of fields(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
@if (more().length) {
<mat-expansion-panel class="more">
<mat-expansion-panel-header>Más opciones</mat-expansion-panel-header>
<div class="fields">
@for (e of more(); track e[0]) {
<ng-container *ngTemplateOutlet="field; context: { $implicit: e[0], f: e[1] }" />
}
</div>
</mat-expansion-panel>
}
<div class="test">
<button
mat-stroked-button
type="button"
(click)="test()"
[disabled]="testing() || missing().length > 0"
>
<mat-icon>network_check</mat-icon> Probar conexión
</button>
@if (testing()) {
<mat-spinner diameter="24" /> <span role="status">Conectando…</span>
} @else if (missing().length) {
<span class="hint">Falta: {{ missing().join(', ') }}</span>
}
</div>
@if (problem()) {
<p class="error" role="alert"><mat-icon>error</mat-icon> {{ problem() }}</p>
}
@if (tested(); as t) {
<div class="result" [class.bad]="!t.ok" role="status">
<p>
<mat-icon>{{ t.ok ? 'check_circle' : 'error' }}</mat-icon> {{ t.message }}
</p>
@if (t.detail) {
<details>
<summary>Lo que respondió el sistema</summary>
<pre>{{ t.detail }}</pre>
</details>
}
@if (t.tables?.length) {
<p class="hint">Elija una tabla arriba para ver sus primeras filas.</p>
}
@if (t.rows?.length) {
<p class="hint">
{{
t.rows!.length === 1
? 'La primera fila:'
: 'Las primeras ' + t.rows!.length + ' filas:'
}}
</p>
<div class="rows">
<table mat-table [dataSource]="t.rows!">
@for (c of columns(); track c) {
<ng-container [matColumnDef]="c">
<th mat-header-cell *matHeaderCellDef>{{ c }}</th>
<td mat-cell *matCellDef="let row">{{ cell(row[c]) }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
<tr mat-row *matRowDef="let row; columns: columns()"></tr>
</table>
</div>
}
</div>
}
<mat-form-field appearance="outline" class="full name">
<mat-label>Nombre de esta fuente</mat-label>
<input matInput [ngModel]="label()" (ngModelChange)="label.set($event)" />
<mat-hint>Cómo se verá en el diagrama.</mat-hint>
</mat-form-field>
</mat-dialog-content>
<mat-dialog-actions>
@if (!data.guided) {
<button mat-button type="button" (click)="back()">
<mat-icon>arrow_back</mat-icon> Otro tipo
</button>
}
<span class="spacer"></span>
<button mat-button mat-dialog-close>Cancelar</button>
<button mat-flat-button type="button" (click)="save()" [disabled]="!ready()">Guardar</button>
</mat-dialog-actions>
}
+230
View File
@@ -0,0 +1,230 @@
:host {
display: block;
}
.with-icon {
align-items: center;
display: flex;
gap: var(--space-2);
}
.hint {
color: var(--color-text-secondary);
font-size: 13px;
margin: 0 0 var(--space-2);
}
.loading,
.test {
align-items: center;
display: flex;
gap: var(--space-2);
margin: var(--space-2) 0;
}
.group h3 {
font-size: 15px;
font-weight: 600;
margin: var(--space-3) 0 2px;
}
.types {
display: grid;
gap: var(--space-2);
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
}
.type {
align-items: start;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 10px;
cursor: pointer;
display: grid;
font: inherit;
gap: 2px 10px;
grid-template-columns: auto 1fr;
padding: 12px;
text-align: left;
&:hover,
&:focus-visible {
border-color: var(--color-primary);
box-shadow: 0 0 0 1px var(--color-primary);
}
mat-icon {
color: var(--color-primary);
grid-row: span 2;
}
}
.type-title {
font-weight: 600;
}
.type-text {
color: var(--color-text-secondary);
font-size: 12.5px;
line-height: 1.35;
}
.fields {
display: flex;
flex-direction: column;
gap: 12px;
}
.full,
.grow {
width: 100%;
}
.picker {
align-items: start;
display: flex;
gap: var(--space-2);
.grow {
flex: 1;
}
button {
margin-top: 10px;
}
}
.browser {
border: 1px solid var(--color-border);
border-radius: 8px;
padding: var(--space-2);
ul {
list-style: none;
margin: 0;
max-height: 220px;
overflow-y: auto;
padding: 0;
}
}
.browser-head,
.browser-actions {
align-items: center;
display: flex;
gap: var(--space-2);
}
.browser-actions {
justify-content: flex-end;
}
.entry {
align-items: center;
background: none;
border: 0;
cursor: pointer;
display: flex;
font: inherit;
gap: 6px;
padding: 4px 2px;
text-align: left;
width: 100%;
&.file {
color: var(--color-text-secondary);
cursor: default;
}
&:not(.file):hover {
color: var(--color-primary);
}
}
.drop {
align-items: center;
border: 2px dashed var(--color-border);
border-radius: 10px;
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
padding: var(--space-3);
text-align: center;
mat-progress-bar {
width: 100%;
}
}
.drop-buttons {
display: flex;
gap: var(--space-2);
}
.signin {
display: flex;
flex-direction: column;
gap: var(--space-1, 4px);
align-items: flex-start;
}
.ok,
.error,
.result p {
align-items: center;
display: flex;
gap: 6px;
margin: var(--space-1, 4px) 0;
}
.ok mat-icon,
.result mat-icon {
color: var(--color-success, #2e7d32);
}
.error,
.result.bad p {
color: var(--color-error, #b3261e);
mat-icon {
color: inherit;
}
}
.result {
border: 1px solid var(--color-border);
border-radius: 8px;
margin-top: var(--space-2);
padding: var(--space-2);
pre {
font-size: 12px;
white-space: pre-wrap;
}
}
.rows {
max-height: 260px;
overflow: auto;
td,
th {
font-size: 12px;
max-width: 260px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.more {
margin: var(--space-2) 0;
}
.name {
margin-top: var(--space-3);
}
.spacer {
flex: 1;
}
+349
View File
@@ -0,0 +1,349 @@
import { NgTemplateOutlet } from '@angular/common';
import { HttpClient, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { Component, computed, inject, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTableModule } from '@angular/material/table';
import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration';
import { browse } from '../api/fn/ingest/browse';
import { oauthStart } from '../api/fn/ingest/oauth-start';
import { sourceTypes } from '../api/fn/ingest/source-types';
import { testSource } from '../api/fn/ingest/test-source';
import type { Browsed } from '../api/models/browsed';
import type { FieldSpec } from '../api/models/field-spec';
import type { Guided } from '../api/models/guided';
import type { SourceType } from '../api/models/source-type';
import type { Tested } from '../api/models/tested';
import type { Uploaded } from '../api/models/uploaded';
/** What the dialog is opened with: the source being edited, if any. */
export interface SourceDialogData {
pipeline?: string;
node?: string;
guided?: Guided | null;
label?: string;
}
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult {
guided: Guided;
label: string;
}
/** The catalog's generic icon words, as Material Symbols. */
const ICONS: Record<string, string> = {
database: 'database',
upload: 'upload_file',
folder: 'folder_open',
link: 'link',
'folder-network': 'lan',
server: 'dns',
cloud: 'cloud',
onedrive: 'cloud',
sharepoint: 'groups',
'google-drive': 'add_to_drive',
web: 'api',
fhir: 'local_hospital',
};
const MASK = '********';
/** "Nueva fuente": the operator picks what kind of source the data is in, answers only what
* that kind needs (in plain words, with pickers and sign-in buttons), tests the connection,
* picks a table if there are several, sees the first rows, and saves. No dlt, no JSON. */
@Component({
selector: 'app-source-dialog',
imports: [
FormsModule,
NgTemplateOutlet,
MatButtonModule,
MatDialogModule,
MatExpansionModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSlideToggleModule,
MatTableModule,
],
templateUrl: './source-dialog.html',
styleUrl: './source-dialog.scss',
})
export class SourceDialog {
private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
private readonly ref = inject(MatDialogRef<SourceDialog, SourceDialogResult>);
protected readonly data = inject<SourceDialogData>(MAT_DIALOG_DATA, { optional: true }) ?? {};
protected readonly catalog = resource({ loader: () => this.api.invoke(sourceTypes) });
protected readonly groups = computed(() => {
const c = this.catalog.value();
if (!c) return [];
return Object.entries(c.groups).map(([id, g]) => ({
id,
...g,
types: Object.entries(c.types)
.filter(([, t]) => t.group === id)
.map(([tid, t]) => ({ id: tid, ...t })),
}));
});
protected readonly typeId = signal<string | undefined>(this.data.guided?.type);
protected readonly type = computed<SourceType | undefined>(() => {
const id = this.typeId();
return id ? this.catalog.value()?.types[id] : undefined;
});
protected readonly answers = signal<Record<string, unknown>>({
...(this.data.guided?.answers ?? {}),
});
protected readonly label = signal(this.data.label ?? '');
protected readonly fields = computed(() => entries(this.type()).filter(([, f]) => !f.advanced));
protected readonly more = computed(() => entries(this.type()).filter(([, f]) => f.advanced));
protected readonly showPassword = signal<Record<string, boolean>>({});
protected readonly testing = signal(false);
/** The tables the last listing found: kept while one is picked and its rows shown. */
protected readonly tableList = signal<string[]>([]);
protected readonly tested = signal<Tested | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.tested()?.rows?.[0] ?? {}));
protected readonly browsing = signal<{ field: string; at: Browsed } | undefined>(undefined);
protected readonly uploading = signal<{ field: string; percent: number } | undefined>(undefined);
protected readonly uploaded = signal<Record<string, string[]>>({});
protected readonly problem = signal('');
icon(name: string): string {
return ICONS[name] ?? 'input';
}
protected pick(id: string): void {
const t = this.catalog.value()!.types[id];
this.typeId.set(id);
this.answers.set(
Object.fromEntries(
Object.entries(t.fields)
.filter(([, f]) => f.default !== null && f.default !== undefined)
.map(([k, f]) => [k, f.default]),
),
);
if (!this.label()) this.label.set(t.title);
this.tested.set(undefined);
this.problem.set('');
}
protected back(): void {
this.typeId.set(undefined);
this.tested.set(undefined);
this.problem.set('');
}
protected value(name: string): unknown {
return this.answers()[name];
}
protected text(name: string): string {
const v = this.answers()[name];
return v === null || v === undefined ? '' : String(v);
}
protected set(name: string, value: unknown): void {
this.answers.update((a) => ({ ...a, [name]: value }));
if (this.type()?.fields[name]?.type === 'table') return;
this.tested.set(undefined); // another connection: test again
this.tableList.set([]);
}
protected setNumber(name: string, value: string): void {
this.set(name, value === '' ? null : Number(value));
}
protected togglePassword(name: string): void {
this.showPassword.update((s) => ({ ...s, [name]: !s[name] }));
}
protected isMasked(name: string): boolean {
return this.answers()[name] === MASK;
}
protected formats() {
return this.catalog.value()?.formats ?? [];
}
protected account(name: string): string | undefined {
const a = this.answers()[name] as { user?: string } | undefined;
return a ? (a.user ?? 'cuenta conectada') : undefined;
}
/** "Probar conexión": what the source holds, in plain words. */
protected async test(): Promise<void> {
const type = this.typeId();
if (!type) return;
this.testing.set(true);
this.problem.set('');
try {
const found = await this.api.invoke(testSource, {
limit: 20,
body: {
type,
answers: this.cleaned(),
pipeline: this.data.pipeline,
node: this.data.node,
},
});
this.tested.set(found);
if (found.tables?.length) this.tableList.set(found.tables);
} catch (e) {
this.problem.set(message(e));
} finally {
this.testing.set(false);
}
}
/** The tables a database listed, for its table field. */
protected tables(): string[] {
return this.tableList();
}
/** Server folders, under the roots the operator mounted. */
protected async openFolder(field: string, path?: string | null): Promise<void> {
try {
const at = await this.api.invoke(browse, path ? { path } : {});
this.browsing.set({ field, at });
} catch (e) {
this.problem.set(message(e));
}
}
protected chooseFolder(): void {
const b = this.browsing();
if (b?.at.path) this.set(b.field, b.at.path);
this.browsing.set(undefined);
}
protected chooseFile(path: string): void {
const b = this.browsing();
if (b) this.set(b.field, path);
this.browsing.set(undefined);
}
/** Whether the field being browsed takes a file (else a folder). */
protected readonly browsingFiles = computed(() => {
const b = this.browsing();
return !!b && this.type()?.fields[b.field]?.type === 'server_file';
});
/** Files or a whole folder from this computer, sent with progress; a folder keeps its
* subfolders. More files can be added to the same set. */
protected upload(field: string, list: FileList | null): void {
if (!list?.length) return;
const body = new FormData();
for (const file of Array.from(list)) {
body.append('files', file, file.webkitRelativePath || file.name);
}
const folder = this.answers()[field];
if (typeof folder === 'string' && folder) body.append('folder', folder);
this.uploading.set({ field, percent: 0 });
this.problem.set('');
this.http
.post<Uploaded>(`${this.root}/ingest/uploads`, body, {
reportProgress: true,
observe: 'events',
})
.subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
this.uploading.set({ field, percent: Math.round((100 * event.loaded) / event.total) });
} else if (event.type === HttpEventType.Response && event.body) {
this.set(field, event.body.bucket_url);
this.uploaded.update((u) => ({
...u,
[field]: [...(u[field] ?? []), ...event.body!.files],
}));
}
},
error: (e) => {
this.uploading.set(undefined);
this.problem.set(message(e));
},
complete: () => this.uploading.set(undefined),
});
}
protected dropped(field: string, event: DragEvent): void {
event.preventDefault();
this.upload(field, event.dataTransfer?.files ?? null);
}
/** "Iniciar sesión con …": the provider's page in a window; it hands the account back. */
protected async signIn(field: string, provider: string): Promise<void> {
this.problem.set('');
let started;
try {
started = await this.api.invoke(oauthStart, { provider, origin: location.origin });
} catch (e) {
this.problem.set(message(e));
return;
}
const popup = window.open(started.url, 'isssteleon-oauth', 'width=520,height=680');
const listen = (event: MessageEvent) => {
const m = event.data as { type?: string; state?: string; account?: unknown; error?: string };
if (event.origin !== location.origin || m?.type !== 'isssteleon-oauth') return;
if (m.state !== started.state) return;
window.removeEventListener('message', listen);
if (m.error) this.problem.set(m.error);
else this.set(field, m.account);
popup?.close();
};
window.addEventListener('message', listen);
}
protected cell(v: unknown): string {
return typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
}
/** Answers without empty ones (a default takes their place on the server). */
private cleaned(): Record<string, unknown> {
return Object.fromEntries(
Object.entries(this.answers()).filter(([, v]) => v !== '' && v !== null && v !== undefined),
);
}
protected readonly missing = computed(() =>
entries(this.type())
.filter(([k, f]) => f.required && f.type !== 'table' && isEmpty(this.answers()[k]))
.filter(([, f]) => f.default === null || f.default === undefined)
.map(([, f]) => f.label),
);
protected readonly ready = computed(
() =>
!this.missing().length &&
entries(this.type())
.filter(([, f]) => f.type === 'table' && f.required)
.every(([k]) => !isEmpty(this.answers()[k])),
);
protected save(): void {
const type = this.typeId();
if (!type || !this.ready()) return;
this.ref.close({
guided: { type, answers: this.cleaned() },
label: this.label() || this.type()!.title,
});
}
}
function entries(t: SourceType | undefined): [string, FieldSpec][] {
return Object.entries(t?.fields ?? {});
}
function isEmpty(v: unknown): boolean {
return v === '' || v === null || v === undefined;
}
function message(e: unknown): string {
if (e instanceof HttpErrorResponse) {
const d = e.error?.detail;
if (typeof d === 'string') return d;
if (e.status === 0) return 'No hay conexión con la plataforma. Intente de nuevo.';
return JSON.stringify(d ?? e.message);
}
return String(e);
}
+136
View File
@@ -0,0 +1,136 @@
import type { Figure } from './plot';
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
export const METRIC_NAMES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal media',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
/** The association's biomarkers (core.tea.association.BIOMARKERS). */
export const BIOMARKER_NAMES: Record<string, string> = {
spikes: 'Picos paroxísticos',
spindles: 'Husos de sueño N2',
posterior_rhythm: 'Ritmo posterior',
gradient: 'Gradiente anteroposterior',
};
/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */
export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_01: 'Vocalización espontánea dirigida a otros',
ados2_item_02: 'Señalar',
ados2_item_03: 'Gestos',
ados2_item_04: 'Contacto visual inusual',
ados2_item_05: 'Expresiones faciales dirigidas a otros',
ados2_item_06: 'Integración de la mirada con otras conductas',
ados2_item_07: 'Disfrute compartido en la interacción',
ados2_item_08: 'Respuesta al nombre',
ados2_item_09: 'Búsqueda de atención cuando se le ignora',
ados2_item_10: 'Pedir',
ados2_item_11: 'Mostrar',
ados2_item_12: 'Iniciación espontánea de la atención conjunta',
ados2_item_13: 'Respuesta a la atención conjunta',
ados2_item_14: 'Calidad de los acercamientos sociales',
ados2_item_15: 'Cantidad de acercamientos sociales al cuidador',
ados2_item_16: 'Cantidad de comunicación social recíproca',
ados2_item_17: 'Calidad general de la relación',
ados2_item_18: 'Entonación de vocalizaciones o verbalizaciones',
ados2_item_19: 'Uso estereotipado o idiosincrático de palabras',
ados2_item_20: 'Interés sensorial inusual',
ados2_item_21: 'Manierismos de manos y dedos',
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
CSS: 'Puntuación de severidad (CSS)',
};
/** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */
const AT: Record<string, [number, number]> = {
Fp1: [-0.31, 0.95], Fp2: [0.31, 0.95],
F7: [-0.81, 0.59], F3: [-0.4, 0.53], Fz: [0, 0.5], F4: [0.4, 0.53], F8: [0.81, 0.59],
T3: [-1, 0], C3: [-0.5, 0], Cz: [0, 0], C4: [0.5, 0], T4: [1, 0],
T5: [-0.81, -0.59], P3: [-0.4, -0.53], Pz: [0, -0.5], P4: [0.4, -0.53], T6: [0.81, -0.59],
O1: [-0.31, -0.95], O2: [0.31, -0.95],
}; // prettier-ignore
export interface Site {
site: string;
value: number;
z?: number | null;
}
/** Her electrodes on the head, coloured by how far each is from its age curve (z, blue
* below and red above), or by her own value where no curve scores electrodes. */
export function headMap(electrodes: Site[]): Figure {
const placed = electrodes.filter((e) => AT[e.site]);
const scored = placed.some((e) => e.z !== null && e.z !== undefined);
const colour = placed.map((e) => (scored ? (e.z ?? 0) : e.value));
const ring = Array.from({ length: 73 }, (_, i) => (i * 2 * Math.PI) / 72);
return {
data: [
{
x: ring.map((t) => 1.12 * Math.sin(t)),
y: ring.map((t) => 1.12 * Math.cos(t)),
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: [-0.12, 0, 0.12],
y: [1.1, 1.24, 1.1],
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: placed.map((e) => AT[e.site][0]),
y: placed.map((e) => AT[e.site][1]),
text: placed.map((e) => e.site),
customdata: colour,
mode: 'markers+text',
textposition: 'top center',
marker: {
size: 22,
color: colour,
colorscale: 'RdBu',
reversescale: true,
...(scored ? { cmin: -3, cmax: 3, cmid: 0 } : {}),
colorbar: { title: { text: scored ? 'z' : 'valor' }, thickness: 10 },
line: { color: '#ffffff', width: 1 },
},
hovertemplate: scored ? '%{text}: z = %{customdata:.2f}<extra></extra>'
: '%{text}: %{customdata:.3f}<extra></extra>', // prettier-ignore
showlegend: false,
},
],
layout: {
xaxis: { visible: false, range: [-1.35, 1.35], scaleanchor: 'y' },
yaxis: { visible: false, range: [-1.25, 1.35] },
margin: { l: 10, r: 10, t: 10, b: 10 },
},
} as Figure;
}
/** The zones, most affected first: by how far from the age curve, else by value. */
export function byDeviation(zones: Site[]): Site[] {
const scored = zones.some((z) => z.z !== null && z.z !== undefined);
return [...zones].sort((a, b) =>
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
);
}
+9 -9
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures } from './figures';
import { interpretabilityFigures, scenarioFigure } from './figures';
describe('governance figures', () => {
it('draws a survival report as curves with bands and the model points', () => {
@@ -13,7 +13,7 @@ describe('governance figures', () => {
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
});
it("draws each survival scenario after the cohort's curves, titled with its deaths", () => {
it('leaves the survival scenarios to the patient record, which draws them whole', () => {
const scenario = {
escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)',
n: 1142,
@@ -30,14 +30,14 @@ describe('governance figures', () => {
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
escenarios: [scenario],
});
expect(found.length).toBe(2);
expect(found[1].title).toContain('fallecidos = 308');
expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]);
expect(found.length).toBe(1); // the cohort's curves only
const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
});
it('draws a recurrence scenario: KM band, both Weibulls and the model points', () => {
const [found] = interpretabilityFigures({
it('leaves recurrence scenarios to the patient record', () => {
const found = interpretabilityFigures({
kind: 'scenarios',
recurrencia: {
horizons_months: [12, 36],
@@ -55,7 +55,7 @@ describe('governance figures', () => {
],
},
});
expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect(found).toEqual([]);
});
it('draws an age curve with its centile band', () => {
+62 -22
View File
@@ -1,5 +1,6 @@
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them. */
interface Band {
@@ -70,15 +71,7 @@ export function interpretabilityFigures(
},
},
},
// Its clinical scenarios, those with enough deaths to draw.
...((report['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
];
}
case 'subgroups':
@@ -147,17 +140,8 @@ export function interpretabilityFigures(
},
];
}
case 'scenarios':
return (report['recurrencia']['escenarios'] as any[])
.slice(0, 6)
.map((e) =>
scenarioFigure(
`${e.cohorte_nombre} · ${e.escenario} (n = ${e.n}, ${e.recaidas} recaídas)`,
e,
report['recurrencia']['horizons_months'],
'Supervivencia libre de recaída',
),
);
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return [];
case 'age_curves': {
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
@@ -205,14 +189,70 @@ export function interpretabilityFigures(
},
];
}
case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
const label = (r: any) =>
`${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${
OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code
}`;
return [
{
title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${
report['level'] === 'item' ? 'reactivo' : 'dominio'
})`,
figure: {
data: [
{
type: 'scatter',
mode: 'markers',
x: rows.map((r) => r.odds_ratio),
y: rows.map(label),
error_x: {
type: 'data',
symmetric: false,
array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio),
arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)),
},
marker: {
color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')),
size: 9,
},
customdata: rows.map((r) => r.q),
hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}<extra>%{y}</extra>',
showlegend: false,
},
],
layout: {
xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' },
yaxis: { automargin: true, autorange: 'reversed' },
shapes: [
{
type: 'line',
x0: 1,
x1: 1,
yref: 'paper',
y0: 0,
y1: 1,
line: { color: '#9aa0a6', dash: 'dot' },
},
],
height: Math.max(320, 22 * rows.length + 80),
},
},
},
];
}
default:
return [];
}
}
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band. */
function scenarioFigure(
* and the model's points with their bootstrap band (also a patient's, in her record). */
export function scenarioFigure(
title: string,
e: any,
horizons: number[],
+1 -1
View File
@@ -31,7 +31,7 @@
}
@if (models.isLoading()) {
<p class="muted">Cargando modelos…</p>
<app-loading what="los modelos" />
} @else if (!models.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
}
+4 -7
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { HttpErrorResponse } from '@angular/common/http';
import { DatePipe, DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
@@ -25,6 +26,7 @@ import type { Version } from '../api/models/version';
import { DOMAINS } from '../app';
import { Plot } from '../plot';
import { interpretabilityFigures } from './figures';
import { Loading } from '../loading';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
@@ -38,6 +40,7 @@ const REPORTS: Record<string, string> = {
@Component({
selector: 'app-gobernanza',
imports: [
Loading,
DatePipe,
DecimalPipe,
FormsModule,
@@ -91,13 +94,7 @@ export class Gobernanza {
params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
});
protected readonly metricNames: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
protected readonly metricNames = METRIC_NAMES;
protected readonly asOf = signal('');
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
protected readonly message = signal('');
+478
View File
@@ -0,0 +1,478 @@
import { type Figure, PALETTE } from '../plot';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
/** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
ticksuffix: ' %',
range: [0, 100],
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
legend: { orientation: 'h', y: -0.25 },
},
};
}
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record<string, string> = {
n: count(p['initial-population'] ?? 0),
obs: count(p['measure-observation'] ?? 0),
median: r.score === undefined ? '' : decimal(r.score),
q1: decimal(r.low ?? r.score ?? 0),
q3: decimal(r.high ?? r.score ?? 0),
num: count(p['numerator'] ?? 0),
den: count(p['denominator'] ?? 0),
pct: r.score === undefined ? '' : percent(r.score * 100),
};
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
/** A duration's quartile box in the period. */
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
return {
data: [
{
type: 'box',
name: 'Total',
x: [period],
q1: [q1],
median: [r.score!],
q3: [q3],
lowerfence: [q1],
upperfence: [q3],
marker: { color: '#4269C2' },
fillcolor: 'rgba(66,105,194,0.55)',
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
};
}
/** One ring: the categories' shares, the total in the centre. */
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
return {
data: [
{
type: 'pie',
hole: 0.54,
sort: false,
direction: 'clockwise',
labels: catalog.categories.map((c) => c.label),
values,
marker: {
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 30, l: 60, r: 60, b: 30 },
annotations: [
{
text: `<b>${count(total)}</b><br>${center}`,
showarrow: false,
x: 0.5,
y: 0.5,
xref: 'paper',
yref: 'paper',
},
],
},
};
}
/** A category's count per bar, one bar each, in the period. */
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label);
return {
data: [
{
type: 'bar',
orientation: 'h',
name: period,
y,
x: catalog.categories.map((c) => counted(r, c.code)),
marker: { color: catalog.categories.map((c) => c.color) },
texttemplate: '%{x}',
textposition: 'outside',
hovertemplate: '%{y}: %{x}<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: axis }, rangemode: 'tozero' },
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
},
};
}
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2'];
/** "16-23" as the screens say it: "16 a 23 meses". */
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
function ages(r: Reading): [string, Record<string, number>][] {
return Object.entries(r.strata['age_group'] ?? {}).sort(
([a], [b]) => parseInt(a, 10) - parseInt(b, 10),
);
}
/** By age group: the numerator and the rest of the denominator, stacked. */
export function ageStack(r: Reading, names: [string, string]): Figure {
const rows = ages(r);
const x = rows.map(([a]) => ageLabel(a));
return {
data: [
{
type: 'bar',
name: names[0],
x,
y: rows.map(([, c]) => c['numerator'] ?? 0),
marker: { color: AGE_COLORS[0] },
},
{
type: 'bar',
name: names[1],
x,
y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)),
marker: { color: AGE_COLORS[1] },
},
] as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' },
},
};
}
/** By age group: the numerator's share of the denominator, one bar each. */
export function ageShare(r: Reading, axis: string): Figure {
const rows = ages(r);
return {
data: [
{
type: 'bar',
x: rows.map(([a]) => ageLabel(a)),
y: rows.map(([, c]) =>
c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0,
),
marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) },
texttemplate: '%{y:.1f} %',
textposition: 'outside',
hovertemplate: '%{x}: %{y:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
},
};
}
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
* closed shape. */
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
return {
data: named.map((c) => ({
type: 'bar',
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
})),
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
mode: 'lines',
fill: 'toself',
fillcolor: line + '33',
line: { width: 0 },
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => at(s.r?.score)),
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
};
}
+33 -9
View File
@@ -6,35 +6,37 @@ import { Fhir, resources } from '../fhir';
import { TabDefiniciones } from './tab-definiciones';
import { TabIndicadores } from './tab-indicadores';
import { TabRiesgos } from './tab-riesgos';
import { TabRiesgosTea } from './tab-riesgos-tea';
import { TabSeguimiento } from './tab-seguimiento';
import { TabTrazabilidad } from './tab-trazabilidad';
import { Loading } from '../loading';
/** A domain's indicator page: four tabs over its FHIR measures and patients. */
@Component({
selector: 'app-indicadores',
imports: [
Loading,
MatTabsModule,
TabIndicadores,
TabTrazabilidad,
TabRiesgos,
TabRiesgosTea,
TabSeguimiento,
TabDefiniciones,
],
template: `
<section class="page">
<h1>{{ title() }}</h1>
<p class="subtitle">
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
</p>
<p class="subtitle">Explora los indicadores de {{ title().toLowerCase() }}.</p>
@if (measures.isLoading()) {
<p class="muted">Cargando indicadores…</p>
<app-loading what="los indicadores" />
} @else if (measures.error()) {
<p class="muted" role="alert">No se pudieron leer los indicadores.</p>
} @else if (!measures.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab label="Indicadores">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab>
<mat-tab label="Trazabilidad">
@@ -48,8 +50,14 @@ import { TabTrazabilidad } from './tab-trazabilidad';
<app-tab-riesgos [domain]="domain()" />
</ng-template>
</mat-tab>
} @else if (domain() === 'tea') {
<mat-tab label="Análisis de Riesgo">
<ng-template matTabContent>
<app-tab-riesgos-tea [domain]="domain()" />
</ng-template>
</mat-tab>
} @else if (domain() === 'cama') {
<mat-tab label="Seguimiento">
<mat-tab label="Análisis de riesgos">
<ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" />
</ng-template>
@@ -57,7 +65,7 @@ import { TabTrazabilidad } from './tab-trazabilidad';
}
<mat-tab label="Datos y definiciones">
<ng-template matTabContent>
<app-tab-definiciones [measures]="measures.value()!" />
<app-tab-definiciones [domain]="domain()" [measures]="measures.value()!" />
</ng-template>
</mat-tab>
</mat-tab-group>
@@ -68,11 +76,27 @@ import { TabTrazabilidad } from './tab-trazabilidad';
:host {
display: block;
}
/* As the old page: the domain's name and a line under it, then a white tab bar under
an olive rule. */
h1 {
text-align: center;
font-size: 28px;
font-weight: 500;
margin: 16px 0 8px;
}
.subtitle {
text-align: center;
font-size: 16px;
margin: 0 0 24px;
}
::ng-deep .mat-mdc-tab-header {
background: var(--color-surface);
border-top: 2px solid var(--color-primary);
}
::ng-deep .mat-mdc-tab .mdc-tab__text-label {
font-size: 16px;
font-weight: 400;
}
::ng-deep .mat-mdc-tab.mdc-tab--active .mdc-tab__text-label {
font-weight: 700;
}
.empty {
padding: 48px 0;
+9 -3
View File
@@ -66,9 +66,15 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
const score = group.measureScore;
const strata: Reading['strata'] = {};
for (const s of group.stratifier ?? []) {
const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? '';
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [x.value?.text ?? '', counts(x)]),
(s.stratum ?? []).map((x) => [
x.component?.length
? x.component.map((c) => c.value?.text ?? '').join('|')
: (x.value?.text ?? ''),
counts(x),
]),
);
}
return {
@@ -82,7 +88,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
}
/** Codes as the screens name them. */
const LABELS: Record<string, string> = {
export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)',
LSIL: 'LIEBG',
HSIL: 'LIEAG',
+630
View File
@@ -0,0 +1,630 @@
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */
export interface Page {
kpis: Kpi[];
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[];
clinical: Section[];
/** The measure whose data decides the default period. */
anchor: string;
}
/** A card: its measure (none: not published yet), its title, and its value and note as
* templates (figures.fill). */
export interface Kpi {
measure?: string;
title: string;
value?: string;
note?: string;
}
export type Section =
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] }
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
| {
kind: 'boxes';
/** none: the boxes stand alone (TEA) */
title?: string;
cards: { measure?: string; title: string }[];
/** the measure's own title under each card's (CaMa) */
subtitles?: boolean;
}
/** Each figure in its own card, titled, two to a row (TEA). */
| { kind: 'grid'; figures: FigureSpec[] }
/** TEA's period summary in words, its numbers from the measures. */
| { kind: 'tea-summary' }
| ({ kind: 'card' } & Kpi);
/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec =
| {
kind: 'donut' | 'share-donut';
title: string;
measure: string;
catalog: Catalog;
center: string;
}
| { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string }
| { kind: 'counts'; title: string; measure: string; catalog: Catalog; axis: string }
| {
kind: 'age-stack' | 'age-share';
title: string;
measure: string;
/** the numerator's and the rest's names (stack), or the axis (share) */
names: [string, string];
}
| {
kind: 'rates';
title: string;
measure: string;
stratum: string;
rows: Category[];
/** each row in its category's colour (else all rose) */
colored?: boolean;
/** the categories (of the measure) that count as a positive */
positive: string[];
axis: string;
};
export interface Category {
code: string;
label: string;
color: string;
group: string;
}
export interface Catalog {
groups: { id: string; label: string; color: string }[];
categories: Category[];
/** categories drawn faded (not the ones the figure is about) */
faded?: string[];
}
const OLIVE = '#A8C243';
const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
],
faded: ['normal', 'LSIL'],
};
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
const PENDING = 'Este indicador aún no está publicado por el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
groups: [],
categories: [
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
],
};
const BREAST_BIOPSY: Catalog = {
groups: [
{ id: 'benign', label: 'No maligno', color: '#42C29C' },
{ id: 'malignant', label: 'Maligno', color: ROSE },
],
categories: [
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
],
};
export const PAGES: Record<string, Page> = {
tea: {
anchor: 'M23_PACIENTES_EVALUADOS',
kpis: [],
opportunity: [
{ kind: 'tea-summary' },
{
kind: 'boxes',
cards: [
{ measure: 'M26_DIAS_MCHAT_ADOS2', title: 'Días de M-CHAT a ADOS-2' },
{ measure: 'M27_DIAS_ADOS2_DIAGNOSTICO', title: 'Días de ADOS-2 a diagnóstico' },
{ measure: 'M25_DIAS_MCHAT_DIAGNOSTICO', title: 'Días de M-CHAT a diagnóstico positivo' },
],
},
],
clinical: [
{
kind: 'grid',
figures: [
{
kind: 'counts',
title: 'Pacientes evaluados por resultado diagnóstico',
measure: 'M23_PACIENTES_EVALUADOS',
axis: 'Conteo (paciente)',
catalog: {
groups: [],
categories: [
{ code: 'confirmed', label: 'Diagnóstico confirmado', color: OLIVE, group: '' },
{ code: 'in_process', label: 'En proceso', color: '#B8433A', group: '' },
],
},
},
{
kind: 'age-stack',
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
names: ['Diagnóstico confirmado', 'En proceso'],
},
{
kind: 'age-share',
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
names: ['% de pacientes con EEG', ''],
},
{
kind: 'age-share',
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
names: ['% de pacientes sin EEG', ''],
},
{
kind: 'counts',
title: 'Casos por estatus',
measure: 'M28_CASOS_POR_ESTADO',
axis: 'Conteo (paciente)',
catalog: {
groups: [],
categories: [
{ code: 'mchat_only', label: 'Solo M-CHAT', color: '#B8433A', group: '' },
{
code: 'psychology',
label: 'Hasta evaluación psicológica',
color: '#42C29C',
group: '',
},
{
code: 'neuropediatrics',
label: 'Hasta evaluación neuropediátrica',
color: '#7184A2',
group: '',
},
{ code: 'eeg', label: 'Con EEG', color: OLIVE, group: '' },
],
},
},
{
kind: 'counts',
title: 'Calidad del EEG',
measure: 'M29_CALIDAD_EEG',
axis: 'Conteo (examen)',
catalog: {
groups: [],
categories: [
{ code: 'good', label: 'Bueno', color: OLIVE, group: '' },
{ code: 'bad', label: 'No aceptable', color: '#B8433A', group: '' },
{ code: 'not_analyzed', label: 'Sin analizar', color: '#C9CDD2', group: '' },
],
},
},
],
},
],
},
cama: {
anchor: 'CAMA_BIRADS456_PACIENTE',
kpis: [
{
measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
},
{
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} biopsias con riesgo a carcinoma.',
},
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
...CAMA_DAYS,
},
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: PENDING,
},
],
opportunity: [
{
kind: 'boxes',
title: 'Tiempo de tamizaje a diagnóstico',
subtitles: true,
cards: [
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
},
{
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
},
{ title: 'Tiempo de interpretación radiológica a resultado de biopsia' },
{ title: 'Tiempo de diagnóstico a tratamiento' },
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
],
},
],
clinical: [
{
kind: 'figures',
figures: [
{
kind: 'share-donut',
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
catalog: BIRADS,
center: 'mastografías',
},
{
kind: 'share-donut',
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_PACIENTE',
catalog: BIRADS,
center: 'pacientes',
},
],
},
{
kind: 'figures',
title: 'Resultado histopatológico por categoría BI-RADS',
figures: [
{
kind: 'rates',
title: 'Por categoría BI-RADS, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
colored: true,
positive: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
},
{
kind: 'donut',
title: 'Resultado de la biopsia, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: BREAST_BIOPSY,
center: 'con resultado',
},
],
},
{
kind: 'card',
measure: 'CAMA_CONFIRMACION_BIRADS45',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
},
],
},
cacu: {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
clinical: [
{
kind: 'route',
title: 'Tiempos de la ruta del tamizaje',
steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
],
},
{
kind: 'figures',
title: 'Distribución de resultados citológicos',
figures: [
{
kind: 'donut',
title: 'Distribución de resultados, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
center: 'pacientes',
},
{
kind: 'scenario-bars',
title: 'TOTAL por escenario clínico, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
stratum: 'follow_up_status',
},
],
},
{
kind: 'figures',
title: 'Tasa de confirmación histopatológica',
figures: [
{
kind: 'rates',
title: 'Por resultado de la citología, {p}',
measure: 'CACU_CONFIRMACION_CITOLOGIA',
stratum: 'result',
rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)),
positive: ['HSIL', 'CIS', 'carcinoma'],
axis: 'Verdaderos positivos (valor predictivo positivo)',
},
{
kind: 'donut',
title: 'Resultado de la biopsia, {p}',
measure: 'CACU_CONFIRMACION_CITOLOGIA',
catalog: BIOPSY,
center: 'con biopsia',
},
],
},
],
},
};
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
export interface HistoryPanel {
title: string;
measure: string;
kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string;
group?: string;
}
export interface History {
panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number;
}
const GREY = '#C9CDD2';
const stack = (
title: string,
measure: string,
axis: string,
series: [string, string, string][],
): HistoryPanel => ({
title,
measure,
kind: 'stack',
axis,
series: series.map(([code, label, color]) => ({ code, label, color })),
});
const BIRADS_SERIES: [string, string, string][] = [
['4A', 'BI-RADS 4A', '#C24269'],
['4B', 'BI-RADS 4B', '#9C42C2'],
['4C', 'BI-RADS 4C', '#5C42C2'],
['5', 'BI-RADS 5', '#C2429C'],
['6', 'BI-RADS 6', '#8E2F62'],
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
];
export const HISTORY: Record<string, History> = {
cacu: {
line: '#6A8000',
months: 5,
panels: [
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
['NILM', 'Normal', '#9DBFE3'],
['ASC-US', 'ASC-US', '#2F6DB3'],
['LSIL', 'LIEBG', '#9C42C2'],
['ASC-H', 'ASC-H', '#5C42C2'],
['HSIL', 'LIEAG', '#C2429C'],
['CIS', 'Carcinoma in situ', '#8E2F62'],
['no_data', 'Sin dato', GREY],
]),
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
stack(
'Resultado de biopsia tras citología de alto grado',
'CACU_CONFIRMACION_CITOLOGIA',
'Pacientes',
[
['normal', 'Normal', '#9DBFE3'],
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
['CIS', 'Carcinoma in situ', '#9C42C2'],
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
['no_biopsy', 'Sin biopsia aún', GREY],
['no_data', 'Biopsia sin grado', GREY],
],
),
{
title: 'Días de la toma de la citología a su resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median',
},
{
title: 'Tiempo de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
{
title: 'Riesgo CIN2+ por banda',
measure: 'CACU_RIESGO_BANDA',
kind: 'stack',
axis: 'Pacientes',
},
],
},
cama: {
line: '#9C42C2',
panels: [
{
title: 'Días de la toma de la mastografía a su resultado',
measure: 'CAMA_EU38A',
kind: 'median',
},
{
title: 'Días del resultado de la mastografía al diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Días de tamizaje a diagnóstico',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
stack(
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_MASTOGRAFIA',
'Mastografías',
BIRADS_SERIES,
),
stack(
'Pacientes con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_PACIENTE',
'Pacientes',
BIRADS_SERIES,
),
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
['benign', 'Benigno', '#9DBFE3'],
['in_situ', 'Carcinoma in situ', '#C24269'],
['invasive', 'Carcinoma invasor', '#9C42C2'],
['no_biopsy', 'Sin biopsia reportada', GREY],
['no_data', 'Sin dato', GREY],
]),
{
title: 'Tasa de confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent',
},
],
},
tea: {
line: '#9C42C2',
panels: [
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a ADOS-2',
measure: 'M26_DIAS_MCHAT_ADOS2',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de ADOS-2 a diagnóstico',
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a diagnóstico positivo',
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
kind: 'median',
},
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
['in_process', 'En proceso', '#B8433A'],
]),
{
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
kind: 'percent',
},
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
['mchat_only', 'Solo M-CHAT', '#B8433A'],
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
['eeg', 'Con EEG', '#A8C243'],
]),
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
['good', 'Bueno', '#A8C243'],
['bad', 'No aceptable', '#B8433A'],
['not_analyzed', 'Sin analizar', GREY],
]),
],
},
};
+106 -32
View File
@@ -1,5 +1,7 @@
import { Component, input } from '@angular/core';
import { Component, computed, input } from '@angular/core';
import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app';
import type { Domain } from '../api/models/domain';
import { code, label } from '../fhir';
import { periodTypes, STRATA } from './measures';
@@ -14,48 +16,120 @@ const IMPROVEMENT: Record<string, string> = {
};
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** What each measure is: how it scores, which way is better, its periods and strata. */
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
* indicator opening to what it is (how it scores, which way is better, its periods and
* strata). */
@Component({
selector: 'app-tab-definiciones',
template: `
<table class="plain card">
<thead>
<tr>
<th>Indicador</th>
<th>Clave</th>
<th>Cálculo</th>
<th>Mejora</th>
<th>Periodos</th>
<th>Estratos</th>
</tr>
</thead>
<tbody>
@for (m of measures(); track m.id) {
<tr>
<td>{{ m.title }}</td>
<td>
<code>{{ m.name }}</code> v{{ m.version }}
</td>
<td>{{ scoring[code(m.scoring) ?? ''] }}</td>
<td>{{ improvement[code(m.improvementNotation) ?? ''] ?? '—' }}</td>
<td>{{ types(m) }}</td>
<td>{{ strata(m) }}</td>
</tr>
<section class="card">
<h2>Datos y definiciones de {{ domainName() }}</h2>
<section aria-labelledby="domain-info-title">
<h3 id="domain-info-title">Información del dominio</h3>
@if (domain() === 'cacu') {
<p>
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
espécimen fue insatisfactorio.
</p>
}
</tbody>
</table>
@if (available().length) {
<p>Periodicidad disponible: {{ available().join(', ') }}.</p>
} @else {
<p>Periodicidad: pendiente de información.</p>
}
</section>
<section aria-labelledby="definitions-catalog-title">
<h3 id="definitions-catalog-title">Catálogo de indicadores</h3>
<p>Consulta las gráficas disponibles y la periodicidad de cada indicador.</p>
@for (m of measures(); track m.id) {
<details>
<summary>{{ m.title || 'Nombre pendiente de publicación' }}</summary>
<div class="indicator-detail">
@if (m.description) {
<p>{{ m.description }}</p>
}
<h4>Cálculo</h4>
<p>
{{ scoring[code(m.scoring) ?? ''] }}
@if (improvement[code(m.improvementNotation) ?? '']; as better) {
· {{ better }}
}
</p>
<h4>Tipos de periodo admitidos</h4>
@if (types(m).length) {
<ul>
@for (t of types(m); track t) {
<li>{{ t }}</li>
}
</ul>
} @else {
<p>Pendiente de información.</p>
}
<h4>Estratos</h4>
<p>{{ strata(m) }}</p>
<p class="muted">
Clave <code>{{ m.name }}</code> · versión {{ m.version }}
</p>
</div>
</details>
} @empty {
<p role="status">
No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de
información.
</p>
}
</section>
</section>
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
}
h2,
h3 {
font-size: 20px;
font-weight: 500;
}
h4 {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
details {
border-bottom: 1px solid var(--mat-sys-outline-variant);
padding: 8px 0;
}
summary {
cursor: pointer;
font-weight: 500;
}
.indicator-detail {
padding: 4px 0 8px 16px;
}
`,
styles: ':host { display: block; padding-top: 16px; overflow-x: auto; }',
})
export class TabDefiniciones {
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly scoring = SCORING;
protected readonly improvement = IMPROVEMENT;
protected readonly code = code;
protected types(m: Measure): string {
return periodTypes(m)
.map((p) => PERIODS[p] ?? p)
.join(', ');
protected readonly domainName = computed(
() => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(),
);
/** The periodicities any of its indicators admits. */
protected readonly available = computed(() =>
[...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p),
);
protected types(m: Measure): string[] {
return periodTypes(m).map((p) => PERIODS[p] ?? p);
}
protected strata(m: Measure): string {
const names = (m.group?.[0]?.stratifier ?? []).map((s) => code(s.code) ?? label(s.code));
+227 -52
View File
@@ -1,4 +1,5 @@
<div class="filters card">
<h2 class="filters-title">Filtros</h2>
<div class="field">
<span class="label">Intervalo de análisis</span>
<mat-button-toggle-group
@@ -14,7 +15,7 @@
<mat-label>Periodo seleccionado</mat-label>
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
@for (p of options(); track p) {
<mat-option [value]="p">{{ label(p) }}</mat-option>
<mat-option [value]="p">{{ p }}</mat-option>
}
</mat-select>
</mat-form-field>
@@ -25,65 +26,239 @@
>
Aplicar
</button>
@if (applied(); as p) {
<span class="muted applied">Mostrando {{ label(p) }}</span>
}
</div>
@if (reports.isLoading()) {
<p class="muted">Calculando…</p>
<app-loading what="los indicadores" text="Calculando los indicadores…" />
}
@if (kpis().length) {
<h2>Indicadores de oportunidad</h2>
<div class="kpis">
@for (m of kpis(); track m.id) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
@if (reports.error()) {
<div class="load-error" role="alert">
<p>No se pudieron leer los indicadores del periodo. Vuelve a intentar.</p>
<button mat-stroked-button (click)="reports.reload()">Reintentar</button>
</div>
}
@if (page(); as pg) {
@if (applied(); as period) {
<section class="card opportunity" aria-labelledby="opportunity-title">
<div class="section-head">
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span>
</div>
<div class="kpis">
@for (k of pg.kpis; track k.title) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3>
@if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" />
} @else {
<div class="kpi-value" [class.pending]="!k.measure">{{ kpiValue(k) }}</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div>
}
</mat-card-content>
</mat-card>
}
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
<section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
}
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('route') {
<h3 class="route-title">{{ section.title }}</h3>
@if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" />
} @else if (routeOf(section); as fig) {
<app-plot [figure]="fig" [height]="300" />
} @else {
<p class="state">Sin tiempos publicados en el periodo.</p>
}
}
@case ('tea-summary') {
@if (teaSummary(); as t) {
<mat-card appearance="outlined" class="summary">
<mat-card-content>
<h2 class="box-title">Resumen</h2>
<p>
Al cierre del periodo <mark>{{ period }}</mark>, se evaluaron
<mark>{{ t.evaluated }}</mark> niños entre 16 y 36 meses;
<mark>{{ t.mchatOnly }}</mark> únicamente tienen M-CHAT,
<mark>{{ t.psychology }}</mark> hasta la evaluación psicológica y
<mark>{{ t.neuropediatrics }}</mark> presentan evaluación neuropediátrica. En este
periodo el <mark>{{ t.confirmed }}</mark> de los pacientes tiene diagnóstico
confirmado de TEA (CIE-10 F84.0). Las ventanas de tiempo<sup>*</sup> de tamizaje
son: <mark>{{ t.toAdos }}</mark> de M-CHAT (psicología) a ADOS-2,
<mark>{{ t.toDiagnosis }}</mark> de ADOS-2 a diagnóstico. El tiempo<sup>*</sup> de
tamizaje completo de M-CHAT a diagnóstico fue de <mark>{{ t.whole }}</mark>.
</p>
<p>
De los <mark>{{ t.diagnosed }}</mark> niños con diagnóstico confirmado en este
periodo, <mark>{{ t.eeg }}</mark> presentan estudio de EEG y faltan
<mark>{{ t.missing }}</mark> por realizarlo. <mark>{{ t.unusable }}</mark> estudios
de EEG no son aceptables para un análisis.
</p>
<p class="state">*tomando la mediana de los tiempos</p>
</mat-card-content>
</mat-card>
} @else if (reports.isLoading()) {
<app-loading what="el resumen del periodo" />
}
}
@case ('grid') {
<div class="grid-figures">
@for (f of section.figures; track f.title) {
<mat-card appearance="outlined" class="figure-card" [attr.data-figure]="f.kind">
<mat-card-content>
<h2 class="box-title">{{ f.title }}</h2>
<p class="state">Filtro general aplicado: {{ period }}</p>
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) {
<app-plot [figure]="fig" [height]="320" />
} @else {
<div class="empty-figure">Sin datos publicados</div>
}
</mat-card-content>
</mat-card>
}
</div>
}
@case ('boxes') {
@if (section.title) {
<h3 class="boxes-title">{{ section.title }}</h3>
}
<div class="box-grid" [class.standalone]="!section.title">
@for (b of section.cards; track b.title) {
<mat-card
appearance="outlined"
class="box-card"
[attr.data-measure]="b.measure ?? null"
>
<mat-card-content>
<h2 class="box-title">{{ b.title }}</h2>
@if (!b.measure) {
<p class="state"><strong>Integración pendiente.</strong> {{ pending }}</p>
<div class="empty-figure">Sin datos publicados</div>
} @else {
<p class="state">Filtro general aplicado: {{ period }}</p>
@if (section.subtitles) {
<h2 class="box-subtitle">{{ measureTitle(b.measure) }}</h2>
<p class="state">Figura: Caja de cuartiles</p>
}
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (boxOf(b.measure); as fig) {
<app-plot [figure]="fig" [height]="320" />
} @else {
<div class="empty-figure">Sin datos publicados</div>
}
}
</mat-card-content>
</mat-card>
}
</div>
}
@case ('card') {
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
<mat-card-content>
<h3 class="kpi-title">{{ section.title }}</h3>
<div class="kpi-value">{{ kpiValue(section) }}</div>
<div class="kpi-detail">{{ kpiNote(section) }}</div>
</mat-card-content>
</mat-card>
}
@default {
<mat-card appearance="outlined" class="figure-card">
<mat-card-content>
@if (section.title) {
<h2 class="figure-card-title">{{ section.title }}</h2>
}
<div class="figure-row">
@for (f of section.figures; track f.title) {
<div class="figure" [attr.data-figure]="f.kind">
<h3 [class.light]="f.kind === 'share-donut'">{{ titled(f.title) }}</h3>
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) {
<app-plot [figure]="fig" [height]="360" />
} @else {
<p class="state">Sin datos en el periodo.</p>
}
</div>
}
</div>
</mat-card-content>
</mat-card>
}
}
</ng-template>
} @else {
@if (kpis().length) {
<h2>Indicadores de oportunidad</h2>
<div class="kpis">
@for (m of kpis(); track m.id) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
<mat-card-content>
<div class="kpi-title">{{ m.title }}</div>
<div class="kpi-value">{{ score(m) }}</div>
<div class="kpi-detail muted">{{ detail(m) }}</div>
</mat-card-content>
</mat-card>
}
</div>
}
@if (layout().route.length) {
<mat-card appearance="outlined" class="route">
<mat-card-header>
<mat-card-title>Ruta del tamizaje</mat-card-title>
<mat-button-toggle-group
[value]="routeView()"
(change)="routeView.set($event.value)"
class="route-toggle"
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</mat-card-header>
<mat-card-content>
<app-plot [figure]="route()" [height]="260" />
</mat-card-content>
</mat-card>
}
<h2>Indicadores clínicos</h2>
<div class="clinical">
@for (m of clinical(); track m.id) {
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
<mat-card-header>
<mat-card-title>{{ m.title }}</mat-card-title>
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<div class="kpi-title">{{ m.title }}</div>
<div class="kpi-value">{{ score(m) }}</div>
<div class="kpi-detail muted">{{ detail(m) }}</div>
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
<h3 class="figure-title">{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="260" />
} @empty {
<p class="muted">Sin datos en el periodo.</p>
}
</mat-card-content>
</mat-card>
}
</div>
}
@if (layout().route.length) {
<mat-card appearance="outlined" class="route">
<mat-card-header>
<mat-card-title>Ruta del tamizaje</mat-card-title>
<mat-button-toggle-group
[value]="routeView()"
(change)="routeView.set($event.value)"
class="route-toggle"
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</mat-card-header>
<mat-card-content>
<app-plot [figure]="route()" [height]="260" />
</mat-card-content>
</mat-card>
}
<h2>Indicadores clínicos</h2>
<div class="clinical">
@for (m of clinical(); track m.id) {
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
<mat-card-header>
<mat-card-title>{{ m.title }}</mat-card-title>
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
<h3 class="figure-title">{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="260" />
} @empty {
<p class="muted">Sin datos en el periodo.</p>
}
</mat-card-content>
</mat-card>
}
</div>
+200
View File
@@ -97,3 +97,203 @@ h2 {
font-weight: 500;
margin: var(--space-3) 0 0;
}
/* The old app's page: white sections with a title, cards inside. */
.card.opportunity,
.card.clinical-page {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 8px;
margin-bottom: 24px;
padding: 20px;
}
.section-head {
align-items: baseline;
display: flex;
justify-content: space-between;
.period {
color: var(--color-text-secondary);
font-size: 12px;
}
}
.card h2 {
font-size: 20px;
font-weight: 500;
margin: 0 0 20px;
}
h3.kpi-title {
font-size: 16px;
font-weight: 500;
margin: 0;
min-height: 2.6em;
}
.kpi-detail {
color: var(--color-text-secondary);
}
h3.route-title {
font-size: 16px;
font-weight: 700;
margin: 24px 0 8px;
}
.figure-card {
margin-top: 24px;
}
h2.figure-card-title {
font-size: 18px;
font-weight: 500;
margin: 0 0 12px;
}
.figure-row {
display: grid;
gap: 24px;
grid-template-columns: 1fr;
}
@media (min-width: 1100px) {
.figure-row {
grid-template-columns: 1fr 1fr;
}
}
.figure h3 {
font-size: 16px;
font-weight: 700;
margin: 0 0 8px;
}
.state {
color: var(--color-text-secondary);
font-size: 14px;
}
.filters {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 8px;
padding: 16px;
}
h2.filters-title {
flex-basis: 100%;
font-size: 16px;
font-weight: 500;
margin: 0;
}
h3.boxes-title {
font-size: 18px;
font-weight: 500;
margin: 24px 0 12px;
}
.box-grid {
display: grid;
gap: 16px;
grid-template-columns: 1fr;
}
@media (min-width: 1000px) {
.box-grid {
grid-template-columns: 1fr 1fr;
}
}
h2.box-title {
font-size: 18px;
font-weight: 500;
margin: 0 0 4px;
}
h2.box-subtitle {
font-size: 16px;
font-weight: 500;
margin: 8px 0 0;
}
.empty-figure {
align-items: center;
border: 1px solid var(--color-border);
border-radius: 8px;
color: var(--color-text-secondary);
display: flex;
justify-content: center;
min-height: 120px;
}
.kpi-value.pending {
font-size: 14px;
font-weight: 400;
}
.figure h3.light {
font-weight: 500;
}
.kpi.closing {
margin-top: 24px;
}
.summary {
margin-bottom: 24px;
p {
font-size: 20px;
line-height: 2.1;
margin: 0;
}
p.state {
font-size: 14px;
line-height: 1.5;
margin-top: 12px;
}
mark {
background: #f1f5df;
border: 1px solid #d8e3a8;
border-radius: 4px;
font-weight: 700;
padding: 1px 8px;
}
}
.grid-figures {
display: grid;
gap: 24px;
grid-template-columns: 1fr;
}
@media (min-width: 1100px) {
.grid-figures {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1000px) {
.box-grid.standalone {
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
}
.load-error {
align-items: center;
border: 1px solid var(--color-border);
border-radius: 8px;
display: flex;
gap: 16px;
margin-bottom: 16px;
padding: 12px 16px;
p {
margin: 0;
}
}
+123 -6
View File
@@ -1,4 +1,5 @@
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
@@ -8,6 +9,19 @@ import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import {
ageShare,
ageStack,
boxFigure,
countBars,
fill,
nestedDonut,
rateDots,
routeFigure,
scenarioBars,
shareDonut,
} from './figures';
import { FigureSpec, Kpi, PAGES, Section } from './pages';
import {
detail,
donut,
@@ -23,13 +37,16 @@ import {
STRATA,
strataBars,
} from './measures';
import { Loading } from '../loading';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per
* clinical measure with its figures. */
@Component({
selector: 'app-tab-indicadores',
imports: [
Loading,
FormsModule,
NgTemplateOutlet,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
@@ -54,6 +71,10 @@ export class TabIndicadores {
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
);
protected readonly pending =
'Este indicador aún no está publicado por el catálogo institucional.';
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */
protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
protected readonly kpis = computed(() =>
this.layout()
@@ -72,7 +93,7 @@ export class TabIndicadores {
private readonly latest = resource({
params: () => ({
domain: this.domain(),
anchor: this.byName().get(this.layout().anchor) ?? this.measures()[0],
anchor: this.byName().get(this.page()?.anchor ?? this.layout().anchor) ?? this.measures()[0],
all: this.options(),
}),
loader: async ({ params }) => {
@@ -105,6 +126,12 @@ export class TabIndicadores {
},
});
/** The period's readings; none while they load or when reading them failed (an errored
* resource throws on `value()`). */
protected loaded(): Map<string, Reading | undefined> | undefined {
return this.reports.hasValue() ? this.reports.value() : undefined;
}
constructor() {
effect(() => {
const latest = this.latest.value();
@@ -118,7 +145,7 @@ export class TabIndicadores {
protected readonly label = periodLabel;
protected readonly strataNames = STRATA;
protected r(m: Measure): Reading | undefined {
return this.reports.value()?.get(m.name!);
return this.loaded()?.get(m.name!);
}
protected score(m: Measure): string {
return formatScore(m, this.r(m));
@@ -145,16 +172,14 @@ export class TabIndicadores {
/** Each clinical card's figures, built once per loaded period. */
protected readonly figureSets = computed(
() =>
new Map(
this.clinical().map((m) => [m.name!, this.build(m, this.reports.value()?.get(m.name!))]),
),
new Map(this.clinical().map((m) => [m.name!, this.build(m, this.loaded()?.get(m.name!))])),
);
/** A clinical card's figures: the overall split, then one per stratum. */
private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] {
if (!r || !(r.populations['initial-population'] ?? 0)) return [];
const strata = Object.keys(r.strata).filter(
(s) => s !== 'category' && Object.keys(r.strata[s]).length,
(s) => s !== 'category' && !s.includes('-') && Object.keys(r.strata[s]).length,
);
const kind = scoring(m);
if (kind === 'continuous-variable')
@@ -168,4 +193,96 @@ export class TabIndicadores {
];
}
protected readonly name = name;
/** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code);
}
protected kpi(code: string): Measure | undefined {
return this.byName().get(code);
}
/** A card's value and note, from its templates (a card with no measure: its words). */
protected kpiValue(k: Kpi): string {
if (!k.measure) return k.value ?? '';
const r = this.rd(k.measure);
return r && r.score !== undefined && k.value ? fill(k.value, r) : '';
}
protected kpiNote(k: Kpi): string {
if (!k.measure) return k.note ?? '';
const r = this.rd(k.measure);
if (!r || r.score === undefined) return 'Sin valor disponible';
return k.note ? fill(k.note, r) : '';
}
/** A figure's title, with the applied period in it. */
protected titled(title: string): string {
return title.replace('{p}', this.applied() ?? '');
}
/** A duration's box, or nothing to draw. */
protected boxOf(measure: string | undefined): Figure | undefined {
const r = measure ? this.rd(measure) : undefined;
return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined;
}
/** TEA's summary of the period: its numbers from the measures (none: no summary). */
protected readonly teaSummary = computed(() => {
const rd = (c: string) => this.loaded()?.get(c);
const status = rd('M28_CASOS_POR_ESTADO');
if (!status) return undefined;
const n = (r: Reading | undefined, pop: string) => r?.populations[pop] ?? 0;
const cat = (r: Reading | undefined, c: string) =>
r?.strata['category']?.[c]?.['initial-population'] ?? 0;
const days = (c: string) => {
const v = rd(c)?.score;
return v === undefined
? '—'
: `${v.toLocaleString('es-MX', { maximumFractionDigits: 1 })} días`;
};
const confirmed = rd('M24_CONFIRMACION_DIAGNOSTICO')?.score;
const withEeg = rd('M21_DIAGNOSTICADOS_CON_EEG');
return {
evaluated: n(status, 'initial-population'),
mchatOnly: cat(status, 'mchat_only'),
psychology: cat(status, 'psychology'),
neuropediatrics: cat(status, 'neuropediatrics') + cat(status, 'eeg'),
confirmed:
confirmed === undefined
? '—'
: `${(confirmed * 100).toLocaleString('es-MX', { maximumFractionDigits: 1 })}%`,
toAdos: days('M26_DIAS_MCHAT_ADOS2'),
toDiagnosis: days('M27_DIAS_ADOS2_DIAGNOSTICO'),
whole: days('M25_DIAS_MCHAT_DIAGNOSTICO'),
diagnosed: n(withEeg, 'denominator'),
eeg: n(withEeg, 'numerator'),
missing: n(rd('M22_DIAGNOSTICADOS_SIN_EEG'), 'numerator'),
unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'),
};
});
protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || '';
}
/** A clinical section's route or figures, drawn from the applied period's reports. */
protected routeOf(section: Section): Figure | undefined {
if (section.kind !== 'route') return undefined;
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) }));
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined;
}
protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
switch (spec.kind) {
case 'donut':
return nestedDonut(r, spec.catalog, spec.center);
case 'share-donut':
return shareDonut(r, spec.catalog, spec.center);
case 'counts':
return countBars(r, spec.catalog, spec.axis, this.applied() ?? '');
case 'age-stack':
return ageStack(r, spec.names);
case 'age-share':
return ageShare(r, spec.names[0]);
case 'scenario-bars':
return scenarioBars(r, spec.catalog, spec.stratum, name);
case 'rates':
return rateDots(r, spec);
}
}
}
+169
View File
@@ -0,0 +1,169 @@
<section class="card risk-tea" aria-labelledby="tea-risk-title">
<h2 id="tea-risk-title" class="risk-title">Alteraciones de EEG relacionadas al TEA</h2>
<div class="filters">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" />
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana de meses</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 de EEG</mat-label>
<mat-select [value]="eeg()" (selectionChange)="setFilter(eeg.set.bind(eeg), $event.value)">
<mat-option value="">Todos</mat-option>
@for (s of eegStatuses | keyvalue; track s.key) {
<mat-option [value]="s.key">{{ s.value }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Grupo de edad</mat-label>
<mat-select [value]="age()" (selectionChange)="setFilter(age.set.bind(age), $event.value)">
<mat-option value="">Todos</mat-option>
@for (a of ages(); track a) {
<mat-option [value]="a">{{ ageLabel(a) }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Puntaje M-CHAT</mat-label>
<mat-select
[value]="mchat()"
(selectionChange)="setFilter(mchat.set.bind(mchat), $event.value)"
>
<mat-option value="">Todos</mat-option>
@for (b of mchatBands; track b.id) {
<mat-option [value]="b.id">{{ b.label }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>CSS ADOS-2</mat-label>
<mat-select [value]="css()" (selectionChange)="setFilter(css.set.bind(css), $event.value)">
<mat-option value="">Todos</mat-option>
@for (l of cssLevels; track l.id) {
<mat-option [value]="l.id">{{ l.label }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estado del caso</mat-label>
<mat-select
[value]="caseState()"
(selectionChange)="setFilter(caseState.set.bind(caseState), $event.value)"
>
<mat-option value="">Todos</mat-option>
@for (c of cases | keyvalue; track c.key) {
<mat-option [value]="c.key">{{ c.value }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Tipo de alteración</mat-label>
<mat-select
[value]="altered()"
(selectionChange)="setFilter(altered.set.bind(altered), $event.value)"
>
<mat-option value="">Todas</mat-option>
@for (a of alterations(); track a) {
<mat-option [value]="a">{{ alteration(a) }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="narrow">
<mat-label>Registros por página</mat-label>
<input
matInput
type="number"
min="10"
max="200"
[ngModel]="size()"
(ngModelChange)="size.set(+$event || 50); pageIndex.set(0)"
/>
</mat-form-field>
<button mat-stroked-button (click)="consult()">Consultar</button>
</div>
@if (loading()) {
<app-loading what="el seguimiento" />
} @else {
@let s = summary();
<div class="eeg-summary" aria-label="EEG de los pacientes filtrados">
<h3>EEG de los pacientes filtrados</h3>
<div class="counts">
<span
><strong>{{ s.normal }}</strong> Normales</span
>
<span
><strong>{{ s.abnormal }}</strong> Anormales</span
>
<span
><strong>{{ s.none }}</strong> Sin EEG válido</span
>
</div>
@if (s.alterations.length) {
<ul class="by-alteration">
@for (a of s.alterations; track a[0]) {
<li>
{{ alteration(a[0]) }}: <strong>{{ a[1] }}</strong>
</li>
}
</ul>
}
</div>
<table class="worklist">
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Estado del caso</th>
<th>Último EEG</th>
<th class="num">Puntaje M-CHAT</th>
<th class="num">CSS ADOS-2</th>
<th>Estatus de EEG</th>
</tr>
</thead>
<tbody>
@for (r of shown(); track r.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', r.patient.id]">{{
r.name
}}</a>
</td>
<td>{{ r.ageGroup ? ageLabel(r.ageGroup) : 'Sin dato' }}</td>
<td>{{ cases[r.case] ?? r.case }}</td>
<td>{{ r.lastEeg ?? '—' }}</td>
<td class="num">{{ r.mchat ?? '—' }}</td>
<td class="num">{{ r.css ?? '—' }}</td>
<td>{{ eegStatuses[r.eegStatus] ?? r.eegStatus }}</td>
</tr>
} @empty {
<tr>
<td colspan="7" class="muted">Nadie en la lista con estos filtros.</td>
</tr>
}
</tbody>
</table>
<div class="pager">
<button mat-button [disabled]="pageIndex() === 0" (click)="pageIndex.set(pageIndex() - 1)">
Anterior
</button>
<span>Página {{ pageIndex() + 1 }} de {{ pages() }} · {{ filtered().length }} pacientes</span>
<button
mat-button
[disabled]="pageIndex() + 1 >= pages()"
(click)="pageIndex.set(pageIndex() + 1)"
>
Siguiente
</button>
</div>
}
</section>
+80
View File
@@ -0,0 +1,80 @@
.risk-tea {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 8px;
margin-top: 24px;
padding: 16px;
}
.risk-title {
font-family: var(--font-heading);
font-size: 24px;
font-weight: 700;
margin: 0 0 16px;
}
.filters {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 16px;
.narrow {
width: 160px;
}
}
.eeg-summary {
border: 1px solid var(--color-border);
border-radius: 8px;
margin-bottom: 16px;
padding: 12px 16px;
h3 {
font-size: 16px;
font-weight: 500;
margin: 0 0 8px;
}
.counts {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.by-alteration {
columns: 2;
margin: 8px 0 0;
padding-left: 18px;
}
}
.pager {
align-items: center;
display: flex;
gap: 12px;
justify-content: flex-end;
margin-top: 8px;
}
.worklist {
border-collapse: collapse;
width: 100%;
th,
td {
border-bottom: 1px solid var(--color-border);
padding: 8px 10px;
text-align: left;
}
th {
font-size: 14px;
font-weight: 600;
}
.num {
text-align: right;
}
}
+176
View File
@@ -0,0 +1,176 @@
import { KeyValuePipe } 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 { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Patient } from 'fhir/r4';
import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { ageLabel } from './figures';
import { name } from './measures';
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */
export interface TeaRow {
patient: Patient;
name: string;
ageGroup: string;
case: string;
status: string;
eegStatus: string;
alterations: string[];
lastEeg?: string;
mchat?: number;
css?: number;
}
const has = (p: Patient, n: string) => (p.extension ?? []).filter((e) => e.url === EXT + n);
export function teaRow(p: Patient): TeaRow {
const coded = (n: string) => has(p, n)[0]?.valueCoding?.code ?? '';
return {
patient: p,
name: p.name?.[0]?.text ?? (p.id ?? '').slice(0, 8),
ageGroup: has(p, 'tea-age-group')[0]?.valueString ?? '',
case: coded('tea-case'),
status: coded('follow-up-status'),
eegStatus: coded('tea-eeg-status'),
alterations: has(p, 'tea-eeg-alteration').map((e) => e.valueCoding?.code ?? ''),
lastEeg: has(p, 'tea-last-eeg')[0]?.valueDate,
mchat: has(p, 'mchat-score')[0]?.valueInteger,
css: has(p, 'ados2-css')[0]?.valueInteger,
};
}
/** M-CHAT-R risk bands and ADOS-2 CSS levels, as the filters offer them. */
const MCHAT = [
{ id: 'low', label: 'Bajo (0 a 2)', test: (v: number) => v <= 2 },
{ id: 'medium', label: 'Medio (3 a 7)', test: (v: number) => v >= 3 && v <= 7 },
{ id: 'high', label: 'Alto (8 a 20)', test: (v: number) => v >= 8 },
];
const CSS = [
{ id: 'minimal', label: 'Mínimo (1 a 2)', test: (v: number) => v <= 2 },
{ id: 'low', label: 'Bajo (3 a 4)', test: (v: number) => v >= 3 && v <= 4 },
{ id: 'moderate', label: 'Moderado (5 a 7)', test: (v: number) => v >= 5 && v <= 7 },
{ id: 'high', label: 'Alto (8 a 10)', test: (v: number) => v >= 8 },
];
const EEG_STATUS: Record<string, string> = {
normal: 'Normal',
abnormal: 'Anormal',
no_valid_eeg: 'Sin EEG válido',
};
const CASE: Record<string, string> = {
confirmed: 'Diagnóstico confirmado',
in_process: 'En proceso',
not_confirmed: 'Sin TEA',
};
/** `theta_power:above` → "theta_power (aumentado)". */
export const alteration = (a: string) =>
a.replace(/:(above|below)$/, (_, s) => (s === 'above' ? ' (aumentado)' : ' (disminuido)'));
/** "Análisis de Riesgo" for TEA: the children active in the window, what their EEGs show,
* filtered as the old page filtered them. */
@Component({
selector: 'app-tab-riesgos-tea',
imports: [
FormsModule,
KeyValuePipe,
Loading,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
RouterLink,
],
templateUrl: './tab-riesgos-tea.html',
styleUrls: ['./tab-riesgos.scss', './tab-riesgos-tea.scss'],
})
export class TabRiesgosTea {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
protected readonly cutoff = signal('');
protected readonly window = signal(3);
protected readonly eeg = signal('');
protected readonly age = signal('');
protected readonly mchat = signal('');
protected readonly css = signal('');
protected readonly caseState = signal('');
protected readonly altered = signal('');
protected readonly size = signal(50);
protected readonly pageIndex = signal(0);
/** The query as last asked for ("Consultar"). */
private readonly asked = signal({ cutoff: '', window: 3 });
protected readonly mchatBands = MCHAT;
protected readonly cssLevels = CSS;
protected readonly eegStatuses = EEG_STATUS;
protected readonly cases = CASE;
protected readonly label = name;
protected readonly ageLabel = ageLabel;
protected readonly alteration = alteration;
private readonly list = resource({
params: () => ({ domain: this.domain(), ...this.asked() }),
loader: async ({ params: { domain, cutoff, window } }) => {
const pages = await this.fhir.all(domain, 'Patient', {
'follow-up-window': window,
...(cutoff ? { 'follow-up-cutoff': cutoff } : {}),
_count: 200,
});
return resources<Patient>(pages, 'Patient').map(teaRow);
},
});
protected readonly loading = computed(() => this.list.isLoading());
protected readonly all = computed(() => this.list.value() ?? []);
protected readonly ages = computed(() => [...new Set(this.all().map((r) => r.ageGroup))].sort());
protected readonly alterations = computed(() =>
[...new Set(this.all().flatMap((r) => r.alterations))].sort(),
);
/** The children the filters keep. */
protected readonly filtered = computed(() => {
const band = MCHAT.find((b) => b.id === this.mchat());
const level = CSS.find((l) => l.id === this.css());
return this.all().filter(
(r) =>
(!this.eeg() || r.eegStatus === this.eeg()) &&
(!this.age() || r.ageGroup === this.age()) &&
(!band || (r.mchat !== undefined && band.test(r.mchat))) &&
(!level || (r.css !== undefined && level.test(r.css))) &&
(!this.caseState() || r.case === this.caseState()) &&
(!this.altered() || r.alterations.includes(this.altered())),
);
});
protected readonly shown = computed(() =>
this.filtered().slice(this.pageIndex() * this.size(), (this.pageIndex() + 1) * this.size()),
);
protected readonly pages = computed(() =>
Math.max(1, Math.ceil(this.filtered().length / this.size())),
);
/** "EEG de los pacientes filtrados": how many normal, abnormal, without one, by alteration. */
protected readonly summary = computed(() => {
const rows = this.filtered();
const count = (s: string) => rows.filter((r) => r.eegStatus === s).length;
const by = new Map<string, number>();
for (const r of rows) for (const a of r.alterations) by.set(a, (by.get(a) ?? 0) + 1);
return {
normal: count('normal'),
abnormal: count('abnormal'),
none: count('no_valid_eeg'),
alterations: [...by.entries()].sort((a, b) => b[1] - a[1]),
};
});
protected consult(): void {
this.pageIndex.set(0);
this.asked.set({ cutoff: this.cutoff(), window: this.window() });
}
protected setFilter(set: (v: string) => void, value: string): void {
set(value);
this.pageIndex.set(0);
}
}
+58 -28
View File
@@ -10,7 +10,7 @@
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label>
<mat-label>Ventana de meses</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>
@@ -18,7 +18,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label>
<mat-label>Estatus de seguimiento</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option>
@for (s of statuses; track s) {
@@ -27,7 +27,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Horizonte</mat-label>
<mat-label>Horizonte de la probabilidad</mat-label>
<mat-select [value]="horizon()" (selectionChange)="horizon.set($event.value)">
@for (h of [1, 2, 3, 4, 5]; track h) {
<mat-option [value]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</mat-option>
@@ -35,7 +35,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Orden</mat-label>
<mat-label>Ordenar por</mat-label>
<mat-select [value]="sort()" (selectionChange)="sort.set($event.value)">
<mat-option value="-recent">Estudio más reciente</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option>
@@ -43,7 +43,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label>
<mat-label>Registros 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>
@@ -53,22 +53,33 @@
</form>
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
<p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
<button mat-button type="button" (click)="retry()">Reintentar seguimiento</button>
</p>
} @else if (!page() || loading()) {
<app-loading what="seguimiento" />
} @else if (applied()) {
<p class="muted window">Ventana consultada: {{ start() }} al {{ applied() }}.</p>
}
<div class="table-wrap card">
<table class="plain worklist">
<caption>
Resultados disponibles por paciente
</caption>
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Estatus</th>
<th>Estatus de seguimiento</th>
<th>Última citología</th>
<th>VPH</th>
<th>Biopsia</th>
<th>Riesgo LIEAG+ ({{ horizon() }} a)</th>
<th>Riesgo cáncer ({{ horizon() }} a)</th>
<th>Días toma → diagnóstico</th>
<th>Último resultado de VPH</th>
<th>Última biopsia</th>
<th>Probabilidad a LIEAG+ a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Probabilidad a cáncer a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Estudio más reciente</th>
<th>Días de toma a diagnóstico</th>
</tr>
</thead>
<tbody>
@@ -86,7 +97,6 @@
<td>{{ name(row.status) }}</td>
<td>
@if (row.cytology; as c) {
{{ c.date }} ·
{{
c.result
? name(c.result)
@@ -94,40 +104,61 @@
? 'Insatisfactoria'
: 'Pendiente'
}}
<small>Fecha: {{ c.date }}</small>
<small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
} @else {
—
No disponible
}
</td>
<td>
@if (row.hpv; as h) {
{{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }}
{{ h.positive ? 'Positivo' : 'Negativo' }}
<small>Fecha: {{ h.date }}</small>
<small
>Genotipo 16/18:
{{
h.types1618 === undefined
? 'No disponible'
: h.types1618
? 'Presente'
: 'No detectado'
}}</small
>
} @else {
—
No disponible
}
</td>
<td>
@if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }}
{{ name(b.histology ?? '') || 'Sin grado' }}
<small>Fecha: {{ b.date }}</small>
} @else {
—
No disponible
}
</td>
<td class="num">
{{ row.risk.cin2 === undefined ? '—' : (row.risk.cin2 * 100 | number: '1.1-1') + ' %' }}
{{
row.risk.cin2 === undefined
? 'No disponible'
: (row.risk.cin2 * 100 | number: '1.1-1') + ' %'
}}
</td>
<td class="num">
{{
row.risk.cancer === undefined ? '—' : (row.risk.cancer * 100 | number: '1.1-1') + ' %'
row.risk.cancer === undefined
? 'No disponible'
: (row.risk.cancer * 100 | number: '1.1-1') + ' %'
}}
</td>
<td class="num">{{ row.daysToDiagnosis ?? '—' }}</td>
<td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr>
} @empty {
<tr>
<td colspan="9" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td>
</tr>
@if (page() && !loading()) {
<tr>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
}
</tbody>
</table>
@@ -136,8 +167,7 @@
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte
{{ applied() }}
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
+14
View File
@@ -40,3 +40,17 @@ a {
.pager .muted {
margin-right: auto;
}
.worklist td small {
display: block;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
.worklist caption {
text-align: left;
font-weight: 500;
padding: 8px 0;
}
.window {
margin: 4px 0 8px;
}
+26 -2
View File
@@ -8,7 +8,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { rows, windowStart } from './follow-up';
import { Row, rows, windowStart } from './follow-up';
import { Loading } from '../loading';
import { name } from './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
@@ -20,6 +21,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
imports: [
DecimalPipe,
FormsModule,
Loading,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
@@ -65,7 +67,9 @@ export class TabRiesgos {
},
});
protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value());
protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
@@ -84,6 +88,26 @@ export class TabRiesgos {
});
protected readonly error = computed(() => this.first.error());
/** "Ventana consultada": the window's first day for the applied cut-off. */
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
/** "Estudio más reciente": her latest cytology or HPV sample. */
protected latest(row: Row): string | undefined {
return [row.cytology?.date, row.hpv?.date]
.filter((d) => !!d)
.sort()
.at(-1)
?.slice(0, 10);
}
protected retry(): void {
this.first.reload();
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
+30 -17
View File
@@ -10,7 +10,7 @@
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label>
<mat-label>Ventana de meses</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>
@@ -18,7 +18,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label>
<mat-label>Estatus de seguimiento</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option>
@for (s of statuses; track s) {
@@ -27,7 +27,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label>
<mat-label>Registros 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>
@@ -37,18 +37,28 @@
</form>
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
<p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
<button mat-button type="button" (click)="retry()">Reintentar seguimiento</button>
</p>
} @else if (!page() || loading()) {
<app-loading what="seguimiento" />
} @else if (applied()) {
<p class="muted window">Ventana consultada: {{ start() }} al {{ applied() }}.</p>
}
<div class="table-wrap card">
<table class="plain worklist">
<caption>
Resultados disponibles por paciente
</caption>
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Mastografía</th>
<th>Biopsia</th>
<th>Estatus</th>
<th>Última mastografía</th>
<th>Última biopsia</th>
<th>Estatus de seguimiento</th>
<th>Prioridad</th>
</tr>
</thead>
@@ -64,23 +74,27 @@
}
</td>
<td>{{ row.ageGroup }}</td>
<td>{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }}</td>
<td>
{{ name(row.mammogram.birads ?? '') || 'Sin dato' }}
<small>Fecha: {{ row.mammogram.date }}</small>
</td>
<td>
@if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }}
{{ name(b.histology ?? '') || 'Sin resultado' }}
<small>Fecha: {{ b.date }}</small>
} @else {
—
No disponible
}
</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>
@if (page() && !loading()) {
<tr>
<td colspan="6" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
}
</tbody>
</table>
@@ -89,8 +103,7 @@
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte
{{ applied() }}
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
+17 -2
View File
@@ -7,7 +7,8 @@ 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 { camaRows, windowStart } from './follow-up';
import { Loading } from '../loading';
import { name, PRIORITY } from './measures';
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
@@ -18,6 +19,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy
selector: 'app-tab-seguimiento',
imports: [
FormsModule,
Loading,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
@@ -59,7 +61,9 @@ export class TabSeguimiento {
},
});
protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value());
protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
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') ?? '') : '';
@@ -75,6 +79,17 @@ export class TabSeguimiento {
});
protected readonly error = computed(() => this.first.error());
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
protected retry(): void {
this.first.reload();
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
+90 -38
View File
@@ -1,57 +1,92 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { history, periods, PeriodType, periodTypes, reading } from './measures';
import { historyFigure } from './figures';
import { periodLabel, periods, PeriodType, reading } from './measures';
import { HISTORY, HistoryPanel } from './pages';
/** Each measure over time: every period of the chosen kind, oldest first. */
interface Drawn {
panel: HistoryPanel;
/** the group's heading, on the first panel of its run */
heading?: string;
figure?: Figure;
}
/** Trazabilidad as the old tab: the domain's declared panels (pages.HISTORY), in their order,
* each measure period by period. */
@Component({
selector: 'app-tab-trazabilidad',
imports: [MatButtonToggleModule, MatCardModule, Plot],
imports: [Loading, MatButtonToggleModule, Plot],
template: `
<div class="bar">
<section class="card filters" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group
[value]="type()"
(change)="type.set($event.value)"
aria-label="Intervalo"
aria-label="Intervalo de análisis"
>
<mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group>
</div>
</section>
@if (series.isLoading()) {
<p class="muted">Calculando…</p>
}
<div class="grid">
@for (item of figures(); track item.measure.id) {
<mat-card appearance="outlined" [attr.data-measure]="item.measure.name">
<mat-card-header
><mat-card-title>{{ item.measure.title }}</mat-card-title></mat-card-header
>
<mat-card-content><app-plot [figure]="item.figure" [height]="280" /></mat-card-content>
</mat-card>
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" />
} @else if (series.error()) {
<p class="muted" role="alert">
No se pudo cargar la trazabilidad.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p>
} @else {
@for (d of drawn(); track d.panel.measure) {
@if (d.heading) {
<h2 class="group-title">{{ d.heading }}</h2>
}
<section class="card panel" [attr.data-measure]="d.panel.measure">
@if (d.panel.group) {
<h3 class="panel-title">{{ d.panel.title }}</h3>
} @else {
<h2 class="panel-title">{{ d.panel.title }}</h2>
}
@if (d.figure) {
<app-plot [figure]="d.figure" [height]="320" />
} @else {
<p class="muted">Sin datos para el periodo.</p>
}
</section>
}
</div>
}
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.bar {
.card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
margin-bottom: 16px;
}
.grid {
display: grid;
gap: 16px;
grid-template-columns: 1fr;
.filters-title {
font-size: 16px;
font-weight: 500;
margin: 0 0 12px;
}
@media (min-width: 1304px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
.panel-title,
.group-title {
font-size: 20px;
font-weight: 700;
margin: 0 0 8px;
}
h3.panel-title {
font-size: 16px;
}
.group-title {
margin: 24px 0 12px;
}
`,
})
@@ -59,31 +94,48 @@ export class TabTrazabilidad {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('semester');
protected readonly type = signal<PeriodType>('month');
protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
loader: async ({ params }) => {
const history = HISTORY[params.domain];
if (!history) return [];
const asked = periods(params.type).reverse();
const shown = params.measures.filter((m) => periodTypes(m).includes(params.type));
return Promise.all(
shown.map(async (measure) => {
history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure);
if (!measure) return { panel, points: [] };
const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!,
'reporting-period': asked.join(','),
});
// One report per period asked, in the order asked.
const found = resources<MeasureReport>(pages, 'MeasureReport');
return { measure, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
return { panel, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
}),
);
},
});
protected readonly figures = computed<{ measure: Measure; figure: Figure }[]>(() =>
(this.series.value() ?? []).map(({ measure, points }) => {
// From the first period with data on.
const first = points.findIndex((p) => (p.r?.populations['initial-population'] ?? 0) > 0);
return { measure, figure: history(measure, first < 0 ? [] : points.slice(first)) };
}),
);
protected readonly drawn = computed<Drawn[]>(() => {
const history = HISTORY[this.domain()];
const xTitle = this.type() === 'month' ? 'Mes y año' : 'Semestre';
let group: string | undefined;
if (!this.series.hasValue()) return [];
return this.series.value().map(({ panel, points }) => {
const heading = panel.group && panel.group !== group ? panel.group : undefined;
group = panel.group;
const has = (p: (typeof points)[number]) => (p.r?.populations['initial-population'] ?? 0) > 0;
const first = points.findIndex(has);
if (first < 0 || !history) return { panel, heading };
const last = points.length - 1 - [...points].reverse().findIndex(has);
const shown =
history.months && this.type() === 'month'
? points.slice(Math.max(first, last + 1 - history.months), last + 1)
: points.slice(first, last + 1);
const series = shown.map((p) => ({ label: periodLabel(p.period), r: p.r }));
return { panel, heading, figure: historyFigure(panel, series, history.line, xTitle) };
});
});
}
+46
View File
@@ -0,0 +1,46 @@
import { Component, input } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
/** What a page or a figure shows while its data comes, as the old app did: a progress bar
* named for what loads, "Cargando …" in words, and for a figure the place it will take. */
@Component({
selector: 'app-loading',
imports: [MatProgressBarModule],
template: `
<mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + what()" />
<p class="state" role="status">{{ text() || 'Cargando ' + what() + '…' }}</p>
@if (figure()) {
<div class="skeleton" aria-hidden="true"></div>
}
`,
styles: `
:host {
display: flex;
flex-direction: column;
}
:host(.figure) {
min-height: 12rem;
}
.state {
color: var(--color-text-secondary);
font-size: 0.875rem;
margin: 8px 0;
}
.skeleton {
background: var(--color-border);
border-radius: 10px;
flex: 1;
min-height: 10rem;
opacity: 0.35;
}
`,
host: { '[class.figure]': 'figure()' },
})
export class Loading {
/** What is loading, in words: "los indicadores", "la figura". */
readonly what = input.required<string>();
/** The whole line instead ("Calculando los indicadores…"). */
readonly text = input('');
/** A figure's skeleton under the bar. */
readonly figure = input(false);
}
+281 -1
View File
@@ -146,8 +146,288 @@
}
</mat-card-content>
</mat-card>
@if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
<mat-card-content>
@if (ados2(); as a) {
<h3>Puntajes por reactivo · {{ a.date }}</h3>
<app-plot [figure]="a.figure" [height]="a.height" />
<p class="totals">
@for (t of a.totals; track t.label) {
<span
>{{ t.label }}: <strong>{{ t.value }}</strong></span
>
}
</p>
} @else {
<p class="muted">Sin evaluación ADOS-2.</p>
}
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" class="wide" data-section="eeg">
<mat-card-header><mat-card-title>EEG</mat-card-title></mat-card-header>
<mat-card-content>
@if (eeg.isLoading()) {
<app-loading what="el EEG" />
} @else if (eeg.value()?.study; as st) {
<h3>Calidad del EEG</h3>
<p>
Estudio del {{ st.study_date }}:
<strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong>
@if (st.level) {
({{ st.level }})
}
</p>
<h3>Alteraciones del EEG</h3>
@if (!st.valid) {
<p class="muted">Un EEG no aceptable no se compara con la norma por edad.</p>
} @else if (!scored()) {
<p class="muted">
Ninguna curva por edad vigente ha evaluado este EEG (se promueven en Gobernanza).
</p>
} @else if (alterations().length) {
<table class="plain">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>Norma por edad (P5–P95)</th>
<th>Mediana</th>
<th>Desviación (z)</th>
<th>Detalle</th>
</tr>
</thead>
<tbody>
@for (m of alterations(); track m.code) {
<tr [class.chosen]="zoned()?.code === m.code">
<td>
<button
mat-button
type="button"
class="metric"
[attr.aria-expanded]="zoned()?.code === m.code"
(click)="zone.set(zoned()?.code === m.code ? undefined : m.code)"
>
{{ metricNames[m.code] ?? m.code }}
</button>
</td>
<td>{{ m.value | number: '1.0-3' }}</td>
<td>{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}</td>
<td>{{ m.median | number: '1.0-3' }}</td>
<td>{{ m.z | number: '1.1-2' }}</td>
<td>{{ m.outside! > 0 ? 'Aumentado' : 'Disminuido' }}</td>
</tr>
}
</tbody>
</table>
<p class="muted">Elija una alteración para ver sus zonas más afectadas.</p>
@if (zoned(); as z) {
<section class="zones" aria-label="Zonas más afectadas">
<h3>Zonas más afectadas</h3>
<p class="muted">
{{ metricNames[z.code] ?? z.code }} ·
{{
zonesScored()
? 'desviación de cada zona frente a su norma por edad'
: 'valor de cada zona (sin norma por edad por zona)'
}}
</p>
@if (z.electrodes.length) {
<app-plot [figure]="head()" [height]="280" />
}
@if (z.zones.length) {
<ol class="regions" aria-label="Zonas ordenadas por desviación">
@for (r of zoneOrder(); track r.site) {
<li [class.marked]="(r.z ?? 0) >= 2 || (r.z ?? 0) <= -2">
<span>{{ zoneNames[r.site] ?? r.site }}</span>
<span>{{
r.z !== null && r.z !== undefined
? 'z = ' + (r.z | number: '1.1-2')
: (r.value | number: '1.0-3')
}}</span>
</li>
}
</ol>
} @else if (!z.electrodes.length) {
<p class="muted">Esta métrica no se mide por zona.</p>
}
</section>
}
} @else {
<p>Sin alteraciones: todas sus métricas están dentro de la norma por edad.</p>
}
@if (st.valid && scored()) {
<section
class="relation"
aria-label="Relación de las alteraciones del EEG con el ADOS-2"
>
<h3>Relación con el ADOS-2</h3>
@if (!eeg.value()?.analysis?.relation?.length) {
<p class="muted">
Ningún modelo de asociación vigente ha evaluado este EEG (se promueven en
Gobernanza).
</p>
} @else if (!related().length) {
<p>
Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara
con el ADOS-2 en la cohorte.
</p>
} @else {
<p class="muted">
Modelo de asociación ajustado en la cohorte ({{ related()[0].n }} niños, por
edad y módulo del ADOS-2): qué tanto se asocia cada alteración del EEG por
zona con un aspecto del ADOS-2. No es un diagnóstico ni indica qué causa qué.
</p>
<table class="plain">
<thead>
<tr>
<th>Zona del EEG</th>
<th>Aspecto del ADOS-2</th>
<th>Asociación en la cohorte</th>
<th>Probabilidad para este paciente</th>
<th>Lo que muestra su ADOS-2</th>
</tr>
</thead>
<tbody>
@for (f of related(); track f.biomarker + f.zone + f.outcome_code) {
<tr>
<td>
<strong>{{ biomarkerNames[f.biomarker] ?? f.biomarker }}</strong>
<small
>{{ zoneNames[f.zone] ?? f.zone }} · z =
{{ f.z | number: '1.1-2' }}</small
>
</td>
<td>
{{ outcomeNames[f.outcome_code] ?? f.outcome_code }}
<small>{{ f.kind === 'item' ? 'Reactivo' : 'Dominio' }}</small>
</td>
<td>
OR {{ f.odds_ratio | number: '1.2-2' }}
<small
>IC 95 % {{ f.ci_low | number: '1.2-2' }}–{{
f.ci_high | number: '1.2-2'
}}
· q {{ qText(f.q) }}</small
>
<small>{{
f.odds_ratio >= 1
? 'A mayor z, mayor probabilidad'
: 'A menor z, mayor probabilidad'
}}</small>
</td>
<td>
<strong>{{ f.probability * 100 | number: '1.0-0' }} %</strong>
<small
>{{ f.event }} · con z = 0:
{{ f.reference_probability * 100 | number: '1.0-0' }} %</small
>
</td>
<td>
{{ observed(f) }}
@if (matches(f); as m) {
<small>{{ m }}</small>
}
</td>
</tr>
}
</tbody>
</table>
<p class="muted">
OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga
alterado; menor que 1, al revés. Solo se muestran las zonas alteradas del
paciente (|z| ≥ 2) con una asociación clara en la cohorte (q &lt; 0.05).
Versión del modelo: {{ related()[0].model }}.
</p>
}
</section>
}
} @else {
<p class="muted">Sin EEG analizado.</p>
}
</mat-card-content>
</mat-card>
}
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header
><mat-card-title>Análisis de supervivencia</mat-card-title></mat-card-header
>
<mat-card-content>
@if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas.
</p>
}
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
}
</mat-card-content>
</mat-card>
}
@if (recurrenceModel(); as rm) {
<mat-card appearance="outlined" class="wide" data-section="recurrencia">
<mat-card-header
><mat-card-title>Análisis de recurrencia</mat-card-title></mat-card-header
>
<mat-card-content>
<table class="plain">
<thead>
<tr>
<th>Horizonte</th>
<th>Probabilidad de recurrencia</th>
</tr>
</thead>
<tbody>
@for (p of rm.predictions; track p.years) {
<tr>
<td>{{ p.years | number: '1.0-1' }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td class="num">{{ p.p * 100 | number: '1.1-1' }} %</td>
</tr>
}
</tbody>
</table>
@if (recurrence.isLoading()) {
<app-loading what="las curvas de recurrencia" [figure]="true" />
} @else if (recurrence.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios tienen menos recaídas de las necesarias para trazar curvas.
</p>
}
} @else if (recurrence.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
}
</mat-card-content>
</mat-card>
}
</div>
} @else if (loading()) {
<p class="muted">Cargando…</p>
<app-loading what="el expediente" />
}
</section>
+55
View File
@@ -33,3 +33,58 @@
mat-card-content {
overflow-x: auto;
}
.scenarios {
display: flex;
flex-wrap: wrap;
gap: 6px 8px;
list-style: none;
margin: 0 0 12px;
padding: 0;
li {
background: var(--color-action-hover, #f1f6f6);
border: 1px solid var(--color-border);
border-radius: 999px;
font-size: 13px;
padding: 2px 10px;
}
}
.totals {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.zones {
margin-top: 12px;
}
.regions {
list-style: none;
margin: 8px 0 0;
padding: 0;
max-width: 420px;
li {
display: flex;
justify-content: space-between;
padding: 4px 8px;
border-bottom: 1px solid var(--mat-sys-outline-variant);
}
li.marked {
font-weight: 600;
color: var(--mat-sys-error);
}
}
tr.chosen td {
background: var(--mat-sys-surface-container);
}
.relation {
margin-top: 16px;
td small {
display: block;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
}
+189 -5
View File
@@ -12,16 +12,35 @@ import type {
Procedure,
RiskAssessment,
} from 'fhir/r4';
import { code, ext, Fhir, label, resources } from '../fhir';
import { Api } from '../api/api';
import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study';
import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { CURP } from '../indicadores/follow-up';
import { name } from '../indicadores/measures';
import { LABELS, name } from '../indicadores/measures';
import {
BIOMARKER_NAMES,
byDeviation,
headMap,
METRIC_NAMES,
OUTCOME_NAMES,
ZONE_NAMES,
} from '../eeg-labels';
import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading';
/** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string {
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
if (o.valueCodeableConcept)
return name(code(o.valueCodeableConcept) ?? '') || label(o.valueCodeableConcept);
if (o.valueCodeableConcept) {
// The screens' own name for the code (BI-RADS 4C), else the server's display.
const c = code(o.valueCodeableConcept) ?? '';
return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept);
}
if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim();
return o.valueString ?? o.valueDateTime ?? '';
}
@@ -30,12 +49,13 @@ function shown(o: Observation): string {
* champion models' risks with their curves. Everything read from the FHIR API. */
@Component({
selector: 'app-paciente',
imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
imports: [Loading, DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
})
export class Paciente {
private readonly fhir = inject(Fhir);
private readonly api = inject(Api);
readonly domain = input.required<string>();
readonly id = input.required<string>();
@@ -114,7 +134,12 @@ export class Paciente {
return [...latest.values()].map((r) => ({
model: code(r.method) ?? '',
text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '',
// the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico')
.map((e) => e.valueString ?? ''),
predictions: (r.prediction ?? []).map((p) => ({
years: p.whenRange?.high?.value ?? 0,
p: p.probabilityDecimal ?? 0,
@@ -123,7 +148,166 @@ export class Paciente {
})),
}));
});
/** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical
* scenarios, from the report of the model version that scored her. */
protected readonly survival = this.analysis('survival');
protected readonly recurrence = this.analysis('recurrence');
protected readonly recurrenceModel = computed(() =>
this.models().find((m) => m.model.endsWith('.recurrence') && m.version),
);
private analysis(name: 'survival' | 'recurrence') {
return resource({
params: () => {
const m = this.models().find(
(x) => x.model === `${this.domain()}.${name}` && x.scenarios.length && x.version,
);
return m ? { m, domain: this.domain() } : undefined;
},
loader: async ({ params: { m, domain } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: domain as Domain,
name,
version: m.version,
report: 'interpretability',
});
const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
if (name === 'recurrence') {
const r = (report?.['recurrencia'] ?? {}) as any;
return {
scenarios: m.scenarios,
figures: mine(r['escenarios'] ?? []).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
e,
r['horizons_months'],
'Supervivencia libre de recaída',
),
),
};
}
return {
scenarios: m.scenarios,
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
};
},
});
}
/** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's
* `ados2.*` fields), item by item, and its totals. */
protected readonly ados2 = computed(() => {
const d = this.data.value();
if (!d) return undefined;
const field = (o: Observation) => (code(o.code) ?? '').replace(/^ados2\./, '');
const scored = [...d.observations.values()].filter(
(o) => (code(o.code) ?? '').startsWith('ados2.') && o.valueQuantity?.value !== undefined,
);
const latest = scored
.map((o) => o.effectiveDateTime ?? '')
.sort()
.at(-1);
if (latest === undefined) return undefined;
const results = scored.filter((o) => (o.effectiveDateTime ?? '') === latest);
const totals = ['social_affect_total', 'restricted_repetitive_total', 'overall_total'];
const items = results.filter((o) => !totals.includes(field(o)));
const figure: Figure = {
data: [
{
type: 'bar',
orientation: 'h',
y: items.map((o) => label(o.code)),
x: items.map((o) => o.valueQuantity!.value!),
marker: { color: PALETTE[0] },
hovertemplate: '%{y}: %{x}<extra></extra>',
},
],
layout: {
showlegend: false,
margin: { t: 10, r: 16, b: 40, l: 16 },
xaxis: { title: { text: 'Puntaje (0 a 3)' }, range: [0, 3], dtick: 1 },
yaxis: { autorange: 'reversed', automargin: true, type: 'category' },
},
};
return {
date: latest.slice(0, 10),
figure,
height: 60 + items.length * 22,
totals: results
.filter((o) => totals.includes(field(o)))
.map((o) => ({ label: label(o.code), value: o.valueQuantity!.value! })),
};
});
/** TEA: her EEG as analysed (the latest), its quality and its metrics against the age
* curves: those outside the band are its alterations. */
protected readonly eeg = resource({
params: () => (this.domain() === 'tea' ? this.id() : undefined),
loader: async ({ params: person }) => {
const mine = (await this.api.invoke(eegStudies))
.filter((s) => s.person_id === person && s.analysed)
.sort((a, b) => b.study_date.localeCompare(a.study_date));
if (!mine.length) return { study: undefined, analysis: undefined };
return {
study: mine[0],
analysis: await this.api.invoke(eegStudy, { eeg_id: mine[0].id }),
};
},
});
protected readonly alterations = computed(() =>
(this.eeg.value()?.analysis?.metrics ?? []).filter((m) => m.outside),
);
protected readonly scored = computed(() =>
(this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined),
);
protected readonly shown = signal<string | undefined>(undefined);
protected readonly metricNames = METRIC_NAMES;
protected readonly zoneNames = ZONE_NAMES;
/** "Zonas más afectadas": the alteration chosen, its zones and electrodes. */
protected readonly zone = signal<string | undefined>(undefined);
protected readonly zoned = computed(() => {
const m = this.alterations().find((a) => a.code === this.zone());
return m ? { code: m.code, zones: m.zones ?? [], electrodes: m.electrodes ?? [] } : undefined;
});
protected readonly zonesScored = computed(() =>
[...(this.zoned()?.zones ?? []), ...(this.zoned()?.electrodes ?? [])].some(
(s) => s.z !== null && s.z !== undefined,
),
);
protected readonly biomarkerNames = BIOMARKER_NAMES;
protected readonly outcomeNames = OUTCOME_NAMES;
/** "Relación con el ADOS-2": her altered zones (|z| ≥ 2) with a clear association in the
* cohort (q < 0.05), clearest first, as the old summary showed them. */
protected readonly related = computed(() =>
(this.eeg.value()?.analysis?.relation ?? [])
.filter((f) => Math.abs(f.z) >= 2 && f.q !== null && f.q !== undefined && f.q < 0.05)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1)),
);
protected qText(q?: number | null): string {
return q === null || q === undefined ? '—' : q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`;
}
protected observed(f: Relation): string {
if (f.observed === null || f.observed === undefined) return 'Sin dato';
if (f.kind === 'item')
return f.observed >= 1 ? `Alterado (${f.observed})` : 'Sin anormalidad (0)';
return `CSS ${f.observed}`;
}
/** Whether what she shows is what the model leans to (above or below one half). */
protected matches(f: Relation): string | undefined {
if (f.observed === null || f.observed === undefined) return undefined;
const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8;
return present === f.probability >= 0.5
? 'Coincide con lo que el modelo esperaba'
: 'No coincide con lo que el modelo esperaba';
}
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
protected readonly curve = computed<Figure>(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
return {
+1
View File
@@ -33,6 +33,7 @@ const ENTITIES: Record<Entity, string> = {
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',