One shell with the current look: indicators, follow-up list and patient view from FHIR; /conectar canvas; /revision; Playwright page tests

This commit is contained in:
Roberto Treviño
2026-11-25 10:21:30 -06:00
parent 70b6d6c646
commit cd7bbaf11a
70 changed files with 5459 additions and 182 deletions
+4
View File
@@ -42,3 +42,7 @@ __screenshots__/
# System files
.DS_Store
Thumbs.db
# Playwright
/test-results/
/playwright-report/
+1
View File
@@ -0,0 +1 @@
src/app/api/
+14 -2
View File
@@ -29,14 +29,26 @@
"input": "public"
}
],
"styles": ["src/styles.scss"]
"styles": [
"@fontsource/roboto/300.css",
"@fontsource/roboto/400.css",
"@fontsource/roboto/500.css",
"@fontsource/roboto/700.css",
"@fontsource/rajdhani/500.css",
"@fontsource/rajdhani/600.css",
"material-symbols/outlined.css",
"src/styles.scss"
],
"allowedCommonJsDependencies": [
"plotly.js-cartesian-dist-min"
]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumWarning": "600kB",
"maximumError": "1MB"
},
{
+85
View File
@@ -0,0 +1,85 @@
import { expect, Page, test } from '@playwright/test';
/** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] {
const problems: string[] = [];
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
page.on('response', (r) => r.status() >= 400 && problems.push(`${r.status()} ${r.url()}`));
page.on('pageerror', (e) => problems.push(`page: ${e.message}`));
return problems;
}
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page,
}) => {
const problems = watch(page);
const report = page.waitForResponse(
(r) =>
r.url().includes('MeasureReport') &&
r.url().includes('measure=cacu-eu7') &&
!r.url().includes('%2C'),
);
await page.goto('/indicadores/cacu');
const eu7 = await (await report).json();
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));
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const bundle = await (await list).json();
const first = bundle.entry.find((e: any) => e.search.mode === 'match').resource.id;
const rows = page.locator('table.worklist tbody tr');
await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a.id')).toHaveText(first.slice(0, 10));
await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(`21–`)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a.id').click();
await expect(page.getByText('Historial médico')).toBeVisible();
await expect(page.getByText('Pruebas y resultados')).toBeVisible();
await expect(
page.locator('app-paciente table').nth(1).locator('tbody tr').first(),
).not.toContainText('Sin estudios');
await page.goto('/indicadores/cama');
await expect(page.getByText('todavía no tiene indicadores')).toBeVisible();
expect(problems).toEqual([]);
});
test('conectar: open the hospital pipeline, preview a source, run it to success', async ({
page,
}) => {
const problems = watch(page);
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.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
await page.getByRole('button', { name: 'Ejecutar' }).click();
await expect(page.getByText('SUCCESS')).toBeVisible({ timeout: 10 * 60_000 });
expect(problems).toEqual([]);
});
test('revision: what the messy site holds, and a decision through the page', async ({ page }) => {
const problems = watch(page);
await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click();
await page.locator('mat-form-field', { hasText: 'Canalización' }).click();
await page.getByRole('option', { name: 'site', exact: true }).click();
await expect(page.getByText(/Posibles pacientes duplicadas \([1-9]/)).toBeVisible();
await page.getByRole('button', { name: 'Distintas' }).first().click();
await expect(page.getByText('Decisión registrada.')).toBeVisible();
expect(problems).toEqual([]);
});
+940 -33
View File
File diff suppressed because it is too large Load Diff
+289
View File
@@ -16,6 +16,15 @@
"@angular/material": "^22.3.0",
"@angular/platform-browser": "^22.3.0",
"@angular/router": "^22.3.0",
"@fontsource/rajdhani": "5.3.0",
"@fontsource/roboto": "5.3.0",
"@ngx-formly/core": "11.2.0",
"@ngx-formly/material": "11.2.0",
"d3-drag": "3.0.0",
"d3-selection": "3.0.0",
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
@@ -24,6 +33,12 @@
"@angular/build": "^22.3.0",
"@angular/cli": "^22.3.0",
"@angular/compiler-cli": "^22.3.0",
"@playwright/test": "1.64.1",
"@types/d3-drag": "3.0.7",
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
"prettier": "^3.8.1",
@@ -1179,6 +1194,24 @@
}
}
},
"node_modules/@fontsource/rajdhani": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/rajdhani/-/rajdhani-5.3.0.tgz",
"integrity": "sha512-oBJgSIibWJvVBKseme1JczqPLoDHN97LHti4uh0LjfcJqQoVmnQQlRKIpEjTJV559rmVQ6qbVZZwKwk2wkBTtw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/roboto": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.3.0.tgz",
"integrity": "sha512-BapRJOWYP+LZ21zp+wBQjfpPYKRoxc4LspJ/RLuI+HSMBD5u/X4O+ESDrSvEqDSy0rAl7GwBJ+09mdc16cVQ1Q==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@harperfast/extended-iterable": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.5.tgz",
@@ -2343,6 +2376,32 @@
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3"
}
},
"node_modules/@ngx-formly/core": {
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/@ngx-formly/core/-/core-11.2.0.tgz",
"integrity": "sha512-Yj3P4UdSaS9AzpXR343GUN3s1BOPCGW/NugIbsvRT0w/JwAYD8SyNXxnzswKHqo3fQAFA6qDV5FUm25L0tVHeA==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"@angular/forms": ">=22.0.0",
"rxjs": "^6.5.3 || ^7.0.0"
}
},
"node_modules/@ngx-formly/material": {
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/@ngx-formly/material/-/material-11.2.0.tgz",
"integrity": "sha512-1oSGkyCXMrxfFdy/a7Ec7qq214FHHylCeKhw77kKMhuS286gc7dWXRe9bvZX2JNMtKUjXthInj8JP+WWwSA/4A==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"@angular/material": ">=22.0.0",
"@ngx-formly/core": "11.2.0"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.158.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
@@ -3044,6 +3103,22 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/@playwright/test": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
"integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.1.tgz",
@@ -3412,6 +3487,46 @@
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-drag": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
"integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
"license": "MIT",
"dependencies": {
"@types/d3-selection": "*"
}
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-selection": {
"version": "3.0.13",
"resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.13.tgz",
"integrity": "sha512-oXz0iHVpWOhurycj7P8KehdevbbwQfdOyYPd6u5TUcrk6ofXeQfY0e4Ow+0/35arZ24gs6ubpjJX0CuZHV5fdw==",
"license": "MIT"
},
"node_modules/@types/d3-zoom": {
"version": "3.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.9.tgz",
"integrity": "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==",
"license": "MIT",
"dependencies": {
"@types/d3-interpolate": "*",
"@types/d3-selection": "*"
}
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
@@ -3426,6 +3541,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/fhir": {
"version": "0.0.44",
"resolved": "https://registry.npmjs.org/@types/fhir/-/fhir-0.0.44.tgz",
"integrity": "sha512-RhqRUNcUFeQSbEK9cOEYQ98sfsUFFRCUKbgozHvryiUfEAPiXuhgk2wqYV3MoD1T1qHp0gztrHDywU68bN7KYQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/gensync": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@types/gensync/-/gensync-1.0.5.tgz",
@@ -3448,6 +3570,13 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/plotly.js": {
"version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
"integrity": "sha512-ftBxk2fB7BxxeMpT0IVEb/3HKpYTXO5nCdR5mGEz6gHpLd6GGRFxvDVoG1gpD/gBAgoN36KIyRflxCnOfWlskQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@vitejs/plugin-basic-ssl": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-basic-ssl/-/plugin-basic-ssl-2.3.0.tgz",
@@ -4043,6 +4172,111 @@
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/d3-color": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.1.tgz",
"integrity": "sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-dispatch": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.2.tgz",
"integrity": "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-drag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
"integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-selection": "3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.2.tgz",
"integrity": "sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-selection": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-transition": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.2.tgz",
"integrity": "sha512-RcjCsdFgyFoDB+QXLC5m60ZkTN0k9zH+ovoLlTdJnDS1AbfbcuowiM4pCKSTOclNibS4f4J4cbv2m7O7y8NTOQ==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3",
"d3-dispatch": "1 - 3",
"d3-ease": "1 - 3",
"d3-interpolate": "1 - 3",
"d3-timer": "1 - 3"
},
"engines": {
"node": ">=12"
},
"peerDependencies": {
"d3-selection": "2 - 3"
}
},
"node_modules/d3-zoom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
"integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-drag": "2 - 3",
"d3-interpolate": "1 - 3",
"d3-selection": "2 - 3",
"d3-transition": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/data-urls": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz",
@@ -5279,6 +5513,12 @@
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
"node_modules/material-symbols": {
"version": "0.48.3",
"resolved": "https://registry.npmjs.org/material-symbols/-/material-symbols-0.48.3.tgz",
"integrity": "sha512-usgMIp78cFFuxREnkNHRYBLAI152vJlnKqFCBiiwtNQfozlpIN2i00zrPBBkOxMLNTFaR7uPcJLWXlmMDOI+WA==",
"license": "Apache-2.0"
},
"node_modules/mimic-function": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
@@ -5413,6 +5653,26 @@
"rxjs": ">=6.5.0"
}
},
"node_modules/ngx-vflow": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/ngx-vflow/-/ngx-vflow-2.7.0.tgz",
"integrity": "sha512-9kyaa9QpXSvg/5Z8xrFRzah82LTORcH+ZgYCikyb1Fz4vlbbUaqb9eyFDvQHZBUXIbBOYFppxXmTcSm2P7eHlA==",
"license": "MIT",
"dependencies": {
"tslib": "^2.3.0"
},
"peerDependencies": {
"@angular/common": ">=19.2.17",
"@angular/core": ">=19.2.17",
"@types/d3-drag": "^3.0.7",
"@types/d3-selection": "^3.0.10",
"@types/d3-zoom": "^3.0.8",
"d3-drag": "^3.0.0",
"d3-selection": "^3.0.0",
"d3-zoom": "^3.0.0",
"rxjs": ">=6.0.0"
}
},
"node_modules/node-addon-api": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
@@ -5695,6 +5955,35 @@
"@napi-rs/nice": "^1.0.4"
}
},
"node_modules/playwright": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/plotly.js-cartesian-dist-min": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz",
+15
View File
@@ -20,6 +20,15 @@
"@angular/material": "^22.3.0",
"@angular/platform-browser": "^22.3.0",
"@angular/router": "^22.3.0",
"@fontsource/rajdhani": "5.3.0",
"@fontsource/roboto": "5.3.0",
"@ngx-formly/core": "11.2.0",
"@ngx-formly/material": "11.2.0",
"d3-drag": "3.0.0",
"d3-selection": "3.0.0",
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
@@ -28,6 +37,12 @@
"@angular/build": "^22.3.0",
"@angular/cli": "^22.3.0",
"@angular/compiler-cli": "^22.3.0",
"@playwright/test": "1.64.1",
"@types/d3-drag": "3.0.7",
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
"prettier": "^3.8.1",
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from '@playwright/test';
/** The pages against a running API (API_URL), served by the dev server with the same
* proxy the app uses in production (`/api`). Run by WebApi/tests/test_webapp.py, which
* starts the platform and loads the synthetic hospital first. */
export default defineConfig({
testDir: 'e2e',
timeout: 15 * 60_000,
expect: { timeout: 60_000 },
workers: 1,
reporter: 'list',
use: {
baseURL: 'http://127.0.0.1:4310',
viewport: { width: 1440, height: 1000 },
actionTimeout: 60_000, // a stuck step fails, not the whole run
},
webServer: {
command: 'npx ng serve --port 4310 --proxy-config proxy.e2e.mjs',
url: 'http://127.0.0.1:4310',
timeout: 180_000,
reuseExistingServer: false,
},
});
+2
View File
@@ -0,0 +1,2 @@
// `/api` to the API the e2e run started (API_URL).
export default { '/api': { target: process.env.API_URL, pathRewrite: { '^/api': '' } } };
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 717 B

+137
View File
@@ -0,0 +1,137 @@
// This file was generated by running 'ng generate @angular/material:theme-color'.
// Proceed with caution if making changes to this file.
@use 'sass:map';
@use '@angular/material' as mat;
// Note: Color palettes are generated from primary: #a8c243, tertiary: #5f9ea0
$_palettes: (
primary: (
0: #000000,
10: #171e00,
20: #2a3400,
25: #344000,
30: #3e4c00,
35: #495900,
40: #546500,
50: #6a8000,
60: #829a1c,
70: #9cb638,
80: #b7d251,
90: #d3ef6a,
95: #e1fd77,
98: #f5ffc6,
99: #faffe3,
100: #ffffff,
),
secondary: (
0: #000000,
10: #171e00,
20: #2b3407,
25: #363f12,
30: #414b1c,
35: #4d5727,
40: #596332,
50: #717c48,
60: #8b965f,
70: #a5b177,
80: #c1cc90,
90: #dde9aa,
95: #ebf7b7,
98: #f5ffc6,
99: #faffe3,
100: #ffffff,
),
tertiary: (
0: #000000,
10: #002021,
20: #003738,
25: #004345,
30: #004f51,
35: #145b5e,
40: #25686a,
50: #418183,
60: #5c9b9d,
70: #77b6b8,
80: #92d2d3,
90: #aeeef0,
95: #bcfcfe,
98: #e3ffff,
99: #f1ffff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1b1c14,
20: #303128,
25: #3b3c32,
30: #46483d,
35: #525348,
40: #5e5f54,
50: #77786c,
60: #919285,
70: #acac9f,
80: #c7c7b9,
90: #e4e3d5,
95: #f2f2e3,
98: #fbfaeb,
99: #fdfdf5,
100: #ffffff,
4: #0d0f07,
6: #13140c,
12: #1f2017,
17: #292b21,
22: #34362c,
24: #393a30,
87: #dbdbcd,
92: #e9e9da,
94: #efefe0,
96: #f5f4e6,
),
neutral-variant: (
0: #000000,
10: #1a1d0f,
20: #2f3222,
25: #3a3d2d,
30: #454837,
35: #515442,
40: #5d604e,
50: #767965,
60: #90927e,
70: #aaad98,
80: #c6c8b2,
90: #e2e4cd,
95: #f1f3db,
98: #f9fbe3,
99: #fcfdf1,
100: #ffffff,
),
error: (
0: #000000,
10: #410002,
20: #690005,
25: #7e0007,
30: #93000a,
35: #a80710,
40: #ba1a1a,
50: #de3730,
60: #ff5449,
70: #ff897d,
80: #ffb4ab,
90: #ffdad6,
95: #ffedea,
98: #fff8f7,
99: #fffbff,
100: #ffffff,
),
);
$_rest: (
secondary: map.get($_palettes, secondary),
neutral: map.get($_palettes, neutral),
neutral-variant: map.get($_palettes, neutral-variant),
error: map.get($_palettes, error),
);
$primary-palette: map.merge(map.get($_palettes, primary), $_rest);
$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);
@@ -9,28 +9,26 @@ import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Measures$Params {
export interface Metadata$Params {
domain: Domain;
}
export function measures(http: HttpClient, rootUrl: string, params: Measures$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
[key: string]: string;
}>>> {
const rb = new RequestBuilder(rootUrl, measures.PATH, 'get');
export function metadata(http: HttpClient, rootUrl: string, params: Metadata$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, metadata.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<{
[key: string]: string;
}>>;
return r as StrictHttpResponse<{
}>;
})
);
}
measures.PATH = '/{domain}/measures';
metadata.PATH = '/{domain}/fhir/metadata';
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ReadMeasure$Params {
domain: Domain;
id: string;
}
export function readMeasure(http: HttpClient, rootUrl: string, params: ReadMeasure$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, readMeasure.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
readMeasure.PATH = '/{domain}/fhir/Measure/{id}';
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ReadPatient$Params {
domain: Domain;
id: string;
}
export function readPatient(http: HttpClient, rootUrl: string, params: ReadPatient$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, readPatient.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
readPatient.PATH = '/{domain}/fhir/Patient/{id}';
+44
View File
@@ -0,0 +1,44 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchCondition$Params {
domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
export function searchCondition(http: HttpClient, rootUrl: string, params: SearchCondition$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchCondition.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchCondition.PATH = '/{domain}/fhir/Condition';
@@ -0,0 +1,44 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchDiagnosticReport$Params {
domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
export function searchDiagnosticReport(http: HttpClient, rootUrl: string, params: SearchDiagnosticReport$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchDiagnosticReport.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchDiagnosticReport.PATH = '/{domain}/fhir/DiagnosticReport';
@@ -0,0 +1,62 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchMeasureReport$Params {
domain: Domain;
/**
* the Measure's id or canonical URL
*/
measure: string;
/**
* semesters (2025-S1) or months (2025-03), comma-separated
*/
'reporting-period': string;
/**
* count only what was known by then
*/
'as-of'?: (string | null);
/**
* durations count to this day
*/
'event-cutoff'?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
export function searchMeasureReport(http: HttpClient, rootUrl: string, params: SearchMeasureReport$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchMeasureReport.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('measure', params.measure, {});
rb.query('reporting-period', params['reporting-period'], {});
rb.query('as-of', params['as-of'], {});
rb.query('event-cutoff', params['event-cutoff'], {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchMeasureReport.PATH = '/{domain}/fhir/MeasureReport';
+38
View File
@@ -0,0 +1,38 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchMeasure$Params {
domain: Domain;
'_count'?: (number | null);
'_offset'?: number;
}
export function searchMeasure(http: HttpClient, rootUrl: string, params: SearchMeasure$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchMeasure.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchMeasure.PATH = '/{domain}/fhir/Measure';
+44
View File
@@ -0,0 +1,44 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchObservation$Params {
domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
export function searchObservation(http: HttpClient, rootUrl: string, params: SearchObservation$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchObservation.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchObservation.PATH = '/{domain}/fhir/Observation';
+78
View File
@@ -0,0 +1,78 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchPatient$Params {
domain: Domain;
'_id'?: (string | null);
/**
* months: whoever had a cytology sampled within them up to the cut-off
*/
'follow-up-window'?: (number | null);
/**
* default: the last day with data
*/
'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null);
/**
* one of ('-recent', '-risk-cin2', '-risk-cancer'); the list only
*/
'_sort'?: string;
/**
* years
*/
'risk-horizon'?: number;
/**
* any of ('DiagnosticReport:subject', 'RiskAssessment:subject', 'Observation:subject')
*/
'_revinclude'?: Array<string>;
/**
* DiagnosticReport:result
*/
'_include:iterate'?: Array<string>;
'_count'?: (number | null);
'_offset'?: number;
}
export function searchPatient(http: HttpClient, rootUrl: string, params: SearchPatient$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchPatient.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('_id', params['_id'], {});
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('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {});
rb.query('_include:iterate', params['_include:iterate'], {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchPatient.PATH = '/{domain}/fhir/Patient';
+44
View File
@@ -0,0 +1,44 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchProcedure$Params {
domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
export function searchProcedure(http: HttpClient, rootUrl: string, params: SearchProcedure$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchProcedure.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchProcedure.PATH = '/{domain}/fhir/Procedure';
@@ -0,0 +1,44 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface SearchRiskAssessment$Params {
domain: Domain;
/**
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
export function searchRiskAssessment(http: HttpClient, rootUrl: string, params: SearchRiskAssessment$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, searchRiskAssessment.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
searchRiskAssessment.PATH = '/{domain}/fhir/RiskAssessment';
-56
View File
@@ -1,56 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Measure$Params {
domain: Domain;
measure_id: string;
/**
* comma-separated semesters (2025-S1) or months (2025-03)
*/
periods: string;
/**
* count only what was known by then
*/
as_of?: (string | null);
/**
* durations count to this day
*/
event_cutoff?: (string | null);
}
export function measure(http: HttpClient, rootUrl: string, params: Measure$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: any;
}>> {
const rb = new RequestBuilder(rootUrl, measure.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('measure_id', params.measure_id, {});
rb.query('periods', params.periods, {});
rb.query('as_of', params.as_of, {});
rb.query('event_cutoff', params.event_cutoff, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: any;
}>;
})
);
}
measure.PATH = '/{domain}/measures/{measure_id}';
+22 -4
View File
@@ -49,7 +49,25 @@ export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status';
export type { Measures$Params as Measures$Params } from './fn/measures/measures';
export { measures as measures } from './fn/measures/measures';
export type { Measure$Params as Measure$Params } from './fn/measures/measure';
export { measure as measure } from './fn/measures/measure';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
export { searchCondition as searchCondition } from './fn/fhir/search-condition';
export type { SearchDiagnosticReport$Params as SearchDiagnosticReport$Params } from './fn/fhir/search-diagnostic-report';
export { searchDiagnosticReport as searchDiagnosticReport } from './fn/fhir/search-diagnostic-report';
export type { SearchMeasure$Params as SearchMeasure$Params } from './fn/fhir/search-measure';
export { searchMeasure as searchMeasure } from './fn/fhir/search-measure';
export type { ReadMeasure$Params as ReadMeasure$Params } from './fn/fhir/read-measure';
export { readMeasure as readMeasure } from './fn/fhir/read-measure';
export type { SearchMeasureReport$Params as SearchMeasureReport$Params } from './fn/fhir/search-measure-report';
export { searchMeasureReport as searchMeasureReport } from './fn/fhir/search-measure-report';
export type { SearchObservation$Params as SearchObservation$Params } from './fn/fhir/search-observation';
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/search-patient';
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
export { readPatient as readPatient } from './fn/fhir/read-patient';
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
export { searchRiskAssessment as searchRiskAssessment } from './fn/fhir/search-risk-assessment';
export type { Metadata$Params as Metadata$Params } from './fn/fhir/metadata';
export { metadata as metadata } from './fn/fhir/metadata';
+1
View File
@@ -13,6 +13,7 @@ export type { Link } from './models/link';
export type { Map } from './models/map';
export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline';
export type { Position } from './models/position';
export type { Read } from './models/read';
export type { Rejection } from './models/rejection';
export type { Route } from './models/route';
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* Platform fields read from text, each kept with the text it was read from.
@@ -25,6 +26,7 @@ export interface Extract {
patterns?: {
[key: string]: string;
};
position?: (Position | null);
values?: {
[key: string]: {
[key: string]: string;
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* Two inputs side by side where their columns match.
@@ -12,4 +13,5 @@ export interface Join {
kind?: 'join';
label?: string;
on: Array<[string, string]>;
position?: (Position | null);
}
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* Identity rows from every input, grouped into persons (Splink).
@@ -16,6 +17,7 @@ export interface Link {
inputs?: Array<string>;
kind?: 'link';
label?: string;
position?: (Position | null);
review?: number;
rules?: Array<string>;
}
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* Columns to platform fields, with the site's codes and date formats.
@@ -16,6 +17,7 @@ export interface Map {
inputs?: Array<string>;
kind?: 'map';
label?: string;
position?: (Position | null);
values?: {
[key: string]: {
[key: string]: string;
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Position {
x: number;
y: number;
}
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
@@ -11,4 +12,5 @@ export interface Read {
inputs?: Array<string>;
kind?: 'read';
label?: string;
position?: (Position | null);
}
+2
View File
@@ -2,6 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Condition } from '../models/condition';
import { Position } from '../models/position';
/**
* Only the rows where every condition holds (e.g. reports titled "Citología").
@@ -11,5 +12,6 @@ export interface Route {
inputs?: Array<string>;
kind?: 'route';
label?: string;
position?: (Position | null);
when: Array<Condition>;
}
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* One table, file set or API resource, copied as it is (dlt). Merged on the source's
@@ -14,6 +15,7 @@ export interface Source {
inputs?: Array<string>;
kind?: 'source';
label?: string;
position?: (Position | null);
primary_key?: Array<string>;
resource?: (string | null);
source: string;
+2
View File
@@ -1,6 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Position } from '../models/position';
/**
* Rows of platform fields into one platform entity, each row given its person by the
@@ -12,4 +13,5 @@ export interface Target {
inputs?: Array<string>;
kind?: 'target';
label?: string;
position?: (Position | null);
}
+13 -3
View File
@@ -1,14 +1,24 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import {
ApplicationConfig,
inject,
provideAppInitializer,
provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { MatIconRegistry } from '@angular/material/icon';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideApiConfiguration } from './api/api-configuration';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(),
provideApiConfiguration('/api'),
// Icons are the Material Symbols font served with the app.
provideAppInitializer(() => {
inject(MatIconRegistry).setDefaultFontSetClass('material-symbols-outlined');
}),
],
};
+38 -18
View File
@@ -1,19 +1,39 @@
<mat-toolbar class="bar">
<span class="brand">ISSSTELEON</span>
<mat-button-toggle-group
aria-label="Dominio"
[value]="domain()"
(change)="domain.set($event.value)"
>
@for (d of domains.value() ?? []; track d) {
<mat-button-toggle [value]="d">{{ labels[d] }}</mat-button-toggle>
<div class="shell">
<header class="header">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (domain(); as current) {
<span class="title">Plataforma de Indicadores</span>
<button
mat-flat-button
class="domain"
[matMenuTriggerFor]="menu"
[disabled]="!others().length"
>
{{ labels[current] }}
<mat-icon iconPositionEnd>expand_more</mat-icon>
</button>
<mat-menu #menu="matMenu">
@for (d of others(); track d) {
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a>
}
</mat-menu>
} @else {
<span class="title"></span>
}
</mat-button-toggle-group>
<span class="spacer"></span>
<span class="status" [class.down]="health.error()">
API {{ health.value()?.['status'] ?? (health.error() ? 'sin conexión' : '…') }}
</span>
</mat-toolbar>
<main>
<router-outlet />
</main>
<nav class="sections" aria-label="Secciones">
<a routerLink="/indicadores/cacu" routerLinkActive="active">Indicadores</a>
<a routerLink="/conectar" routerLinkActive="active">Conectar</a>
<a routerLink="/revision" routerLinkActive="active">Revisión</a>
</nav>
</header>
<main class="main">
<router-outlet />
</main>
<footer class="footer">
<img src="assets/branding/isssteleon-logo.png" alt="" />
</footer>
</div>
+14 -1
View File
@@ -1,3 +1,16 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'indicadores/cacu' },
{
path: 'indicadores/:domain',
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
},
{
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: '**', redirectTo: 'indicadores/cacu' },
];
+66 -11
View File
@@ -1,19 +1,74 @@
.bar {
gap: 16px;
.shell {
display: flex;
flex-direction: column;
min-height: 100dvh;
}
.brand {
.header {
align-items: center;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
display: flex;
gap: var(--space-4);
min-height: var(--header-height);
padding: 0 clamp(16px, 3.2vw, 48px);
}
.brand img {
display: block;
width: clamp(132px, 16vw, 200px);
}
.title {
flex: 1;
font-size: 1.25rem;
font-weight: 500;
}
.spacer {
.domain {
--mat-button-filled-container-color: var(--color-primary);
--mat-button-filled-label-text-color: var(--color-text);
font-weight: 700;
}
.sections {
display: flex;
gap: var(--space-4);
}
.sections a {
color: var(--color-text-secondary);
font-size: 15px;
font-weight: 600;
text-decoration: none;
}
.sections a.active {
color: var(--color-primary);
}
.main {
display: flex;
flex: 1;
flex-direction: column;
min-height: 0;
}
.status {
font-size: 14px;
opacity: 0.8;
.footer {
align-items: center;
background: var(--color-text-secondary);
display: flex;
justify-content: center;
min-height: 86px;
}
.status.down {
color: var(--mat-sys-error);
.footer img {
filter: brightness(0) invert(1);
width: clamp(155px, 15vw, 185px);
}
main {
padding: 16px;
@media (max-width: 720px) {
.title {
display: none;
}
}
+2 -1
View File
@@ -1,13 +1,14 @@
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { App } from './app';
describe('App', () => {
it('creates the shell', async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideHttpClient(), provideHttpClientTesting()],
providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])],
}).compileComponents();
expect(TestBed.createComponent(App).componentInstance).toBeTruthy();
});
+37 -10
View File
@@ -1,24 +1,51 @@
import { Component, inject, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatToolbarModule } from '@angular/material/toolbar';
import { RouterOutlet } from '@angular/router';
import { Component, computed, inject, resource } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { NavigationEnd, Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
import { Api } from './api/api';
import { domains } from './api/fn/operations/domains';
import { health } from './api/fn/operations/health';
import { Domain } from './api/models/domain';
const LABELS: Record<Domain, string> = { cacu: 'CaCu', cama: 'CaMa', tea: 'TEA' };
export const DOMAINS: Record<Domain, string> = {
cacu: 'Cáncer cervicouterino',
cama: 'Cáncer de mama',
tea: 'TEA',
};
/** The shell: header (logo, the domain's title and switcher, or the section), page, footer. */
@Component({
selector: 'app-root',
imports: [RouterOutlet, MatToolbarModule, MatButtonToggleModule],
imports: [
RouterOutlet,
RouterLink,
RouterLinkActive,
MatButtonModule,
MatIconModule,
MatMenuModule,
],
templateUrl: './app.html',
styleUrl: './app.scss',
})
export class App {
private readonly api = inject(Api);
protected readonly labels = LABELS;
protected readonly domain = signal<Domain>('cacu');
private readonly router = inject(Router);
protected readonly labels = DOMAINS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
protected readonly health = resource({ loader: () => this.api.invoke(health) });
private readonly url = toSignal(
this.router.events.pipe(
filter((e) => e instanceof NavigationEnd),
map((e) => (e as NavigationEnd).urlAfterRedirects),
),
{ initialValue: '' },
);
/** The domain of an indicator page, if this is one. */
protected readonly domain = computed(
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined,
);
protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain()),
);
}
+112
View File
@@ -0,0 +1,112 @@
<div class="workspace">
<aside class="pipelines">
<h2>Canalizaciones</h2>
<mat-nav-list dense>
@for (p of list.value() ?? []; track p['pipeline_id']) {
<a
mat-list-item
[activated]="p['pipeline_id'] === pipelineId()"
(click)="open(p['pipeline_id'])"
>
<span matListItemTitle>{{ p['pipeline_id'] }}</span>
<span matListItemLine>v{{ p['version'] }}</span>
</a>
}
</mat-nav-list>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="new">
<mat-label>Nueva canalización</mat-label>
<input matInput #name (keydown.enter)="create(name.value)" placeholder="hospital_norte" />
</mat-form-field>
</aside>
<section class="canvas-area">
<div class="toolbar">
<span class="title"
>{{ pipelineId() ?? 'Elija o cree una canalización' }}
@if (version()) {
<span class="muted"> · v{{ version() }}</span>
}
</span>
@if (pipelineId()) {
@for (k of kinds; track k[0]) {
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
}
<span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button>
<button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button>
}
</div>
@if (message()) {
<p class="message" role="status">{{ message() }}</p>
}
@if (run(); as r) {
<p class="run" role="status">
Ejecución <code>{{ r.id.slice(0, 8) }}</code>: <strong>{{ r.status }}</strong> ·
<a [href]="dagster()" target="_blank" rel="noopener">ver en Dagster</a>
</p>
}
<div class="canvas">
@if (pipelineId()) {
<vflow
[nodes]="nodes()"
[edges]="edges()"
[connection]="{ curve: 'smooth-step', marker: { type: 'arrow-closed' } }"
(connect)="connect($event)"
(nodesChanges)="changed($event)"
view="auto"
background="#f7f8f6"
/>
}
</div>
</section>
@if (doc(); as d) {
<aside class="panel">
<div class="panel-head">
<h2>
{{ kindLabel(d.kind) }} · <span class="muted">{{ d.id }}</span>
</h2>
<button mat-icon-button (click)="remove(d.id)" aria-label="Quitar nodo">
<mat-icon>delete</mat-icon>
</button>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) {
<div class="inputs">
Entradas:
@for (i of d.inputs; track i) {
<button mat-stroked-button class="chip" (click)="disconnect(d.id, i)">
{{ i }} <mat-icon>close</mat-icon>
</button>
}
</div>
} @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
<button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) {
<div class="preview">
<table mat-table [dataSource]="rows">
@for (c of columns(); track c) {
<ng-container [matColumnDef]="c">
<th mat-header-cell *matHeaderCellDef>{{ c }}</th>
<td mat-cell *matCellDef="let row">{{ cell(row[c]) }}</td>
</ng-container>
}
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
<tr mat-row *matRowDef="let row; columns: columns()"></tr>
</table>
</div>
}
</aside>
}
</div>
+111
View File
@@ -0,0 +1,111 @@
:host {
display: block;
flex: 1;
}
.workspace {
display: grid;
grid-template-columns: 220px 1fr auto;
height: calc(100dvh - var(--header-height) - 86px);
min-height: 560px;
}
.pipelines,
.panel {
background: var(--color-surface);
border-right: 1px solid var(--color-border);
overflow-y: auto;
padding: var(--space-3);
}
.panel {
border-left: 1px solid var(--color-border);
border-right: 0;
width: 380px;
}
h2 {
font-size: 1rem;
font-weight: 500;
margin: 0 0 var(--space-2);
}
.new,
.full {
width: 100%;
}
.canvas-area {
display: flex;
flex-direction: column;
min-width: 0;
}
.toolbar {
align-items: center;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
}
.title {
font-weight: 500;
margin-right: var(--space-3);
}
.spacer {
flex: 1;
}
.message,
.run {
margin: var(--space-2) var(--space-3) 0;
}
.canvas {
flex: 1;
min-height: 400px;
}
.panel-head {
align-items: center;
display: flex;
justify-content: space-between;
}
.inputs {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-1);
margin: var(--space-2) 0;
}
.preview {
margin-top: var(--space-3);
max-height: 360px;
overflow: auto;
}
.preview td,
.preview th {
font-size: 12px;
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (max-width: 900px) {
.workspace {
grid-template-columns: 1fr;
height: auto;
}
.panel {
width: auto;
}
}
+344
View File
@@ -0,0 +1,344 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } 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 { MatListModule } from '@angular/material/list';
import { MatTableModule } from '@angular/material/table';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material';
import { Connection, NodeChange, Vflow } from 'ngx-vflow';
import { Api } from '../api/api';
import { nodeRows } from '../api/fn/ingest/node-rows';
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
import { pipelines } from '../api/fn/ingest/pipelines';
import { savePipeline } from '../api/fn/ingest/save-pipeline';
import { schema } from '../api/fn/ingest/schema';
import { sourcePreview } from '../api/fn/ingest/source-preview';
import { startRun } from '../api/fn/ingest/start-run';
import { runStatus } from '../api/fn/runs/run-status';
import type { Pipeline } from '../api/models/pipeline';
import type { Source } from '../api/models/source';
import { FORMLY_TYPES, nodeSchema } from './schema-form';
type Doc = Pipeline['nodes'][number];
type Kind = NonNullable<Doc['kind']>;
interface CanvasNode {
id: string;
type: 'default';
point: WritableSignal<{ x: number; y: number }>;
text: WritableSignal<string>;
width: WritableSignal<number>;
height: WritableSignal<number>;
}
function canvasNode(id: string, point: { x: number; y: number }, label: string): CanvasNode {
return {
id,
type: 'default',
point: signal(point),
text: signal(label),
width: signal(190),
height: signal(56),
};
}
export const KINDS: Record<Kind, string> = {
source: 'Fuente',
read: 'Leer',
route: 'Filtrar',
map: 'Mapear',
extract: 'Extraer',
join: 'Unir',
link: 'Vincular',
target: 'Destino',
};
const ID = /^[a-z][a-z0-9_]*$/;
/** /conectar: an operator draws a site's pipeline on a canvas (nodes and the edges between
* them), fills each node's form, previews what it gives, saves a version and runs it. */
@Component({
selector: 'app-conectar',
imports: [
FormsModule,
ReactiveFormsModule,
FormlyForm,
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatListModule,
MatTableModule,
Vflow,
],
// Forms are this page's only: Formly loads with it, not with the app.
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
templateUrl: './conectar.html',
styleUrl: './conectar.scss',
})
export class Conectar {
private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
protected readonly pipelineId = signal<string | undefined>(undefined);
protected readonly version = signal<number | undefined>(undefined);
/** The drawn pipeline: node configs (positions live on the canvas nodes). */
protected readonly docs = signal<Doc[]>([]);
protected readonly nodes = signal<CanvasNode[]>([]);
protected readonly edges = computed(() =>
this.docs().flatMap((d) =>
(d.inputs ?? []).map((i) => ({ id: `${i}->${d.id}`, source: i, target: d.id })),
),
);
protected readonly selected = signal<string | undefined>(undefined);
protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected()));
protected readonly message = signal('');
protected readonly run = signal<{ id: string; status: string } | undefined>(undefined);
protected readonly running = computed(() => {
const run = this.run();
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
});
protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */
protected readonly fields = computed<FormlyFieldConfig[]>(() => {
const kind = this.doc()?.kind;
const pipeline = this.schema.value()?.['pipeline'];
if (!kind || !pipeline) return [];
return [this.jsonschema.toFieldConfig(nodeSchema(pipeline as never, kind))];
});
protected readonly preview = signal<Record<string, unknown>[] | undefined>(undefined);
protected readonly columns = computed(() => Object.keys(this.preview()?.[0] ?? {}));
async open(id: string): Promise<void> {
const saved = await this.api.invoke(getPipeline, { pipeline_id: id });
this.pipelineId.set(id);
this.version.set(saved.version);
this.load(saved.pipeline.nodes);
this.message.set('');
}
protected create(id: string): void {
if (!ID.test(id)) {
this.message.set('El nombre va en minúsculas, sin espacios (a-z, 0-9, _).');
return;
}
this.pipelineId.set(id);
this.version.set(undefined);
this.load([]);
this.message.set('');
}
private load(docs: Doc[]): void {
this.docs.set(docs);
const depth = depths(docs);
const row = new Map<number, number>();
this.nodes.set(
docs.map((d) => {
const level = depth.get(d.id) ?? 0;
const n = row.get(level) ?? 0;
row.set(level, n + 1);
const point = d.position ?? { x: 40 + level * 260, y: 40 + n * 90 };
return canvasNode(d.id, point, text(d));
}),
);
this.select(undefined);
}
protected add(kind: Kind): 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;
this.docs.update((ds) => [...ds, doc]);
this.nodes.update((ns) => [
...ns,
canvasNode(id, { x: 60, y: 60 + ns.length * 30 }, text(doc)),
]);
this.select(id);
}
protected remove(id: string): void {
this.docs.update((ds) =>
ds
.filter((d) => d.id !== id)
.map((d) => ({ ...d, inputs: (d.inputs ?? []).filter((i) => i !== id) })),
);
this.nodes.update((ns) => ns.filter((n) => n.id !== id));
this.select(undefined);
}
protected connect({ source, target }: Connection): void {
this.update(target, (d) => ({ ...d, inputs: [...new Set([...(d.inputs ?? []), source])] }));
}
protected disconnect(target: string, source: string): void {
this.update(target, (d) => ({ ...d, inputs: (d.inputs ?? []).filter((i) => i !== source) }));
}
protected changed(changes: NodeChange[]): void {
for (const c of changes) {
if (c.type === 'select' && c.selected) this.select(c.id);
}
}
protected select(id: string | undefined): void {
this.selected.set(id);
const doc = (this.docs().find((d) => d.id === id) ?? {}) as Record<string, unknown>;
this.model = Object.fromEntries(
Object.entries(structuredClone(doc)).filter(
([k]) => !['id', 'kind', 'inputs', 'position'].includes(k),
),
);
this.form = new UntypedFormGroup({});
this.preview.set(undefined);
}
/** The form's values into the selected node. */
protected edited(model: Record<string, unknown>): void {
const id = this.selected();
if (!id) return;
const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
);
this.update(
id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
);
}
protected rename(to: string): void {
const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
this.docs.update((ds) =>
ds.map((d) => ({
...d,
id: d.id === from ? to : d.id,
inputs: (d.inputs ?? []).map((i) => (i === from ? to : i)),
})),
);
this.nodes.update((ns) => ns.map((n) => (n.id === from ? { ...n, id: to } : n)));
this.selected.set(to);
}
private update(id: string, change: (d: Doc) => Doc): void {
this.docs.update((ds) => ds.map((d) => (d.id === id ? change(d) : d)));
const doc = this.docs().find((d) => d.id === id);
if (doc)
this.nodes()
.find((n) => n.id === id)
?.text.set(text(doc));
}
/** The drawn pipeline, each node where it sits on the canvas. */
private drawn(): Pipeline {
const at = new Map(this.nodes().map((n) => [n.id, n.point()]));
return { nodes: this.docs().map((d) => ({ ...d, position: at.get(d.id) })) } as Pipeline;
}
protected async save(): Promise<boolean> {
const id = this.pipelineId();
if (!id) return false;
try {
const { version } = await this.api.invoke(savePipeline, {
pipeline_id: id,
body: this.drawn(),
});
this.version.set(version);
this.message.set(`Versión ${version} guardada.`);
this.list.reload();
return true;
} catch (e) {
this.message.set(problem(e));
return false;
}
}
/** Saves, starts the `ingest` job and follows it to its end. */
protected async start(): Promise<void> {
const id = this.pipelineId();
if (!id || !(await this.save())) return;
try {
const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
this.run.set({ id: run_id, status: 'STARTING' });
while (this.running()) {
await new Promise((r) => setTimeout(r, 2000));
this.run.set({
id: run_id,
status: (await this.api.invoke(runStatus, { run_id }))['status'],
});
}
} catch (e) {
this.message.set(problem(e));
}
}
/** What the node gives: a source's first rows, or what any other node gave in the last run. */
protected async show(): Promise<void> {
const doc = this.doc();
const id = this.pipelineId();
if (!doc || !id) return;
try {
const rows =
doc.kind === 'source'
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.');
} catch (e) {
this.message.set(problem(e));
}
}
/** The run in Dagster's own UI (its port beside this app's). */
protected readonly dagster = computed(() => {
const run = this.run();
return run ? `${location.protocol}//${location.hostname}:5712/runs/${run.id}` : '';
});
protected kindLabel(kind: Doc['kind']): string {
return KINDS[kind ?? 'source'];
}
protected cell(value: unknown): string {
return typeof value === 'object' && value !== null
? JSON.stringify(value)
: String(value ?? '');
}
}
function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`;
}
/** Each node's distance from the sources: its column when it has no saved position. */
function depths(docs: Doc[]): Map<string, number> {
const by = new Map(docs.map((d) => [d.id, d]));
const found = new Map<string, number>();
const depth = (id: string, seen: Set<string>): number => {
if (found.has(id)) return found.get(id)!;
if (seen.has(id)) return 0;
seen.add(id);
const inputs = by.get(id)?.inputs ?? [];
const d = inputs.length ? 1 + Math.max(...inputs.map((i) => depth(i, seen))) : 0;
found.set(id, d);
return d;
};
docs.forEach((d) => depth(d.id, new Set()));
return found;
}
function problem(e: unknown): string {
if (e instanceof HttpErrorResponse) {
const detail = e.error?.detail;
return typeof detail === 'string' ? detail : JSON.stringify(detail ?? e.message);
}
return String(e);
}
+40
View File
@@ -0,0 +1,40 @@
import { nodeSchema } from './schema-form';
const PIPELINE = {
$defs: {
Position: { type: 'object', properties: { x: { type: 'number' } } },
Condition: { type: 'object', properties: { column: { type: 'string' } } },
Route: {
type: 'object',
additionalProperties: false,
required: ['id', 'when'],
properties: {
id: { type: 'string' },
kind: { const: 'route' },
inputs: { type: 'array' },
position: { anyOf: [{ $ref: '#/$defs/Position' }, { type: 'null' }] },
when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
},
},
},
} as never;
describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']);
expect(schema.required).toEqual(['when']);
});
it('inlines references and drops null from optional values', () => {
expect(schema.properties.when.items.properties.column.type).toBe('string');
expect(schema.properties.resource.type).toBe('string');
});
it('edits maps as JSON', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json');
});
});
+166
View File
@@ -0,0 +1,166 @@
import { Component } from '@angular/core';
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 { ReactiveFormsModule } from '@angular/forms';
import {
ConfigOption,
FieldArrayType,
FieldType,
FormlyField,
FormlyFieldConfig,
} from '@ngx-formly/core';
import type { JSONSchema7 } from 'json-schema';
type Schema = JSONSchema7 & { $defs?: Record<string, Schema>; prefixItems?: unknown };
/** The canvas edits these itself; the form leaves them out. */
const CANVAS_FIELDS = ['id', 'kind', 'inputs', 'position'];
/** A node kind's form schema from the pipeline's JSON Schema (pydantic's): `$ref`s inlined,
* optional values as their type, and maps or tuples (which forms don't draw) as JSON. */
export function nodeSchema(pipeline: Schema, kind: string): Schema {
const defs = pipeline.$defs ?? {};
const name = Object.keys(defs).find(
(k) => (defs[k].properties?.['kind'] as Schema | undefined)?.const === kind,
)!;
const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field];
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f));
delete node.additionalProperties;
return simplify(node, defs);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) {
const { $ref, ...rest } = schema;
return simplify({ ...structuredClone(defs[$ref.split('/').pop()!]), ...rest }, defs);
}
const options = schema.anyOf as Schema[] | undefined;
if (options) {
const kept = options.filter((o) => o.type !== 'null');
if (kept.length === 1) {
const { anyOf, ...rest } = schema;
return simplify({ ...kept[0], ...rest }, defs);
}
}
const isMap = schema.type === 'object' && !schema.properties;
const isTuple =
schema.type === 'array' &&
(schema.prefixItems || (schema.items as Schema | undefined)?.prefixItems);
if (isMap || isTuple || (!schema.type && !schema.enum && !schema.const)) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'json' } },
} as Schema;
}
const out: Schema = { ...schema };
if (schema.properties) {
out.properties = Object.fromEntries(
Object.entries(schema.properties).map(([k, v]) => [k, simplify(v as Schema, defs)]),
);
}
if (schema.items && !Array.isArray(schema.items))
out.items = simplify(schema.items as Schema, defs);
return out;
}
/** An object's fields, one after another. */
@Component({
selector: 'app-formly-object',
imports: [FormlyField],
template: `
@if (props.label) {
<div class="legend">{{ props.label }}</div>
}
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (f of field.fieldGroup; track $index) {
<formly-field [field]="f" />
}
`,
styles:
'.legend { font-weight: 500; margin: 8px 0 4px; } .hint { color: var(--color-text-secondary); font-size: 12px; margin: 0 0 8px; }',
})
export class ObjectType extends FieldType {}
/** A list: each item with a remove button, and an add button. */
@Component({
selector: 'app-formly-array',
imports: [FormlyField, MatButtonModule, MatIconModule],
template: `
<div class="legend">{{ props.label }}</div>
@for (f of field.fieldGroup; track $index; let i = $index) {
<div class="item">
<formly-field [field]="f" />
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles:
'.legend { font-weight: 500; margin: 8px 0 4px; } .item { display: flex; align-items: flex-start; gap: 4px; } .item formly-field { flex: 1; }',
})
export class ArrayType extends FieldArrayType {}
/** A value forms don't draw (a map, a pair, anything), edited as JSON. */
@Component({
selector: 'app-formly-json',
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: `
<mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }} (JSON)</mat-label>
<textarea
matInput
rows="4"
[value]="text()"
(change)="parse($any($event.target).value)"
></textarea>
@if (error) {
<mat-error>{{ error }}</mat-error>
}
@if (props.description) {
<mat-hint>{{ props.description }}</mat-hint>
}
</mat-form-field>
`,
styles: '.json { width: 100%; } textarea { font-family: monospace; font-size: 12px; }',
})
export class JsonType extends FieldType<FormlyFieldConfig> {
protected error = '';
protected text(): string {
return this.formControl.value === undefined
? ''
: JSON.stringify(this.formControl.value, null, 1);
}
protected parse(value: string): void {
try {
this.formControl.setValue(value.trim() ? JSON.parse(value) : undefined);
this.formControl.markAsDirty();
this.error = '';
} catch {
this.error = 'No es JSON válido';
}
}
}
export const FORMLY_TYPES: ConfigOption = {
types: [
{ name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType },
{ name: 'json', component: JsonType },
{ name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
{ name: 'integer', extends: 'input', defaultOptions: { props: { type: 'number' } } },
{ name: 'boolean', extends: 'checkbox' },
],
};
+81
View File
@@ -0,0 +1,81 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import type { Bundle, CodeableConcept, Extension, FhirResource } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from './api/api-configuration';
/** Our extensions and code systems (core.fhir). */
export const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
export type Params = Record<string, string | number | readonly (string | number)[] | undefined>;
/** The domain's FHIR base (`/{domain}/fhir`): reads and searches, typed as R4. */
@Injectable({ providedIn: 'root' })
export class Fhir {
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
read<T extends FhirResource>(domain: string, type: T['resourceType'], id: string): Promise<T> {
return firstValueFrom(this.http.get<T>(`${this.root}/${domain}/fhir/${type}/${id}`));
}
/** One page of a search. */
search(domain: string, type: string, params: Params = {}): Promise<Bundle> {
const query = Object.fromEntries(
Object.entries(params).filter(([, v]) => v !== undefined),
) as Record<string, string | number | readonly (string | number)[]>;
return firstValueFrom(
this.http.get<Bundle>(`${this.root}/${domain}/fhir/${type}`, { params: query }),
);
}
/** The page a bundle's `next` (or `previous`) link points to, through our own base. */
follow(domain: string, bundle: Bundle, relation: 'next' | 'previous'): Promise<Bundle> | null {
const link = bundle.link?.find((l) => l.relation === relation)?.url;
if (!link) return null;
const url = new URL(link);
const type = url.pathname.split('/').pop();
return firstValueFrom(
this.http.get<Bundle>(`${this.root}/${domain}/fhir/${type}${url.search}`),
);
}
/** Every page of a search. */
async all(domain: string, type: string, params: Params = {}): Promise<Bundle[]> {
const pages = [await this.search(domain, type, params)];
for (let next = this.follow(domain, pages[0], 'next'); next;) {
const page = await next;
pages.push(page);
next = this.follow(domain, page, 'next');
}
return pages;
}
}
/** The resources of a bundle (or of several pages), by search mode. */
export function resources<T extends FhirResource>(
bundles: Bundle | Bundle[],
type: T['resourceType'],
mode?: 'match' | 'include',
): T[] {
return [bundles]
.flat()
.flatMap((b) => b.entry ?? [])
.filter((e) => e.resource?.resourceType === type && (!mode || e.search?.mode === mode))
.map((e) => e.resource as T);
}
export function ext(
element: { extension?: Extension[] } | undefined,
name: string,
): Extension | undefined {
return element?.extension?.find((e) => e.url === EXT + name);
}
export function code(concept: CodeableConcept | undefined): string | undefined {
return concept?.coding?.[0]?.code;
}
export function label(concept: CodeableConcept | undefined): string {
return concept?.text ?? concept?.coding?.[0]?.display ?? concept?.coding?.[0]?.code ?? '';
}
+47
View File
@@ -0,0 +1,47 @@
import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart } from './follow-up';
import { periods } from './measures';
describe('follow-up list', () => {
it('starts the window the day after the same day months before (core.follow_up)', () => {
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
expect(windowStart('2026-01-15', 1)).toBe('2025-12-16');
});
it('groups ages at the cut-off, open at both ends', () => {
expect(ageGroup('1980-11-23', '2026-11-22')).toBe('45-54');
expect(ageGroup('2002-01-01', '2026-11-22')).toBe('<25');
expect(ageGroup('1950-01-01', '2026-11-22')).toBe('65+');
expect(ageGroup(undefined, '2026-11-22')).toBe('Sin dato');
});
it('takes the latest index date, the highest risk there', () => {
const risk = (model: string, at: string, p: number): RiskAssessment => ({
resourceType: 'RiskAssessment',
status: 'final',
subject: {},
occurrenceDateTime: at,
method: { coding: [{ code: model }] },
prediction: [{ probabilityDecimal: p, whenRange: { high: { value: 5 } } }],
});
const risks = [
risk('cacu.cin2_pim', '2025-01-01', 0.9),
risk('cacu.cin2_logistic', '2026-01-01', 0.2),
risk('cacu.cin2_pim_post_colposcopy', '2026-01-01', 0.3),
risk('cacu.cancer_pim', '2026-01-01', 0.05),
];
expect(currentRisk(risks, 'cin2', 5)).toBe(0.3);
expect(currentRisk(risks, 'cancer', 5)).toBe(0.05);
expect(currentRisk(risks, 'cin2', 3)).toBeUndefined();
});
it('lists periods most recent first', () => {
expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']);
expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([
'2026-02',
'2026-01',
'2025-12',
]);
});
});
+128
View File
@@ -0,0 +1,128 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
patient: Patient;
status: string;
ageGroup: string;
cytology?: { date: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string };
risk: Record<'cin2' | 'cancer', number | undefined>;
}
const AGE_GROUPS: [number, number][] = [
[25, 34],
[35, 44],
[45, 54],
[55, 64],
];
export function ageGroup(birth: string | undefined, at: string): string {
if (!birth) return 'Sin dato';
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const found = AGE_GROUPS.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`;
return age < AGE_GROUPS[0][0] ? `<${AGE_GROUPS[0][0]}` : `${AGE_GROUPS.at(-1)![1] + 1}+`;
}
/** Her current risk of an outcome at a horizon: from the latest index date any of the
* outcome's models scored her at, the highest when several did (as the list is sorted). */
export function currentRisk(
risks: RiskAssessment[],
outcome: 'cin2' | 'cancer',
horizon: number,
): number | undefined {
const mine = risks
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) =>
(r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon)
.map((p) => ({ r, p })),
);
if (!mine.length) return undefined;
const latest = mine
.map((x) => x.r.occurrenceDateTime ?? '')
.sort()
.at(-1);
return Math.max(
...mine
.filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal ?? 0),
);
}
/** The list's rows from one page: per patient, her latest cytology and HPV sampled in the
* window, her days to diagnosis, and her latest reported biopsy. */
export function rows(page: Bundle, start: string, cutoff: string, horizon: number): Row[] {
const reports = resources<DiagnosticReport>(page, 'DiagnosticReport');
const observations = new Map(resources<Observation>(page, 'Observation').map((o) => [o.id, o]));
const risks = resources<RiskAssessment>(page, 'RiskAssessment');
const results = (r: DiagnosticReport) =>
new Map(
(r.result ?? [])
.map((x) => observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o)
.map((o) => [code(o!.code), o!]),
);
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
const mine = reports.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
const by = (kind: string) => mine.filter((r) => code(r.code) === kind);
const cytologies = by('cervical-cytology')
.filter((r) => start <= r.effectiveDateTime! && r.effectiveDateTime! <= cutoff)
.sort((a, b) => a.effectiveDateTime!.localeCompare(b.effectiveDateTime!));
const last = cytologies.at(-1);
const lastResults = last ? results(last) : new Map();
const hpv = cytologies.filter((r) => results(r).has('hpv')).at(-1);
const hpvResults = hpv ? results(hpv) : new Map();
const types = ['hpv-16', 'hpv-18']
.filter((k) => hpvResults.has(k))
.map((k) => hpvResults.get(k)!.valueBoolean);
const biopsy = by('cervical-biopsy')
.filter((r) => ext(r, 'report-date'))
.sort((a, b) =>
ext(a, 'report-date')!.valueDate!.localeCompare(ext(b, 'report-date')!.valueDate!),
)
.at(-1);
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return {
patient,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
cytology: last && {
date: last.effectiveDateTime!,
result: code(lastResults.get('cytology-result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cytology-adequacy')?.valueCodeableConcept),
},
hpv: hpv && {
date: hpv.effectiveDateTime!,
positive: !!hpvResults.get('hpv')?.valueBoolean,
types1618: types.length ? types.some((t) => t) : undefined,
},
daysToDiagnosis: last ? ext(last, 'days-to-diagnosis')?.valueInteger : undefined,
biopsy: biopsy && {
date: ext(biopsy, 'report-date')!.valueDate!,
histology: code(biopsy.conclusionCode?.[0]),
},
risk: {
cin2: currentRisk(theirs, 'cin2', horizon),
cancer: currentRisk(theirs, 'cancer', horizon),
},
};
});
}
/** The window's first day: `months` before the cut-off (the month's last day when shorter), plus one. */
export function windowStart(cutoff: string, months: number): string {
const [y, m, d] = cutoff.split('-').map(Number);
const total = y * 12 + (m - 1) - months;
const year = Math.floor(total / 12);
const month = total % 12;
const last = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
const day = new Date(Date.UTC(year, month, Math.min(d, last) + 1));
return day.toISOString().slice(0, 10);
}
+85
View File
@@ -0,0 +1,85 @@
import { Component, computed, inject, input, resource } from '@angular/core';
import { MatTabsModule } from '@angular/material/tabs';
import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app';
import { Fhir, resources } from '../fhir';
import { TabDefiniciones } from './tab-definiciones';
import { TabIndicadores } from './tab-indicadores';
import { TabRiesgos } from './tab-riesgos';
import { TabTrazabilidad } from './tab-trazabilidad';
/** A domain's indicator page: four tabs over its FHIR measures and patients. */
@Component({
selector: 'app-indicadores',
imports: [MatTabsModule, TabIndicadores, TabTrazabilidad, TabRiesgos, TabDefiniciones],
template: `
<section class="page">
<h1>{{ title() }}</h1>
<p class="subtitle">
Indicadores de calidad y oportunidad del tamizaje, a partir de los datos cargados.
</p>
@if (measures.isLoading()) {
<p class="muted">Cargando indicadores…</p>
} @else if (measures.error()) {
<p class="muted" role="alert">No se pudieron leer los indicadores.</p>
} @else if (!measures.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab label="Indicadores">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab>
<mat-tab label="Trazabilidad">
<ng-template matTabContent>
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
</ng-template>
</mat-tab>
@if (patients()) {
<mat-tab label="Análisis de riesgos">
<ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" />
</ng-template>
</mat-tab>
}
<mat-tab label="Datos y definiciones">
<ng-template matTabContent>
<app-tab-definiciones [measures]="measures.value()!" />
</ng-template>
</mat-tab>
</mat-tab-group>
}
</section>
`,
styles: `
:host {
display: block;
}
h1 {
text-align: center;
}
.subtitle {
text-align: center;
}
.empty {
padding: 48px 0;
text-align: center;
}
::ng-deep .mdc-tab-indicator__content--underline {
border-color: var(--color-primary) !important;
}
`,
})
export class Indicadores {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
protected readonly title = computed(
() => DOMAINS[this.domain() as keyof typeof DOMAINS] ?? this.domain(),
);
protected readonly measures = resource({
params: () => this.domain(),
loader: async ({ params }) =>
resources<Measure>(await this.fhir.all(params, 'Measure'), 'Measure'),
});
/** Patient-level analysis is served for CaCu only (so far). */
protected readonly patients = computed(() => this.domain() === 'cacu');
}
+47
View File
@@ -0,0 +1,47 @@
/** Where each measure goes on a domain's indicator page (today's layout); measures not
* named here are clinical cards. Measures are named by their code (`Measure.name`). */
export interface Layout {
kpis: string[];
route: { label: string; fromSample: string; fromStep: string; step: string }[];
/** The measure whose data decides the default period. */
anchor: string;
}
export const LAYOUTS: Record<string, Layout> = {
cacu: {
kpis: [
'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
],
route: [
{
label: 'Resultado de citología',
step: 'Toma a resultado de citología',
fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE',
},
{
label: 'Colposcopía',
step: 'Del resultado de citología a la colposcopía',
fromSample: 'CACU_DIAS_TOMA_COLPOSCOPIA',
fromStep: 'CACU_DIAS_RESULTADO_COLPOSCOPIA',
},
{
label: 'Resultado de biopsia',
step: 'De la colposcopía al resultado de biopsia',
fromSample: 'CACU_DIAS_TOMA_BIOPSIA',
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
anchor: 'IND1',
},
};
+280
View File
@@ -0,0 +1,280 @@
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
import { code, ext } from '../fhir';
import { Figure, PALETTE } from '../plot';
export type PeriodType = 'semester' | 'month';
export type Scoring = 'proportion' | 'continuous-variable' | 'cohort';
/** The periods back from today, most recent first: semesters (`2025-S1`) or months. */
export function periods(type: PeriodType, years = 6, today = new Date()): string[] {
const found: string[] = [];
const year = today.getFullYear();
if (type === 'semester') {
for (let y = year; y > year - years; y--) {
if (y < year || today.getMonth() >= 6) found.push(`${y}-S2`);
found.push(`${y}-S1`);
}
} else {
for (let i = 0; i < years * 12; i++) {
const d = new Date(year, today.getMonth() - i, 1);
found.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
}
}
return found;
}
export function periodLabel(period: string): string {
const [year, part] = period.split('-');
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
const month = new Date(Number(year), Number(part) - 1, 1).toLocaleString('es-MX', {
month: 'short',
});
return `${month} ${year}`;
}
export function scoring(measure: Measure): Scoring {
return code(measure.scoring) as Scoring;
}
export function periodTypes(measure: Measure): PeriodType[] {
return (measure.extension ?? [])
.filter((e) => e.url.endsWith('/period-type'))
.map((e) => e.valueCode as PeriodType);
}
/** What one report says: its counts, its score and interval, and its strata. */
export interface Reading {
populations: Record<string, number>;
score?: number;
low?: number;
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
}
function counts(group: {
population?: { code?: { coding?: { code?: string }[] }; count?: number }[];
}) {
return Object.fromEntries(
(group.population ?? []).map((p) => [p.code?.coding?.[0]?.code ?? '', p.count ?? 0]),
);
}
export function reading(report: MeasureReport | undefined): Reading | undefined {
const group: MeasureReportGroup | undefined = report?.group?.[0];
if (!group) return 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 ?? '';
strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [x.value?.text ?? '', counts(x)]),
);
}
return {
populations: counts(group),
score: score?.value,
low: (ext(score, 'ic-bajo') ?? ext(score, 'q1'))?.valueDecimal,
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit,
strata,
};
}
/** Codes as the screens name them. */
const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)',
LSIL: 'LIEBG',
HSIL: 'LIEAG',
normal: 'Normal',
carcinoma: 'Carcinoma',
no_data: 'Sin dato',
no_biopsy: 'Sin biopsia',
pre_colposcopy: 'Pre colposcopia',
post_colposcopy: 'Post colposcopia',
post_treatment: 'Post tratamiento',
case: 'Caso (cáncer)',
low: 'Bajo',
intermediate: 'Intermedio',
high: 'Alto',
satisfactory: 'satisfactoria',
unsatisfactory: 'insatisfactoria',
};
export const STRATA: Record<string, string> = {
category: 'Categoría',
age_group: 'Grupo de edad',
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
};
export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
if (!r || r.score === undefined) return 'Sin dato';
switch (scoring(measure)) {
case 'proportion':
return `${(r.score * 100).toFixed(1)} %`;
case 'continuous-variable':
return `${Math.round(r.score * 10) / 10} días`;
default:
return `${r.score}`;
}
}
export function detail(measure: Measure, r: Reading | undefined): string {
if (!r) return '';
const p = r.populations;
switch (scoring(measure)) {
case 'proportion':
return r.score === undefined
? 'Sin pacientes en el periodo.'
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable':
return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
: `Mediana de ${p['measure-observation']} mediciones; cuartiles ${r.low}–${r.high} días.`;
default:
return `${p['initial-population'] ?? 0} pacientes.`;
}
}
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure {
let labels: string[], values: number[];
if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto'];
values = [numerator, denominator - numerator];
} else {
const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v));
values = cells.map(([, c]) => c['initial-population'] ?? 0);
}
return {
data: [
{
type: 'pie',
hole: 0.62,
labels,
values,
sort: false,
textinfo: 'value+percent',
marker: { colors: PALETTE },
},
],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
};
}
/** Bars per stratum: the rate (proportion) or the count (others). */
export function strataBars(measure: Measure, r: Reading, stratifier: string): Figure {
const cells = Object.entries(r.strata[stratifier] ?? {});
const proportion = scoring(measure) === 'proportion';
const values = cells.map(([, c]) =>
proportion
? c['denominator']
? (100 * (c['numerator'] ?? 0)) / c['denominator']
: 0
: (c['initial-population'] ?? 0),
);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: cells.map(([v]) => name(v)),
x: values,
marker: { color: PALETTE[0] },
},
],
layout: {
xaxis: { title: { text: proportion ? '%' : 'Pacientes' } },
yaxis: { automargin: true },
margin: { t: 8, r: 16, b: 48, l: 8 },
},
};
}
/** Horizontal median bars with their interquartile range, one per measure. */
export function medians(rows: { label: string; r: Reading | undefined }[]): Figure {
const shown = rows.filter((x) => x.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map((x) => x.label),
x: shown.map((x) => x.r!.score!),
error_x: {
type: 'data',
symmetric: false,
array: shown.map((x) => (x.r!.high ?? x.r!.score!) - x.r!.score!),
arrayminus: shown.map((x) => x.r!.score! - (x.r!.low ?? x.r!.score!)),
color: '#17324d',
},
marker: { color: PALETTE[0] },
hovertemplate: '%{y}: %{x} días<extra></extra>',
},
],
layout: {
xaxis: { title: { text: 'Días (mediana, Q1–Q3)' } },
yaxis: { automargin: true, autorange: 'reversed' },
},
};
}
/** A measure over time: % with its interval, median with its quartiles, or counts by category. */
export function history(
measure: Measure,
series: { period: string; r: Reading | undefined }[],
): Figure {
const x = series.map((s) => periodLabel(s.period));
const kind = scoring(measure);
if (kind === 'cohort') {
const categories = [
...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {}))),
];
return {
data: categories.map((c, i) => ({
type: 'bar',
name: name(c),
x,
y: series.map((s) => s.r?.strata['category']?.[c]?.['initial-population'] ?? 0),
marker: { color: PALETTE[i % PALETTE.length] },
})),
layout: { barmode: 'stack', yaxis: { title: { text: 'Pacientes' } } },
};
}
const k = kind === 'proportion' ? 100 : 1;
const value = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x,
y: series.map((s) => value(s.r?.high)),
mode: 'lines',
line: { width: 0 },
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => value(s.r?.low)),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
fillcolor: 'rgba(168,194,67,0.25)',
name: kind === 'proportion' ? 'IC 95 %' : 'Q1–Q3',
},
{
x,
y: series.map((s) => value(s.r?.score)),
mode: 'lines+markers',
name: kind === 'proportion' ? '%' : 'Mediana',
line: { color: PALETTE[0] },
},
],
layout: { yaxis: { title: { text: kind === 'proportion' ? '%' : 'Días' } } },
};
}
+64
View File
@@ -0,0 +1,64 @@
import { Component, input } from '@angular/core';
import type { Measure } from 'fhir/r4';
import { code, label } from '../fhir';
import { periodTypes, STRATA } from './measures';
const SCORING: Record<string, string> = {
proportion: 'Proporción',
'continuous-variable': 'Variable continua (mediana)',
cohort: 'Composición (conteo)',
};
const IMPROVEMENT: Record<string, string> = {
increase: 'Mejor si sube',
decrease: 'Mejor si baja',
};
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** What each measure is: how it scores, which way is better, its periods and strata. */
@Component({
selector: 'app-tab-definiciones',
template: `
<table class="plain card">
<thead>
<tr>
<th>Indicador</th>
<th>Clave</th>
<th>Cálculo</th>
<th>Mejora</th>
<th>Periodos</th>
<th>Estratos</th>
</tr>
</thead>
<tbody>
@for (m of measures(); track m.id) {
<tr>
<td>{{ m.title }}</td>
<td>
<code>{{ m.name }}</code> v{{ m.version }}
</td>
<td>{{ scoring[code(m.scoring) ?? ''] }}</td>
<td>{{ improvement[code(m.improvementNotation) ?? ''] ?? '—' }}</td>
<td>{{ types(m) }}</td>
<td>{{ strata(m) }}</td>
</tr>
}
</tbody>
</table>
`,
styles: ':host { display: block; padding-top: 16px; overflow-x: auto; }',
})
export class TabDefiniciones {
readonly measures = input.required<Measure[]>();
protected readonly scoring = SCORING;
protected readonly improvement = IMPROVEMENT;
protected readonly code = code;
protected types(m: Measure): string {
return periodTypes(m)
.map((p) => PERIODS[p] ?? p)
.join(', ');
}
protected strata(m: Measure): string {
const names = (m.group?.[0]?.stratifier ?? []).map((s) => code(s.code) ?? label(s.code));
return names.map((n) => STRATA[n] ?? n).join(', ') || '—';
}
}
+89
View File
@@ -0,0 +1,89 @@
<div class="filters card">
<div class="field">
<span class="label">Intervalo de análisis</span>
<mat-button-toggle-group
[value]="type()"
(change)="setType($event.value)"
aria-label="Intervalo de análisis"
>
<mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodo seleccionado</mat-label>
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
@for (p of options(); track p) {
<mat-option [value]="p">{{ label(p) }}</mat-option>
}
</mat-select>
</mat-form-field>
<button
mat-flat-button
(click)="applied.set(chosen())"
[disabled]="!chosen() || chosen() === applied()"
>
Aplicar
</button>
@if (applied(); as p) {
<span class="muted applied">Mostrando {{ label(p) }}</span>
}
</div>
@if (reports.isLoading()) {
<p class="muted">Calculando…</p>
}
@if (kpis().length) {
<h2>Indicadores de oportunidad</h2>
<div class="kpis">
@for (m of kpis(); track m.id) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="m.name">
<mat-card-content>
<div class="kpi-title">{{ m.title }}</div>
<div class="kpi-value">{{ score(m) }}</div>
<div class="kpi-detail muted">{{ detail(m) }}</div>
</mat-card-content>
</mat-card>
}
</div>
}
@if (layout().route.length) {
<mat-card appearance="outlined" class="route">
<mat-card-header>
<mat-card-title>Ruta del tamizaje</mat-card-title>
<mat-button-toggle-group
[value]="routeView()"
(change)="routeView.set($event.value)"
class="route-toggle"
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</mat-card-header>
<mat-card-content>
<app-plot [figure]="route()" [height]="260" />
</mat-card-content>
</mat-card>
}
<h2>Indicadores clínicos</h2>
<div class="clinical">
@for (m of clinical(); track m.id) {
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
<mat-card-header>
<mat-card-title>{{ m.title }}</mat-card-title>
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
@for (f of figureSets().get(m.name!) ?? []; track f.title) {
<h3 class="figure-title">{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="260" />
} @empty {
<p class="muted">Sin datos en el periodo.</p>
}
</mat-card-content>
</mat-card>
}
</div>
+99
View File
@@ -0,0 +1,99 @@
:host {
display: block;
padding-top: var(--space-4);
}
.filters {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.field {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.label {
color: var(--color-text-secondary);
font-size: 12px;
}
h2 {
font-size: 1.15rem;
font-weight: 500;
margin: var(--space-6) 0 var(--space-3);
}
.kpis {
display: grid;
gap: var(--space-3);
grid-template-columns: 1fr;
}
@media (min-width: 600px) {
.kpis {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1000px) {
.kpis {
grid-template-columns: repeat(3, 1fr);
}
}
@media (min-width: 1350px) {
.kpis {
grid-template-columns: repeat(5, 1fr);
}
}
.kpi-title {
font-weight: 500;
min-height: 2.6em;
}
.kpi-value {
font-size: 2rem;
font-weight: 500;
margin: var(--space-2) 0;
}
.kpi-detail {
font-size: 13px;
}
.route {
margin-top: var(--space-4);
}
.route mat-card-header {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
.clinical {
display: grid;
gap: var(--space-4);
grid-template-columns: 1fr;
}
@media (min-width: 1304px) {
.clinical {
grid-template-columns: repeat(2, 1fr);
}
}
.figure-title {
color: var(--color-text-secondary);
font-size: 14px;
font-weight: 500;
margin: var(--space-3) 0 0;
}
+171
View File
@@ -0,0 +1,171 @@
import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout';
import {
detail,
donut,
formatScore,
medians,
name,
periodLabel,
periods,
PeriodType,
reading,
Reading,
scoring,
STRATA,
strataBars,
} from './measures';
/** 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: [
FormsModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatSelectModule,
Plot,
],
templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss',
})
export class TabIndicadores {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('semester');
protected readonly options = computed(() => periods(this.type()));
protected readonly chosen = signal<string | undefined>(undefined);
/** The period the figures show (set by Aplicar). */
protected readonly applied = signal<string | undefined>(undefined);
protected readonly routeView = signal<'sample' | 'step'>('sample');
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
protected readonly kpis = computed(() =>
this.layout()
.kpis.map((n) => this.byName().get(n))
.filter((m) => !!m),
);
protected readonly clinical = computed(() => {
const placed = new Set([
...this.layout().kpis,
...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]),
]);
return this.measures().filter((m) => !placed.has(m.name!));
});
/** The latest period with data, the default. */
private readonly latest = resource({
params: () => ({
domain: this.domain(),
anchor: this.byName().get(this.layout().anchor) ?? this.measures()[0],
all: this.options(),
}),
loader: async ({ params }) => {
const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: params.anchor.id!,
'reporting-period': params.all.join(','),
});
const found = resources<MeasureReport>(pages, 'MeasureReport');
const index = found.findIndex(
(r) => (reading(r)?.populations['initial-population'] ?? 0) > 0,
);
return params.all[Math.max(index, 0)];
},
});
protected readonly reports = resource({
params: () => ({ domain: this.domain(), period: this.applied(), measures: this.measures() }),
loader: async ({ params }) => {
if (!params.period) return new Map<string, Reading | undefined>();
const found = await Promise.all(
params.measures.map(async (m) => {
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
}),
);
return new Map(found);
},
});
constructor() {
effect(() => {
const latest = this.latest.value();
if (latest && !this.applied()) {
this.chosen.set(latest);
this.applied.set(latest);
}
});
}
protected readonly label = periodLabel;
protected readonly strataNames = STRATA;
protected r(m: Measure): Reading | undefined {
return this.reports.value()?.get(m.name!);
}
protected score(m: Measure): string {
return formatScore(m, this.r(m));
}
protected detail(m: Measure): string {
return detail(m, this.r(m));
}
protected setType(type: PeriodType): void {
this.type.set(type);
this.chosen.set(this.options()[0]);
}
protected readonly route = computed<Figure>(() => {
const view = this.routeView();
return medians(
this.layout().route.map((s) => {
const m = this.byName().get(view === 'sample' ? s.fromSample : s.fromStep);
return { label: view === 'sample' ? s.label : s.step, r: m && this.r(m) };
}),
);
});
/** 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!))]),
),
);
/** A clinical card's figures: the overall split, then one per stratum. */
private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] {
if (!r || !(r.populations['initial-population'] ?? 0)) return [];
const strata = Object.keys(r.strata).filter(
(s) => s !== 'category' && Object.keys(r.strata[s]).length,
);
const kind = scoring(m);
if (kind === 'continuous-variable')
return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }];
return [
{ title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) },
...strata.map((s) => ({
title: `Por ${STRATA[s]?.toLowerCase() ?? s}`,
figure: strataBars(m, r, s),
})),
];
}
protected readonly name = name;
}
+146
View File
@@ -0,0 +1,146 @@
<form class="filters card" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
matInput
type="date"
[ngModel]="cutoff() || applied()"
(ngModelChange)="cutoff.set($event)"
name="cutoff"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@for (m of [1, 3, 6, 12]; track m) {
<mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option>
@for (s of statuses; track s) {
<mat-option [value]="s">{{ name(s) }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Horizonte</mat-label>
<mat-select [value]="horizon()" (selectionChange)="horizon.set($event.value)">
@for (h of [1, 2, 3, 4, 5]; track h) {
<mat-option [value]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Orden</mat-label>
<mat-select [value]="sort()" (selectionChange)="sort.set($event.value)">
<mat-option value="-recent">Estudio más reciente</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option>
<mat-option value="-risk-cancer">Mayor riesgo de cáncer</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label>
<mat-select [value]="size()" (selectionChange)="size.set($event.value)">
@for (n of [20, 50, 100]; track n) {
<mat-option [value]="n">{{ n }}</mat-option>
}
</mat-select>
</mat-form-field>
</form>
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
}
<div class="table-wrap card">
<table class="plain worklist">
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Estatus</th>
<th>Última citología</th>
<th>VPH</th>
<th>Biopsia</th>
<th>Riesgo LIEAG+ ({{ horizon() }} a)</th>
<th>Riesgo cáncer ({{ horizon() }} a)</th>
<th>Días toma → diagnóstico</th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]" class="id">{{
row.patient.id!.slice(0, 10)
}}</a>
</td>
<td>{{ row.ageGroup }}</td>
<td>{{ name(row.status) }}</td>
<td>
@if (row.cytology; as c) {
{{ c.date }} ·
{{
c.result
? name(c.result)
: c.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}}
} @else {
—
}
</td>
<td>
@if (row.hpv; as h) {
{{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }}
} @else {
—
}
</td>
<td>
@if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }}
} @else {
—
}
</td>
<td class="num">
{{ row.risk.cin2 === undefined ? '—' : (row.risk.cin2 * 100 | number: '1.1-1') + ' %' }}
</td>
<td class="num">
{{
row.risk.cancer === undefined ? '—' : (row.risk.cancer * 100 | number: '1.1-1') + ' %'
}}
</td>
<td class="num">{{ row.daysToDiagnosis ?? '—' }}</td>
</tr>
} @empty {
<tr>
<td colspan="9" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte
{{ applied() }}
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
Anterior
</button>
<button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()">
Siguiente
</button>
</div>
+38
View File
@@ -0,0 +1,38 @@
:host {
display: block;
padding-top: var(--space-4);
}
.filters {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
margin-bottom: var(--space-4);
}
.table-wrap {
overflow-x: auto;
padding: 0;
}
.worklist .num {
text-align: right;
white-space: nowrap;
}
.id {
color: var(--color-action);
font-family: monospace;
}
.pager {
align-items: center;
display: flex;
gap: var(--space-3);
justify-content: flex-end;
margin-top: var(--space-3);
}
.pager .muted {
margin-right: auto;
}
+102
View File
@@ -0,0 +1,102 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { rows, windowStart } from './follow-up';
import { name } from './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status,
* results and current risks, in the order asked for. */
@Component({
selector: 'app-tab-riesgos',
imports: [
DecimalPipe,
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
RouterLink,
],
templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss',
})
export class TabRiesgos {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
protected readonly cutoff = signal<string>('');
protected readonly window = signal(3);
protected readonly status = signal<string>('');
protected readonly horizon = signal(5);
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
/** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES;
protected readonly name = name;
private readonly first = resource({
params: () => ({
domain: this.domain(),
'follow-up-window': this.window(),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', {
...params,
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
},
});
protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value());
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
});
protected readonly offset = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? Number(new URL(self).searchParams.get('_offset') ?? 0) : 0;
});
protected readonly rows = computed(() => {
const page = this.page();
const cutoff = this.applied();
return page && cutoff
? rows(page, windowStart(cutoff, this.window()), cutoff, this.horizon())
: [];
});
protected readonly error = computed(() => this.first.error());
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
protected async go(relation: 'next' | 'previous'): Promise<void> {
const page = this.page();
const next = page && this.fhir.follow(this.domain(), page, relation);
if (!next) return;
this.loading.set(true);
try {
this.moved.set(await next);
} finally {
this.loading.set(false);
}
}
}
+89
View File
@@ -0,0 +1,89 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { history, periods, PeriodType, periodTypes, reading } from './measures';
/** Each measure over time: every period of the chosen kind, oldest first. */
@Component({
selector: 'app-tab-trazabilidad',
imports: [MatButtonToggleModule, MatCardModule, Plot],
template: `
<div class="bar">
<mat-button-toggle-group
[value]="type()"
(change)="type.set($event.value)"
aria-label="Intervalo"
>
<mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group>
</div>
@if (series.isLoading()) {
<p class="muted">Calculando…</p>
}
<div class="grid">
@for (item of figures(); track item.measure.id) {
<mat-card appearance="outlined" [attr.data-measure]="item.measure.name">
<mat-card-header
><mat-card-title>{{ item.measure.title }}</mat-card-title></mat-card-header
>
<mat-card-content><app-plot [figure]="item.figure" [height]="280" /></mat-card-content>
</mat-card>
}
</div>
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.bar {
margin-bottom: 16px;
}
.grid {
display: grid;
gap: 16px;
grid-template-columns: 1fr;
}
@media (min-width: 1304px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
`,
})
export class TabTrazabilidad {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('semester');
protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
loader: async ({ params }) => {
const asked = periods(params.type).reverse();
const shown = params.measures.filter((m) => periodTypes(m).includes(params.type));
return Promise.all(
shown.map(async (measure) => {
const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!,
'reporting-period': asked.join(','),
});
const found = resources<MeasureReport>(pages, 'MeasureReport');
return { measure, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
}),
);
},
});
protected readonly figures = computed<{ measure: Measure; figure: Figure }[]>(() =>
(this.series.value() ?? []).map(({ measure, points }) => {
// From the first period with data on.
const first = points.findIndex((p) => (p.r?.populations['initial-population'] ?? 0) > 0);
return { measure, figure: history(measure, first < 0 ? [] : points.slice(first)) };
}),
);
}
+145
View File
@@ -0,0 +1,145 @@
<section class="page">
<a mat-button [routerLink]="['/indicadores', domain()]"
><mat-icon>arrow_back</mat-icon> Regresar</a
>
@if (error()) {
<p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) {
<h1>
Paciente <code>{{ p.id!.slice(0, 10) }}</code>
</h1>
<dl class="summary">
<div>
<dt>Fecha de nacimiento</dt>
<dd>{{ p.birthDate ?? 'Sin dato' }}</dd>
</div>
<div>
<dt>Sexo</dt>
<dd>
{{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }}
</dd>
</div>
<div>
<dt>Estatus de seguimiento</dt>
<dd>{{ status() }}</dd>
</div>
@if (p.deceasedDateTime) {
<div>
<dt>Defunción</dt>
<dd>{{ p.deceasedDateTime }}</dd>
</div>
}
</dl>
<div class="cards">
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content>
<table class="plain">
<thead>
<tr>
<th>Fecha</th>
<th>Tipo</th>
<th>Detalle</th>
</tr>
</thead>
<tbody>
@for (h of history(); track $index) {
<tr>
<td class="nowrap">{{ h.date }}</td>
<td>{{ h.kind }}</td>
<td>
{{ h.text }}
@if (h.code && h.code !== h.text) {
<span class="muted">({{ h.code }})</span>
}
</td>
</tr>
} @empty {
<tr>
<td colspan="3" class="muted">Sin registros.</td>
</tr>
}
</tbody>
</table>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Pruebas y resultados</mat-card-title></mat-card-header>
<mat-card-content>
<table class="plain">
<thead>
<tr>
<th>Toma</th>
<th>Estudio</th>
<th>Reporte</th>
<th>Resultados</th>
</tr>
</thead>
<tbody>
@for (t of tests(); track $index) {
<tr>
<td class="nowrap">{{ t.date }}</td>
<td>{{ t.kind }}</td>
<td class="nowrap">{{ t.reported ?? 'Pendiente' }}</td>
<td>{{ t.results.join(' · ') || '—' }}</td>
</tr>
} @empty {
<tr>
<td colspan="4" class="muted">Sin estudios.</td>
</tr>
}
</tbody>
</table>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" class="wide">
<mat-card-header
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
@if (models().length) {
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Probabilidad</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (m of models(); track m.model) {
@for (p of m.predictions; track p.years) {
<tr>
<td>{{ $first ? m.text : '' }}</td>
<td>{{ $first ? m.index : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }}
%
} @else {
—
}
</td>
</tr>
}
}
</tbody>
</table>
<app-plot [figure]="curve()" [height]="300" />
} @else {
<p class="muted">Ningún modelo vigente la ha evaluado.</p>
}
</mat-card-content>
</mat-card>
</div>
} @else if (loading()) {
<p class="muted">Cargando…</p>
}
</section>
+35
View File
@@ -0,0 +1,35 @@
.summary {
display: flex;
flex-wrap: wrap;
gap: var(--space-6);
margin: var(--space-3) 0 var(--space-4);
}
.summary dt {
color: var(--color-text-secondary);
font-size: 12px;
}
.summary dd {
font-weight: 500;
margin: 0;
}
.cards {
display: grid;
gap: var(--space-4);
grid-template-columns: 1fr;
}
@media (min-width: 1100px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
.wide {
grid-column: 1 / -1;
}
}
mat-card-content {
overflow-x: auto;
}
+176
View File
@@ -0,0 +1,176 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { RouterLink } from '@angular/router';
import type {
Condition,
DiagnosticReport,
Observation,
Patient,
Procedure,
RiskAssessment,
} from 'fhir/r4';
import { code, ext, Fhir, label, resources } from '../fhir';
import { name } from '../indicadores/measures';
import { Figure, PALETTE, Plot } from '../plot';
/** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */
@Component({
selector: 'app-paciente',
imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
})
export class Paciente {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
readonly id = input.required<string>();
private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }),
loader: async ({ params: { domain, id } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 };
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
this.fhir.read<Patient>(domain, 'Patient', id),
this.fhir.all(domain, 'Condition', subject),
this.fhir.all(domain, 'Procedure', subject),
this.fhir.all(domain, 'DiagnosticReport', subject),
this.fhir.all(domain, 'Observation', subject),
this.fhir.all(domain, 'RiskAssessment', subject),
]);
return {
patient,
conditions: resources<Condition>(conditions, 'Condition'),
procedures: resources<Procedure>(procedures, 'Procedure'),
reports: resources<DiagnosticReport>(reports, 'DiagnosticReport').reverse(),
observations: new Map(
resources<Observation>(observations, 'Observation').map((o) => [o.id, o]),
),
risks: resources<RiskAssessment>(risks, 'RiskAssessment'),
};
},
});
protected readonly patient = computed(() => this.data.value()?.patient);
protected readonly error = computed(() => this.data.error());
protected readonly loading = computed(() => this.data.isLoading());
protected readonly history = computed(() => {
const d = this.data.value();
if (!d) return [];
return [
...d.conditions.map((c) => ({
date: c.recordedDate ?? '',
kind: 'Diagnóstico',
text: label(c.code),
code: code(c.code),
})),
...d.procedures.map((p) => ({
date: p.performedDateTime ?? '',
kind: 'Procedimiento',
text: label(p.code),
code: undefined,
})),
].sort((a, b) => b.date.localeCompare(a.date));
});
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
return d.reports.map((r) => {
const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[];
return {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
status: r.status,
results: [
...results.map(
(o) =>
`${label(o.code)}: ${o.valueBoolean !== undefined ? (o.valueBoolean ? 'positivo' : 'negativo') : name(code(o.valueCodeableConcept) ?? '')}`,
),
...(r.conclusionCode ?? []).map((c) => `Histología: ${name(code(c) ?? '')}`),
],
};
});
});
/** One model's latest risk assessment per model. */
protected readonly models = computed(() => {
const latest = new Map<string, RiskAssessment>();
for (const r of this.data.value()?.risks ?? []) {
const key = code(r.method) ?? '';
if (
!latest.has(key) ||
(latest.get(key)!.occurrenceDateTime ?? '') < (r.occurrenceDateTime ?? '')
)
latest.set(key, r);
}
return [...latest.values()].map((r) => ({
model: code(r.method) ?? '',
text: r.method?.text ?? '',
index: r.occurrenceDateTime ?? '',
predictions: (r.prediction ?? []).map((p) => ({
years: p.whenRange?.high?.value ?? 0,
p: p.probabilityDecimal ?? 0,
low: ext(p, 'ic-bajo')?.valueDecimal,
high: ext(p, 'ic-alto')?.valueDecimal,
})),
}));
});
protected readonly shown = signal<string | undefined>(undefined);
protected readonly curve = computed<Figure>(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
return {
data: models.flatMap((m, i) => {
const x = m.predictions.map((p) => p.years);
const color = PALETTE[i % PALETTE.length];
return [
{
x,
y: m.predictions.map((p) => (p.high ?? p.p) * 100),
mode: 'lines',
line: { width: 0 },
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: m.predictions.map((p) => (p.low ?? p.p) * 100),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
fillcolor: color + '33',
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: m.predictions.map((p) => p.p * 100),
mode: 'lines+markers',
name: m.model.replace('cacu.', ''),
line: { color },
},
];
}),
layout: {
xaxis: { title: { text: 'Años desde la fecha índice' }, dtick: 1 },
// At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: {
title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, this.top() * 110)],
tickformat: '.1f',
},
},
};
});
private top(): number {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
}
protected readonly name = name;
protected readonly status = computed(() => {
const p = this.patient();
return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : '';
});
}
+58
View File
@@ -0,0 +1,58 @@
import { Component, effect, ElementRef, input, OnDestroy, viewChild } from '@angular/core';
// The cartesian bundle: bars, lines, box and pie, as today's charts use.
import Plotly from 'plotly.js-cartesian-dist-min';
export type Figure = { data: Partial<Plotly.Data>[]; layout?: Partial<Plotly.Layout> };
/** The series colours today's charts use, in order. */
export const PALETTE = [
'#A8C243',
'#42C29C',
'#C24269',
'#9C42C2',
'#4269C2',
'#C29C42',
'#7A7A7A',
];
const LAYOUT: Partial<Plotly.Layout> = {
font: { family: 'Roboto, Arial, sans-serif', size: 14, color: '#17324d' },
colorway: PALETTE,
margin: { t: 24, r: 16, b: 48, l: 56 },
paper_bgcolor: 'rgba(0,0,0,0)',
plot_bgcolor: 'rgba(0,0,0,0)',
legend: { orientation: 'h', y: -0.2 },
};
const CONFIG: Partial<Plotly.Config> = {
responsive: true,
displaylogo: false,
modeBarButtonsToRemove: ['sendDataToCloud', 'lasso2d', 'select2d'],
};
/** One Plotly chart: the figure, drawn with the platform's layout and config. */
@Component({
selector: 'app-plot',
template: '<div #host class="plot" [style.height.px]="height()"></div>',
styles: ':host { display: block; } .plot { width: 100%; }',
})
export class Plot implements OnDestroy {
readonly figure = input.required<Figure>();
readonly height = input(320);
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() {
effect(() => {
const { data, layout } = this.figure();
void Plotly.react(
this.host().nativeElement,
data as Plotly.Data[],
{ ...LAYOUT, ...layout },
CONFIG,
);
});
}
ngOnDestroy(): void {
Plotly.purge(this.host().nativeElement);
}
}
+247
View File
@@ -0,0 +1,247 @@
<section class="page">
<h1>Revisión</h1>
<p class="subtitle">
Lo que la carga retuvo para que una persona decida. Cada decisión queda registrada y se aplica
en la siguiente ejecución.
</p>
@if (message()) {
<p class="message" role="status">{{ message() }}</p>
}
<mat-tab-group animationDuration="0ms">
<mat-tab [label]="'Retenidos (' + (held.value()?.length ?? 0) + ')'">
<div class="bar">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Entidad</mat-label>
<mat-select [value]="entity()" (selectionChange)="entity.set($event.value)">
@for (e of entities; track e[0]) {
<mat-option [value]="e[0]">{{ e[1] }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<table class="plain card">
<thead>
<tr>
<th>Canalización</th>
<th>Motivo</th>
<th>Valores como llegaron</th>
<th></th>
</tr>
</thead>
<tbody>
@for (row of held.value() ?? []; track row['_record']) {
<tr>
<td>{{ row['_pipeline'] }} · {{ row['_target'] }}</td>
<td>{{ reasons(row) }}</td>
<td class="values">
@for (v of values(row) | keyvalue; track v.key) {
<span
><b>{{ v.key }}</b
>: {{ text(v.value) }}</span
>
}
</td>
<td>
<button
mat-stroked-button
[disabled]="decided().has($any(row['_record']))"
(click)="rejectRow(entity(), $any(row['_record']), reasons(row))"
>
Rechazar
</button>
</td>
</tr>
} @empty {
<tr>
<td colspan="4" class="muted">Nada retenido.</td>
</tr>
}
</tbody>
</table>
</mat-tab>
<mat-tab [label]="'Conflictos (' + (conflicts.value()?.length ?? 0) + ')'">
<div class="bar">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Entidad</mat-label>
<mat-select [value]="entity()" (selectionChange)="entity.set($event.value)">
@for (e of entities; track e[0]) {
<mat-option [value]="e[0]">{{ e[1] }}</mat-option>
}
</mat-select>
</mat-form-field>
<span class="muted"
>Registros de una misma paciente y fecha que no coinciden: rechace los equivocados.</span
>
</div>
<table class="plain card">
<thead>
<tr>
<th>Paciente</th>
<th>Valores</th>
<th></th>
</tr>
</thead>
<tbody>
@for (row of conflicts.value() ?? []; track row['_record']) {
<tr>
<td>
<code>{{ text(row['person_id']).slice(0, 10) }}</code>
</td>
<td class="values">
@for (v of values(row) | keyvalue; track v.key) {
<span
><b>{{ v.key }}</b
>: {{ text(v.value) }}</span
>
}
</td>
<td>
<button
mat-stroked-button
[disabled]="decided().has($any(row['_record']))"
(click)="rejectRow(entity(), $any(row['_record']), 'conflicto')"
>
Rechazar
</button>
</td>
</tr>
} @empty {
<tr>
<td colspan="3" class="muted">Sin conflictos.</td>
</tr>
}
</tbody>
</table>
</mat-tab>
<mat-tab label="Personas">
<div class="bar">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Canalización</mat-label>
<mat-select
[value]="pipeline()"
(selectionChange)="pipeline.set($event.value); node.set(undefined)"
>
@for (p of pipelines.value() ?? []; track p['pipeline_id']) {
<mat-option [value]="p['pipeline_id']">{{ p['pipeline_id'] }}</mat-option>
}
</mat-select>
</mat-form-field>
@if ((links.value() ?? []).length > 1) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Nodo de vinculación</mat-label>
<mat-select [value]="link()" (selectionChange)="node.set($event.value)">
@for (l of links.value() ?? []; track l) {
<mat-option [value]="l">{{ l }}</mat-option>
}
</mat-select>
</mat-form-field>
}
@if (pipeline()) {
<button
mat-flat-button
(click)="apply()"
[disabled]="!!run() && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run())"
>
Aplicar decisiones (ejecutar)
</button>
@if (run()) {
<span class="muted">Ejecución: {{ run() }}</span>
}
}
</div>
@if (persons.value(); as p) {
<h2>Posibles pacientes duplicadas ({{ p['to_settle'].length }})</h2>
@for (entry of p['to_settle']; track entry['person']) {
<div class="card person">
<div>
<b>Registro</b> <code>{{ text(entry['person']).slice(0, 10) }}</code> ·
{{ text(entry['record_number']) }} · {{ text(entry['full_name']) }} ·
{{ text(entry['birth_date']) }}
</div>
@for (c of candidates(entry); track c['candidate']) {
<div class="candidate">
<span
>¿Es <code>{{ text(c['candidate']).slice(0, 10) }}</code> ({{
text(c['record_number'])
}}
· {{ text(c['full_name']) }} · {{ text(c['birth_date']) }})?
<span class="muted"
>{{ c['reason'] }}
@if (c['probability'] !== null) {
· p = {{ $any(c['probability']) | number: '1.2-2' }}
}
</span></span
>
<button
mat-stroked-button
[disabled]="decided().has(entry['person'] + '|' + c['candidate'])"
(click)="decide($any(entry['person']), $any(c['candidate']), true)"
>
Misma paciente
</button>
<button
mat-stroked-button
[disabled]="decided().has(entry['person'] + '|' + c['candidate'])"
(click)="decide($any(entry['person']), $any(c['candidate']), false)"
>
Distintas
</button>
</div>
}
</div>
} @empty {
<p class="muted">Nada que decidir.</p>
}
<h2>Registros que no coinciden en fecha de nacimiento o sexo ({{ p['torn'].length }})</h2>
@for (entry of p['torn']; track entry['person']) {
<div class="card person">
@for (r of records(entry); track r['_record']) {
<div class="candidate">
<span class="values">
@for (v of values(r) | keyvalue; track v.key) {
<span
><b>{{ v.key }}</b
>: {{ text(v.value) }}</span
>
}
</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="small">
<mat-label>Campo</mat-label>
<mat-select #field value="record_number">
@for (f of fields; track f) {
<mat-option [value]="f">{{ f }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="small">
<mat-label>Valor correcto</mat-label>
<input matInput #value />
</mat-form-field>
<button
mat-stroked-button
(click)="fix($any(r['_record']), field.value, value.value)"
>
Corregir
</button>
<button
mat-stroked-button
[disabled]="decided().has($any(r['_record']))"
(click)="rejectRow('identity', $any(r['_record']), 'identidad equivocada')"
>
Rechazar
</button>
</div>
}
</div>
} @empty {
<p class="muted">Nada que decidir.</p>
}
}
</mat-tab>
</mat-tab-group>
</section>
+48
View File
@@ -0,0 +1,48 @@
.bar {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
margin: var(--space-4) 0;
}
.message {
background: var(--color-action-hover);
border-left: 3px solid var(--color-action);
padding: var(--space-2) var(--space-3);
}
.values span {
display: inline-block;
font-size: 13px;
margin-right: var(--space-3);
}
h2 {
font-size: 1.05rem;
font-weight: 500;
margin: var(--space-6) 0 var(--space-2);
}
.person {
margin-bottom: var(--space-3);
}
.candidate {
align-items: center;
border-top: 1px solid var(--color-border);
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin-top: var(--space-2);
padding-top: var(--space-2);
}
.candidate > span:first-child {
flex: 1;
min-width: 280px;
}
.small {
width: 160px;
}
+195
View File
@@ -0,0 +1,195 @@
import { HttpErrorResponse } from '@angular/common/http';
import { DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, computed, inject, linkedSignal, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatTabsModule } from '@angular/material/tabs';
import { Api } from '../api/api';
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
import { pipelines } from '../api/fn/ingest/pipelines';
import { startRun } from '../api/fn/ingest/start-run';
import { conflicts } from '../api/fn/review/conflicts';
import { correct } from '../api/fn/review/correct';
import { decidePersons } from '../api/fn/review/decide-persons';
import { held } from '../api/fn/review/held';
import { persons } from '../api/fn/review/persons';
import { reject } from '../api/fn/review/reject';
import { runStatus } from '../api/fn/runs/run-status';
import type { Correction } from '../api/models/correction';
import type { Rejection } from '../api/models/rejection';
type Entity = Rejection['entity'];
type Row = Record<string, unknown>;
const ENTITIES: Record<Entity, string> = {
cervical_cytology: 'Citología cervical',
cervical_biopsy: 'Biopsia cervical',
clinical_note: 'Nota médica',
death: 'Defunción',
identity: 'Identidad',
mammography: 'Mastografía',
breast_biopsy: 'Biopsia de mama',
};
const IDENTITY_FIELDS: Correction['field'][] = [
'record_number',
'full_name',
'curp',
'nss',
'birth_date',
'sex',
'postal_code',
];
/** Bookkeeping columns, not values a reviewer judges. */
const HIDDEN = [
'_pipeline',
'_target',
'_record',
'_held',
'_raw',
'_quotes',
'_index',
'rows_merged',
'known_at',
];
/** /revision: what ingestion held for a person to decide. Every decision is logged and
* applied on the pipeline's next run. */
@Component({
selector: 'app-revision',
imports: [
DecimalPipe,
KeyValuePipe,
FormsModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatTabsModule,
],
templateUrl: './revision.html',
styleUrl: './revision.scss',
})
export class Revision {
private readonly api = inject(Api);
protected readonly entities = Object.entries(ENTITIES) as [Entity, string][];
protected readonly fields = IDENTITY_FIELDS;
protected readonly entity = signal<Entity>('cervical_cytology');
protected readonly held = resource({
params: () => this.entity(),
loader: ({ params }) => this.api.invoke(held, { entity: params }),
});
protected readonly conflicts = resource({
params: () => this.entity(),
loader: ({ params }) => this.api.invoke(conflicts, { entity: params }),
});
/** The pipeline and link node whose persons are reviewed. */
protected readonly pipelines = resource({ loader: () => this.api.invoke(pipelines) });
/** The chosen pipeline; the first one until the reviewer picks another. */
protected readonly pipeline = linkedSignal<string | undefined>(
() => this.pipelines.value()?.[0]?.['pipeline_id'],
);
protected readonly links = resource({
params: () => this.pipeline(),
loader: async ({ params }) => {
if (!params) return [];
const saved = await this.api.invoke(getPipeline, { pipeline_id: params });
return saved.pipeline.nodes.filter((n) => n.kind === 'link').map((n) => n.id);
},
});
protected readonly node = signal<string | undefined>(undefined);
protected readonly link = computed(() => this.node() ?? this.links.value()?.[0]);
protected readonly persons = resource({
params: () => ({ pipeline: this.pipeline(), node: this.link() }),
loader: ({ params }) =>
params.pipeline && params.node
? this.api.invoke(persons, { pipeline: params.pipeline, node: params.node })
: Promise.resolve({ to_settle: [], torn: [] } as Record<string, Row[]>),
});
protected readonly message = signal('');
protected readonly decided = signal(new Set<string>());
protected readonly run = signal<string>('');
protected readonly entityLabel = ENTITIES;
protected values(row: Row): Row {
const raw = (row['_raw'] as Row | undefined) ?? row;
return Object.fromEntries(
Object.entries(raw).filter(([k]) => !HIDDEN.includes(k) && !k.startsWith('_dlt')),
);
}
protected reasons(row: Row): string {
const found = row['_held'];
return Array.isArray(found) ? found.join('; ') : String(found ?? '');
}
protected text(value: unknown): string {
return typeof value === 'object' && value !== null
? JSON.stringify(value)
: String(value ?? '—');
}
protected candidates(entry: Row): Row[] {
return (entry['candidates'] as Row[]) ?? [];
}
protected records(entry: Row): Row[] {
return (entry['records'] as Row[]) ?? [];
}
private async done(key: string, call: Promise<unknown>, what: string): Promise<void> {
try {
await call;
this.decided.update((s) => new Set(s).add(key));
this.message.set(`${what} Se aplica en la siguiente ejecución.`);
} catch (e) {
this.message.set(
e instanceof HttpErrorResponse ? JSON.stringify(e.error?.detail ?? e.message) : String(e),
);
}
}
protected rejectRow(entity: Entity, record: string, reason: string): Promise<void> {
return this.done(
record,
this.api.invoke(reject, { body: { entity, record, reason } }),
'Registro rechazado.',
);
}
protected decide(person: string, candidate: string, same: boolean): Promise<void> {
const body = { person, candidate, same };
return this.done(
`${person}|${candidate}`,
this.api.invoke(decidePersons, { body }),
'Decisión registrada.',
);
}
protected fix(record: string, field: Correction['field'], value: string): Promise<void> {
return this.done(
`${record}|${field}`,
this.api.invoke(correct, { body: { record, field, value } }),
'Corrección registrada.',
);
}
/** Runs the pipeline so the decisions apply, then reloads what is left. */
protected async apply(): Promise<void> {
const id = this.pipeline();
if (!id) return;
const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
let status = 'STARTING';
while (!['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) {
this.run.set(status);
await new Promise((r) => setTimeout(r, 2000));
status = (await this.api.invoke(runStatus, { run_id }))['status'];
}
this.run.set(status);
this.decided.set(new Set());
this.held.reload();
this.conflicts.reload();
this.persons.reload();
}
}
+2 -12
View File
@@ -1,21 +1,11 @@
<!doctype html>
<html lang="en">
<html lang="es">
<head>
<meta charset="utf-8" />
<title>Webapp</title>
<title>ISSSTELEON</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/icon?family=Material+Symbols+Outlined"
rel="stylesheet"
/>
</head>
<body>
<app-root></app-root>
+5
View File
@@ -0,0 +1,5 @@
// The cartesian bundle has plotly.js's API.
declare module 'plotly.js-cartesian-dist-min' {
import Plotly from 'plotly.js';
export default Plotly;
}
+105 -21
View File
@@ -1,39 +1,123 @@
// Include theming for Angular Material with `mat.theme()`.
// This Sass mixin will define CSS variables that are used for styling Angular Material
// components according to the Material 3 design spec.
// Learn more about theming and how to use it for your application's
// custom components at https://material.angular.dev/guide/theming
// The platform's look: Material 3 from the brand seeds (olive primary, teal tertiary),
// Roboto for text and Rajdhani for headings, served from the app (internal network).
@use '@angular/material' as mat;
@use './theme-colors' as brand;
:root {
--color-primary: #a8c243;
--color-text: #081839;
--color-text-secondary: #7a7a7a;
--color-background: #f7f8f6;
--color-surface: #ffffff;
--color-border: #e3e7df;
--color-action: #5f9ea0;
--color-action-hover: #f1f6f6;
--font-body: 'Roboto', sans-serif;
--font-heading: 'Rajdhani', 'Roboto Condensed', sans-serif;
--header-height: 72px;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-6: 24px;
--space-7: 32px;
--radius: 4px;
}
html {
height: 100%;
@include mat.theme(
(
color: (
primary: mat.$azure-palette,
tertiary: mat.$blue-palette,
primary: brand.$primary-palette,
tertiary: brand.$tertiary-palette,
theme-type: light,
),
typography: Roboto,
density: 0,
)
);
// Indicator pages use small corners, as today.
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
}
body {
// Default the application to a light color theme. This can be changed to
// `dark` to enable the dark color theme, or to `light dark` to defer to the
// user's system settings.
color-scheme: light;
// Set a default background, font and text colors for the application using
// Angular Material's system-level CSS variables. Learn more about these
// variables at https://material.angular.dev/guide/system-variables
background-color: var(--mat-sys-surface);
color: var(--mat-sys-on-surface);
font: var(--mat-sys-body-medium);
// Reset the user agent margin.
background: var(--color-background);
color: var(--color-text);
font-family: var(--font-body);
margin: 0;
height: 100%;
min-height: 100%;
}
h1,
h2,
h3 {
font-family: var(--font-body);
color: var(--color-text);
}
.page {
box-sizing: border-box;
margin: 0 auto;
max-width: 1440px;
padding: var(--space-6) clamp(16px, 3.2vw, 48px) var(--space-7);
width: 100%;
}
.page h1 {
font-size: 1.75rem;
font-weight: 500;
margin: 0 0 var(--space-1);
}
.page .subtitle {
color: var(--color-text-secondary);
margin: 0 0 var(--space-4);
}
.muted {
color: var(--color-text-secondary);
}
.card {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
box-sizing: border-box;
padding: var(--space-4);
}
table.plain {
border-collapse: collapse;
width: 100%;
font-size: 14px;
}
table.plain th,
table.plain td {
border-bottom: 1px solid var(--color-border);
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
table.plain th {
color: var(--color-text-secondary);
font-weight: 500;
}
// Cards are white on the light background, as today (no M3 surface tint).
html {
--mat-card-outlined-container-color: var(--color-surface);
--mat-card-elevated-container-color: var(--color-surface);
--mat-card-outlined-outline-color: var(--color-border);
}
.nowrap {
white-space: nowrap;
}
/* You can add global styles to this file, and also import other style files */