From 672091d19a0fab6cfb21bb72587a64caca1d138c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Fri, 27 Nov 2026 16:25:01 -0600
Subject: [PATCH 01/32] Client for extract fields taken from columns
---
openapi.json | 8 ++++++++
src/app/api/models/extract.ts | 3 +++
2 files changed, 11 insertions(+)
diff --git a/openapi.json b/openapi.json
index ca0cacd..77e232e 100644
--- a/openapi.json
+++ b/openapi.json
@@ -184,6 +184,14 @@
],
"title": "Column"
},
+ "columns": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "default": {},
+ "title": "Columns",
+ "type": "object"
+ },
"concept_map": {
"anyOf": [
{
diff --git a/src/app/api/models/extract.ts b/src/app/api/models/extract.ts
index f3253f8..69490cb 100644
--- a/src/app/api/models/extract.ts
+++ b/src/app/api/models/extract.ts
@@ -13,6 +13,9 @@ import { Position } from '../models/position';
*/
export interface Extract {
column: (string | Array);
+ 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';
formats?: {
From cc22840c3c276a48efbed0cfe59bca16da542d9c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Fri, 27 Nov 2026 19:17:49 -0600
Subject: [PATCH 02/32] Client for otherwise routes and unrecognised documents
---
openapi.json | 61 +++++++++++++++++++++++++--
src/app/api/fn/review/unrecognised.ts | 35 +++++++++++++++
src/app/api/functions.ts | 2 +
src/app/api/models/route.ts | 7 ++-
4 files changed, 100 insertions(+), 5 deletions(-)
create mode 100644 src/app/api/fn/review/unrecognised.ts
diff --git a/openapi.json b/openapi.json
index 77e232e..62f1427 100644
--- a/openapi.json
+++ b/openapi.json
@@ -878,7 +878,7 @@
},
"Route": {
"additionalProperties": false,
- "description": "Only the rows where every condition holds (e.g. reports titled \"Citolog\u00eda\").",
+ "description": "Only the rows where every condition holds (e.g. reports titled \"Citolog\u00eda\"). An\n`otherwise` route takes the rows of its input that none of the other routes on that\ninput take (documents nobody recognises, for a reviewer), then its own conditions.",
"properties": {
"id": {
"maxLength": 40,
@@ -907,6 +907,11 @@
"title": "Label",
"type": "string"
},
+ "otherwise": {
+ "default": false,
+ "title": "Otherwise",
+ "type": "boolean"
+ },
"position": {
"anyOf": [
{
@@ -918,6 +923,7 @@
]
},
"when": {
+ "default": [],
"items": {
"$ref": "#/components/schemas/Condition"
},
@@ -926,8 +932,7 @@
}
},
"required": [
- "id",
- "when"
+ "id"
],
"title": "Route",
"type": "object"
@@ -2730,6 +2735,56 @@
]
}
},
+ "/review/unrecognised": {
+ "get": {
+ "description": "Documents a pipeline's routes don't recognise (what its `otherwise` routes took):\na new layout, a study the platform doesn't know, a scan nothing could read.",
+ "operationId": "unrecognised",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "pipeline",
+ "required": true,
+ "schema": {
+ "maxLength": 40,
+ "pattern": "^[a-z][a-z0-9_]*$",
+ "title": "Pipeline",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Response Unrecognised",
+ "type": "array"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Unrecognised",
+ "tags": [
+ "review"
+ ]
+ }
+ },
"/runs/{run_id}": {
"get": {
"operationId": "run_status",
diff --git a/src/app/api/fn/review/unrecognised.ts b/src/app/api/fn/review/unrecognised.ts
new file mode 100644
index 0000000..6dae77a
--- /dev/null
+++ b/src/app/api/fn/review/unrecognised.ts
@@ -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>> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse>;
+ })
+ );
+}
+
+unrecognised.PATH = '/review/unrecognised';
diff --git a/src/app/api/functions.ts b/src/app/api/functions.ts
index eb51e68..83cb499 100644
--- a/src/app/api/functions.ts
+++ b/src/app/api/functions.ts
@@ -59,6 +59,8 @@ 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';
diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts
index 47395e6..de24e93 100644
--- a/src/app/api/models/route.ts
+++ b/src/app/api/models/route.ts
@@ -5,13 +5,16 @@ 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;
kind?: 'route';
label?: string;
+ otherwise?: boolean;
position?: (Position | null);
- when: Array;
+ when?: Array;
}
From 198aae59dae83dc51193425d2bd8af561a84d2ac Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 09:30:00 -0600
Subject: [PATCH 03/32] 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
---
e2e/pages.spec.ts | 70 +-
openapi.json | 1704 ++++++++++++++++-
src/app/api/fn/auth/auth-cookie-login.ts | 32 +
src/app/api/fn/auth/auth-cookie-logout.ts | 29 +
src/app/api/fn/ingest/browse.ts | 32 +
src/app/api/fn/ingest/oauth-start.ts | 34 +
src/app/api/fn/ingest/source-types.ts | 30 +
src/app/api/fn/ingest/test-source.ts | 35 +
src/app/api/fn/ingest/upload.ts | 9 +-
src/app/api/fn/users/register-register.ts | 33 +
src/app/api/fn/users/users-current-user.ts | 30 +
src/app/api/fn/users/users-delete-user.ts | 31 +
.../api/fn/users/users-patch-current-user.ts | 33 +
src/app/api/fn/users/users-patch-user.ts | 35 +
src/app/api/fn/users/users-user.ts | 32 +
src/app/api/functions.ts | 24 +
src/app/api/models.ts | 19 +
src/app/api/models/answers.ts | 11 +
src/app/api/models/body-upload.ts | 3 +-
src/app/api/models/browsed.ts | 9 +
src/app/api/models/catalog.ts | 19 +
src/app/api/models/condition.ts | 8 +
src/app/api/models/entry.ts | 9 +
src/app/api/models/error-model.ts | 8 +
src/app/api/models/extract.ts | 20 +
src/app/api/models/fhir.ts | 4 +
src/app/api/models/field-spec.ts | 15 +
src/app/api/models/group.ts | 7 +
src/app/api/models/guided.ts | 14 +
src/app/api/models/join.ts | 8 +
src/app/api/models/link.ts | 12 +
src/app/api/models/listing.ts | 15 +
src/app/api/models/login.ts | 11 +
src/app/api/models/map.ts | 20 +
src/app/api/models/option.ts | 7 +
src/app/api/models/provider.ts | 17 +
src/app/api/models/read.ts | 8 +
src/app/api/models/route.ts | 8 +
src/app/api/models/sign-in.ts | 7 +
src/app/api/models/source-type.ts | 22 +
src/app/api/models/source.ts | 26 +
src/app/api/models/target.ts | 8 +
src/app/api/models/tested.ts | 12 +
src/app/api/models/uploaded.ts | 7 +
src/app/api/models/user-create.ts | 13 +
src/app/api/models/user-read.ts | 13 +
src/app/api/models/user-update.ts | 13 +
src/app/app.html | 23 +-
src/app/app.routes.ts | 47 +-
src/app/app.scss | 5 +
src/app/app.ts | 15 +-
src/app/auth/auth.ts | 83 +
src/app/auth/login.html | 49 +
src/app/auth/login.scss | 141 ++
src/app/auth/login.ts | 42 +
src/app/conectar/conectar.html | 40 +-
src/app/conectar/conectar.scss | 31 +
src/app/conectar/conectar.ts | 87 +-
src/app/conectar/source-dialog.html | 369 ++++
src/app/conectar/source-dialog.scss | 230 +++
src/app/conectar/source-dialog.ts | 349 ++++
src/app/gobernanza/figures.ts | 4 +-
src/app/gobernanza/gobernanza.html | 2 +-
src/app/gobernanza/gobernanza.ts | 2 +
src/app/indicadores/indicadores.ts | 4 +-
src/app/indicadores/tab-indicadores.html | 2 +-
src/app/indicadores/tab-indicadores.ts | 2 +
src/app/indicadores/tab-trazabilidad.ts | 5 +-
src/app/loading.ts | 46 +
src/app/paciente/paciente.html | 32 +-
src/app/paciente/paciente.scss | 17 +
src/app/paciente/paciente.ts | 45 +-
72 files changed, 4122 insertions(+), 116 deletions(-)
create mode 100644 src/app/api/fn/auth/auth-cookie-login.ts
create mode 100644 src/app/api/fn/auth/auth-cookie-logout.ts
create mode 100644 src/app/api/fn/ingest/browse.ts
create mode 100644 src/app/api/fn/ingest/oauth-start.ts
create mode 100644 src/app/api/fn/ingest/source-types.ts
create mode 100644 src/app/api/fn/ingest/test-source.ts
create mode 100644 src/app/api/fn/users/register-register.ts
create mode 100644 src/app/api/fn/users/users-current-user.ts
create mode 100644 src/app/api/fn/users/users-delete-user.ts
create mode 100644 src/app/api/fn/users/users-patch-current-user.ts
create mode 100644 src/app/api/fn/users/users-patch-user.ts
create mode 100644 src/app/api/fn/users/users-user.ts
create mode 100644 src/app/api/models/answers.ts
create mode 100644 src/app/api/models/browsed.ts
create mode 100644 src/app/api/models/catalog.ts
create mode 100644 src/app/api/models/entry.ts
create mode 100644 src/app/api/models/error-model.ts
create mode 100644 src/app/api/models/field-spec.ts
create mode 100644 src/app/api/models/group.ts
create mode 100644 src/app/api/models/guided.ts
create mode 100644 src/app/api/models/listing.ts
create mode 100644 src/app/api/models/login.ts
create mode 100644 src/app/api/models/option.ts
create mode 100644 src/app/api/models/provider.ts
create mode 100644 src/app/api/models/sign-in.ts
create mode 100644 src/app/api/models/source-type.ts
create mode 100644 src/app/api/models/tested.ts
create mode 100644 src/app/api/models/uploaded.ts
create mode 100644 src/app/api/models/user-create.ts
create mode 100644 src/app/api/models/user-read.ts
create mode 100644 src/app/api/models/user-update.ts
create mode 100644 src/app/auth/auth.ts
create mode 100644 src/app/auth/login.html
create mode 100644 src/app/auth/login.scss
create mode 100644 src/app/auth/login.ts
create mode 100644 src/app/conectar/source-dialog.html
create mode 100644 src/app/conectar/source-dialog.scss
create mode 100644 src/app/conectar/source-dialog.ts
create mode 100644 src/app/loading.ts
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index 6e54e0a..f6d3651 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -9,6 +9,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.test', 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.test');
+ 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,
}) => {
@@ -71,12 +97,12 @@ 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 page.getByText('Traducir códigos · cytology', { exact: true }).click();
await expect(page.getByText('Códigos del sitio')).toBeVisible();
await expect
.poll(() =>
@@ -90,7 +116,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 +144,37 @@ 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(/Primeras \d+ filas/)).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 page.getByRole('button', { name: 'Guardar', exact: true }).click();
+ await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
+ expect(problems).toEqual([]);
+});
diff --git a/openapi.json b/openapi.json
index 62f1427..fb5c0c3 100644
--- a/openapi.json
+++ b/openapi.json
@@ -58,6 +58,47 @@
"title": "Analysis",
"type": "object"
},
+ "Answers": {
+ "properties": {
+ "answers": {
+ "additionalProperties": true,
+ "default": {},
+ "title": "Answers",
+ "type": "object"
+ },
+ "node": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Node"
+ },
+ "pipeline": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Pipeline"
+ },
+ "type": {
+ "title": "Type",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "title": "Answers",
+ "type": "object"
+ },
"Body_add_clinical_validation": {
"properties": {
"file": {
@@ -74,22 +115,118 @@
},
"Body_upload": {
"properties": {
- "file": {
- "contentMediaType": "application/octet-stream",
- "title": "File",
- "type": "string"
+ "files": {
+ "items": {
+ "contentMediaType": "application/octet-stream",
+ "type": "string"
+ },
+ "title": "Files",
+ "type": "array"
+ },
+ "folder": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Folder"
}
},
"required": [
- "file"
+ "files"
],
"title": "Body_upload",
"type": "object"
},
+ "Browsed": {
+ "properties": {
+ "entries": {
+ "items": {
+ "$ref": "#/components/schemas/Entry"
+ },
+ "title": "Entries",
+ "type": "array"
+ },
+ "parent": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Parent"
+ },
+ "path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Path"
+ }
+ },
+ "required": [
+ "path",
+ "parent",
+ "entries"
+ ],
+ "title": "Browsed",
+ "type": "object"
+ },
+ "Catalog": {
+ "additionalProperties": false,
+ "properties": {
+ "formats": {
+ "items": {
+ "$ref": "#/components/schemas/Option"
+ },
+ "title": "Formats",
+ "type": "array"
+ },
+ "groups": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/Group"
+ },
+ "title": "Groups",
+ "type": "object"
+ },
+ "providers": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/Provider"
+ },
+ "title": "Providers",
+ "type": "object"
+ },
+ "types": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/SourceType"
+ },
+ "title": "Types",
+ "type": "object"
+ }
+ },
+ "required": [
+ "groups",
+ "providers",
+ "formats",
+ "types"
+ ],
+ "title": "Catalog",
+ "type": "object"
+ },
"Condition": {
"properties": {
"column": {
- "title": "Column",
+ "description": "Por ejemplo \u00abtext\u00bb, el texto le\u00eddo del documento.",
+ "title": "Columna",
"type": "string"
},
"op": {
@@ -99,12 +236,37 @@
"matches",
"present"
],
- "title": "Op",
- "type": "string"
+ "title": "Condici\u00f3n",
+ "type": "string",
+ "widget": {
+ "formlyConfig": {
+ "props": {
+ "options": [
+ {
+ "label": "es igual a",
+ "value": "equals"
+ },
+ {
+ "label": "contiene",
+ "value": "contains"
+ },
+ {
+ "label": "coincide con la expresi\u00f3n",
+ "value": "matches"
+ },
+ {
+ "label": "tiene alg\u00fan valor",
+ "value": "present"
+ }
+ ]
+ }
+ }
+ }
},
"value": {
"default": "",
- "title": "Value",
+ "description": "Lo que se busca; por ejemplo \u00abcitolog\u00eda\u00bb.",
+ "title": "Valor",
"type": "string"
}
},
@@ -166,6 +328,67 @@
"title": "Domain",
"type": "string"
},
+ "Entry": {
+ "properties": {
+ "kind": {
+ "enum": [
+ "folder",
+ "file"
+ ],
+ "title": "Kind",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "path": {
+ "title": "Path",
+ "type": "string"
+ },
+ "size": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Size"
+ }
+ },
+ "required": [
+ "name",
+ "path",
+ "kind"
+ ],
+ "title": "Entry",
+ "type": "object"
+ },
+ "ErrorModel": {
+ "properties": {
+ "detail": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object"
+ }
+ ],
+ "title": "Detail"
+ }
+ },
+ "required": [
+ "detail"
+ ],
+ "title": "ErrorModel",
+ "type": "object"
+ },
"Extract": {
"additionalProperties": false,
"description": "Platform fields read from text, each kept with the text it was read from.\n\n`auto` asks the LLM when one is configured and answering, else applies `patterns`;\nwith neither, the row is held. Patterns are regexes with one group, per field (the\nLLM can propose them from sample documents); their values go through the ConceptMap\nand `formats` as in `map`.",
@@ -182,14 +405,15 @@
"type": "array"
}
],
- "title": "Column"
+ "title": "Columna con el texto"
},
"columns": {
"additionalProperties": {
"type": "string"
},
"default": {},
- "title": "Columns",
+ "description": "Dato \u2192 columna, sin leer el texto.",
+ "title": "Datos tomados de columnas",
"type": "object"
},
"concept_map": {
@@ -203,9 +427,10 @@
"type": "null"
}
],
- "title": "Concept Map"
+ "title": "Equivalencias de c\u00f3digos"
},
"entity": {
+ "description": "Qu\u00e9 estudio se saca del documento.",
"enum": [
"identity",
"cervical_cytology",
@@ -219,7 +444,7 @@
"ados2",
"eeg"
],
- "title": "Entity",
+ "title": "Estudio",
"type": "string"
},
"formats": {
@@ -227,12 +452,13 @@
"type": "string"
},
"default": {},
- "title": "Formats",
+ "title": "Formatos de fecha",
"type": "object"
},
"hints": {
"default": "",
- "title": "Hints",
+ "description": "Para el modelo de lenguaje.",
+ "title": "Indicaciones",
"type": "string"
},
"id": {
@@ -259,7 +485,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"method": {
@@ -269,15 +496,36 @@
"llm",
"patterns"
],
- "title": "Method",
- "type": "string"
+ "title": "C\u00f3mo leer",
+ "type": "string",
+ "widget": {
+ "formlyConfig": {
+ "props": {
+ "options": [
+ {
+ "label": "Autom\u00e1tico",
+ "value": "auto"
+ },
+ {
+ "label": "Con el modelo de lenguaje",
+ "value": "llm"
+ },
+ {
+ "label": "Con patrones",
+ "value": "patterns"
+ }
+ ]
+ }
+ }
+ }
},
"patterns": {
"additionalProperties": {
"type": "string"
},
"default": {},
- "title": "Patterns",
+ "description": "Dato \u2192 expresi\u00f3n con un grupo ( ).",
+ "title": "Patrones",
"type": "object"
},
"position": {
@@ -305,7 +553,7 @@
"properties": {
"column": {
"default": "doc",
- "title": "Column",
+ "title": "Columna con el FHIR",
"type": "string"
},
"concept_map": {
@@ -319,7 +567,7 @@
"type": "null"
}
],
- "title": "Concept Map"
+ "title": "Equivalencias de c\u00f3digos"
},
"entity": {
"enum": [
@@ -335,7 +583,7 @@
"ados2",
"eeg"
],
- "title": "Entity",
+ "title": "Estudio",
"type": "string"
},
"id": {
@@ -362,7 +610,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"position": {
@@ -383,6 +632,120 @@
"title": "Fhir",
"type": "object"
},
+ "FieldSpec": {
+ "additionalProperties": false,
+ "properties": {
+ "advanced": {
+ "default": false,
+ "title": "Advanced",
+ "type": "boolean"
+ },
+ "default": {
+ "title": "Default"
+ },
+ "help": {
+ "default": "",
+ "title": "Help",
+ "type": "string"
+ },
+ "label": {
+ "title": "Label",
+ "type": "string"
+ },
+ "options": {
+ "default": [],
+ "items": {
+ "$ref": "#/components/schemas/Option"
+ },
+ "title": "Options",
+ "type": "array"
+ },
+ "placeholder": {
+ "default": "",
+ "title": "Placeholder",
+ "type": "string"
+ },
+ "provider": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Provider"
+ },
+ "required": {
+ "default": true,
+ "title": "Required",
+ "type": "boolean"
+ },
+ "type": {
+ "default": "text",
+ "enum": [
+ "text",
+ "number",
+ "password",
+ "select",
+ "folder",
+ "server_file",
+ "upload",
+ "url",
+ "oauth",
+ "table",
+ "format"
+ ],
+ "title": "Type",
+ "type": "string"
+ }
+ },
+ "required": [
+ "label"
+ ],
+ "title": "FieldSpec",
+ "type": "object"
+ },
+ "Group": {
+ "additionalProperties": false,
+ "properties": {
+ "description": {
+ "title": "Description",
+ "type": "string"
+ },
+ "title": {
+ "title": "Title",
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description"
+ ],
+ "title": "Group",
+ "type": "object"
+ },
+ "Guided": {
+ "additionalProperties": false,
+ "description": "How the Conectar dialog drew a source: its type (core.sources) and the answers given.\nThe node's dlt fields are made from them; drawn by hand (\"Avanzado\"), a node has none.",
+ "properties": {
+ "answers": {
+ "additionalProperties": true,
+ "default": {},
+ "title": "Answers",
+ "type": "object"
+ },
+ "type": {
+ "title": "Type",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "title": "Guided",
+ "type": "object"
+ },
"HTTPValidationError": {
"properties": {
"detail": {
@@ -406,8 +769,24 @@
"inner",
"left"
],
- "title": "How",
- "type": "string"
+ "title": "Cu\u00e1les quedan",
+ "type": "string",
+ "widget": {
+ "formlyConfig": {
+ "props": {
+ "options": [
+ {
+ "label": "Solo las que tienen pareja",
+ "value": "inner"
+ },
+ {
+ "label": "Todas las de la izquierda",
+ "value": "left"
+ }
+ ]
+ }
+ }
+ }
},
"id": {
"maxLength": 40,
@@ -433,10 +812,12 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"on": {
+ "description": "Pares [columna izquierda, derecha].",
"items": {
"maxItems": 2,
"minItems": 2,
@@ -450,7 +831,7 @@
],
"type": "array"
},
- "title": "On",
+ "title": "Columnas iguales",
"type": "array"
},
"position": {
@@ -487,7 +868,7 @@
"items": {
"type": "string"
},
- "title": "Fields",
+ "title": "Datos que comparar",
"type": "array"
},
"id": {
@@ -514,7 +895,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"position": {
@@ -529,17 +911,19 @@
},
"review": {
"default": 0.5,
+ "description": "Parecidos por encima de esto los ve un revisor.",
"exclusiveMinimum": 0.0,
"maximum": 1.0,
- "title": "Review",
+ "title": "Umbral para revisar",
"type": "number"
},
"rules": {
"default": [],
+ "description": "Vac\u00edo: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).",
"items": {
"type": "string"
},
- "title": "Rules",
+ "title": "Reglas",
"type": "array"
}
},
@@ -549,6 +933,42 @@
"title": "Link",
"type": "object"
},
+ "Listing": {
+ "additionalProperties": false,
+ "description": "What \"Probar conexi\u00f3n\" shows: a database's tables (the resources of `source`, built\nfrom `args`), or the first rows the type's own node reads (files, records).",
+ "properties": {
+ "args": {
+ "additionalProperties": true,
+ "default": {},
+ "title": "Args",
+ "type": "object"
+ },
+ "kind": {
+ "enum": [
+ "tables",
+ "rows"
+ ],
+ "title": "Kind",
+ "type": "string"
+ },
+ "source": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source"
+ }
+ },
+ "required": [
+ "kind"
+ ],
+ "title": "Listing",
+ "type": "object"
+ },
"Map": {
"additionalProperties": false,
"description": "Columns to platform fields, the site's codes translated by its ConceptMap\n(core.concept_map), and its date formats.",
@@ -564,13 +984,15 @@
"type": "null"
}
],
- "title": "Concept Map"
+ "description": "La tabla de c\u00f3digos del sitio.",
+ "title": "Equivalencias de c\u00f3digos"
},
"fields": {
"additionalProperties": {
"type": "string"
},
- "title": "Fields",
+ "description": "Dato de la plataforma \u2192 columna del sitio.",
+ "title": "Campos",
"type": "object"
},
"formats": {
@@ -578,7 +1000,8 @@
"type": "string"
},
"default": {},
- "title": "Formats",
+ "description": "Por ejemplo %d/%m/%Y.",
+ "title": "Formatos de fecha",
"type": "object"
},
"id": {
@@ -605,7 +1028,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"position": {
@@ -623,7 +1047,8 @@
"type": "string"
},
"default": {},
- "title": "Values",
+ "description": "Un dato igual para todas las filas.",
+ "title": "Valores fijos",
"type": "object"
}
},
@@ -688,6 +1113,24 @@
"title": "Metric",
"type": "object"
},
+ "Option": {
+ "additionalProperties": false,
+ "properties": {
+ "label": {
+ "title": "Label",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value"
+ }
+ },
+ "required": [
+ "value",
+ "label"
+ ],
+ "title": "Option",
+ "type": "object"
+ },
"PersonDecision": {
"properties": {
"candidate": {
@@ -787,12 +1230,56 @@
"title": "Position",
"type": "object"
},
+ "Provider": {
+ "additionalProperties": false,
+ "description": "A sign-in button's OAuth 2.0 provider (authorization code flow).",
+ "properties": {
+ "authorize_params": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "default": {},
+ "title": "Authorize Params",
+ "type": "object"
+ },
+ "authorize_url": {
+ "title": "Authorize Url",
+ "type": "string"
+ },
+ "env": {
+ "title": "Env",
+ "type": "string"
+ },
+ "scope": {
+ "title": "Scope",
+ "type": "string"
+ },
+ "title": {
+ "title": "Title",
+ "type": "string"
+ },
+ "token_url": {
+ "title": "Token Url",
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "env",
+ "authorize_url",
+ "token_url",
+ "scope"
+ ],
+ "title": "Provider",
+ "type": "object"
+ },
"Read": {
"additionalProperties": false,
"description": "Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).",
"properties": {
"column": {
- "title": "Column",
+ "description": "Donde la entrada trae cada documento.",
+ "title": "Columna con los archivos",
"type": "string"
},
"id": {
@@ -819,7 +1306,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"position": {
@@ -904,12 +1392,14 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"otherwise": {
"default": false,
- "title": "Otherwise",
+ "description": "Recoge lo que nadie reconoce, para revisarlo.",
+ "title": "Lo que ning\u00fan otro tome",
"type": "boolean"
},
"position": {
@@ -927,7 +1417,7 @@
"items": {
"$ref": "#/components/schemas/Condition"
},
- "title": "When",
+ "title": "Pasan las filas donde",
"type": "array"
}
},
@@ -971,6 +1461,24 @@
"title": "SavedPipeline",
"type": "object"
},
+ "SignIn": {
+ "properties": {
+ "state": {
+ "title": "State",
+ "type": "string"
+ },
+ "url": {
+ "title": "Url",
+ "type": "string"
+ }
+ },
+ "required": [
+ "url",
+ "state"
+ ],
+ "title": "SignIn",
+ "type": "object"
+ },
"Source": {
"additionalProperties": false,
"description": "One table, file set or API resource, copied as it is (dlt). Merged on the source's\nown primary key or `primary_key`; replaced whole when it has none.",
@@ -978,9 +1486,20 @@
"args": {
"additionalProperties": true,
"default": {},
- "title": "Args",
+ "description": "Los de la fuente dlt.",
+ "title": "Argumentos (JSON)",
"type": "object"
},
+ "guided": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/Guided"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"id": {
"maxLength": 40,
"pattern": "^[a-z][a-z0-9_]*$",
@@ -1005,7 +1524,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"position": {
@@ -1020,10 +1540,11 @@
},
"primary_key": {
"default": [],
+ "description": "Columnas que identifican una fila.",
"items": {
"type": "string"
},
- "title": "Primary Key",
+ "title": "Llave",
"type": "array"
},
"resource": {
@@ -1035,11 +1556,13 @@
"type": "null"
}
],
- "title": "Resource"
+ "description": "Cu\u00e1l, si la fuente ofrece varios (una tabla).",
+ "title": "Recurso"
},
"source": {
+ "description": "M\u00f3dulo:funci\u00f3n de la fuente dlt.",
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
- "title": "Source",
+ "title": "Fuente dlt",
"type": "string"
},
"then": {
@@ -1052,7 +1575,8 @@
"type": "null"
}
],
- "title": "Then"
+ "description": "Transformador dlt para los archivos.",
+ "title": "Lector"
}
},
"required": [
@@ -1082,6 +1606,94 @@
"title": "SourceRef",
"type": "object"
},
+ "SourceType": {
+ "additionalProperties": false,
+ "properties": {
+ "args": {
+ "additionalProperties": true,
+ "default": {},
+ "title": "Args",
+ "type": "object"
+ },
+ "description": {
+ "title": "Description",
+ "type": "string"
+ },
+ "fields": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/FieldSpec"
+ },
+ "title": "Fields",
+ "type": "object"
+ },
+ "group": {
+ "title": "Group",
+ "type": "string"
+ },
+ "icon": {
+ "title": "Icon",
+ "type": "string"
+ },
+ "listing": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/Listing"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "primary_key": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "title": "Primary Key",
+ "type": "array"
+ },
+ "resource": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Resource"
+ },
+ "source": {
+ "title": "Source",
+ "type": "string"
+ },
+ "then": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Then"
+ },
+ "title": {
+ "title": "Title",
+ "type": "string"
+ }
+ },
+ "required": [
+ "group",
+ "title",
+ "description",
+ "icon",
+ "fields",
+ "source"
+ ],
+ "title": "SourceType",
+ "type": "object"
+ },
"Study": {
"properties": {
"analysed": {
@@ -1151,6 +1763,7 @@
"description": "Rows of platform fields into one platform entity, each row given its person by the\none `link` node among the inputs. Rule breaks are held for review.",
"properties": {
"entity": {
+ "description": "En qu\u00e9 estudio de la plataforma se guarda.",
"enum": [
"identity",
"cervical_cytology",
@@ -1164,7 +1777,7 @@
"ados2",
"eeg"
],
- "title": "Entity",
+ "title": "Estudio",
"type": "string"
},
"id": {
@@ -1191,7 +1804,8 @@
},
"label": {
"default": "",
- "title": "Label",
+ "description": "C\u00f3mo se ve en el diagrama.",
+ "title": "Nombre",
"type": "string"
},
"position": {
@@ -1212,6 +1826,52 @@
"title": "Target",
"type": "object"
},
+ "Tested": {
+ "properties": {
+ "detail": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Detail"
+ },
+ "message": {
+ "title": "Message",
+ "type": "string"
+ },
+ "ok": {
+ "title": "Ok",
+ "type": "boolean"
+ },
+ "rows": {
+ "default": [],
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Rows",
+ "type": "array"
+ },
+ "tables": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "title": "Tables",
+ "type": "array"
+ }
+ },
+ "required": [
+ "ok",
+ "message"
+ ],
+ "title": "Tested",
+ "type": "object"
+ },
"Training": {
"properties": {
"as_of": {
@@ -1238,6 +1898,230 @@
"title": "Training",
"type": "object"
},
+ "Uploaded": {
+ "properties": {
+ "bucket_url": {
+ "title": "Bucket Url",
+ "type": "string"
+ },
+ "files": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Files",
+ "type": "array"
+ }
+ },
+ "required": [
+ "bucket_url",
+ "files"
+ ],
+ "title": "Uploaded",
+ "type": "object"
+ },
+ "UserCreate": {
+ "properties": {
+ "domains": {
+ "default": [],
+ "items": {
+ "$ref": "#/components/schemas/Domain"
+ },
+ "title": "Domains",
+ "type": "array"
+ },
+ "email": {
+ "format": "email",
+ "title": "Email",
+ "type": "string"
+ },
+ "is_active": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": true,
+ "title": "Is Active"
+ },
+ "is_superuser": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": false,
+ "title": "Is Superuser"
+ },
+ "is_verified": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": false,
+ "title": "Is Verified"
+ },
+ "name": {
+ "default": "",
+ "title": "Name",
+ "type": "string"
+ },
+ "password": {
+ "title": "Password",
+ "type": "string"
+ }
+ },
+ "required": [
+ "email",
+ "password"
+ ],
+ "title": "UserCreate",
+ "type": "object"
+ },
+ "UserRead": {
+ "properties": {
+ "domains": {
+ "default": [],
+ "items": {
+ "$ref": "#/components/schemas/Domain"
+ },
+ "title": "Domains",
+ "type": "array"
+ },
+ "email": {
+ "format": "email",
+ "title": "Email",
+ "type": "string"
+ },
+ "id": {
+ "format": "uuid",
+ "title": "Id",
+ "type": "string"
+ },
+ "is_active": {
+ "default": true,
+ "title": "Is Active",
+ "type": "boolean"
+ },
+ "is_superuser": {
+ "default": false,
+ "title": "Is Superuser",
+ "type": "boolean"
+ },
+ "is_verified": {
+ "default": false,
+ "title": "Is Verified",
+ "type": "boolean"
+ },
+ "name": {
+ "default": "",
+ "title": "Name",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "email"
+ ],
+ "title": "UserRead",
+ "type": "object"
+ },
+ "UserUpdate": {
+ "properties": {
+ "domains": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/Domain"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Domains"
+ },
+ "email": {
+ "anyOf": [
+ {
+ "format": "email",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Email"
+ },
+ "is_active": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Is Active"
+ },
+ "is_superuser": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Is Superuser"
+ },
+ "is_verified": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Is Verified"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Name"
+ },
+ "password": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Password"
+ }
+ },
+ "title": "UserUpdate",
+ "type": "object"
+ },
"ValidationError": {
"properties": {
"ctx": {
@@ -1327,6 +2211,72 @@
],
"title": "Version",
"type": "object"
+ },
+ "login": {
+ "properties": {
+ "client_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Client Id"
+ },
+ "client_secret": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "format": "password",
+ "title": "Client Secret"
+ },
+ "grant_type": {
+ "anyOf": [
+ {
+ "pattern": "^password$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Grant Type"
+ },
+ "password": {
+ "format": "password",
+ "title": "Password",
+ "type": "string"
+ },
+ "scope": {
+ "default": "",
+ "title": "Scope",
+ "type": "string"
+ },
+ "username": {
+ "title": "Username",
+ "type": "string"
+ }
+ },
+ "required": [
+ "username",
+ "password"
+ ],
+ "title": "Body_auth:cookie.login",
+ "type": "object"
+ }
+ },
+ "securitySchemes": {
+ "APIKeyCookie": {
+ "in": "cookie",
+ "name": "isssteleon_session",
+ "type": "apiKey"
}
}
},
@@ -1336,6 +2286,102 @@
},
"openapi": "3.1.0",
"paths": {
+ "/auth/login": {
+ "post": {
+ "operationId": "auth:cookie.login",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {
+ "$ref": "#/components/schemas/login"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ },
+ "description": "Successful Response"
+ },
+ "204": {
+ "description": "No Content"
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "examples": {
+ "LOGIN_BAD_CREDENTIALS": {
+ "summary": "Bad credentials or the user is inactive.",
+ "value": {
+ "detail": "LOGIN_BAD_CREDENTIALS"
+ }
+ },
+ "LOGIN_USER_NOT_VERIFIED": {
+ "summary": "The user is not verified.",
+ "value": {
+ "detail": "LOGIN_USER_NOT_VERIFIED"
+ }
+ }
+ },
+ "schema": {
+ "$ref": "#/components/schemas/ErrorModel"
+ }
+ }
+ },
+ "description": "Bad Request"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Auth:Cookie.Login",
+ "tags": [
+ "auth"
+ ]
+ }
+ },
+ "/auth/logout": {
+ "post": {
+ "operationId": "auth:cookie.logout",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ },
+ "description": "Successful Response"
+ },
+ "204": {
+ "description": "No Content"
+ },
+ "401": {
+ "description": "Missing token or inactive user."
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Auth:Cookie.Logout",
+ "tags": [
+ "auth"
+ ]
+ }
+ },
"/domains": {
"get": {
"operationId": "domains",
@@ -1813,6 +2859,108 @@
]
}
},
+ "/ingest/sources/browse": {
+ "get": {
+ "description": "The server folders a source may read: the roots, or what one folder under them\nholds. Nothing outside the roots is shown.",
+ "operationId": "browse",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "path",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Path"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Browsed"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Browse",
+ "tags": [
+ "ingest"
+ ]
+ }
+ },
+ "/ingest/sources/oauth/{provider}/start": {
+ "get": {
+ "description": "The provider's sign-in address. `origin` is the web app's (where the user returns:\n`{origin}/api/\u2026/callback`, the address IT registered).",
+ "operationId": "oauth_start",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "provider",
+ "required": true,
+ "schema": {
+ "title": "Provider",
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "origin",
+ "required": true,
+ "schema": {
+ "title": "Origin",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SignIn"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Oauth Start",
+ "tags": [
+ "ingest"
+ ]
+ }
+ },
"/ingest/sources/preview": {
"post": {
"description": "The first rows a source node would load.",
@@ -1920,9 +3068,87 @@
]
}
},
+ "/ingest/sources/test": {
+ "post": {
+ "description": "\"Probar conexi\u00f3n\": reaches the source with the answers given. A database lists its\ntables (until one is picked; then its first rows); files and records show their first\nrows. Never a server error: what went wrong comes back in plain words.",
+ "operationId": "test_source",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 20,
+ "maximum": 100,
+ "minimum": 1,
+ "title": "Limit",
+ "type": "integer"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Answers"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Tested"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Test Source",
+ "tags": [
+ "ingest"
+ ]
+ }
+ },
+ "/ingest/sources/types": {
+ "get": {
+ "description": "Every kind of source the dialog offers, grouped, with the fields each one asks.",
+ "operationId": "source_types",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Catalog"
+ }
+ }
+ },
+ "description": "Successful Response"
+ }
+ },
+ "summary": "Source Types",
+ "tags": [
+ "ingest"
+ ]
+ }
+ },
"/ingest/uploads": {
"post": {
- "description": "A CSV, Excel or document file for a `filesystem` source: use `bucket_url`.",
+ "description": "Files from the operator's computer (one, many, or a whole folder), kept on the\nserver for a `filesystem` source; streamed to disk, so large recordings fit. Send\n`folder` from a previous answer to add to the same set.",
"operationId": "upload",
"requestBody": {
"content": {
@@ -1939,11 +3165,7 @@
"content": {
"application/json": {
"schema": {
- "additionalProperties": {
- "type": "string"
- },
- "title": "Response Upload",
- "type": "object"
+ "$ref": "#/components/schemas/Uploaded"
}
}
},
@@ -2583,7 +3805,7 @@
},
"/review/persons": {
"get": {
- "description": "Persons to settle (with their possible owners) and torn persons (with their\nrecords) left by a pipeline's link node.",
+ "description": "Persons to settle (with their possible owners), torn persons and persons nothing\nnames (with their records) left by a pipeline's link node.",
"operationId": "persons",
"parameters": [
{
@@ -2898,6 +4120,376 @@
]
}
},
+ "/users/me": {
+ "get": {
+ "operationId": "users:current_user",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "401": {
+ "description": "Missing token or inactive user."
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Users:Current User",
+ "tags": [
+ "users"
+ ]
+ },
+ "patch": {
+ "operationId": "users:patch_current_user",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserUpdate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "examples": {
+ "UPDATE_USER_EMAIL_ALREADY_EXISTS": {
+ "summary": "A user with this email already exists.",
+ "value": {
+ "detail": "UPDATE_USER_EMAIL_ALREADY_EXISTS"
+ }
+ },
+ "UPDATE_USER_INVALID_PASSWORD": {
+ "summary": "Password validation failed.",
+ "value": {
+ "detail": {
+ "code": "UPDATE_USER_INVALID_PASSWORD",
+ "reason": "Password should beat least 3 characters"
+ }
+ }
+ }
+ },
+ "schema": {
+ "$ref": "#/components/schemas/ErrorModel"
+ }
+ }
+ },
+ "description": "Bad Request"
+ },
+ "401": {
+ "description": "Missing token or inactive user."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Users:Patch Current User",
+ "tags": [
+ "users"
+ ]
+ }
+ },
+ "/users/register": {
+ "post": {
+ "operationId": "register:register",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserCreate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "examples": {
+ "REGISTER_INVALID_PASSWORD": {
+ "summary": "Password validation failed.",
+ "value": {
+ "detail": {
+ "code": "REGISTER_INVALID_PASSWORD",
+ "reason": "Password should beat least 3 characters"
+ }
+ }
+ },
+ "REGISTER_USER_ALREADY_EXISTS": {
+ "summary": "A user with this email already exists.",
+ "value": {
+ "detail": "REGISTER_USER_ALREADY_EXISTS"
+ }
+ }
+ },
+ "schema": {
+ "$ref": "#/components/schemas/ErrorModel"
+ }
+ }
+ },
+ "description": "Bad Request"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Register:Register",
+ "tags": [
+ "users"
+ ]
+ }
+ },
+ "/users/{id}": {
+ "delete": {
+ "operationId": "users:delete_user",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "title": "Id",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Successful Response"
+ },
+ "401": {
+ "description": "Missing token or inactive user."
+ },
+ "403": {
+ "description": "Not a superuser."
+ },
+ "404": {
+ "description": "The user does not exist."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Users:Delete User",
+ "tags": [
+ "users"
+ ]
+ },
+ "get": {
+ "operationId": "users:user",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "title": "Id",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "401": {
+ "description": "Missing token or inactive user."
+ },
+ "403": {
+ "description": "Not a superuser."
+ },
+ "404": {
+ "description": "The user does not exist."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Users:User",
+ "tags": [
+ "users"
+ ]
+ },
+ "patch": {
+ "operationId": "users:patch_user",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "title": "Id",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserUpdate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "examples": {
+ "UPDATE_USER_EMAIL_ALREADY_EXISTS": {
+ "summary": "A user with this email already exists.",
+ "value": {
+ "detail": "UPDATE_USER_EMAIL_ALREADY_EXISTS"
+ }
+ },
+ "UPDATE_USER_INVALID_PASSWORD": {
+ "summary": "Password validation failed.",
+ "value": {
+ "detail": {
+ "code": "UPDATE_USER_INVALID_PASSWORD",
+ "reason": "Password should beat least 3 characters"
+ }
+ }
+ }
+ },
+ "schema": {
+ "$ref": "#/components/schemas/ErrorModel"
+ }
+ }
+ },
+ "description": "Bad Request"
+ },
+ "401": {
+ "description": "Missing token or inactive user."
+ },
+ "403": {
+ "description": "Not a superuser."
+ },
+ "404": {
+ "description": "The user does not exist."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "APIKeyCookie": []
+ }
+ ],
+ "summary": "Users:Patch User",
+ "tags": [
+ "users"
+ ]
+ }
+ },
"/{domain}/fhir": {
"post": {
"description": "A standard hospital's Bundle: checked as FHIR, kept as sent in the sender's inbox,\nand placed by the sender's pipeline (a run starts; follow it at the Location).",
diff --git a/src/app/api/fn/auth/auth-cookie-login.ts b/src/app/api/fn/auth/auth-cookie-login.ts
new file mode 100644
index 0000000..01a450b
--- /dev/null
+++ b/src/app/api/fn/auth/auth-cookie-login.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+authCookieLogin.PATH = '/auth/login';
diff --git a/src/app/api/fn/auth/auth-cookie-logout.ts b/src/app/api/fn/auth/auth-cookie-logout.ts
new file mode 100644
index 0000000..ff5ac75
--- /dev/null
+++ b/src/app/api/fn/auth/auth-cookie-logout.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+authCookieLogout.PATH = '/auth/logout';
diff --git a/src/app/api/fn/ingest/browse.ts b/src/app/api/fn/ingest/browse.ts
new file mode 100644
index 0000000..ba99f04
--- /dev/null
+++ b/src/app/api/fn/ingest/browse.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+browse.PATH = '/ingest/sources/browse';
diff --git a/src/app/api/fn/ingest/oauth-start.ts b/src/app/api/fn/ingest/oauth-start.ts
new file mode 100644
index 0000000..0e61283
--- /dev/null
+++ b/src/app/api/fn/ingest/oauth-start.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+oauthStart.PATH = '/ingest/sources/oauth/{provider}/start';
diff --git a/src/app/api/fn/ingest/source-types.ts b/src/app/api/fn/ingest/source-types.ts
new file mode 100644
index 0000000..62b7206
--- /dev/null
+++ b/src/app/api/fn/ingest/source-types.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+sourceTypes.PATH = '/ingest/sources/types';
diff --git a/src/app/api/fn/ingest/test-source.ts b/src/app/api/fn/ingest/test-source.ts
new file mode 100644
index 0000000..3f2b67c
--- /dev/null
+++ b/src/app/api/fn/ingest/test-source.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+testSource.PATH = '/ingest/sources/test';
diff --git a/src/app/api/fn/ingest/upload.ts b/src/app/api/fn/ingest/upload.ts
index f5055fe..c35dc19 100644
--- a/src/app/api/fn/ingest/upload.ts
+++ b/src/app/api/fn/ingest/upload.ts
@@ -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> {
+export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable> {
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 => r instanceof HttpResponse),
map((r: HttpResponse) => {
- return r as StrictHttpResponse<{
- [key: string]: string;
- }>;
+ return r as StrictHttpResponse;
})
);
}
diff --git a/src/app/api/fn/users/register-register.ts b/src/app/api/fn/users/register-register.ts
new file mode 100644
index 0000000..7c1d739
--- /dev/null
+++ b/src/app/api/fn/users/register-register.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+registerRegister.PATH = '/users/register';
diff --git a/src/app/api/fn/users/users-current-user.ts b/src/app/api/fn/users/users-current-user.ts
new file mode 100644
index 0000000..c208f35
--- /dev/null
+++ b/src/app/api/fn/users/users-current-user.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+usersCurrentUser.PATH = '/users/me';
diff --git a/src/app/api/fn/users/users-delete-user.ts b/src/app/api/fn/users/users-delete-user.ts
new file mode 100644
index 0000000..256549f
--- /dev/null
+++ b/src/app/api/fn/users/users-delete-user.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return (r as HttpResponse).clone({ body: undefined }) as StrictHttpResponse;
+ })
+ );
+}
+
+usersDeleteUser.PATH = '/users/{id}';
diff --git a/src/app/api/fn/users/users-patch-current-user.ts b/src/app/api/fn/users/users-patch-current-user.ts
new file mode 100644
index 0000000..5e611bf
--- /dev/null
+++ b/src/app/api/fn/users/users-patch-current-user.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+usersPatchCurrentUser.PATH = '/users/me';
diff --git a/src/app/api/fn/users/users-patch-user.ts b/src/app/api/fn/users/users-patch-user.ts
new file mode 100644
index 0000000..c1534d7
--- /dev/null
+++ b/src/app/api/fn/users/users-patch-user.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+usersPatchUser.PATH = '/users/{id}';
diff --git a/src/app/api/fn/users/users-user.ts b/src/app/api/fn/users/users-user.ts
new file mode 100644
index 0000000..f58fe4e
--- /dev/null
+++ b/src/app/api/fn/users/users-user.ts
@@ -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> {
+ 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 => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse;
+ })
+ );
+}
+
+usersUser.PATH = '/users/{id}';
diff --git a/src/app/api/functions.ts b/src/app/api/functions.ts
index 83cb499..2e4b639 100644
--- a/src/app/api/functions.ts
+++ b/src/app/api/functions.ts
@@ -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';
@@ -67,6 +79,18 @@ 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';
diff --git a/src/app/api/models.ts b/src/app/api/models.ts
index 12a9984..0521c53 100644
--- a/src/app/api/models.ts
+++ b/src/app/api/models.ts
@@ -2,30 +2,49 @@
/* 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 { 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 { 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';
diff --git a/src/app/api/models/answers.ts b/src/app/api/models/answers.ts
new file mode 100644
index 0000000..45da8fa
--- /dev/null
+++ b/src/app/api/models/answers.ts
@@ -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;
+}
diff --git a/src/app/api/models/body-upload.ts b/src/app/api/models/body-upload.ts
index 0600f02..28c29b7 100644
--- a/src/app/api/models/body-upload.ts
+++ b/src/app/api/models/body-upload.ts
@@ -2,5 +2,6 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface BodyUpload {
- file: string;
+ files: Array;
+ folder?: (string | null);
}
diff --git a/src/app/api/models/browsed.ts b/src/app/api/models/browsed.ts
new file mode 100644
index 0000000..7a18d7e
--- /dev/null
+++ b/src/app/api/models/browsed.ts
@@ -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;
+ parent: (string | null);
+ path: (string | null);
+}
diff --git a/src/app/api/models/catalog.ts b/src/app/api/models/catalog.ts
new file mode 100644
index 0000000..f377243
--- /dev/null
+++ b/src/app/api/models/catalog.ts
@@ -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;
+ groups: {
+[key: string]: Group;
+};
+ providers: {
+[key: string]: Provider;
+};
+ types: {
+[key: string]: SourceType;
+};
+}
diff --git a/src/app/api/models/condition.ts b/src/app/api/models/condition.ts
index 7e39071..045ab03 100644
--- a/src/app/api/models/condition.ts
+++ b/src/app/api/models/condition.ts
@@ -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;
}
diff --git a/src/app/api/models/entry.ts b/src/app/api/models/entry.ts
new file mode 100644
index 0000000..9fe297d
--- /dev/null
+++ b/src/app/api/models/entry.ts
@@ -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);
+}
diff --git a/src/app/api/models/error-model.ts b/src/app/api/models/error-model.ts
new file mode 100644
index 0000000..356aace
--- /dev/null
+++ b/src/app/api/models/error-model.ts
@@ -0,0 +1,8 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+export interface ErrorModel {
+ detail: (string | {
+[key: string]: string;
+});
+}
diff --git a/src/app/api/models/extract.ts b/src/app/api/models/extract.ts
index 69490cb..d43a9b9 100644
--- a/src/app/api/models/extract.ts
+++ b/src/app/api/models/extract.ts
@@ -13,20 +13,40 @@ import { Position } from '../models/position';
*/
export interface Extract {
column: (string | Array);
+
+ /**
+ * Dato → columna, sin leer el texto.
+ */
columns?: {
[key: string]: string;
};
concept_map?: (string | null);
+
+ /**
+ * Qué estudio se saca del documento.
+ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
+
+ /**
+ * Para el modelo de lenguaje.
+ */
hints?: string;
id: string;
inputs?: Array;
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;
};
diff --git a/src/app/api/models/fhir.ts b/src/app/api/models/fhir.ts
index 6022b5e..56b036e 100644
--- a/src/app/api/models/fhir.ts
+++ b/src/app/api/models/fhir.ts
@@ -15,6 +15,10 @@ export interface Fhir {
id: string;
inputs?: Array;
kind?: 'fhir';
+
+ /**
+ * Cómo se ve en el diagrama.
+ */
label?: string;
position?: (Position | null);
}
diff --git a/src/app/api/models/field-spec.ts b/src/app/api/models/field-spec.ts
new file mode 100644
index 0000000..2c5d061
--- /dev/null
+++ b/src/app/api/models/field-spec.ts
@@ -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;
+ placeholder?: string;
+ provider?: (string | null);
+ required?: boolean;
+ type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format';
+}
diff --git a/src/app/api/models/group.ts b/src/app/api/models/group.ts
new file mode 100644
index 0000000..8fea9a9
--- /dev/null
+++ b/src/app/api/models/group.ts
@@ -0,0 +1,7 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+export interface Group {
+ description: string;
+ title: string;
+}
diff --git a/src/app/api/models/guided.ts b/src/app/api/models/guided.ts
new file mode 100644
index 0000000..e75cc8f
--- /dev/null
+++ b/src/app/api/models/guided.ts
@@ -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;
+}
diff --git a/src/app/api/models/join.ts b/src/app/api/models/join.ts
index a795d6b..96c7fe6 100644
--- a/src/app/api/models/join.ts
+++ b/src/app/api/models/join.ts
@@ -11,7 +11,15 @@ export interface Join {
id: string;
inputs?: Array;
kind?: 'join';
+
+ /**
+ * Cómo se ve en el diagrama.
+ */
label?: string;
+
+ /**
+ * Pares [columna izquierda, derecha].
+ */
on: Array<[string, string]>;
position?: (Position | null);
}
diff --git a/src/app/api/models/link.ts b/src/app/api/models/link.ts
index fbfaca9..9e3d8b0 100644
--- a/src/app/api/models/link.ts
+++ b/src/app/api/models/link.ts
@@ -16,8 +16,20 @@ export interface Link {
id: string;
inputs?: Array;
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;
}
diff --git a/src/app/api/models/listing.ts b/src/app/api/models/listing.ts
new file mode 100644
index 0000000..f669610
--- /dev/null
+++ b/src/app/api/models/listing.ts
@@ -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);
+}
diff --git a/src/app/api/models/login.ts b/src/app/api/models/login.ts
new file mode 100644
index 0000000..63d5b65
--- /dev/null
+++ b/src/app/api/models/login.ts
@@ -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;
+}
diff --git a/src/app/api/models/map.ts b/src/app/api/models/map.ts
index 5eb663a..3efccb7 100644
--- a/src/app/api/models/map.ts
+++ b/src/app/api/models/map.ts
@@ -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;
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;
};
diff --git a/src/app/api/models/option.ts b/src/app/api/models/option.ts
new file mode 100644
index 0000000..75a85c8
--- /dev/null
+++ b/src/app/api/models/option.ts
@@ -0,0 +1,7 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+export interface Option {
+ label: string;
+ value: any;
+}
diff --git a/src/app/api/models/provider.ts b/src/app/api/models/provider.ts
new file mode 100644
index 0000000..43e30cc
--- /dev/null
+++ b/src/app/api/models/provider.ts
@@ -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;
+}
diff --git a/src/app/api/models/read.ts b/src/app/api/models/read.ts
index a02b620..2f7b104 100644
--- a/src/app/api/models/read.ts
+++ b/src/app/api/models/read.ts
@@ -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;
kind?: 'read';
+
+ /**
+ * Cómo se ve en el diagrama.
+ */
label?: string;
position?: (Position | null);
}
diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts
index de24e93..57ac688 100644
--- a/src/app/api/models/route.ts
+++ b/src/app/api/models/route.ts
@@ -13,7 +13,15 @@ export interface Route {
id: string;
inputs?: Array;
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;
diff --git a/src/app/api/models/sign-in.ts b/src/app/api/models/sign-in.ts
new file mode 100644
index 0000000..4722984
--- /dev/null
+++ b/src/app/api/models/sign-in.ts
@@ -0,0 +1,7 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+export interface SignIn {
+ state: string;
+ url: string;
+}
diff --git a/src/app/api/models/source-type.ts b/src/app/api/models/source-type.ts
new file mode 100644
index 0000000..d7539f8
--- /dev/null
+++ b/src/app/api/models/source-type.ts
@@ -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;
+ resource?: (string | null);
+ source: string;
+ then?: (string | null);
+ title: string;
+}
diff --git a/src/app/api/models/source.ts b/src/app/api/models/source.ts
index e72ff7f..ca4498a 100644
--- a/src/app/api/models/source.ts
+++ b/src/app/api/models/source.ts
@@ -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;
kind?: 'source';
+
+ /**
+ * Cómo se ve en el diagrama.
+ */
label?: string;
position?: (Position | null);
+
+ /**
+ * Columnas que identifican una fila.
+ */
primary_key?: Array;
+
+ /**
+ * 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);
}
diff --git a/src/app/api/models/target.ts b/src/app/api/models/target.ts
index ea0da43..e198c5a 100644
--- a/src/app/api/models/target.ts
+++ b/src/app/api/models/target.ts
@@ -8,10 +8,18 @@ import { Position } from '../models/position';
* one `link` node among the inputs. Rule breaks are held for review.
*/
export interface Target {
+
+ /**
+ * En qué estudio de la plataforma se guarda.
+ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array;
kind?: 'target';
+
+ /**
+ * Cómo se ve en el diagrama.
+ */
label?: string;
position?: (Position | null);
}
diff --git a/src/app/api/models/tested.ts b/src/app/api/models/tested.ts
new file mode 100644
index 0000000..7441852
--- /dev/null
+++ b/src/app/api/models/tested.ts
@@ -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;
+}
diff --git a/src/app/api/models/uploaded.ts b/src/app/api/models/uploaded.ts
new file mode 100644
index 0000000..2fac9c8
--- /dev/null
+++ b/src/app/api/models/uploaded.ts
@@ -0,0 +1,7 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+export interface Uploaded {
+ bucket_url: string;
+ files: Array;
+}
diff --git a/src/app/api/models/user-create.ts b/src/app/api/models/user-create.ts
new file mode 100644
index 0000000..84d737e
--- /dev/null
+++ b/src/app/api/models/user-create.ts
@@ -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;
+ email: string;
+ is_active?: (boolean | null);
+ is_superuser?: (boolean | null);
+ is_verified?: (boolean | null);
+ name?: string;
+ password: string;
+}
diff --git a/src/app/api/models/user-read.ts b/src/app/api/models/user-read.ts
new file mode 100644
index 0000000..763c9f3
--- /dev/null
+++ b/src/app/api/models/user-read.ts
@@ -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;
+ email: string;
+ id: string;
+ is_active?: boolean;
+ is_superuser?: boolean;
+ is_verified?: boolean;
+ name?: string;
+}
diff --git a/src/app/api/models/user-update.ts b/src/app/api/models/user-update.ts
new file mode 100644
index 0000000..a9dddbb
--- /dev/null
+++ b/src/app/api/models/user-update.ts
@@ -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 | null);
+ email?: (string | null);
+ is_active?: (boolean | null);
+ is_superuser?: (boolean | null);
+ is_verified?: (boolean | null);
+ name?: (string | null);
+ password?: (string | null);
+}
diff --git a/src/app/app.html b/src/app/app.html
index 4d3a5bd..74ebbdb 100644
--- a/src/app/app.html
+++ b/src/app/app.html
@@ -22,12 +22,23 @@
} @else {
}
-
- Indicadores
- Conectar
- Revisión
- Gobernanza
-
+ @if (!onLogin()) {
+
+ Indicadores
+ Conectar
+ Revisión
+ Gobernanza
+
+ @if (auth.user(); as u) {
+
+ account_circle {{ u.name || u.email }}
+
+
+ {{ u.email }}
+ logout Salir
+
+ }
+ }
diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts
index bb8e565..1155d75 100644
--- a/src/app/app.routes.ts
+++ b/src/app/app.routes.ts
@@ -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' },
];
diff --git a/src/app/app.scss b/src/app/app.scss
index 5fab037..91046ef 100644
--- a/src/app/app.scss
+++ b/src/app/app.scss
@@ -72,3 +72,8 @@
display: none;
}
}
+
+.user {
+ color: var(--color-text-secondary);
+ font-weight: 600;
+}
diff --git a/src/app/app.ts b/src/app/app.ts
index e086b65..50a8bfa 100644
--- a/src/app/app.ts
+++ b/src/app/app.ts
@@ -8,6 +8,7 @@ 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 = {
cacu: 'Cáncer cervicouterino',
@@ -32,6 +33,7 @@ export const DOMAINS: Record = {
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 {
+ await this.auth.logout();
+ await this.router.navigateByUrl('/login');
+ }
}
diff --git a/src/app/auth/auth.ts b/src/app/auth/auth.ts
new file mode 100644
index 0000000..1e04c52
--- /dev/null
+++ b/src/app/auth/auth.ts
@@ -0,0 +1,83 @@
+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(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 {
+ try {
+ this.current.set(await firstValueFrom(this.http.get(`${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 {
+ 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 {
+ 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 user = auth.user() === undefined ? await auth.load() : auth.user();
+ return user
+ ? true
+ : inject(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']);
+};
diff --git a/src/app/auth/login.html b/src/app/auth/login.html
new file mode 100644
index 0000000..512e04c
--- /dev/null
+++ b/src/app/auth/login.html
@@ -0,0 +1,49 @@
+
+
+
+
Inicio de sesión
+
+
©{{ year }} Todos los derechos reservados.
+
+
diff --git a/src/app/auth/login.scss b/src/app/auth/login.scss
new file mode 100644
index 0000000..b99692c
--- /dev/null
+++ b/src/app/auth/login.scss
@@ -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;
+ }
+}
diff --git a/src/app/auth/login.ts b/src/app/auth/login.ts
new file mode 100644
index 0000000..76f6ed8
--- /dev/null
+++ b/src/app/auth/login.ts
@@ -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('');
+ 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 {
+ 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}`);
+ }
+}
diff --git a/src/app/conectar/conectar.html b/src/app/conectar/conectar.html
index 3b922c8..876c82c 100644
--- a/src/app/conectar/conectar.html
+++ b/src/app/conectar/conectar.html
@@ -29,7 +29,9 @@
@if (pipelineId()) {
@for (k of kinds; track k[0]) {
- add {{ k[1] }}
+
+ add {{ k[1] }}
+
}
Guardar
@@ -70,6 +72,7 @@
delete
+ {{ help[d.kind ?? 'source'] }}
Id
@@ -86,12 +89,35 @@
} @else if (d.kind !== 'source') {
Una flecha desde otro nodo le da su entrada.
}
-
+ @if (guided(d); as g) {
+
+
+ check_circle
+ {{ d.label || d.id }}
+
+
+ edit Editar conexión
+
+
+
+ Avanzado (para personal técnico)
+
+ } @else if (d.kind === 'source') {
+
+ cable Conectar con ayuda
+
+ }
+ @if (!guided(d) || advanced()) {
+ @if (guided(d)) {
+ Si cambia algo aquí, la fuente deja de editarse con ayuda.
+ }
+
+ }
@if (conceptMap(d); as cm) {
}
diff --git a/src/app/conectar/conectar.scss b/src/app/conectar/conectar.scss
index 2b54587..83c9ff4 100644
--- a/src/app/conectar/conectar.scss
+++ b/src/app/conectar/conectar.scss
@@ -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);
+ }
+}
diff --git a/src/app/conectar/conectar.ts b/src/app/conectar/conectar.ts
index 912e5ed..3b6f5db 100644
--- a/src/app/conectar/conectar.ts
+++ b/src/app/conectar/conectar.ts
@@ -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;
@@ -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 = {
- 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 = {
+ 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 {
+ 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, {
+ data,
+ width: '760px',
+ maxWidth: '96vw',
+ maxHeight: '92vh',
+ autoFocus: false,
+ });
+ const result = await new Promise((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): 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,
diff --git a/src/app/conectar/source-dialog.html b/src/app/conectar/source-dialog.html
new file mode 100644
index 0000000..cfa7156
--- /dev/null
+++ b/src/app/conectar/source-dialog.html
@@ -0,0 +1,369 @@
+@if (!type()) {
+ ¿Dónde están los datos?
+
+ @if (catalog.isLoading()) {
+
+ Cargando opciones…
+
+ }
+ @for (g of groups(); track g.id) {
+
+ {{ g.title }}
+ {{ g.description }}
+
+ @for (t of g.types; track t.id) {
+
+ {{ icon(t.icon) }}
+ {{ t.title }}
+ {{ t.description }}
+
+ }
+
+
+ }
+
+
+ Cancelar
+
+} @else {
+
+ {{ icon(type()!.icon) }} {{ type()!.title }}
+
+
+ {{ type()!.description }}
+
+
+ @switch (f.type === 'server_file' ? 'folder' : f.type) {
+ @case ('password') {
+
+ {{ f.label }}
+
+
+ {{ showPassword()[name] ? 'visibility_off' : 'visibility' }}
+
+ @if (f.help) {
+ {{ f.help }}
+ }
+
+ }
+ @case ('number') {
+
+ {{ f.label }}
+
+ @if (f.help) {
+ {{ f.help }}
+ }
+
+ }
+ @case ('select') {
+
+ {{ f.label }}
+
+ @for (o of f.options; track o.value) {
+ {{ o.label }}
+ }
+
+ @if (f.help) {
+ {{ f.help }}
+ }
+
+ }
+ @case ('format') {
+
+ {{ f.label }}
+
+ @for (o of formats(); track o.value) {
+ {{ o.label }}
+ }
+
+
+ }
+ @case ('table') {
+
+ {{ f.label }}
+ @if (tables().length) {
+
+ @for (t of tables(); track t) {
+ {{ t }}
+ }
+
+ } @else {
+
+ }
+ @if (f.help) {
+ {{ f.help }}
+ }
+
+ }
+ @case ('folder') {
+
+
+ {{ f.label }}
+
+ @if (f.help) {
+ {{ f.help }}
+ }
+
+
+ folder_open Examinar…
+
+
+ @if (browsing(); as b) {
+ @if (b.field === name) {
+
+
+ @if (b.at.path) {
+
+ arrow_upward
+
+ {{ b.at.path }}
+ } @else {
+ Carpetas habilitadas en el servidor
+ }
+
+
+ @for (e of b.at.entries; track e.path) {
+
+ @if (e.kind === 'folder') {
+
+ folder {{ e.name }}
+
+ } @else if (browsingFiles()) {
+
+ description {{ e.name }}
+
+ } @else {
+ description {{ e.name }}
+ }
+
+ } @empty {
+ Vacía.
+ }
+
+
+ Cerrar
+ @if (!browsingFiles()) {
+
+ Elegir esta carpeta
+
+ }
+
+
+ }
+ }
+ }
+ @case ('upload') {
+
+
cloud_upload
+
Arrastre aquí los archivos, o
+
+
+ Elegir archivos
+
+
+ Elegir una carpeta
+
+
+
+
+ @if (uploading(); as u) {
+ @if (u.field === name) {
+
+
Subiendo… {{ u.percent }} %
+ }
+ }
+ @if (uploaded()[name]?.length) {
+
+ check_circle {{ uploaded()[name].length }} archivos subidos
+
+ } @else if (text(name)) {
+
check_circle Archivos ya subidos
+ }
+
+ }
+ @case ('oauth') {
+
+ @if (account(name); as who) {
+
check_circle Conectado como {{ who }}
+
+ Usar otra cuenta
+
+ } @else {
+
+ login
+ Iniciar sesión con {{ catalog.value()?.providers?.[f.provider]?.title }}
+
+ }
+ @if (f.help) {
+
{{ f.help }}
+ }
+
+ }
+ @default {
+
+ {{ f.label }}
+
+ @if (f.help) {
+ {{ f.help }}
+ }
+
+ }
+ }
+
+
+
+ @for (e of fields(); track e[0]) {
+
+ }
+
+ @if (more().length) {
+
+ Más opciones
+
+ @for (e of more(); track e[0]) {
+
+ }
+
+
+ }
+
+
+ 0"
+ >
+ network_check Probar conexión
+
+ @if (testing()) {
+ Conectando…
+ } @else if (missing().length) {
+ Falta: {{ missing().join(', ') }}
+ }
+
+ @if (problem()) {
+ error {{ problem() }}
+ }
+ @if (tested(); as t) {
+
+
+ {{ t.ok ? 'check_circle' : 'error' }} {{ t.message }}
+
+ @if (t.detail) {
+
+ Lo que respondió el sistema
+ {{ t.detail }}
+
+ }
+ @if (t.tables?.length) {
+
Elija una tabla arriba para ver sus primeras filas.
+ }
+ @if (t.rows?.length) {
+
+ {{
+ t.rows!.length === 1
+ ? 'La primera fila:'
+ : 'Las primeras ' + t.rows!.length + ' filas:'
+ }}
+
+
+
+ @for (c of columns(); track c) {
+
+ {{ c }}
+ {{ cell(row[c]) }}
+
+ }
+
+
+
+
+ }
+
+ }
+
+
+ Nombre de esta fuente
+
+ Cómo se verá en el diagrama.
+
+
+
+ @if (!data.guided) {
+
+ arrow_back Otro tipo
+
+ }
+
+ Cancelar
+ Guardar
+
+}
diff --git a/src/app/conectar/source-dialog.scss b/src/app/conectar/source-dialog.scss
new file mode 100644
index 0000000..db5e7dd
--- /dev/null
+++ b/src/app/conectar/source-dialog.scss
@@ -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;
+}
diff --git a/src/app/conectar/source-dialog.ts b/src/app/conectar/source-dialog.ts
new file mode 100644
index 0000000..a7a7b7e
--- /dev/null
+++ b/src/app/conectar/source-dialog.ts
@@ -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 = {
+ 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);
+ protected readonly data = inject(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(this.data.guided?.type);
+ protected readonly type = computed(() => {
+ const id = this.typeId();
+ return id ? this.catalog.value()?.types[id] : undefined;
+ });
+ protected readonly answers = signal>({
+ ...(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>({});
+
+ protected readonly testing = signal(false);
+ /** The tables the last listing found: kept while one is picked and its rows shown. */
+ protected readonly tableList = signal([]);
+ protected readonly tested = signal(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>({});
+ 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 {
+ 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 {
+ 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(`${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 {
+ 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 {
+ 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);
+}
diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts
index ae8741c..504f7af 100644
--- a/src/app/gobernanza/figures.ts
+++ b/src/app/gobernanza/figures.ts
@@ -211,8 +211,8 @@ export function interpretabilityFigures(
}
/** 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[],
diff --git a/src/app/gobernanza/gobernanza.html b/src/app/gobernanza/gobernanza.html
index fcd4cd7..79fa5b6 100644
--- a/src/app/gobernanza/gobernanza.html
+++ b/src/app/gobernanza/gobernanza.html
@@ -31,7 +31,7 @@
}
@if (models.isLoading()) {
- Cargando modelos…
+
} @else if (!models.value()?.length) {
Este dominio todavía no tiene modelos entrenados.
}
diff --git a/src/app/gobernanza/gobernanza.ts b/src/app/gobernanza/gobernanza.ts
index 3e0289f..d6e21a3 100644
--- a/src/app/gobernanza/gobernanza.ts
+++ b/src/app/gobernanza/gobernanza.ts
@@ -25,6 +25,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 = {
technical_validation: 'Validación técnica',
@@ -38,6 +39,7 @@ const REPORTS: Record = {
@Component({
selector: 'app-gobernanza',
imports: [
+ Loading,
DatePipe,
DecimalPipe,
FormsModule,
diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts
index 10cd4cb..0f51870 100644
--- a/src/app/indicadores/indicadores.ts
+++ b/src/app/indicadores/indicadores.ts
@@ -8,11 +8,13 @@ import { TabIndicadores } from './tab-indicadores';
import { TabRiesgos } from './tab-riesgos';
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,
@@ -27,7 +29,7 @@ import { TabTrazabilidad } from './tab-trazabilidad';
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
@if (measures.isLoading()) {
- Cargando indicadores…
+
} @else if (measures.error()) {
No se pudieron leer los indicadores.
} @else if (!measures.value()?.length) {
diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html
index f0aea1f..017a9da 100644
--- a/src/app/indicadores/tab-indicadores.html
+++ b/src/app/indicadores/tab-indicadores.html
@@ -31,7 +31,7 @@
@if (reports.isLoading()) {
- Calculando…
+
}
@if (kpis().length) {
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts
index 730fc6a..c36d9c0 100644
--- a/src/app/indicadores/tab-indicadores.ts
+++ b/src/app/indicadores/tab-indicadores.ts
@@ -23,12 +23,14 @@ 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,
MatButtonModule,
MatButtonToggleModule,
diff --git a/src/app/indicadores/tab-trazabilidad.ts b/src/app/indicadores/tab-trazabilidad.ts
index b4d8a39..ae703c1 100644
--- a/src/app/indicadores/tab-trazabilidad.ts
+++ b/src/app/indicadores/tab-trazabilidad.ts
@@ -5,11 +5,12 @@ import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { history, periods, PeriodType, periodTypes, reading } from './measures';
+import { Loading } from '../loading';
/** Each measure over time: every period of the chosen kind, oldest first. */
@Component({
selector: 'app-tab-trazabilidad',
- imports: [MatButtonToggleModule, MatCardModule, Plot],
+ imports: [Loading, MatButtonToggleModule, MatCardModule, Plot],
template: `
@if (series.isLoading()) {
- Calculando…
+
}
@for (item of figures(); track item.measure.id) {
diff --git a/src/app/loading.ts b/src/app/loading.ts
new file mode 100644
index 0000000..820974f
--- /dev/null
+++ b/src/app/loading.ts
@@ -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: `
+
+
{{ text() || 'Cargando ' + what() + '…' }}
+ @if (figure()) {
+
+ }
+ `,
+ 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
();
+ /** The whole line instead ("Calculando los indicadores…"). */
+ readonly text = input('');
+ /** A figure's skeleton under the bar. */
+ readonly figure = input(false);
+}
diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html
index 904dfd1..ed5fc49 100644
--- a/src/app/paciente/paciente.html
+++ b/src/app/paciente/paciente.html
@@ -146,8 +146,38 @@
}
+
+ @if (models().some((m) => m.scenarios.length)) {
+
+ Análisis de supervivencia
+
+ @if (survival.isLoading()) {
+
+ } @else if (survival.value(); as s) {
+ Escenario clínico de la paciente
+
+ @for (name of s.scenarios; track name) {
+ {{ name }}
+ }
+
+ @for (f of s.figures; track f.title) {
+ {{ f.title }}
+
+ } @empty {
+
+ Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas.
+
+ }
+ } @else if (survival.error()) {
+ No se pudo leer el informe del modelo.
+ }
+
+
+ }
} @else if (loading()) {
- Cargando…
+
}
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss
index ab298fc..79c9f08 100644
--- a/src/app/paciente/paciente.scss
+++ b/src/app/paciente/paciente.scss
@@ -33,3 +33,20 @@
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;
+ }
+}
diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts
index 65688e6..cf89d55 100644
--- a/src/app/paciente/paciente.ts
+++ b/src/app/paciente/paciente.ts
@@ -12,10 +12,15 @@ import type {
Procedure,
RiskAssessment,
} from 'fhir/r4';
-import { code, ext, Fhir, label, resources } from '../fhir';
+import { Api } from '../api/api';
+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 { 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 {
@@ -30,12 +35,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();
readonly id = input.required();
@@ -114,7 +120,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,6 +134,36 @@ export class Paciente {
})),
}));
});
+ /** "Análisis de supervivencia": the curves of her clinical scenarios, from the report of
+ * the model version that scored her. */
+ protected readonly survival = resource({
+ params: () => {
+ const m = this.models().find((x) => 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: m.model.replace(`${domain}.`, ''),
+ version: m.version,
+ report: 'interpretability',
+ });
+ const drawn = ((report?.['escenarios'] ?? []) as any[]).filter((e) =>
+ m.scenarios.includes(e.escenario),
+ );
+ return {
+ scenarios: m.scenarios,
+ figures: drawn.map((e) =>
+ scenarioFigure(
+ `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
+ e,
+ e.horizons_months,
+ 'Supervivencia S(t)',
+ ),
+ ),
+ };
+ },
+ });
protected readonly shown = signal(undefined);
protected readonly curve = computed(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
From 9a15ac6fcb70e6372d8cee651b679dd690ce2ab9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 10:03:31 -0600
Subject: [PATCH 04/32] 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
---
e2e/pages.spec.ts | 47 ++-
src/app/auth/auth.ts | 5 +-
src/app/indicadores/indicadores.ts | 26 +-
src/app/indicadores/measures.ts | 10 +-
src/app/indicadores/pages.ts | 385 +++++++++++++++++++++++
src/app/indicadores/tab-indicadores.html | 162 +++++++---
src/app/indicadores/tab-indicadores.scss | 91 ++++++
src/app/indicadores/tab-indicadores.ts | 61 +++-
8 files changed, 720 insertions(+), 67 deletions(-)
create mode 100644 src/app/indicadores/pages.ts
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index f6d3651..bc316fa 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -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. */
@@ -12,7 +13,7 @@ function watch(page: Page): string[] {
// 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.test', password: 'solo-para-pruebas' },
+ form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
});
@@ -22,7 +23,7 @@ test('login: the pages wait for a sign-in, and a wrong password says so', async
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.test');
+ 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();
@@ -80,7 +81,7 @@ 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');
@@ -178,3 +179,43 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
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 items = JSON.parse(readFileSync(path, 'utf8')).tabs['Indicadores'] as any[];
+ const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
+ return items.slice(from).filter((i) => ['h2', 'h3', 'plot'].includes(i.kind));
+}
+const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', ');
+const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
+
+for (const domain of ['cacu']) {
+ 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));
+ });
+}
diff --git a/src/app/auth/auth.ts b/src/app/auth/auth.ts
index 1e04c52..5050416 100644
--- a/src/app/auth/auth.ts
+++ b/src/app/auth/auth.ts
@@ -67,10 +67,9 @@ export class Auth {
/** 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
- : inject(Router).createUrlTree(['/login'], { queryParams: { next: state.url } });
+ return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
};
/** A domain's pages show only to whom may see it. */
diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts
index 0f51870..58ce1ad 100644
--- a/src/app/indicadores/indicadores.ts
+++ b/src/app/indicadores/indicadores.ts
@@ -25,9 +25,7 @@ import { Loading } from '../loading';
template: `
{{ title() }}
-
- Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
-
+ Explora los indicadores de {{ title().toLowerCase() }}.
@if (measures.isLoading()) {
} @else if (measures.error()) {
@@ -51,7 +49,7 @@ import { Loading } from '../loading';
} @else if (domain() === 'cama') {
-
+
@@ -70,11 +68,27 @@ import { Loading } from '../loading';
: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;
diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts
index 3c87e87..dd9e47a 100644
--- a/src/app/indicadores/measures.ts
+++ b/src/app/indicadores/measures.ts
@@ -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 {
diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts
new file mode 100644
index 0000000..490421e
--- /dev/null
+++ b/src/app/indicadores/pages.ts
@@ -0,0 +1,385 @@
+import type { Figure } from '../plot';
+import type { Reading } from './measures';
+
+/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference//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: { measure: string; title: string; note?: string }[];
+ clinical: Section[];
+ /** The measure whose data decides the default period. */
+ anchor: string;
+}
+export type Section =
+ | { kind: 'route'; title: string; steps: { label: string; measure: string }[] }
+ | { kind: 'figures'; title: string; figures: FigureSpec[] };
+export type FigureSpec =
+ | { kind: 'donut'; title: string; measure: string; catalog: Catalog; center: string }
+ | { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string }
+ | {
+ kind: 'rates';
+ title: string;
+ measure: string;
+ stratum: string;
+ rows: Category[];
+ /** 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'],
+};
+
+export const PAGES: Record = {
+ cacu: {
+ anchor: 'CACU_EU7',
+ kpis: [
+ {
+ measure: 'CACU_EU7',
+ title: 'Pacientes evaluadas',
+ note: 'Pacientes con citología tomada en el periodo.',
+ },
+ { measure: 'CACU_EU_TIEMPO_REPORTE', title: 'Tiempo desde la toma de muestra al resultado' },
+ { measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
+ { measure: 'CACU_DIAS_TOMA_TRATAMIENTO', title: 'Tiempo de tamizaje a tratamiento' },
+ {
+ measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
+ title: 'Tiempo de diagnóstico a tratamiento',
+ },
+ ],
+ 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',
+ measure: 'CACU_EU7',
+ catalog: CYTOLOGY,
+ center: 'pacientes',
+ },
+ {
+ kind: 'scenario-bars',
+ title: 'TOTAL por escenario clínico',
+ 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',
+ 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',
+ measure: 'CACU_CONFIRMACION_CITOLOGIA',
+ catalog: BIOPSY,
+ center: 'con biopsia',
+ },
+ ],
+ },
+ ],
+ },
+};
+
+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} 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} mediana %{x} días ',
+ } as Partial,
+ ],
+ 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: [`${count(total)} ${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} ${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} %{value} (%{percent}) ',
+ },
+ {
+ ...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} %{value} (%{percent}) ',
+ },
+ ] as Partial[],
+ 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} %{y}: %{customdata} (%{x:.1f} %) `,
+ })) as Partial[],
+ 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 },
+): 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: 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} % ',
+ } as Partial,
+ ],
+ 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 ? `${percent(x.rate!)} % ${x.k}/${x.den}` : 'Sin biopsias',
+ })),
+ },
+ };
+}
diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html
index 017a9da..8ccf2d0 100644
--- a/src/app/indicadores/tab-indicadores.html
+++ b/src/app/indicadores/tab-indicadores.html
@@ -1,4 +1,5 @@
+
Filtros
Intervalo de análisis
Periodo seleccionado
@for (p of options(); track p) {
- {{ label(p) }}
+ {{ p }}
}
@@ -25,65 +26,124 @@
>
Aplicar
- @if (applied(); as p) {
- Mostrando {{ label(p) }}
- }
@if (reports.isLoading()) {
}
-@if (kpis().length) {
-
Indicadores de oportunidad
-
- @for (m of kpis(); track m.id) {
-
+@if (page(); as pg) {
+ @if (applied(); as period) {
+
+
+
Indicadores de oportunidad
+ Periodo {{ period }}
+
+
+ @for (k of pg.kpis; track k.measure) {
+
+
+ {{ k.title }}
+ @if (reports.isLoading()) {
+
+ } @else {
+ {{ kpiValue(k.measure) }}
+ {{ kpiNote(k.measure, k.note) }}
+ }
+
+
+ }
+
+
+
+
+ Indicadores clínicos
+ @for (section of pg.clinical; track section.title) {
+ @if (section.kind === 'route') {
+ {{ section.title }}
+ @if (reports.isLoading()) {
+
+ } @else if (routeOf(section); as fig) {
+
+ } @else {
+ Sin tiempos publicados en el periodo.
+ }
+ } @else {
+
+
+
+
+
+
+ }
+ }
+
+ }
+} @else {
+ @if (kpis().length) {
+ Indicadores de oportunidad
+
+ @for (m of kpis(); track m.id) {
+
+
+ {{ m.title }}
+ {{ score(m) }}
+ {{ detail(m) }}
+
+
+ }
+
+ }
+
+ @if (layout().route.length) {
+
+
+ Ruta del tamizaje
+
+ Acumulado desde la toma
+ Por pasos
+
+
+
+
+
+
+ }
+
+ Indicadores clínicos
+
+ @for (m of clinical(); track m.id) {
+
+
+ {{ m.title }}
+ {{ score(m) }} · {{ detail(m) }}
+
- {{ m.title }}
- {{ score(m) }}
- {{ detail(m) }}
+ @for (f of figureSets().get(m.name!) ?? []; track f.title) {
+
+
+ } @empty {
+ Sin datos en el periodo.
+ }
}
}
-
-@if (layout().route.length) {
-
-
- Ruta del tamizaje
-
- Acumulado desde la toma
- Por pasos
-
-
-
-
-
-
-}
-
-Indicadores clínicos
-
- @for (m of clinical(); track m.id) {
-
-
- {{ m.title }}
- {{ score(m) }} · {{ detail(m) }}
-
-
- @for (f of figureSets().get(m.name!) ?? []; track f.title) {
-
-
- } @empty {
- Sin datos en el periodo.
- }
-
-
- }
-
diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss
index cdebd88..e8bf85d 100644
--- a/src/app/indicadores/tab-indicadores.scss
+++ b/src/app/indicadores/tab-indicadores.scss
@@ -97,3 +97,94 @@ 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;
+}
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts
index c36d9c0..a76f86e 100644
--- a/src/app/indicadores/tab-indicadores.ts
+++ b/src/app/indicadores/tab-indicadores.ts
@@ -8,6 +8,15 @@ import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
+import {
+ FigureSpec,
+ nestedDonut,
+ PAGES,
+ rateDots,
+ routeFigure,
+ scenarioBars,
+ Section,
+} from './pages';
import {
detail,
donut,
@@ -56,6 +65,8 @@ export class TabIndicadores {
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
);
+ /** 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()
@@ -74,7 +85,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 }) => {
@@ -156,7 +167,7 @@ export class TabIndicadores {
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')
@@ -170,4 +181,50 @@ 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.reports.value()?.get(code);
+ }
+ protected kpi(code: string): Measure | undefined {
+ return this.byName().get(code);
+ }
+ /** A KPI card's value as the old cards wrote it. */
+ protected kpiValue(code: string): string {
+ const m = this.kpi(code);
+ const r = this.rd(code);
+ if (!m || !r || r.score === undefined) return '';
+ if (scoring(m) === 'continuous-variable') return `${Math.round(r.score)} días (mediana)`;
+ if (scoring(m) === 'proportion') return `${(r.score * 100).toFixed(1)} %`;
+ const n = r.populations['initial-population'] ?? 0;
+ return `${n.toLocaleString('es-MX')} pacientes`;
+ }
+ protected kpiNote(code: string, note?: string): string {
+ const m = this.kpi(code);
+ const r = this.rd(code);
+ if (!m || !r || r.score === undefined) return 'Sin valor disponible';
+ if (scoring(m) === 'continuous-variable') {
+ const n = (r.populations['measure-observation'] ?? 0).toLocaleString('es-MX');
+ return `${n} citologías; primer cuartil: ${Math.round(r.low ?? r.score)} días; tercer cuartil: ${Math.round(r.high ?? r.score)} días.`;
+ }
+ return note ?? detail(m, r);
+ }
+ /** 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 'scenario-bars':
+ return scenarioBars(r, spec.catalog, spec.stratum, name);
+ case 'rates':
+ return rateDots(r, spec);
+ }
+ }
}
From 3e096dd03f6945552ec8d466e659c10c24f09e57 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 10:09:30 -0600
Subject: [PATCH 05/32] =?UTF-8?q?CaMa=20Indicadores=20as=20the=20old=20pag?=
=?UTF-8?q?e:=20its=20cards,=20timeliness=20boxes=20with=20pending=20ones,?=
=?UTF-8?q?=20BI-RADS=204=E2=80=936=20donuts,=20malignancy=20by=20BI-RADS?=
=?UTF-8?q?=20and=20the=20biopsy=20donut,=20the=20confirmation=20card;=20p?=
=?UTF-8?q?age=20definitions=20apart=20from=20figure=20builders?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
e2e/pages.spec.ts | 7 +-
src/app/indicadores/figures.ts | 328 +++++++++++++++++
src/app/indicadores/pages.ts | 429 ++++++++++-------------
src/app/indicadores/tab-indicadores.html | 128 +++++--
src/app/indicadores/tab-indicadores.scss | 53 +++
src/app/indicadores/tab-indicadores.ts | 55 +--
6 files changed, 692 insertions(+), 308 deletions(-)
create mode 100644 src/app/indicadores/figures.ts
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index bc316fa..21b5010 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -186,12 +186,15 @@ function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const items = JSON.parse(readFileSync(path, 'utf8')).tabs['Indicadores'] as any[];
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
- return items.slice(from).filter((i) => ['h2', 'h3', 'plot'].includes(i.kind));
+ 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})$/, ', ');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
-for (const domain of ['cacu']) {
+for (const domain of ['cacu', 'cama']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts
new file mode 100644
index 0000000..de4690b
--- /dev/null
+++ b/src/app/indicadores/figures.ts
@@ -0,0 +1,328 @@
+import type { Figure } from '../plot';
+import type { Reading } from './measures';
+import type { Catalog, Category } 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} 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} mediana %{x} días ',
+ } as Partial,
+ ],
+ 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: [`${count(total)} ${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} ${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} %{value} (%{percent}) ',
+ },
+ {
+ ...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} %{value} (%{percent}) ',
+ },
+ ] as Partial[],
+ 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} %{y}: %{customdata} (%{x:.1f} %) `,
+ })) as Partial[],
+ 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} % ',
+ } as Partial,
+ ],
+ 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
+ ? `${percent(x.rate!)} % ${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 = {
+ 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 `,
+ } as Partial,
+ ],
+ 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} %{percent}' : '')),
+ textposition: 'outside',
+ hovertemplate: '%{label} %{value} (%{percent}) ',
+ } as Partial,
+ ],
+ layout: {
+ showlegend: false,
+ margin: { t: 30, l: 60, r: 60, b: 30 },
+ annotations: [
+ {
+ text: `${count(total)} ${center}`,
+ showarrow: false,
+ x: 0.5,
+ y: 0.5,
+ xref: 'paper',
+ yref: 'paper',
+ },
+ ],
+ },
+ };
+}
diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts
index 490421e..9e75e3e 100644
--- a/src/app/indicadores/pages.ts
+++ b/src/app/indicadores/pages.ts
@@ -1,20 +1,36 @@
-import type { Figure } from '../plot';
-import type { Reading } from './measures';
-
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference//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: { measure: string; title: string; note?: string }[];
+ 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: 'figures'; title?: string; figures: FigureSpec[] }
+ | { kind: 'boxes'; title: string; cards: { measure?: string; title: string }[] }
+ | ({ kind: 'card' } & Kpi);
+/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec =
- | { kind: 'donut'; title: string; measure: string; catalog: Catalog; center: string }
+ | {
+ kind: 'donut' | 'share-donut';
+ title: string;
+ measure: string;
+ catalog: Catalog;
+ center: string;
+ }
| { kind: 'scenario-bars'; title: string; measure: string; catalog: Catalog; stratum: string }
| {
kind: 'rates';
@@ -22,6 +38,8 @@ export type FigureSpec =
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;
@@ -75,21 +93,171 @@ const BIOPSY: Catalog = {
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 = {
+ 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',
+ 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' },
- { measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
- { measure: 'CACU_DIAS_TOMA_TRATAMIENTO', title: 'Tiempo de tamizaje a tratamiento' },
+ {
+ 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: [
@@ -109,14 +277,14 @@ export const PAGES: Record = {
figures: [
{
kind: 'donut',
- title: 'Distribución de resultados',
+ title: 'Distribución de resultados, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
center: 'pacientes',
},
{
kind: 'scenario-bars',
- title: 'TOTAL por escenario clínico',
+ title: 'TOTAL por escenario clínico, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
stratum: 'follow_up_status',
@@ -129,7 +297,7 @@ export const PAGES: Record = {
figures: [
{
kind: 'rates',
- title: 'Por resultado de la citología',
+ 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)),
@@ -138,7 +306,7 @@ export const PAGES: Record = {
},
{
kind: 'donut',
- title: 'Resultado de la biopsia',
+ title: 'Resultado de la biopsia, {p}',
measure: 'CACU_CONFIRMACION_CITOLOGIA',
catalog: BIOPSY,
center: 'con biopsia',
@@ -148,238 +316,3 @@ export const PAGES: Record = {
],
},
};
-
-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} 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} mediana %{x} días ',
- } as Partial,
- ],
- 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: [`${count(total)} ${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} ${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} %{value} (%{percent}) ',
- },
- {
- ...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} %{value} (%{percent}) ',
- },
- ] as Partial[],
- 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} %{y}: %{customdata} (%{x:.1f} %) `,
- })) as Partial[],
- 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 },
-): 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: 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} % ',
- } as Partial,
- ],
- 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 ? `${percent(x.rate!)} % ${x.k}/${x.den}` : 'Sin biopsias',
- })),
- },
- };
-}
diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html
index 8ccf2d0..f52e2a9 100644
--- a/src/app/indicadores/tab-indicadores.html
+++ b/src/app/indicadores/tab-indicadores.html
@@ -40,58 +40,114 @@
Periodo {{ period }}
- @for (k of pg.kpis; track k.measure) {
-
+ @for (k of pg.kpis; track k.title) {
+
{{ k.title }}
- @if (reports.isLoading()) {
+ @if (reports.isLoading() && k.measure) {
} @else {
- {{ kpiValue(k.measure) }}
- {{ kpiNote(k.measure, k.note) }}
+ {{ kpiValue(k) }}
+ {{ kpiNote(k) }}
}
}
+ @for (section of pg.opportunity ?? []; track $index) {
+
+ }
Indicadores clínicos
- @for (section of pg.clinical; track section.title) {
- @if (section.kind === 'route') {
- {{ section.title }}
- @if (reports.isLoading()) {
-
- } @else if (routeOf(section); as fig) {
-
- } @else {
- Sin tiempos publicados en el periodo.
- }
- } @else {
-
-
-
-
-
-
- }
+ @for (section of pg.clinical; track $index) {
+
}
}
+
+
+ @switch (section.kind) {
+ @case ('route') {
+ {{ section.title }}
+ @if (reports.isLoading()) {
+
+ } @else if (routeOf(section); as fig) {
+
+ } @else {
+ Sin tiempos publicados en el periodo.
+ }
+ }
+ @case ('boxes') {
+ {{ section.title }}
+
+ @for (b of section.cards; track b.title) {
+
+
+ {{ b.title }}
+ @if (!b.measure) {
+ Integración pendiente. {{ pending }}
+ Sin datos publicados
+ } @else {
+ Filtro general aplicado: {{ period }}
+ {{ measureTitle(b.measure) }}
+ Figura: Caja de cuartiles
+ @if (reports.isLoading()) {
+
+ } @else if (boxOf(b.measure); as fig) {
+
+ } @else {
+ Sin datos publicados
+ }
+ }
+
+
+ }
+
+ }
+ @case ('card') {
+
+
+ {{ section.title }}
+ {{ kpiValue(section) }}
+ {{ kpiNote(section) }}
+
+
+ }
+ @default {
+
+
+ @if (section.title) {
+
+ }
+
+
+
+ }
+ }
+
} @else {
@if (kpis().length) {
Indicadores de oportunidad
diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss
index e8bf85d..dc3d8b7 100644
--- a/src/app/indicadores/tab-indicadores.scss
+++ b/src/app/indicadores/tab-indicadores.scss
@@ -188,3 +188,56 @@ h2.filters-title {
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;
+}
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts
index a76f86e..f2aacd9 100644
--- a/src/app/indicadores/tab-indicadores.ts
+++ b/src/app/indicadores/tab-indicadores.ts
@@ -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';
@@ -9,14 +10,15 @@ import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import {
- FigureSpec,
+ boxFigure,
+ fill,
nestedDonut,
- PAGES,
rateDots,
routeFigure,
scenarioBars,
- Section,
-} from './pages';
+ shareDonut,
+} from './figures';
+import { FigureSpec, Kpi, PAGES, Section } from './pages';
import {
detail,
donut,
@@ -41,6 +43,7 @@ import { Loading } from '../loading';
imports: [
Loading,
FormsModule,
+ NgTemplateOutlet,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
@@ -65,6 +68,8 @@ 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])));
@@ -189,25 +194,29 @@ export class TabIndicadores {
protected kpi(code: string): Measure | undefined {
return this.byName().get(code);
}
- /** A KPI card's value as the old cards wrote it. */
- protected kpiValue(code: string): string {
- const m = this.kpi(code);
- const r = this.rd(code);
- if (!m || !r || r.score === undefined) return '';
- if (scoring(m) === 'continuous-variable') return `${Math.round(r.score)} días (mediana)`;
- if (scoring(m) === 'proportion') return `${(r.score * 100).toFixed(1)} %`;
- const n = r.populations['initial-population'] ?? 0;
- return `${n.toLocaleString('es-MX')} pacientes`;
+ /** 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(code: string, note?: string): string {
- const m = this.kpi(code);
- const r = this.rd(code);
- if (!m || !r || r.score === undefined) return 'Sin valor disponible';
- if (scoring(m) === 'continuous-variable') {
- const n = (r.populations['measure-observation'] ?? 0).toLocaleString('es-MX');
- return `${n} citologías; primer cuartil: ${Math.round(r.low ?? r.score)} días; tercer cuartil: ${Math.round(r.high ?? r.score)} días.`;
- }
- return note ?? detail(m, 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;
+ }
+ 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 {
@@ -221,6 +230,8 @@ export class TabIndicadores {
switch (spec.kind) {
case 'donut':
return nestedDonut(r, spec.catalog, spec.center);
+ case 'share-donut':
+ return shareDonut(r, spec.catalog, spec.center);
case 'scenario-bars':
return scenarioBars(r, spec.catalog, spec.stratum, name);
case 'rates':
From aeb2d4ec84dd71123bc72f3c350c14303070bdc5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 10:26:24 -0600
Subject: [PATCH 06/32] TEA Indicadores as the old page: the period summary in
words, the three timeliness boxes, counts and age-group figures; tab named
Resumen
---
e2e/pages.spec.ts | 7 +-
src/app/indicadores/figures.ts | 89 ++++++++++++++++++
src/app/indicadores/indicadores.ts | 2 +-
src/app/indicadores/pages.ts | 114 ++++++++++++++++++++++-
src/app/indicadores/tab-indicadores.html | 61 +++++++++++-
src/app/indicadores/tab-indicadores.scss | 42 +++++++++
src/app/indicadores/tab-indicadores.ts | 43 +++++++++
7 files changed, 349 insertions(+), 9 deletions(-)
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index 21b5010..9db7863 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -87,7 +87,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
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([]);
});
@@ -184,7 +184,8 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
* 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 items = JSON.parse(readFileSync(path, 'utf8')).tabs['Indicadores'] as any[];
+ 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)
@@ -194,7 +195,7 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', ');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
-for (const domain of ['cacu', 'cama']) {
+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,
}) => {
diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts
index de4690b..068bd04 100644
--- a/src/app/indicadores/figures.ts
+++ b/src/app/indicadores/figures.ts
@@ -326,3 +326,92 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
},
};
}
+
+/** 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} ',
+ } as Partial,
+ ],
+ 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][] {
+ 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[],
+ 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} % ',
+ } as Partial,
+ ],
+ layout: {
+ showlegend: false,
+ xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
+ yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
+ },
+ };
+}
diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts
index 58ce1ad..beec0a6 100644
--- a/src/app/indicadores/indicadores.ts
+++ b/src/app/indicadores/indicadores.ts
@@ -34,7 +34,7 @@ import { Loading } from '../loading';
Este dominio todavía no tiene indicadores publicados.
} @else {
-
+
diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts
index 9e75e3e..cf7636f 100644
--- a/src/app/indicadores/pages.ts
+++ b/src/app/indicadores/pages.ts
@@ -20,7 +20,18 @@ export interface Kpi {
export type Section =
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] }
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
- | { kind: 'boxes'; title: string; cards: { measure?: string; title: string }[] }
+ | {
+ 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 =
@@ -32,6 +43,14 @@ export type FigureSpec =
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;
@@ -128,6 +147,98 @@ const BREAST_BIOPSY: Catalog = {
};
export const PAGES: Record = {
+ 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: [
@@ -163,6 +274,7 @@ export const PAGES: Record = {
{
kind: 'boxes',
title: 'Tiempo de tamizaje a diagnóstico',
+ subtitles: true,
cards: [
{
measure: 'CAMA_EU38A',
diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html
index f52e2a9..b75f5e4 100644
--- a/src/app/indicadores/tab-indicadores.html
+++ b/src/app/indicadores/tab-indicadores.html
@@ -83,9 +83,60 @@
Sin tiempos publicados en el periodo.
}
}
+ @case ('tea-summary') {
+ @if (teaSummary(); as t) {
+
+
+ Resumen
+
+ Al cierre del periodo {{ period }} , se evaluaron
+ {{ t.evaluated }} niños entre 16 y 36 meses;
+ {{ t.mchatOnly }} únicamente tienen M-CHAT,
+ {{ t.psychology }} hasta la evaluación psicológica y
+ {{ t.neuropediatrics }} presentan evaluación neuropediátrica. En este
+ periodo el {{ t.confirmed }} de los pacientes tiene diagnóstico
+ confirmado de TEA (CIE-10 F84.0). Las ventanas de tiempo* de tamizaje
+ son: {{ t.toAdos }} de M-CHAT (psicología) a ADOS-2,
+ {{ t.toDiagnosis }} de ADOS-2 a diagnóstico. El tiempo* de
+ tamizaje completo de M-CHAT a diagnóstico fue de {{ t.whole }} .
+
+
+ De los {{ t.diagnosed }} niños con diagnóstico confirmado en este
+ periodo, {{ t.eeg }} presentan estudio de EEG y faltan
+ {{ t.missing }} por realizarlo. {{ t.unusable }} estudios
+ de EEG no son aceptables para un análisis.
+
+ *tomando la mediana de los tiempos
+
+
+ } @else if (reports.isLoading()) {
+
+ }
+ }
+ @case ('grid') {
+
+ }
@case ('boxes') {
- {{ section.title }}
-
+ @if (section.title) {
+
{{ section.title }}
+ }
+
@for (b of section.cards; track b.title) {
Sin datos publicados
} @else {
Filtro general aplicado: {{ period }}
-
{{ measureTitle(b.measure) }}
-
Figura: Caja de cuartiles
+ @if (section.subtitles) {
+
{{ measureTitle(b.measure) }}
+
Figura: Caja de cuartiles
+ }
@if (reports.isLoading()) {
} @else if (boxOf(b.measure); as fig) {
diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss
index dc3d8b7..31bbd11 100644
--- a/src/app/indicadores/tab-indicadores.scss
+++ b/src/app/indicadores/tab-indicadores.scss
@@ -241,3 +241,45 @@ h2.box-subtitle {
.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));
+ }
+}
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts
index f2aacd9..62b1042 100644
--- a/src/app/indicadores/tab-indicadores.ts
+++ b/src/app/indicadores/tab-indicadores.ts
@@ -10,7 +10,10 @@ import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import {
+ ageShare,
+ ageStack,
boxFigure,
+ countBars,
fill,
nestedDonut,
rateDots,
@@ -215,6 +218,40 @@ export class TabIndicadores {
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.reports.value()?.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) || '';
}
@@ -232,6 +269,12 @@ export class TabIndicadores {
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':
From cb0403affb18b2e2d316682889faa686b4e29654 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 10:47:22 -0600
Subject: [PATCH 07/32] =?UTF-8?q?TEA=20An=C3=A1lisis=20de=20Riesgo=20as=20?=
=?UTF-8?q?the=20old=20page:=20its=20filters,=20the=20EEG=20summary=20of?=
=?UTF-8?q?=20the=20filtered=20children=20and=20their=20list;=20the=20doma?=
=?UTF-8?q?in's=20full=20name;=20reports=20that=20fail=20to=20load=20can?=
=?UTF-8?q?=20be=20retried?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/app/app.ts | 2 +-
src/app/indicadores/indicadores.ts | 8 ++
src/app/indicadores/tab-indicadores.html | 6 +
src/app/indicadores/tab-indicadores.scss | 14 ++
src/app/indicadores/tab-indicadores.ts | 16 ++-
src/app/indicadores/tab-riesgos-tea.html | 169 ++++++++++++++++++++++
src/app/indicadores/tab-riesgos-tea.scss | 80 +++++++++++
src/app/indicadores/tab-riesgos-tea.ts | 176 +++++++++++++++++++++++
8 files changed, 464 insertions(+), 7 deletions(-)
create mode 100644 src/app/indicadores/tab-riesgos-tea.html
create mode 100644 src/app/indicadores/tab-riesgos-tea.scss
create mode 100644 src/app/indicadores/tab-riesgos-tea.ts
diff --git a/src/app/app.ts b/src/app/app.ts
index 50a8bfa..9f2123d 100644
--- a/src/app/app.ts
+++ b/src/app/app.ts
@@ -13,7 +13,7 @@ import { Auth } from './auth/auth';
export const DOMAINS: Record = {
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. */
diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts
index beec0a6..032b54f 100644
--- a/src/app/indicadores/indicadores.ts
+++ b/src/app/indicadores/indicadores.ts
@@ -6,6 +6,7 @@ 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';
@@ -19,6 +20,7 @@ import { Loading } from '../loading';
TabIndicadores,
TabTrazabilidad,
TabRiesgos,
+ TabRiesgosTea,
TabSeguimiento,
TabDefiniciones,
],
@@ -48,6 +50,12 @@ import { Loading } from '../loading';
+ } @else if (domain() === 'tea') {
+
+
+
+
+
} @else if (domain() === 'cama') {
diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html
index b75f5e4..12362c8 100644
--- a/src/app/indicadores/tab-indicadores.html
+++ b/src/app/indicadores/tab-indicadores.html
@@ -32,6 +32,12 @@
}
+@if (reports.error()) {
+
+
No se pudieron leer los indicadores del periodo. Vuelve a intentar.
+
Reintentar
+
+}
@if (page(); as pg) {
@if (applied(); as period) {
diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss
index 31bbd11..1cb5d75 100644
--- a/src/app/indicadores/tab-indicadores.scss
+++ b/src/app/indicadores/tab-indicadores.scss
@@ -283,3 +283,17 @@ h2.box-subtitle {
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;
+ }
+}
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts
index 62b1042..f00806b 100644
--- a/src/app/indicadores/tab-indicadores.ts
+++ b/src/app/indicadores/tab-indicadores.ts
@@ -126,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 | undefined {
+ return this.reports.hasValue() ? this.reports.value() : undefined;
+ }
+
constructor() {
effect(() => {
const latest = this.latest.value();
@@ -139,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));
@@ -166,9 +172,7 @@ 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. */
@@ -192,7 +196,7 @@ export class TabIndicadores {
/** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined {
- return this.reports.value()?.get(code);
+ return this.loaded()?.get(code);
}
protected kpi(code: string): Measure | undefined {
return this.byName().get(code);
@@ -220,7 +224,7 @@ export class TabIndicadores {
}
/** TEA's summary of the period: its numbers from the measures (none: no summary). */
protected readonly teaSummary = computed(() => {
- const rd = (c: string) => this.reports.value()?.get(c);
+ 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;
diff --git a/src/app/indicadores/tab-riesgos-tea.html b/src/app/indicadores/tab-riesgos-tea.html
new file mode 100644
index 0000000..a034362
--- /dev/null
+++ b/src/app/indicadores/tab-riesgos-tea.html
@@ -0,0 +1,169 @@
+
+ Alteraciones de EEG relacionadas al TEA
+
+
+ Fecha de corte
+
+
+
+ Ventana de meses
+
+ @for (m of [1, 3, 6, 12]; track m) {
+ {{ m }} {{ m === 1 ? 'mes' : 'meses' }}
+ }
+
+
+
+ Estatus de EEG
+
+ Todos
+ @for (s of eegStatuses | keyvalue; track s.key) {
+ {{ s.value }}
+ }
+
+
+
+ Grupo de edad
+
+ Todos
+ @for (a of ages(); track a) {
+ {{ ageLabel(a) }}
+ }
+
+
+
+ Puntaje M-CHAT
+
+ Todos
+ @for (b of mchatBands; track b.id) {
+ {{ b.label }}
+ }
+
+
+
+ CSS ADOS-2
+
+ Todos
+ @for (l of cssLevels; track l.id) {
+ {{ l.label }}
+ }
+
+
+
+ Estado del caso
+
+ Todos
+ @for (c of cases | keyvalue; track c.key) {
+ {{ c.value }}
+ }
+
+
+
+ Tipo de alteración
+
+ Todas
+ @for (a of alterations(); track a) {
+ {{ alteration(a) }}
+ }
+
+
+
+ Registros por página
+
+
+ Consultar
+
+
+ @if (loading()) {
+
+ } @else {
+ @let s = summary();
+
+
EEG de los pacientes filtrados
+
+ {{ s.normal }} Normales
+ {{ s.abnormal }} Anormales
+ {{ s.none }} Sin EEG válido
+
+ @if (s.alterations.length) {
+
+ @for (a of s.alterations; track a[0]) {
+
+ {{ alteration(a[0]) }}: {{ a[1] }}
+
+ }
+
+ }
+
+
+
+
+
+ Paciente
+ Grupo de edad
+ Estado del caso
+ Último EEG
+ Puntaje M-CHAT
+ CSS ADOS-2
+ Estatus de EEG
+
+
+
+ @for (r of shown(); track r.patient.id) {
+
+
+ {{
+ r.name
+ }}
+
+ {{ r.ageGroup ? ageLabel(r.ageGroup) : 'Sin dato' }}
+ {{ cases[r.case] ?? r.case }}
+ {{ r.lastEeg ?? '—' }}
+ {{ r.mchat ?? '—' }}
+ {{ r.css ?? '—' }}
+ {{ eegStatuses[r.eegStatus] ?? r.eegStatus }}
+
+ } @empty {
+
+ Nadie en la lista con estos filtros.
+
+ }
+
+
+
+ }
+
diff --git a/src/app/indicadores/tab-riesgos-tea.scss b/src/app/indicadores/tab-riesgos-tea.scss
new file mode 100644
index 0000000..d63c466
--- /dev/null
+++ b/src/app/indicadores/tab-riesgos-tea.scss
@@ -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;
+ }
+}
diff --git a/src/app/indicadores/tab-riesgos-tea.ts b/src/app/indicadores/tab-riesgos-tea.ts
new file mode 100644
index 0000000..2cadbf0
--- /dev/null
+++ b/src/app/indicadores/tab-riesgos-tea.ts
@@ -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 = {
+ normal: 'Normal',
+ abnormal: 'Anormal',
+ no_valid_eeg: 'Sin EEG válido',
+};
+const CASE: Record = {
+ 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();
+
+ 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(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();
+ 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);
+ }
+}
From 37444a25a119d71a4fc48ef4131b2b1389a1435b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 13:29:23 -0600
Subject: [PATCH 08/32] TEA record: ADOS-2 by item, EEG quality and its
alterations against the age norm; page tests follow the cards' and dialog's
words
---
e2e/pages.spec.ts | 9 ++--
openapi.json | 33 +++++++++++++++
src/app/api/models/metric.ts | 3 ++
src/app/paciente/paciente.html | 76 ++++++++++++++++++++++++++++++++++
src/app/paciente/paciente.scss | 6 +++
src/app/paciente/paciente.ts | 68 ++++++++++++++++++++++++++++++
6 files changed, 192 insertions(+), 3 deletions(-)
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index 9db7863..483cdc2 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -51,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: " 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();
@@ -104,7 +107,7 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
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('Traducir códigos · cytology', { exact: true }).click();
- await expect(page.getByText('Códigos del sitio')).toBeVisible();
+ await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect
.poll(() =>
page
@@ -165,7 +168,7 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
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(/Primeras \d+ filas/)).toBeVisible();
+ 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();
diff --git a/openapi.json b/openapi.json
index fb5c0c3..0577d59 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1065,6 +1065,17 @@
"title": "Code",
"type": "string"
},
+ "median": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Median"
+ },
"model": {
"anyOf": [
{
@@ -1087,6 +1098,28 @@
],
"title": "Outside"
},
+ "p5": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "P5"
+ },
+ "p95": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "P95"
+ },
"value": {
"title": "Value",
"type": "number"
diff --git a/src/app/api/models/metric.ts b/src/app/api/models/metric.ts
index 476a4bc..fcbbafd 100644
--- a/src/app/api/models/metric.ts
+++ b/src/app/api/models/metric.ts
@@ -3,8 +3,11 @@
export interface Metric {
code: string;
+ median?: (number | null);
model: (string | null);
outside: (number | null);
+ p5?: (number | null);
+ p95?: (number | null);
value: number;
z: (number | null);
}
diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html
index ed5fc49..8461815 100644
--- a/src/app/paciente/paciente.html
+++ b/src/app/paciente/paciente.html
@@ -147,6 +147,82 @@
+ @if (domain() === 'tea') {
+
+ ADOS-2
+
+ @if (ados2(); as a) {
+ Puntajes por reactivo · {{ a.date }}
+
+
+ @for (t of a.totals; track t.label) {
+ {{ t.label }}: {{ t.value }}
+ }
+
+ } @else {
+ Sin evaluación ADOS-2.
+ }
+
+
+
+
+ EEG
+
+ @if (eeg.isLoading()) {
+
+ } @else if (eeg.value()?.study; as st) {
+ Calidad del EEG
+
+ Estudio del {{ st.study_date }}:
+ {{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}
+ @if (st.level) {
+ ({{ st.level }})
+ }
+
+ Alteraciones del EEG
+ @if (!st.valid) {
+ Un EEG no aceptable no se compara con la norma por edad.
+ } @else if (!scored()) {
+
+ Ninguna curva por edad vigente ha evaluado este EEG (se promueven en Gobernanza).
+
+ } @else if (alterations().length) {
+
+
+
+ Métrica
+ Valor
+ Norma por edad (P5–P95)
+ Mediana
+ Desviación (z)
+ Detalle
+
+
+
+ @for (m of alterations(); track m.code) {
+
+ {{ m.code }}
+ {{ m.value | number: '1.0-3' }}
+ {{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}
+ {{ m.median | number: '1.0-3' }}
+ {{ m.z | number: '1.1-2' }}
+ {{ m.outside! > 0 ? 'Aumentado' : 'Disminuido' }}
+
+ }
+
+
+ } @else {
+ Sin alteraciones: todas sus métricas están dentro de la norma por edad.
+ }
+ } @else {
+ Sin EEG analizado.
+ }
+
+
+ }
+
@if (models().some((m) => m.scenarios.length)) {
{
+ 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} ',
+ },
+ ],
+ 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(undefined);
protected readonly curve = computed(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
From 20e26b847ab4d3cfa932e881b53499f8bb25e42f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 16:05:21 -0600
Subject: [PATCH 09/32] Wizard page test waits for the cancelled dialog to
close before saving
---
e2e/pages.spec.ts | 1 +
1 file changed, 1 insertion(+)
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index 483cdc2..5c15f58 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -178,6 +178,7 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
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([]);
From fd19fdaefacccc88cd177d638202176915221f64 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 17:15:43 -0600
Subject: [PATCH 10/32] =?UTF-8?q?TEA=20record:=20Zonas=20m=C3=A1s=20afecta?=
=?UTF-8?q?das=20(head=20map=20and=20zones=20by=20deviation);=20survival?=
=?UTF-8?q?=20scenarios=20leave=20Gobernanza?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
openapi.json | 46 +++++++++++++++
src/app/api/models.ts | 1 +
src/app/api/models/metric.ts | 3 +
src/app/api/models/site.ts | 8 +++
src/app/eeg-labels.ts | 99 ++++++++++++++++++++++++++++++++
src/app/gobernanza/figures.ts | 10 +---
src/app/gobernanza/gobernanza.ts | 9 +--
src/app/paciente/paciente.html | 47 ++++++++++++++-
src/app/paciente/paciente.scss | 23 ++++++++
src/app/paciente/paciente.ts | 16 ++++++
10 files changed, 244 insertions(+), 18 deletions(-)
create mode 100644 src/app/api/models/site.ts
create mode 100644 src/app/eeg-labels.ts
diff --git a/openapi.json b/openapi.json
index 0577d59..1c9d22c 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1065,6 +1065,14 @@
"title": "Code",
"type": "string"
},
+ "electrodes": {
+ "default": [],
+ "items": {
+ "$ref": "#/components/schemas/Site"
+ },
+ "title": "Electrodes",
+ "type": "array"
+ },
"median": {
"anyOf": [
{
@@ -1134,6 +1142,14 @@
}
],
"title": "Z"
+ },
+ "zones": {
+ "default": [],
+ "items": {
+ "$ref": "#/components/schemas/Site"
+ },
+ "title": "Zones",
+ "type": "array"
}
},
"required": [
@@ -1512,6 +1528,36 @@
"title": "SignIn",
"type": "object"
},
+ "Site": {
+ "properties": {
+ "site": {
+ "title": "Site",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "number"
+ },
+ "z": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Z"
+ }
+ },
+ "required": [
+ "site",
+ "value",
+ "z"
+ ],
+ "title": "Site",
+ "type": "object"
+ },
"Source": {
"additionalProperties": false,
"description": "One table, file set or API resource, copied as it is (dlt). Merged on the source's\nown primary key or `primary_key`; replaced whole when it has none.",
diff --git a/src/app/api/models.ts b/src/app/api/models.ts
index 0521c53..0e434a7 100644
--- a/src/app/api/models.ts
+++ b/src/app/api/models.ts
@@ -35,6 +35,7 @@ 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';
diff --git a/src/app/api/models/metric.ts b/src/app/api/models/metric.ts
index fcbbafd..d210c52 100644
--- a/src/app/api/models/metric.ts
+++ b/src/app/api/models/metric.ts
@@ -1,8 +1,10 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
+import { Site } from '../models/site';
export interface Metric {
code: string;
+ electrodes?: Array;
median?: (number | null);
model: (string | null);
outside: (number | null);
@@ -10,4 +12,5 @@ export interface Metric {
p95?: (number | null);
value: number;
z: (number | null);
+ zones?: Array;
}
diff --git a/src/app/api/models/site.ts b/src/app/api/models/site.ts
new file mode 100644
index 0000000..2cfc960
--- /dev/null
+++ b/src/app/api/models/site.ts
@@ -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);
+}
diff --git a/src/app/eeg-labels.ts b/src/app/eeg-labels.ts
new file mode 100644
index 0000000..5431bbd
--- /dev/null
+++ b/src/app/eeg-labels.ts
@@ -0,0 +1,99 @@
+import type { Figure } from './plot';
+
+/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
+export const METRIC_NAMES: Record = {
+ 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 = {
+ 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',
+};
+
+/** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */
+const AT: Record = {
+ 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} '
+ : '%{text}: %{customdata:.3f} ', // 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,
+ );
+}
diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts
index 504f7af..105cbc1 100644
--- a/src/app/gobernanza/figures.ts
+++ b/src/app/gobernanza/figures.ts
@@ -70,15 +70,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':
diff --git a/src/app/gobernanza/gobernanza.ts b/src/app/gobernanza/gobernanza.ts
index d6e21a3..12d6bc1 100644
--- a/src/app/gobernanza/gobernanza.ts
+++ b/src/app/gobernanza/gobernanza.ts
@@ -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';
@@ -93,13 +94,7 @@ export class Gobernanza {
params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
});
- protected readonly metricNames: Record = {
- 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('');
diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html
index 8461815..c3e81bb 100644
--- a/src/app/paciente/paciente.html
+++ b/src/app/paciente/paciente.html
@@ -202,8 +202,18 @@
@for (m of alterations(); track m.code) {
-
- {{ m.code }}
+
+
+
+ {{ metricNames[m.code] ?? m.code }}
+
+
{{ m.value | number: '1.0-3' }}
{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}
{{ m.median | number: '1.0-3' }}
@@ -213,6 +223,39 @@
}
+ Elija una alteración para ver sus zonas más afectadas.
+ @if (zoned(); as z) {
+
+ Zonas más afectadas
+
+ {{ 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)'
+ }}
+
+ @if (z.electrodes.length) {
+
+ }
+ @if (z.zones.length) {
+
+ @for (r of zoneOrder(); track r.site) {
+ = 2 || (r.z ?? 0) <= -2">
+ {{ zoneNames[r.site] ?? r.site }}
+ {{
+ r.z !== null && r.z !== undefined
+ ? 'z = ' + (r.z | number: '1.1-2')
+ : (r.value | number: '1.0-3')
+ }}
+
+ }
+
+ } @else if (!z.electrodes.length) {
+ Esta métrica no se mide por zona.
+ }
+
+ }
} @else {
Sin alteraciones: todas sus métricas están dentro de la norma por edad.
}
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss
index a95f781..6d406c9 100644
--- a/src/app/paciente/paciente.scss
+++ b/src/app/paciente/paciente.scss
@@ -56,3 +56,26 @@ mat-card-content {
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);
+}
diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts
index 87e20da..1459266 100644
--- a/src/app/paciente/paciente.ts
+++ b/src/app/paciente/paciente.ts
@@ -21,6 +21,7 @@ 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 { byDeviation, headMap, METRIC_NAMES, ZONE_NAMES } from '../eeg-labels';
import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading';
@@ -233,6 +234,21 @@ export class Paciente {
(this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined),
);
protected readonly shown = signal(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(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 zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
+ protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
protected readonly curve = computed(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
return {
From cbec0d431eaffc585ad1134de6bb7c0411f11614 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 17:16:25 -0600
Subject: [PATCH 11/32] Governance figures spec: scenarios are drawn by the
record
---
src/app/gobernanza/figures.spec.ts | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/src/app/gobernanza/figures.spec.ts b/src/app/gobernanza/figures.spec.ts
index 76bfc70..e8f3fa4 100644
--- a/src/app/gobernanza/figures.spec.ts
+++ b/src/app/gobernanza/figures.spec.ts
@@ -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,10 +30,10 @@ 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', () => {
From 6ea54d6e6d9909502a76f6fe83d868fc2dcf68ae Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 28 Nov 2026 17:24:29 -0600
Subject: [PATCH 12/32] Trazabilidad, Datos y definiciones and the risk lists
as the old app: declared panels, old labels and order; page tests against the
capture
---
e2e/pages.spec.ts | 56 +++++++
src/app/indicadores/figures.ts | 67 +++++++-
src/app/indicadores/indicadores.ts | 2 +-
src/app/indicadores/pages.ts | 200 +++++++++++++++++++++++
src/app/indicadores/tab-definiciones.ts | 138 ++++++++++++----
src/app/indicadores/tab-riesgos.html | 80 ++++++---
src/app/indicadores/tab-riesgos.scss | 14 ++
src/app/indicadores/tab-riesgos.ts | 28 +++-
src/app/indicadores/tab-seguimiento.html | 41 +++--
src/app/indicadores/tab-seguimiento.ts | 19 ++-
src/app/indicadores/tab-trazabilidad.ts | 129 ++++++++++-----
11 files changed, 654 insertions(+), 120 deletions(-)
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index 5c15f58..0528658 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -227,3 +227,59 @@ for (const domain of ['cacu', 'cama', 'tea']) {
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();
+ });
+}
diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts
index 068bd04..f6adafb 100644
--- a/src/app/indicadores/figures.ts
+++ b/src/app/indicadores/figures.ts
@@ -1,6 +1,6 @@
-import type { Figure } from '../plot';
-import type { Reading } from './measures';
-import type { Catalog, Category } from './pages';
+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';
@@ -415,3 +415,64 @@ export function ageShare(r: Reading, axis: string): Figure {
},
};
}
+
+/** 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'),
+ };
+}
diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts
index 032b54f..eb103a3 100644
--- a/src/app/indicadores/indicadores.ts
+++ b/src/app/indicadores/indicadores.ts
@@ -65,7 +65,7 @@ import { Loading } from '../loading';
}
-
+
diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts
index cf7636f..3875143 100644
--- a/src/app/indicadores/pages.ts
+++ b/src/app/indicadores/pages.ts
@@ -428,3 +428,203 @@ export const PAGES: Record = {
],
},
};
+
+/** One panel of Trazabilidad (tests/fixtures/reference//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 = {
+ 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],
+ ]),
+ ],
+ },
+};
diff --git a/src/app/indicadores/tab-definiciones.ts b/src/app/indicadores/tab-definiciones.ts
index a806cfd..07523bc 100644
--- a/src/app/indicadores/tab-definiciones.ts
+++ b/src/app/indicadores/tab-definiciones.ts
@@ -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 = {
};
const PERIODS: Record = { 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: `
-
-
-
- Indicador
- Clave
- Cálculo
- Mejora
- Periodos
- Estratos
-
-
-
- @for (m of measures(); track m.id) {
-
- {{ m.title }}
-
- {{ m.name }} v{{ m.version }}
-
- {{ scoring[code(m.scoring) ?? ''] }}
- {{ improvement[code(m.improvementNotation) ?? ''] ?? '—' }}
- {{ types(m) }}
- {{ strata(m) }}
-
+
+ Datos y definiciones de {{ domainName() }}
+
+ Información del dominio
+ @if (domain() === 'cacu') {
+
+ Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
+ espécimen fue insatisfactorio.
+
}
-
-
+ @if (available().length) {
+ Periodicidad disponible: {{ available().join(', ') }}.
+ } @else {
+ Periodicidad: pendiente de información.
+ }
+
+
+ Catálogo de indicadores
+ Consulta las gráficas disponibles y la periodicidad de cada indicador.
+ @for (m of measures(); track m.id) {
+
+ {{ m.title || 'Nombre pendiente de publicación' }}
+
+ @if (m.description) {
+
{{ m.description }}
+ }
+
Cálculo
+
+ {{ scoring[code(m.scoring) ?? ''] }}
+ @if (improvement[code(m.improvementNotation) ?? '']; as better) {
+ · {{ better }}
+ }
+
+
Tipos de periodo admitidos
+ @if (types(m).length) {
+
+ @for (t of types(m); track t) {
+ {{ t }}
+ }
+
+ } @else {
+
Pendiente de información.
+ }
+
Estratos
+
{{ strata(m) }}
+
+ Clave {{ m.name }} · versión {{ m.version }}
+
+
+
+ } @empty {
+
+ No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de
+ información.
+
+ }
+
+
+ `,
+ 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();
readonly measures = input.required();
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));
diff --git a/src/app/indicadores/tab-riesgos.html b/src/app/indicadores/tab-riesgos.html
index 6caf560..12223b6 100644
--- a/src/app/indicadores/tab-riesgos.html
+++ b/src/app/indicadores/tab-riesgos.html
@@ -10,7 +10,7 @@
/>
- Ventana
+ Ventana de meses
@for (m of [1, 3, 6, 12]; track m) {
{{ m }} {{ m === 1 ? 'mes' : 'meses' }}
@@ -18,7 +18,7 @@
- Estatus
+ Estatus de seguimiento
Todos
@for (s of statuses; track s) {
@@ -27,7 +27,7 @@
- Horizonte
+ Horizonte de la probabilidad
@for (h of [1, 2, 3, 4, 5]; track h) {
{{ h }} {{ h === 1 ? 'año' : 'años' }}
@@ -35,7 +35,7 @@
- Orden
+ Ordenar por
Estudio más reciente
Mayor riesgo de LIEAG+
@@ -43,7 +43,7 @@
- Por página
+ Registros por página
@for (n of [20, 50, 100]; track n) {
{{ n }}
@@ -53,22 +53,33 @@
@if (error()) {
- No se pudo leer la lista de seguimiento.
+
+ No se pudo leer la lista de seguimiento.
+ Reintentar seguimiento
+
+} @else if (!page() || loading()) {
+
+} @else if (applied()) {
+ Ventana consultada: {{ start() }} al {{ applied() }}.
}
+
+ Resultados disponibles por paciente
+
Paciente
Grupo de edad
- Estatus
+ Estatus de seguimiento
Última citología
- VPH
- Biopsia
- Riesgo LIEAG+ ({{ horizon() }} a)
- Riesgo cáncer ({{ horizon() }} a)
- Días toma → diagnóstico
+ Último resultado de VPH
+ Última biopsia
+ Probabilidad a LIEAG+ a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)
+ Probabilidad a cáncer a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)
+ Estudio más reciente
+ Días de toma a diagnóstico
@@ -86,7 +97,6 @@
{{ name(row.status) }}
@if (row.cytology; as c) {
- {{ c.date }} ·
{{
c.result
? name(c.result)
@@ -94,39 +104,58 @@
? 'Insatisfactoria'
: 'Pendiente'
}}
+ Fecha: {{ c.date }}
+ Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}
} @else {
- —
+ No disponible
}
@if (row.hpv; as h) {
- {{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }}
+ {{ h.positive ? 'Positivo' : 'Negativo' }}
+ Fecha: {{ h.date }}
+ Genotipo 16/18:
+ {{
+ h.types1618 === undefined
+ ? 'No disponible'
+ : h.types1618
+ ? 'Presente'
+ : 'No detectado'
+ }}
} @else {
- —
+ No disponible
}
@if (row.biopsy; as b) {
- {{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }}
+ {{ name(b.histology ?? '') || 'Sin grado' }}
+ Fecha: {{ b.date }}
} @else {
- —
+ No disponible
}
- {{ 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') + ' %'
+ }}
{{
- 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') + ' %'
}}
- {{ row.daysToDiagnosis ?? '—' }}
+ {{ latest(row) ?? 'No disponible' }}
+ {{ row.daysToDiagnosis ?? 'No disponible' }}
} @empty {
-
- {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
-
+ No hay registros para los filtros aplicados.
}
@@ -136,8 +165,7 @@
diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts
index 83156db..924b5c9 100644
--- a/src/app/paciente/paciente.ts
+++ b/src/app/paciente/paciente.ts
@@ -20,7 +20,7 @@ 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,
@@ -36,8 +36,11 @@ 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 ?? '';
}
From 7e50ff9b9035c8326c66d32b95621e90ab09230f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sun, 29 Nov 2026 06:58:38 -0600
Subject: [PATCH 19/32] OpenAPI spec names the configured promotion reports and
CaMa's history
---
openapi.json | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/openapi.json b/openapi.json
index 504cfd0..f21f897 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3645,7 +3645,7 @@
},
"/models/{domain}/{name}/versions/{version}/promote": {
"post": {
- "description": "The version risk batches come from from now on; refused (409) without its three\nreports: technical validation, interpretability and clinical validation.",
+ "description": "The version risk batches come from from now on; refused (409) without the reports\nthe site requires (PROMOTION_REPORTS; default: technical validation, interpretability\nand clinical validation).",
"operationId": "promote",
"parameters": [
{
@@ -3707,7 +3707,7 @@
},
"/models/{domain}/{name}/versions/{version}/reports/clinical_validation": {
"post": {
- "description": "The clinical team's validation of a version: the third report promotion needs.",
+ "description": "The clinical team's validation of a version: the third report, which promotion needs\nunless the site left it out of PROMOTION_REPORTS.",
"operationId": "add_clinical_validation",
"parameters": [
{
@@ -4773,7 +4773,7 @@
},
"/{domain}/fhir/Condition": {
"get": {
- "description": "What clinical notes diagnosed.",
+ "description": "What clinical notes diagnosed (CaMa: and each recurrence).",
"operationId": "search_condition",
"parameters": [
{
@@ -5610,7 +5610,7 @@
},
"/{domain}/fhir/Procedure": {
"get": {
- "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments).",
+ "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
"operationId": "search_procedure",
"parameters": [
{
From 52cca0a84c6ba099982ab442fda34f1876ef8453 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sun, 29 Nov 2026 07:13:57 -0600
Subject: [PATCH 20/32] Record history shows only ICD-10 codes beside a
diagnosis
---
src/app/paciente/paciente.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts
index 924b5c9..da001cd 100644
--- a/src/app/paciente/paciente.ts
+++ b/src/app/paciente/paciente.ts
@@ -94,7 +94,8 @@ export class Paciente {
date: c.recordedDate ?? '',
kind: 'Diagnóstico',
text: label(c.code),
- code: code(c.code),
+ // the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid)
+ code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code,
})),
...d.procedures.map((p) => ({
date: p.performedDateTime ?? '',
From 55c4e0b17385fc29f68637780ee4ac0ca5168984 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sun, 29 Nov 2026 12:39:07 -0600
Subject: [PATCH 21/32] OpenAPI client: model titles, run termination, Patient
name and identifier
---
openapi.json | 104 +++++++++++++++++++++++++-
src/app/api/fn/fhir/search-patient.ts | 12 +++
src/app/api/fn/models/models.ts | 5 +-
src/app/api/fn/runs/terminate-run.ts | 35 +++++++++
src/app/api/functions.ts | 2 +
src/app/api/models.ts | 1 +
src/app/api/models/model.ts | 7 ++
7 files changed, 163 insertions(+), 3 deletions(-)
create mode 100644 src/app/api/fn/runs/terminate-run.ts
create mode 100644 src/app/api/models/model.ts
diff --git a/openapi.json b/openapi.json
index f21f897..4f8abae 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1173,6 +1173,24 @@
"title": "Metric",
"type": "object"
},
+ "Model": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "title": {
+ "title": "Title",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "title"
+ ],
+ "title": "Model",
+ "type": "object"
+ },
"Option": {
"additionalProperties": false,
"properties": {
@@ -3398,6 +3416,7 @@
},
"/models/{domain}": {
"get": {
+ "description": "The domain's registered models, with their names on screen.",
"operationId": "models",
"parameters": [
{
@@ -3415,7 +3434,7 @@
"application/json": {
"schema": {
"items": {
- "type": "string"
+ "$ref": "#/components/schemas/Model"
},
"title": "Response Models",
"type": "array"
@@ -4263,6 +4282,53 @@
]
}
},
+ "/runs/{run_id}/terminate": {
+ "post": {
+ "description": "Stop a run (one started by mistake): Dagster cancels it.",
+ "operationId": "terminate_run",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "run_id",
+ "required": true,
+ "schema": {
+ "title": "Run Id",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "title": "Response Terminate Run",
+ "type": "object"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Terminate Run",
+ "tags": [
+ "runs"
+ ]
+ }
+ },
"/tea/eegs": {
"get": {
"operationId": "studies",
@@ -5443,6 +5509,42 @@
"title": "Follow-Up-Status"
}
},
+ {
+ "description": "each word starts a word of her name (case and accents ignored)",
+ "in": "query",
+ "name": "name",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "each word starts a word of her name (case and accents ignored)",
+ "title": "Name"
+ }
+ },
+ {
+ "description": "[system|]value: a CURP or record number (case ignored)",
+ "in": "query",
+ "name": "identifier",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "[system|]value: a CURP or record number (case ignored)",
+ "title": "Identifier"
+ }
+ },
{
"description": "-recent or -risk-",
"in": "query",
diff --git a/src/app/api/fn/fhir/search-patient.ts b/src/app/api/fn/fhir/search-patient.ts
index dd908e2..bf25154 100644
--- a/src/app/api/fn/fhir/search-patient.ts
+++ b/src/app/api/fn/fhir/search-patient.ts
@@ -24,6 +24,16 @@ export interface SearchPatient$Params {
'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null);
+/**
+ * each word starts a word of her name (case and accents ignored)
+ */
+ name?: (string | null);
+
+/**
+ * [system|]value: a CURP or record number (case ignored)
+ */
+ identifier?: (string | null);
+
/**
* -recent or -risk-
*/
@@ -56,6 +66,8 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {});
+ rb.query('name', params.name, {});
+ rb.query('identifier', params.identifier, {});
rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {});
diff --git a/src/app/api/fn/models/models.ts b/src/app/api/fn/models/models.ts
index 8489857..f64e379 100644
--- a/src/app/api/fn/models/models.ts
+++ b/src/app/api/fn/models/models.ts
@@ -8,12 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
+import { Model } from '../../models/model';
export interface Models$Params {
domain: Domain;
}
-export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable>> {
+export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable>> {
const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
@@ -24,7 +25,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
).pipe(
filter((r: any): r is HttpResponse => r instanceof HttpResponse),
map((r: HttpResponse) => {
- return r as StrictHttpResponse>;
+ return r as StrictHttpResponse>;
})
);
}
diff --git a/src/app/api/fn/runs/terminate-run.ts b/src/app/api/fn/runs/terminate-run.ts
new file mode 100644
index 0000000..c4c97b1
--- /dev/null
+++ b/src/app/api/fn/runs/terminate-run.ts
@@ -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 TerminateRun$Params {
+ run_id: string;
+}
+
+export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable> {
+ const rb = new RequestBuilder(rootUrl, terminateRun.PATH, 'post');
+ if (params) {
+ rb.path('run_id', params.run_id, {});
+ }
+
+ return http.request(
+ rb.build({ responseType: 'json', accept: 'application/json', context })
+ ).pipe(
+ filter((r: any): r is HttpResponse => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse<{
+ [key: string]: string;
+ }>;
+ })
+ );
+}
+
+terminateRun.PATH = '/runs/{run_id}/terminate';
diff --git a/src/app/api/functions.ts b/src/app/api/functions.ts
index 2e4b639..422bdb6 100644
--- a/src/app/api/functions.ts
+++ b/src/app/api/functions.ts
@@ -75,6 +75,8 @@ export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unr
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 { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
+export { terminateRun as terminateRun } from './fn/runs/terminate-run';
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';
diff --git a/src/app/api/models.ts b/src/app/api/models.ts
index 92dcda7..c0d0dac 100644
--- a/src/app/api/models.ts
+++ b/src/app/api/models.ts
@@ -24,6 +24,7 @@ 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 { Model } from './models/model';
export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
diff --git a/src/app/api/models/model.ts b/src/app/api/models/model.ts
new file mode 100644
index 0000000..fdc242a
--- /dev/null
+++ b/src/app/api/models/model.ts
@@ -0,0 +1,7 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+export interface Model {
+ name: string;
+ title: string;
+}
From 2216186d2604f1a0634ae88750357cf05494ebfb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sun, 29 Nov 2026 12:39:07 -0600
Subject: [PATCH 22/32] Patient lists have a search box; TEA alterations by
their Spanish names
---
src/app/indicadores/patient-search.spec.ts | 19 +++++
src/app/indicadores/patient-search.ts | 83 ++++++++++++++++++++++
src/app/indicadores/tab-riesgos-tea.html | 1 +
src/app/indicadores/tab-riesgos-tea.ts | 20 +++++-
src/app/indicadores/tab-riesgos.html | 1 +
src/app/indicadores/tab-riesgos.ts | 5 ++
src/app/indicadores/tab-seguimiento.html | 9 ++-
src/app/indicadores/tab-seguimiento.ts | 5 ++
8 files changed, 137 insertions(+), 6 deletions(-)
create mode 100644 src/app/indicadores/patient-search.spec.ts
create mode 100644 src/app/indicadores/patient-search.ts
diff --git a/src/app/indicadores/patient-search.spec.ts b/src/app/indicadores/patient-search.spec.ts
new file mode 100644
index 0000000..873ca12
--- /dev/null
+++ b/src/app/indicadores/patient-search.spec.ts
@@ -0,0 +1,19 @@
+import { matchesSearch, patientSearch } from './patient-search';
+
+describe('patient search', () => {
+ it('asks the API by identifier for one word with a digit, else by name', () => {
+ expect(patientSearch(' IARM800101MNLBVR09 ')).toEqual({ identifier: 'IARM800101MNLBVR09' });
+ expect(patientSearch('0451A')).toEqual({ identifier: '0451A' });
+ expect(patientSearch('martha ibarra')).toEqual({ name: 'martha ibarra' });
+ expect(patientSearch('')).toEqual({});
+ });
+
+ it('matches in the browser by word starts, case and accents ignored', () => {
+ const texts = ['IBARRA RIVERA MARTHA', 'd5a6a924-f2ad', 'N0183'];
+ expect(matchesSearch('már riv', texts)).toBe(true);
+ expect(matchesSearch('d5a6', texts)).toBe(true);
+ expect(matchesSearch('n0183', texts)).toBe(true);
+ expect(matchesSearch('arth', texts)).toBe(false);
+ expect(matchesSearch('', texts)).toBe(true);
+ });
+});
diff --git a/src/app/indicadores/patient-search.ts b/src/app/indicadores/patient-search.ts
new file mode 100644
index 0000000..ba73080
--- /dev/null
+++ b/src/app/indicadores/patient-search.ts
@@ -0,0 +1,83 @@
+import { Component, model, output, 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';
+
+/** A search box's text as FHIR Patient search parameters: one word with a digit is an
+ * identifier (a CURP or a record number); anything else is her name. */
+export function patientSearch(text: string): { name?: string; identifier?: string } {
+ const t = text.trim();
+ if (!t) return {};
+ return /\d/.test(t) && !/\s/.test(t) ? { identifier: t } : { name: t };
+}
+
+const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
+
+/** Whether a row matches the search in the browser (lists loaded whole): each word starts a
+ * word of one of its texts (a name, an identifier, the pseudonymous id). */
+export function matchesSearch(text: string, texts: (string | undefined)[]): boolean {
+ const words = fold(text).split(/\s+/).filter(Boolean);
+ if (!words.length) return true;
+ const known = texts.filter((t): t is string => !!t).map((t) => fold(t).split(/\s+/));
+ return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w))));
+}
+
+/** "Buscar paciente": applied on Enter or the search button, cleared with the cross. */
+@Component({
+ selector: 'app-patient-search',
+ imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
+ template: `
+
+ Buscar paciente
+
+ @if (value()) {
+
+ close
+
+ } @else {
+
+ search
+
+ }
+
+ `,
+ styles: `
+ .patient-search {
+ min-width: 18rem;
+ }
+ `,
+})
+export class PatientSearch {
+ /** The search as applied. */
+ readonly value = model('');
+ readonly searched = output();
+ protected readonly draft = signal('');
+ protected readonly hint = 'Nombre, CURP o expediente';
+
+ protected apply(): void {
+ const text = this.draft().trim();
+ this.value.set(text);
+ this.searched.emit(text);
+ }
+ protected clear(): void {
+ this.draft.set('');
+ this.apply();
+ }
+}
diff --git a/src/app/indicadores/tab-riesgos-tea.html b/src/app/indicadores/tab-riesgos-tea.html
index a034362..e9f24cb 100644
--- a/src/app/indicadores/tab-riesgos-tea.html
+++ b/src/app/indicadores/tab-riesgos-tea.html
@@ -1,6 +1,7 @@
Alteraciones de EEG relacionadas al TEA
+
Fecha de corte
diff --git a/src/app/indicadores/tab-riesgos-tea.ts b/src/app/indicadores/tab-riesgos-tea.ts
index 2cadbf0..a51de02 100644
--- a/src/app/indicadores/tab-riesgos-tea.ts
+++ b/src/app/indicadores/tab-riesgos-tea.ts
@@ -1,3 +1,4 @@
+import { METRIC_NAMES } from '../eeg-labels';
import { KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@@ -11,6 +12,7 @@ import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { ageLabel } from './figures';
import { name } from './measures';
+import { matchesSearch, PatientSearch } from './patient-search';
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */
export interface TeaRow {
@@ -67,14 +69,18 @@ const CASE: Record = {
not_confirmed: 'Sin TEA',
};
/** `theta_power:above` → "theta_power (aumentado)". */
-export const alteration = (a: string) =>
- a.replace(/:(above|below)$/, (_, s) => (s === 'above' ? ' (aumentado)' : ' (disminuido)'));
+export const alteration = (a: string) => {
+ const [metric, side] = a.split(':');
+ const shown = (METRIC_NAMES[metric] ?? metric).replace(/ \(.*\)$/, '');
+ return side ? `${shown} (${side === 'above' ? 'aumentado' : 'disminuido'})` : shown;
+};
/** "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: [
+ PatientSearch,
FormsModule,
KeyValuePipe,
Loading,
@@ -100,6 +106,8 @@ export class TabRiesgosTea {
protected readonly caseState = signal('');
protected readonly altered = signal('');
protected readonly size = signal(50);
+ /** "Buscar paciente": the pseudonymous id, a record number or a name. */
+ protected readonly search = signal('');
protected readonly pageIndex = signal(0);
/** The query as last asked for ("Consultar"). */
private readonly asked = signal({ cutoff: '', window: 3 });
@@ -141,7 +149,13 @@ export class TabRiesgosTea {
(!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())),
+ (!this.altered() || r.alterations.includes(this.altered())) &&
+ matchesSearch(this.search(), [
+ r.name,
+ r.patient.id,
+ ...(r.patient.name ?? []).map((n) => n.text),
+ ...(r.patient.identifier ?? []).map((i) => i.value),
+ ]),
);
});
protected readonly shown = computed(() =>
diff --git a/src/app/indicadores/tab-riesgos.html b/src/app/indicadores/tab-riesgos.html
index 191a17e..fda4a21 100644
--- a/src/app/indicadores/tab-riesgos.html
+++ b/src/app/indicadores/tab-riesgos.html
@@ -1,4 +1,5 @@