From d3f6f5c214d6edcbe860f83b34478cac557f1e84 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?=
Date: Sat, 5 Dec 2026 23:46:51 -0600
Subject: [PATCH] Indicators: CaCu and CaMa pages read by rounds, genotypes and
steps; history to a chosen period; NCI and indicator references; CaMa
follow-up export; API client for eligibility and risk series
---
e2e/cacu.spec.ts | 67 +++-
e2e/pages.spec.ts | 37 +-
openapi.json | 287 +++++++++++++++
src/app/api/fn/fhir/cacu-eligibility.ts | 45 +++
src/app/api/fn/fhir/cacu-reference-risk.ts | 45 +++
src/app/api/fn/fhir/cacu-risk-series.ts | 45 +++
src/app/api/fn/review/conflicts.ts | 2 +-
src/app/api/fn/review/held.ts | 2 +-
src/app/api/fn/runs/rebuild-gold.ts | 33 ++
src/app/api/functions.ts | 60 ++--
src/app/api/models/correction.ts | 2 +-
src/app/api/models/extract.ts | 2 +-
src/app/api/models/fhir.ts | 2 +-
src/app/api/models/rejection.ts | 2 +-
src/app/api/models/target.ts | 2 +-
src/app/indicadores/bars.spec.ts | 59 +++-
src/app/indicadores/bars.ts | 350 +++++++++++++------
src/app/indicadores/cie10.ts | 19 -
src/app/indicadores/figures.ts | 163 +--------
src/app/indicadores/follow-up-sheet.ts | 38 +-
src/app/indicadores/groups.spec.ts | 136 ++++++++
src/app/indicadores/groups.ts | 231 +++++++++++++
src/app/indicadores/history.ts | 216 ++++++++++++
src/app/indicadores/indicadores.ts | 6 +-
src/app/indicadores/labels.ts | 90 +++++
src/app/indicadores/measures.ts | 86 +----
src/app/indicadores/pages-cacu.ts | 306 ++++++++--------
src/app/indicadores/pages-cama.ts | 228 ++++++++++++
src/app/indicadores/pages.ts | 383 ++-------------------
src/app/indicadores/palette-cacu.ts | 69 ++++
src/app/indicadores/readings.html | 132 +++++++
src/app/indicadores/readings.scss | 156 +++++++++
src/app/indicadores/readings.ts | 159 ++-------
src/app/indicadores/section.ts | 130 ++++---
src/app/indicadores/tab-definiciones.ts | 60 +++-
src/app/indicadores/tab-indicadores.html | 36 +-
src/app/indicadores/tab-indicadores.scss | 14 +-
src/app/indicadores/tab-indicadores.ts | 14 +-
src/app/indicadores/tab-riesgos-tea.ts | 2 +-
src/app/indicadores/tab-riesgos.ts | 2 +-
src/app/indicadores/tab-seguimiento.html | 19 +
src/app/indicadores/tab-seguimiento.ts | 59 +++-
src/app/indicadores/tab-trazabilidad.ts | 52 ++-
src/app/paciente/paciente.ts | 2 +-
src/app/revision/revision.ts | 1 +
45 files changed, 2694 insertions(+), 1157 deletions(-)
create mode 100644 src/app/api/fn/fhir/cacu-eligibility.ts
create mode 100644 src/app/api/fn/fhir/cacu-reference-risk.ts
create mode 100644 src/app/api/fn/fhir/cacu-risk-series.ts
create mode 100644 src/app/api/fn/runs/rebuild-gold.ts
delete mode 100644 src/app/indicadores/cie10.ts
create mode 100644 src/app/indicadores/groups.spec.ts
create mode 100644 src/app/indicadores/groups.ts
create mode 100644 src/app/indicadores/history.ts
create mode 100644 src/app/indicadores/labels.ts
create mode 100644 src/app/indicadores/pages-cama.ts
create mode 100644 src/app/indicadores/palette-cacu.ts
create mode 100644 src/app/indicadores/readings.html
create mode 100644 src/app/indicadores/readings.scss
diff --git a/e2e/cacu.spec.ts b/e2e/cacu.spec.ts
index d7ef7c1..f9a8ee2 100644
--- a/e2e/cacu.spec.ts
+++ b/e2e/cacu.spec.ts
@@ -15,20 +15,33 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
- expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
- 'Indicadores de oportunidad',
- 'Tiempos de la ruta del tamizaje',
+ expect(headings.slice(headings.indexOf('Indicadores clínicos'))).toEqual([
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
- 'Pacientes evaluadas por resultado de VPH',
'Tasa de confirmación histopatológica',
- 'Valor predictivo positivo de la colposcopía',
+ 'Tasa de confirmación histopatológica de referencia a colposcopía',
+ 'Indicadores de oportunidad',
+ 'Tiempos de tamizaje',
]);
- const route = tab.locator('app-readings').first();
- for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
+ // one selector reads both the cytology and the HPV card by group
+ await tab.getByRole('radio', { name: 'Por detección inicial y anterior' }).first().click();
+ for (const card of ['Distribución de resultados citológicos', 'Resultados de VPH por genotipo'])
+ await expect(
+ tab
+ .locator('app-readings', { has: page.getByRole('heading', { name: card }) })
+ .locator('section.group')
+ .first(),
+ ).toBeVisible();
+ const route = tab.locator('app-readings').last();
+ for (const mode of [
+ 'Por ventana de tiempo',
+ 'Diagnóstico precolposcópico',
+ 'Diagnóstico tras biopsia',
+ 'Acumulado desde la toma',
+ ]) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
@@ -36,14 +49,48 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
}
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await expect(
- tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
+ tab.getByRole('heading', {
+ name: 'Tasa de confirmación histopatológica de referencia a biopsia',
+ }),
).toBeVisible();
- await tab.getByRole('radio', { name: 'Solicitudes' }).click();
+});
+
+test('indicadores cama: its sections in order, the route chained and the types by BI-RADS', async ({
+ page,
+}) => {
+ await page.goto('/indicadores/cama');
+ const tab = page.locator('app-tab-indicadores');
+ await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
+ await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
+ const headings = await tab
+ .locator('h2, h3')
+ .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
+ expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
+ 'Indicadores de oportunidad',
+ 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
+ 'Tiempo de toma de mastografía a interpretación radiológica',
+ 'Tiempo de interpretación radiológica a diagnóstico',
+ 'Tiempo de interpretación radiológica a resultado de biopsia',
+ 'Tiempo de diagnóstico tras biopsia a tratamiento',
+ 'Tiempo de tamizaje a diagnóstico',
+ 'Tiempo de tamizaje a diagnóstico y tratamiento',
+ 'Indicadores clínicos',
+ expect.stringMatching(/^Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en /),
+ expect.stringMatching(/^Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en /),
+ 'Tipo histológico por categoría BI-RADS',
+ 'Confirmación histopatológica',
+ ]);
+ const types = tab.locator('app-readings', {
+ has: page.getByRole('heading', { name: 'Tipo histológico por categoría BI-RADS' }),
+ });
+ await expect(types.getByRole('columnheader', { name: '% maligno' })).toBeVisible();
+ await tab.getByRole('radio', { name: 'Mastografías con biopsia' }).click();
+ await expect(tab.getByRole('table', { name: 'Con y sin biopsia' })).toBeVisible();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
- await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
+ await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts
index ad8c6db..da62503 100644
--- a/e2e/pages.spec.ts
+++ b/e2e/pages.spec.ts
@@ -65,7 +65,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
- await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
+ await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
@@ -85,13 +85,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
- await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
+ await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea');
- await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
+ await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
expect(problems).toEqual([]);
});
@@ -205,8 +205,8 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', ');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
-// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
-for (const domain of ['cama', 'tea']) {
+// CaCu's (Phase 6) and CaMa's (Phase 7) pages are their own; TEA's follows the old one.
+for (const domain of ['tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
@@ -235,6 +235,28 @@ for (const domain of ['cama', 'tea']) {
});
}
+/** Phase 7's Trazabilidad panels over the old tab's: an old title stands for these. */
+const PANELS: Record> = {
+ cacu: {
+ 'Tiempo de tamizaje a diagnóstico': [
+ 'Tiempo de tamizaje a primer diagnóstico',
+ 'Tiempo de tamizaje a diagnóstico tras biopsia',
+ ],
+ 'Tiempo de diagnóstico a tratamiento': ['Tiempo de diagnóstico tras biopsia a tratamiento'],
+ },
+ cama: {
+ 'Días de la toma de la mastografía a su resultado': [
+ 'Tiempo de diagnóstico tras biopsia a tratamiento',
+ 'Días de la toma de la mastografía a su resultado',
+ ],
+ 'Días de tamizaje a diagnóstico': [
+ 'Tiempo de tamizaje a diagnóstico',
+ 'Tasa de detección histopatológica',
+ ],
+ 'Tasa de confirmación histopatológica': ['Confirmación histopatológica'],
+ },
+};
+
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
@@ -253,7 +275,10 @@ for (const domain of ['cacu', 'cama', 'tea']) {
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
- expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
+ const now = PANELS[domain] ?? {};
+ expect(headings).toEqual(
+ old.filter((i) => i.kind !== 'plot').flatMap((i) => now[i.text] ?? [i.text]),
+ );
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
diff --git a/openapi.json b/openapi.json
index 80693b3..b516d5c 100644
--- a/openapi.json
+++ b/openapi.json
@@ -292,6 +292,7 @@
"default": "identity",
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -443,6 +444,7 @@
"description": "Qu\u00e9 estudio se saca del documento.",
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -465,6 +467,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
+ {
+ "label": "Evidencia cl\u00ednica para elegibilidad CaCu",
+ "value": "cacu_eligibility_evidence"
+ },
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -641,6 +647,7 @@
"entity": {
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -663,6 +670,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
+ {
+ "label": "Evidencia cl\u00ednica para elegibilidad CaCu",
+ "value": "cacu_eligibility_evidence"
+ },
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -1572,6 +1583,7 @@
"entity": {
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -2159,6 +2171,7 @@
"description": "En qu\u00e9 estudio de la plataforma se guarda.",
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -2181,6 +2194,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
+ {
+ "label": "Evidencia cl\u00ednica para elegibilidad CaCu",
+ "value": "cacu_eligibility_evidence"
+ },
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -2832,6 +2849,248 @@
]
}
},
+ "/cacu/fhir/Patient/{id}/$eligibility": {
+ "get": {
+ "description": "Her indexed candidates of each CaCu cohort: eligible, or every reason she is not.",
+ "operationId": "cacu_eligibility",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "title": "Id",
+ "type": "string"
+ }
+ },
+ {
+ "description": "One CaCu scenario (default: every one)",
+ "in": "query",
+ "name": "scenario",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "One CaCu scenario (default: every one)",
+ "title": "Scenario"
+ }
+ },
+ {
+ "description": "Only index dates up to this day",
+ "in": "query",
+ "name": "cutoff",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "date",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Only index dates up to this day",
+ "title": "Cutoff"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/fhir+json": {
+ "schema": {
+ "type": "object"
+ }
+ }
+ },
+ "description": "FHIR"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Cacu Eligibility",
+ "tags": [
+ "fhir"
+ ]
+ }
+ },
+ "/cacu/fhir/Patient/{id}/$reference-risk": {
+ "get": {
+ "description": "Disabled: the NCI series, the master table's included, are in `$risk-series`.",
+ "operationId": "cacu_reference_risk",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "title": "Id",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Only what was reported by this day",
+ "in": "query",
+ "name": "cutoff",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "date",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Only what was reported by this day",
+ "title": "Cutoff"
+ }
+ },
+ {
+ "description": "The cytology's sample day (default: her latest)",
+ "in": "query",
+ "name": "sample",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "date",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The cytology's sample day (default: her latest)",
+ "title": "Sample"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/fhir+json": {
+ "schema": {
+ "type": "object"
+ }
+ }
+ },
+ "description": "FHIR"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Cacu Reference Risk",
+ "tags": [
+ "fhir"
+ ]
+ }
+ },
+ "/cacu/fhir/Patient/{id}/$risk-series": {
+ "get": {
+ "description": "EXPERIMENTAL. The risk series her record can draw: the models' and the NCI tables',\nby outcome, with their published intervals.",
+ "operationId": "cacu_risk_series",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "title": "Id",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Only what was reported by this day",
+ "in": "query",
+ "name": "cutoff",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "date",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Only what was reported by this day",
+ "title": "Cutoff"
+ }
+ },
+ {
+ "description": "The cytology's sample day (default: her latest)",
+ "in": "query",
+ "name": "sample",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "date",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The cytology's sample day (default: her latest)",
+ "title": "Sample"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/fhir+json": {
+ "schema": {
+ "type": "object"
+ }
+ }
+ },
+ "description": "FHIR"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Cacu Risk Series",
+ "tags": [
+ "fhir"
+ ]
+ }
+ },
"/domains": {
"get": {
"operationId": "domains",
@@ -4179,6 +4438,7 @@
"schema": {
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -4287,6 +4547,7 @@
"schema": {
"enum": [
"identity",
+ "cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -4541,6 +4802,32 @@
]
}
},
+ "/runs/rebuild": {
+ "post": {
+ "description": "Starts rebuilding silver and gold with the deployed code (after an upgrade, before any\nnew data); follow it at /runs/{run_id}. The risk tables keep their last scores.",
+ "operationId": "rebuild_gold",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "title": "Response Rebuild Gold",
+ "type": "object"
+ }
+ }
+ },
+ "description": "Successful Response"
+ }
+ },
+ "summary": "Rebuild Gold",
+ "tags": [
+ "runs"
+ ]
+ }
+ },
"/runs/{run_id}": {
"get": {
"operationId": "run_status",
diff --git a/src/app/api/fn/fhir/cacu-eligibility.ts b/src/app/api/fn/fhir/cacu-eligibility.ts
new file mode 100644
index 0000000..0b0f6ae
--- /dev/null
+++ b/src/app/api/fn/fhir/cacu-eligibility.ts
@@ -0,0 +1,45 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
+import { Observable } from 'rxjs';
+import { filter, map } from 'rxjs/operators';
+import { StrictHttpResponse } from '../../strict-http-response';
+import { RequestBuilder } from '../../request-builder';
+
+
+export interface CacuEligibility$Params {
+ id: string;
+
+/**
+ * One CaCu scenario (default: every one)
+ */
+ scenario?: (string | null);
+
+/**
+ * Only index dates up to this day
+ */
+ cutoff?: (string | null);
+}
+
+export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable> {
+ const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
+ if (params) {
+ rb.path('id', params.id, {});
+ rb.query('scenario', params.scenario, {});
+ rb.query('cutoff', params.cutoff, {});
+ }
+
+ return http.request(
+ rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
+ ).pipe(
+ filter((r: any): r is HttpResponse => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse<{
+ }>;
+ })
+ );
+}
+
+cacuEligibility.PATH = '/cacu/fhir/Patient/{id}/$eligibility';
diff --git a/src/app/api/fn/fhir/cacu-reference-risk.ts b/src/app/api/fn/fhir/cacu-reference-risk.ts
new file mode 100644
index 0000000..cf686e3
--- /dev/null
+++ b/src/app/api/fn/fhir/cacu-reference-risk.ts
@@ -0,0 +1,45 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
+import { Observable } from 'rxjs';
+import { filter, map } from 'rxjs/operators';
+import { StrictHttpResponse } from '../../strict-http-response';
+import { RequestBuilder } from '../../request-builder';
+
+
+export interface CacuReferenceRisk$Params {
+ id: string;
+
+/**
+ * Only what was reported by this day
+ */
+ cutoff?: (string | null);
+
+/**
+ * The cytology's sample day (default: her latest)
+ */
+ sample?: (string | null);
+}
+
+export function cacuReferenceRisk(http: HttpClient, rootUrl: string, params: CacuReferenceRisk$Params, context?: HttpContext): Observable> {
+ const rb = new RequestBuilder(rootUrl, cacuReferenceRisk.PATH, 'get');
+ if (params) {
+ rb.path('id', params.id, {});
+ rb.query('cutoff', params.cutoff, {});
+ rb.query('sample', params.sample, {});
+ }
+
+ return http.request(
+ rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
+ ).pipe(
+ filter((r: any): r is HttpResponse => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse<{
+ }>;
+ })
+ );
+}
+
+cacuReferenceRisk.PATH = '/cacu/fhir/Patient/{id}/$reference-risk';
diff --git a/src/app/api/fn/fhir/cacu-risk-series.ts b/src/app/api/fn/fhir/cacu-risk-series.ts
new file mode 100644
index 0000000..e988c62
--- /dev/null
+++ b/src/app/api/fn/fhir/cacu-risk-series.ts
@@ -0,0 +1,45 @@
+/* eslint-disable */
+/* Code generated by ng-openapi-gen DO NOT EDIT. */
+
+import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
+import { Observable } from 'rxjs';
+import { filter, map } from 'rxjs/operators';
+import { StrictHttpResponse } from '../../strict-http-response';
+import { RequestBuilder } from '../../request-builder';
+
+
+export interface CacuRiskSeries$Params {
+ id: string;
+
+/**
+ * Only what was reported by this day
+ */
+ cutoff?: (string | null);
+
+/**
+ * The cytology's sample day (default: her latest)
+ */
+ sample?: (string | null);
+}
+
+export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable> {
+ const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
+ if (params) {
+ rb.path('id', params.id, {});
+ rb.query('cutoff', params.cutoff, {});
+ rb.query('sample', params.sample, {});
+ }
+
+ return http.request(
+ rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
+ ).pipe(
+ filter((r: any): r is HttpResponse => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse<{
+ }>;
+ })
+ );
+}
+
+cacuRiskSeries.PATH = '/cacu/fhir/Patient/{id}/$risk-series';
diff --git a/src/app/api/fn/review/conflicts.ts b/src/app/api/fn/review/conflicts.ts
index db06c9b..1e28c7c 100644
--- a/src/app/api/fn/review/conflicts.ts
+++ b/src/app/api/fn/review/conflicts.ts
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params {
- entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
+ entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable> {
+ const rb = new RequestBuilder(rootUrl, rebuildGold.PATH, 'post');
+ if (params) {
+ }
+
+ return http.request(
+ rb.build({ responseType: 'json', accept: 'application/json', context })
+ ).pipe(
+ filter((r: any): r is HttpResponse => r instanceof HttpResponse),
+ map((r: HttpResponse) => {
+ return r as StrictHttpResponse<{
+ [key: string]: string;
+ }>;
+ })
+ );
+}
+
+rebuildGold.PATH = '/runs/rebuild';
diff --git a/src/app/api/functions.ts b/src/app/api/functions.ts
index bbb8c19..41326c7 100644
--- a/src/app/api/functions.ts
+++ b/src/app/api/functions.ts
@@ -5,6 +5,38 @@ export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
+export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
+export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
+export type { CacuReferenceRisk$Params as CacuReferenceRisk$Params } from './fn/fhir/cacu-reference-risk';
+export { cacuReferenceRisk as cacuReferenceRisk } from './fn/fhir/cacu-reference-risk';
+export type { CacuRiskSeries$Params as CacuRiskSeries$Params } from './fn/fhir/cacu-risk-series';
+export { cacuRiskSeries as cacuRiskSeries } from './fn/fhir/cacu-risk-series';
+export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
+export { postBundle as postBundle } from './fn/fhir/post-bundle';
+export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
+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 { SearchEncounter$Params as SearchEncounter$Params } from './fn/fhir/search-encounter';
+export { searchEncounter as searchEncounter } from './fn/fhir/search-encounter';
+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';
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
@@ -77,6 +109,8 @@ export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject';
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
export { unrecognised as unrecognised } from './fn/review/unrecognised';
+export type { RebuildGold$Params as RebuildGold$Params } from './fn/runs/rebuild-gold';
+export { rebuildGold as rebuildGold } from './fn/runs/rebuild-gold';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
@@ -97,29 +131,3 @@ export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/user
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
-export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
-export { postBundle as postBundle } from './fn/fhir/post-bundle';
-export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
-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 { SearchEncounter$Params as SearchEncounter$Params } from './fn/fhir/search-encounter';
-export { searchEncounter as searchEncounter } from './fn/fhir/search-encounter';
-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';
diff --git a/src/app/api/models/correction.ts b/src/app/api/models/correction.ts
index bf2543d..30f9d30 100644
--- a/src/app/api/models/correction.ts
+++ b/src/app/api/models/correction.ts
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
- entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
+ entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
diff --git a/src/app/api/models/extract.ts b/src/app/api/models/extract.ts
index 56b7cd5..cccf522 100644
--- a/src/app/api/models/extract.ts
+++ b/src/app/api/models/extract.ts
@@ -25,7 +25,7 @@ export interface Extract {
/**
* Qué estudio se saca del documento.
*/
- entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
+ entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
diff --git a/src/app/api/models/fhir.ts b/src/app/api/models/fhir.ts
index 53d2d6d..4ac5d3c 100644
--- a/src/app/api/models/fhir.ts
+++ b/src/app/api/models/fhir.ts
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
- entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
+ entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array;
kind?: 'fhir';
diff --git a/src/app/api/models/rejection.ts b/src/app/api/models/rejection.ts
index d71f3f5..8152278 100644
--- a/src/app/api/models/rejection.ts
+++ b/src/app/api/models/rejection.ts
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection {
- entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
+ entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
diff --git a/src/app/api/models/target.ts b/src/app/api/models/target.ts
index d06856c..4decb86 100644
--- a/src/app/api/models/target.ts
+++ b/src/app/api/models/target.ts
@@ -12,7 +12,7 @@ export interface Target {
/**
* En qué estudio de la plataforma se guarda.
*/
- entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
+ entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array;
kind?: 'target';
diff --git a/src/app/indicadores/bars.spec.ts b/src/app/indicadores/bars.spec.ts
index 79b264d..e24e3b8 100644
--- a/src/app/indicadores/bars.spec.ts
+++ b/src/app/indicadores/bars.spec.ts
@@ -1,6 +1,9 @@
-import { bars } from './bars';
+import { bars, Mode } from './bars';
import { Reading } from './measures';
+const read = (r: Reading) => () => r;
+const cells = (mode: Mode, r: Reading) => bars(mode, read(r))!.rows.map((x) => x.cells);
+
describe('bars', () => {
it('list every category, so the shares add up', () => {
const r: Reading = {
@@ -10,18 +13,60 @@ describe('bars', () => {
},
};
const catalog = [{ code: 'a', label: 'A', color: '#000' }];
- const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
- expect(t.rows.map((x) => x.cells)).toEqual([
+ expect(cells({ kind: 'counts', label: 'x', measure: 'M', catalog }, r)).toEqual([
['3', '75.0 %'],
['1', '25.0 %'],
]);
});
- it('a group with no patients has no rate', () => {
+ it('add up an aggregate after the first row and indent its parts', () => {
const r: Reading = {
populations: {},
- strata: { s: { initial: { numerator: 0, denominator: 0 } } },
+ strata: {
+ category: {
+ n: { 'initial-population': 6 },
+ a: { 'initial-population': 3 },
+ b: { 'initial-population': 1 },
+ },
+ },
};
- const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
- expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
+ const catalog = ['n', 'a', 'b'].map((code) => ({ code, label: code, color: '#000' }));
+ const aggregate = { label: 'Anormal', color: '#f00', codes: ['a', 'b'] };
+ const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, read(r))!;
+ expect(t.rows.map((x) => [x.label, x.cells[0], !!x.sub])).toEqual([
+ ['n', '6', false],
+ ['Anormal', '4', false],
+ ['a', '3', true],
+ ['b', '1', true],
+ ]);
+ });
+ it('draw a proportion with its interval as marks', () => {
+ const r: Reading = {
+ populations: { numerator: 51, denominator: 70 },
+ strata: {},
+ score: 0.729,
+ low: 0.615,
+ high: 0.819,
+ };
+ const t = bars({ kind: 'ratio', label: 'Total', measure: 'M' }, read(r))!;
+ expect(t.rows[0].cells).toEqual(['51/70', '72.9 %', '61.5 %–81.9 %']);
+ expect(t.rows[0].marks.map(Math.round)).toEqual([62, 82]);
+ });
+ it('stagger steps from where the step they follow ends', () => {
+ const at: Record = {
+ A: { populations: { 'measure-observation': 3 }, strata: {}, score: 10 },
+ B: { populations: { 'measure-observation': 2 }, strata: {}, score: 30 },
+ C: { populations: { 'measure-observation': 1 }, strata: {}, score: 20 },
+ };
+ const steps = [
+ { label: 'a', measure: 'A' },
+ { label: 'b', measure: 'B' },
+ { label: 'c', measure: 'C', after: 0 },
+ { label: 'd', measure: 'D' },
+ ];
+ const mode: Mode = { kind: 'days', label: 'x', steps, staggered: true, scale: true };
+ const t = bars(mode, (m) => at[m])!;
+ expect(t.rows.map((x) => x.offset)).toEqual([0, 25, 25, undefined]);
+ expect(t.rows[3].none).toBe('Sin mediciones en el periodo');
+ expect(t.note).toBe('Escala: 0 a 40 días.');
});
});
diff --git a/src/app/indicadores/bars.ts b/src/app/indicadores/bars.ts
index 5bfba09..6b49f31 100644
--- a/src/app/indicadores/bars.ts
+++ b/src/app/indicadores/bars.ts
@@ -1,145 +1,291 @@
-import { CIE10 } from './cie10';
-import { name, Reading } from './measures';
+import { name } from './labels';
+import { Reading } from './measures';
+import { NEUTRAL_DARK } from './palette-cacu';
/** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string };
+/** A colour by code (the category decides it, never its place in the report). */
+export type Colors = Record;
+/** Categories a card leaves out of its rows: their records stay in its total and its shares. */
+export type Hidden = { codes: string[]; unit: string };
+/** A row adding up some categories, drawn after the first one; those are indented under it. */
+export type Aggregate = { label: string; color: string; codes: string[] };
+/** A step of a route; staggered, it starts where step `after` (by default, the previous) ends. */
+export type Step = { label: string; measure: string; after?: number };
+export type Read = (measure: string) => Reading | undefined;
-/** One way of reading a card, as bars from the reports, or a figure. */
-export type Mode = { label: string; caption?: string } & (
- | { kind: 'counts'; measure: string; catalog: Category[] }
- | { kind: 'shares'; measure: string; stratum: string; order: string[] }
- | { kind: 'positives'; measure: string; stratum: string; order: string[] }
- | { kind: 'signs'; measure: string; strata: string[] }
- | { kind: 'days'; steps: { label: string; measure: string }[] }
- | { kind: 'days-by'; measure: string; stratum: string }
- | { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] }
+/** One way of reading a card: the bars of a table, or groups of bars (`grouped`). */
+export type Mode = {
+ label: string;
+ caption?: string;
+ /** said above the table: what its rows count */
+ heading?: string;
+ /** the header of the rows' names */
+ rowsLabel?: string;
+} & (
+ | {
+ kind: 'counts';
+ measure: string;
+ catalog: Category[];
+ aggregate?: Aggregate;
+ unit?: string;
+ percentLabel?: string;
+ hidden?: Hidden;
+ /** every bar on 0 to 100 % of the total, its length the share shown */
+ percent?: boolean;
+ }
+ | {
+ /** a proportion by group; `complete`: every group of `order`, those left out as zero
+ * when the listed ones add up to every patient (see `reconciles`) */
+ kind: 'shares';
+ measure: string;
+ stratum: string;
+ order: string[];
+ complete?: boolean;
+ colors?: Colors;
+ percentLabel?: string;
+ }
+ | {
+ /** per group (`-category` cells), an independent bar per category */
+ kind: 'grouped';
+ measure: string;
+ catalog: Category[];
+ aggregate?: Aggregate;
+ stratum: string;
+ order: string[];
+ unit: string;
+ complete?: boolean;
+ /** a group's denominator is all its records, not only its categories' */
+ ofAll?: boolean;
+ hidden?: Hidden;
+ }
+ | { kind: 'days'; steps: Step[]; tint?: Tint; staggered?: boolean; scale?: boolean }
+ /** a proportion as one bar of 0 to 100 %, its 95 % interval the two marks */
+ | { kind: 'ratio'; measure: string; color?: string; percentLabel?: string }
+ /** a proportion as its two parts, what counted and what did not */
+ | {
+ kind: 'split';
+ measure: string;
+ yes: string;
+ no: string;
+ colors: [string, string];
+ unit: string;
+ percentLabel: string;
+ }
+ /** each row's units by result, in segments, and the malignant share of those with a grade
+ * (read from `malignancy`); the results are the period's, then `results` */
+ | {
+ kind: 'outcomes';
+ measure: string;
+ stratum: string;
+ rows: Category[];
+ results: Category[];
+ malignant: string[];
+ malignancy: string;
+ }
);
+export type Tint = { bar: string; mark: string };
-/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
+/** One bar: its start, length and marks in % of the scale, and its cells of text. */
export interface Bar {
label: string;
+ /** indented under the aggregate above it */
+ sub?: boolean;
+ /** why the row has no figures */
+ hint?: string;
color?: string;
+ offset?: number;
width: number;
marks: number[];
cells: string[];
+ /** the bar in parts, each with what it says when hovered */
+ segments?: { width: number; color: string; title: string }[];
+ /** said in place of the bar */
+ none?: string;
}
export interface Bars {
head: string[];
rows: Bar[];
+ markColor?: string;
+ /** what the reader must know to take the rows right */
+ note?: string;
+ legend?: { label: string; color: string }[];
}
-const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
-const size = (cell?: Record) => cell?.['initial-population'] ?? 0;
+export const NOT_AVAILABLE = 'No disponible';
+export const NO_PATIENTS = 'Sin pacientes en el periodo';
+export const NO_ROUND =
+ 'Ninguna paciente del periodo tiene clasificación de detección inicial o anterior: los ' +
+ 'grupos en cero reflejan información no registrada, no ausencia de pacientes.';
+
+export const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
+export const size = (cell?: Record) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
+export const whole = (n: unknown): n is number =>
+ typeof n === 'number' && Number.isInteger(n) && n >= 0;
+
+/** The patients of a reading: its cohort, or a proportion's denominator. */
+export const patients = (r?: Reading) =>
+ r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
+
+/** A group the report leaves out is zero only when the listed groups add up to every record
+ * (the report omits empty groups); otherwise it is not available. */
+export const reconciles = (listed: number[], total: number) =>
+ listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
+
+/** What a card says of the categories it does not draw, when the period has any. */
+export function hiddenNote(mode: Mode, read: Read): string | undefined {
+ if (!('hidden' in mode) || !mode.hidden) return undefined;
+ const cells = read(mode.measure)?.strata['category'] ?? {};
+ const found = mode.hidden.codes.filter((c) => size(cells[c]));
+ const n = found.reduce((t, c) => t + size(cells[c]), 0);
+ if (!n) return undefined;
+ const [unit, words] =
+ n === 1
+ ? [mode.hidden.unit.replace(/s$/, ''), 'no se muestra desglosado; está incluido']
+ : [mode.hidden.unit, 'no se muestran desglosados; están incluidos'];
+ return `${n} ${unit} (${found.map(name).join(', ')}) ${words} en el total y en los porcentajes.`;
+}
+
+/** Rows with an aggregate's row after the first, its parts marked by `sub`. */
+export function withAggregate(
+ rows: T[],
+ codes: string[],
+ aggregate: Aggregate | undefined,
+ sum: () => T,
+ sub: (row: T) => T,
+): T[] {
+ if (!aggregate || !rows.length) return rows;
+ const marked = rows.map((row, i) => (aggregate.codes.includes(codes[i]) ? sub(row) : row));
+ return [marked[0], sum(), ...marked.slice(1)];
+}
/** The bars of a mode; none when the period has nothing to draw. */
-export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
+export function bars(mode: Mode, read: Read): Bars | undefined {
switch (mode.kind) {
- case 'counts': {
- const cells = of(mode.measure)?.strata['category'] ?? {};
- const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
- if (!total) return undefined;
- // a category outside the catalog is listed after it, so the shares add up
- const named = mode.catalog.map((c) => c.code);
- const rest = Object.keys(cells).filter((c) => !named.includes(c));
- const all = [
- ...mode.catalog,
- ...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
- ];
- const most = Math.max(...Object.values(cells).map(size));
+ case 'counts':
+ return counts(mode, read);
+ case 'ratio': {
+ const r = read(mode.measure);
+ const { numerator: n = 0, denominator: total = 0 } = r?.populations ?? {};
+ if (r?.score === undefined || !total) return undefined;
+ const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
+ const cells = [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'];
return {
- head: ['n', '%'],
- rows: all.map(({ code, label, color }) => {
- const n = size(cells[code]);
- const cols = [`${n}`, pct(n, total)];
- return { label, color, width: (100 * n) / most, marks: [], cells: cols };
- }),
+ head: ['n/N', mode.percentLabel ?? 'Porcentaje', 'IC 95 %'],
+ rows: [
+ {
+ label: 'Total',
+ color: mode.color,
+ width: 100 * r.score,
+ cells,
+ marks: ends.map((v) => 100 * v),
+ },
+ ],
};
}
- case 'shares': {
- const cells = of(mode.measure)?.strata[mode.stratum] ?? {};
- return ratios(
- mode.order
- .filter((c) => cells[c])
- .map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]),
- );
- }
- case 'positives': {
- const cells = of(mode.measure)?.strata[`${mode.stratum}-category`] ?? {};
- const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
- return ratios(
- mode.order
- .filter((c) => found.has(c))
- .map((c) => {
- const positive = size(cells[`${c}|positive`]);
- return [name(c), positive, positive + size(cells[`${c}|negative`])];
- }),
- );
- }
- case 'signs': {
- const strata = of(mode.measure)?.strata ?? {};
- return ratios(
- mode.strata
- .filter((s) => Object.keys(strata[s] ?? {}).length)
- .map((s) => {
- const positive = size(strata[s]['positive']);
- return [name(s), positive, positive + size(strata[s]['negative'])];
- }),
- );
+ case 'split': {
+ const { numerator: n = 0, denominator: total = 0 } = read(mode.measure)?.populations ?? {};
+ if (!total) return undefined;
+ return {
+ head: [mode.unit, mode.percentLabel],
+ rows: (
+ [
+ [mode.yes, n],
+ [mode.no, total - n],
+ ] as const
+ ).map(([label, k], i) => ({
+ label,
+ color: mode.colors[i],
+ width: (100 * k) / total,
+ marks: [],
+ cells: [`${k}`, pct(k, total)],
+ })),
+ };
}
case 'days':
- return medians(
- mode.steps.map(({ label, measure }) => {
- const r = of(measure);
- return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
- }),
- );
- case 'days-by': {
- const r = of(mode.measure);
- const cells = r?.strata[mode.stratum] ?? {};
- return medians(
- Object.keys(cells)
- .map((c) => ({
- label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
- n: cells[c]['measure-observation'] ?? 0,
- score: r?.scores?.[mode.stratum]?.[c],
- }))
- .sort((a, b) => b.n - a.n),
- );
- }
+ return medians(mode, read);
default:
return undefined;
}
}
-function ratios(rows: [string, number, number][]): Bars | undefined {
- if (!rows.length) return undefined;
+function counts(mode: Extract, read: Read): Bars | undefined {
+ const cells = read(mode.measure)?.strata['category'] ?? {};
+ const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
+ if (!total) return undefined;
+ // a category outside the catalog is listed after it, so the shares add up
+ const hidden = mode.hidden?.codes ?? [];
+ const named = mode.catalog.map((c) => c.code);
+ const all = [
+ ...mode.catalog.filter((c) => !hidden.includes(c.code)),
+ ...Object.keys(cells)
+ .filter((c) => !named.includes(c) && !hidden.includes(c))
+ .map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
+ ];
+ const scale = mode.percent ? total : Math.max(...Object.values(cells).map(size));
+ const row = (label: string, n: number, color?: string): Bar => ({
+ label,
+ color,
+ width: (100 * n) / scale,
+ marks: [],
+ cells: [`${n}`, pct(n, total)],
+ });
+ const a = mode.aggregate;
+ const summed = () =>
+ row(
+ a!.label,
+ a!.codes.reduce((t, c) => t + size(cells[c]), 0),
+ a!.color,
+ );
return {
- head: ['n/N', '%'],
- rows: rows.map(([label, n, total]) => ({
- label,
- width: total ? (100 * n) / total : 0,
- marks: [],
- cells: [`${n}/${total}`, pct(n, total)],
- })),
+ head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
+ rows: withAggregate(
+ all.map((c) => row(c.label, size(cells[c.code]), c.color)),
+ all.map((c) => c.code),
+ a,
+ summed,
+ (r) => ({ ...r, sub: true }),
+ ),
+ note: hiddenNote(mode, read),
};
}
-type Score = { score?: number; low?: number; high?: number };
-function medians(rows: { label: string; n: number; score?: Score }[]): Bars | undefined {
- if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
- const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
+/** Median days per step, with their quartiles; staggered, each from where its step ends. */
+function medians(mode: Extract, read: Read): Bars | undefined {
+ const found = mode.steps.map((s) => read(s.measure));
+ if (!found.some((r) => r?.score !== undefined)) return undefined;
+ const starts: number[] = [];
+ mode.steps.forEach(({ after }, i) => {
+ const j = after ?? i - 1;
+ starts.push(mode.staggered && j >= 0 ? starts[j] + (found[j]?.score ?? 0) : 0);
+ });
+ const top =
+ Math.max(...found.map((r, i) => starts[i] + Math.max(r?.score ?? 0, r?.high ?? 0))) || 1;
const at = (v: number) => (100 * v) / top;
return {
- head: ['Mediana', 'n', 'Q1–Q3'],
- rows: rows.map(({ label, n, score: s }) => {
- if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
- const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
+ head: ['Mediana', 'Observaciones', 'Q1–Q3'],
+ markColor: mode.tint?.mark,
+ note: mode.scale ? `Escala: 0 a ${days(top)} días.` : undefined,
+ rows: mode.steps.map(({ label }, i) => {
+ const r = found[i];
+ const n = `${r?.populations['measure-observation'] ?? 0}`;
+ if (r?.score === undefined)
+ return {
+ label,
+ width: 0,
+ marks: [],
+ none: 'Sin mediciones en el periodo',
+ cells: ['—', n, '—'],
+ };
+ const spread = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return {
label,
- width: at(s.score),
- marks: spread.map(at),
- cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
+ color: mode.tint?.bar,
+ offset: mode.staggered ? at(starts[i]) : undefined,
+ width: at(r.score),
+ marks: spread.map((v) => at(starts[i] + v)),
+ cells: [`${days(r.score)} días`, n, spread.map(days).join('–') || '—'],
};
}),
};
diff --git a/src/app/indicadores/cie10.ts b/src/app/indicadores/cie10.ts
deleted file mode 100644
index 42677e8..0000000
--- a/src/app/indicadores/cie10.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
-export const CIE10: Record = {
- Z014: 'Examen ginecológico',
- Z124: 'Pesquisa de tumor del cuello uterino',
- B977: 'Papilomavirus',
- R876: 'Citología cervical anormal',
- N870: 'Displasia cervical leve',
- N871: 'Displasia cervical moderada',
- N872: 'Displasia cervical severa',
- N879: 'Displasia cervical no especificada',
- D060: 'Carcinoma in situ del endocérvix',
- D061: 'Carcinoma in situ del exocérvix',
- D067: 'Carcinoma in situ de otras partes del cuello',
- D069: 'Carcinoma in situ del cuello',
- C530: 'Cáncer del endocérvix',
- C531: 'Cáncer del exocérvix',
- C538: 'Cáncer de sitios contiguos del cuello',
- C539: 'Cáncer del cuello uterino',
-};
diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts
index 88596dc..7426ea6 100644
--- a/src/app/indicadores/figures.ts
+++ b/src/app/indicadores/figures.ts
@@ -1,6 +1,8 @@
import { type Figure, PALETTE } from '../plot';
-import { name, type Reading } from './measures';
-import type { Catalog, Category, HistoryPanel } from './pages';
+import { name } from './labels';
+import { type Reading } from './measures';
+import type { HistoryPanel } from './history';
+import type { Catalog, Category } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
@@ -17,79 +19,6 @@ function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
-/** Groups inside, their categories outside, the total in the centre. */
-export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
- const values = catalog.categories.map((c) => counted(r, c.code));
- const total = values.reduce((a, b) => a + b, 0);
- const groups = catalog.groups.map((g) =>
- catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
- );
- const faded = new Set(catalog.faded ?? []);
- const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
- const common = {
- type: 'pie',
- sort: false,
- direction: 'clockwise',
- rotation: 0,
- showlegend: false,
- textinfo: 'text',
- textposition: 'inside',
- insidetextorientation: 'horizontal',
- };
- return {
- data: [
- {
- ...common,
- name: 'centro',
- values: [1],
- labels: ['centro'],
- domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
- text: [`${count(total)} ${center}`],
- marker: { colors: ['#FFFFFF'] },
- hoverinfo: 'skip',
- },
- {
- ...common,
- name: 'grupos',
- values: groups,
- labels: catalog.groups.map((g) => g.label),
- hole: 0.62,
- domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
- text: groups.map((n, i) =>
- total && n / total >= 0.05 ? `${catalog.groups[i].label} ${share(n)}` : '',
- ),
- marker: {
- colors: catalog.groups.map((g) =>
- rgba(
- g.color,
- catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
- ),
- ),
- line: { color: '#FFFFFF', width: 2 },
- },
- hovertemplate: '%{label} %{value} (%{percent}) ',
- },
- {
- ...common,
- name: 'categorias',
- values,
- labels: catalog.categories.map((c) => c.label),
- hole: 0.74,
- domain: { x: [0, 1], y: [0, 1] },
- // along the thin ring, so a label fits its slice
- insidetextorientation: 'tangential',
- text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
- marker: {
- colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
- line: { color: '#FFFFFF', width: 2 },
- },
- hovertemplate: '%{label} %{value} (%{percent}) ',
- },
- ] as Partial[],
- layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
- };
-}
-
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars(
r: Reading,
@@ -134,86 +63,6 @@ export function scenarioBars(
};
}
-/** Wilson score interval at 95 %, in percent. */
-export function wilson(k: number, n: number): [number, number] {
- const z = 1.959963984540054;
- const p = k / n;
- const d = 1 + (z * z) / n;
- const c = (p + (z * z) / (2 * n)) / d;
- const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
- return [100 * (c - h), 100 * (c + h)];
-}
-
-/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
- * with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
-export function rateDots(
- r: Reading,
- spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
-): Figure {
- const cells = r.strata[`${spec.stratum}-category`] ?? {};
- const rows = spec.rows.map((row) => {
- const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
- const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
- const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
- const k = biopsied
- .filter(([key]) => spec.positive.includes(key.split('|')[1]))
- .reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
- const rate = den ? (100 * k) / den : null;
- const [low, high] = den ? wilson(k, den) : [null, null];
- return { row, k, den, rate, low, high };
- });
- const y = rows.map((x) => x.row.label);
- return {
- data: [
- {
- type: 'scatter',
- mode: 'markers',
- name: 'tasas',
- y,
- x: rows.map((x) => x.rate),
- marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
- cliponaxis: false,
- error_x: {
- type: 'data',
- symmetric: false,
- color: ROSE,
- thickness: 2,
- width: 6,
- array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
- arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
- },
- hovertemplate: '%{y}: %{x:.1f} % ',
- } as Partial,
- ],
- layout: {
- showlegend: false,
- margin: { t: 24, r: 110, b: 56, l: 56 },
- yaxis: {
- type: 'category',
- categoryorder: 'array',
- categoryarray: [...y].reverse(),
- automargin: true,
- },
- xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
- annotations: rows.map((x) => ({
- x: 1,
- xref: 'paper',
- xanchor: 'left',
- xshift: 8,
- y: x.row.label,
- yref: 'y',
- showarrow: false,
- align: 'left',
- text: x.den
- ? `${percent(x.rate!)} % ${x.k}/${x.den}`
- : spec.colored
- ? 'Sin pacientes'
- : 'Sin biopsias',
- })),
- },
- };
-}
-
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
@@ -275,9 +124,9 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
- texttemplate: values.map((v) => (v ? '%{label} %{percent}' : '')),
+ texttemplate: values.map((v) => (v ? `%{label} %{percent} del total de ${center}` : '')),
textposition: 'outside',
- hovertemplate: '%{label} %{value} (%{percent}) ',
+ hovertemplate: `%{label} %{value} (%{percent} del total de ${center}) `,
} as Partial,
],
layout: {
diff --git a/src/app/indicadores/follow-up-sheet.ts b/src/app/indicadores/follow-up-sheet.ts
index 9b0c45b..a9ada30 100644
--- a/src/app/indicadores/follow-up-sheet.ts
+++ b/src/app/indicadores/follow-up-sheet.ts
@@ -1,7 +1,7 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
-import type { Row } from './follow-up';
-import { name } from './measures';
+import type { CamaRow, Row } from './follow-up';
+import { name } from './labels';
const NONE = 'No disponible';
const HEAD = [
@@ -24,6 +24,40 @@ export function cytologyResult(c: NonNullable): string {
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
+/** CaMa's follow-up list as a table to save: what the page shows, a missing value said so. */
+export function camaFollowUpSheet(
+ rows: CamaRow[],
+ query: [string, string][],
+ priority: (code: string) => string,
+): Sheet {
+ return {
+ title: 'Resultados de seguimiento de cáncer de mama',
+ query: [...query, ['Registros', `${rows.length}`]],
+ head: [
+ 'Paciente',
+ 'CURP',
+ 'Grupo de edad',
+ 'Última mastografía (BI-RADS)',
+ 'Fecha de la mastografía',
+ 'Última biopsia',
+ 'Fecha de reporte de la biopsia',
+ 'Estatus de seguimiento',
+ 'Prioridad',
+ ],
+ rows: rows.map((r) => [
+ r.name ?? r.patient.id!.slice(0, 10),
+ r.curp ?? NONE,
+ r.ageGroup || NONE,
+ (r.mammogram.birads && name(r.mammogram.birads)) || 'Sin dato',
+ r.mammogram.date || NONE,
+ r.biopsy ? name(r.biopsy.histology ?? '') || 'Sin resultado' : NONE,
+ r.biopsy?.date ?? NONE,
+ name(r.status),
+ priority(r.priority) || NONE,
+ ]),
+ };
+}
+
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */
diff --git a/src/app/indicadores/groups.spec.ts b/src/app/indicadores/groups.spec.ts
new file mode 100644
index 0000000..833171f
--- /dev/null
+++ b/src/app/indicadores/groups.spec.ts
@@ -0,0 +1,136 @@
+import { Mode, NO_PATIENTS, NOT_AVAILABLE } from './bars';
+import { grouped, outcomes, shares, unavailable } from './groups';
+import { Reading } from './measures';
+
+const read = (r: Reading) => () => r;
+const cell = (n: number) => ({ 'initial-population': n });
+const catalog = [
+ { code: 'NILM', label: 'Normal', color: '#0f0' },
+ { code: 'HSIL', label: 'LIEAG', color: '#f00' },
+];
+
+describe('shares', () => {
+ const mode: Mode = {
+ kind: 'shares',
+ label: 'Ronda',
+ measure: 'M',
+ stratum: 'round',
+ order: ['initial', 'subsequent', 'no_data'],
+ complete: true,
+ };
+ it('a group with no patients has no rate', () => {
+ const r: Reading = {
+ populations: { denominator: 0 },
+ strata: { round: { initial: { numerator: 0, denominator: 0 } } },
+ };
+ const plain = { ...mode, complete: false } as Mode;
+ expect(shares(plain, read(r))!.rows[0].cells).toEqual(['0/0', '—']);
+ });
+ it('draw a group left out as zero only when the listed ones add up', () => {
+ const listed = { initial: { numerator: 1, denominator: 4 } };
+ const whole = shares(
+ mode,
+ read({ populations: { denominator: 4 }, strata: { round: listed } }),
+ )!;
+ expect(whole.rows[1]).toMatchObject({ hint: NO_PATIENTS, cells: ['0/0', '—'] });
+ const short = shares(
+ mode,
+ read({ populations: { denominator: 5 }, strata: { round: listed } }),
+ )!;
+ expect(short.rows[1]).toMatchObject({ hint: NOT_AVAILABLE, cells: ['—', '—'] });
+ expect(short.note).toContain('no concilian');
+ });
+ it('say when the report does not break the period down', () => {
+ const r: Reading = { populations: { denominator: 4 }, strata: {} };
+ expect(unavailable(mode, read(r))).toContain('no publica el desglose «Ronda»');
+ });
+});
+
+describe('grouped', () => {
+ const mode: Mode = {
+ kind: 'grouped',
+ label: 'Por ronda',
+ measure: 'CACU_EU7',
+ catalog,
+ stratum: 'round',
+ order: ['initial', 'subsequent', 'no_data'],
+ unit: 'pacientes',
+ complete: true,
+ ofAll: true,
+ };
+ it('split the subsequent round by the last screening, each group over its own', () => {
+ const r: Reading = {
+ populations: { 'initial-population': 5 },
+ strata: {
+ 'round-category': {
+ 'initial|NILM': cell(1),
+ 'subsequent|NILM': cell(2),
+ 'subsequent|HSIL': cell(2),
+ },
+ 'subsequent_history-category': {
+ 'within_1_year|NILM': cell(2),
+ '2_years|HSIL': cell(1),
+ '3_or_more_years|HSIL': cell(1),
+ },
+ },
+ };
+ const g = grouped(mode, read(r))!;
+ expect(g.groups.map((x) => [x.code, x.total])).toEqual([
+ ['initial', 1],
+ ['within_1_year', 2],
+ ['2_years', 1],
+ ['3_or_more_years', 1],
+ ['no_data', 0],
+ ]);
+ expect(g.groups[1].label).toBe('Detección anterior hace un año o menos');
+ expect(g.groups[2].rows.map((x) => x.text)).toEqual(['0/1 · 0.0 %', '1/1 · 100.0 %']);
+ expect(g.groups[4].hint).toBe('Sin pacientes en el grupo');
+ });
+ it('name the youngest results group from 15', () => {
+ const r: Reading = {
+ populations: { 'initial-population': 1 },
+ strata: { 'age_group-category': { '<25|NILM': cell(1) } },
+ };
+ const byAge = { ...mode, stratum: 'age_group', order: ['<25'] } as Mode;
+ expect(grouped(byAge, read(r))!.groups[0].label).toBe('15-24');
+ });
+});
+
+describe('outcomes', () => {
+ it('segment each row by result and give the malignant share of the graded', () => {
+ const types: Reading = {
+ populations: {},
+ strata: {
+ category: { '8500/3': cell(1), no_biopsy: cell(1) },
+ birads: { '5': cell(2), '4A': cell(0) },
+ 'birads-category': { '5|8500/3': cell(1), '5|no_biopsy': cell(1) },
+ },
+ };
+ const grades: Reading = {
+ populations: {},
+ strata: { 'birads-category': { '5|invasive': cell(1), '5|no_biopsy': cell(1) } },
+ };
+ const mode: Mode = {
+ kind: 'outcomes',
+ label: 'x',
+ measure: 'T',
+ stratum: 'birads',
+ rows: [
+ { code: '5', label: 'BI-RADS 5', color: '' },
+ { code: '4A', label: 'BI-RADS 4A', color: '' },
+ ],
+ results: [{ code: 'no_biopsy', label: 'Sin biopsia', color: '#ccc' }],
+ malignant: ['in_situ', 'invasive'],
+ malignancy: 'G',
+ };
+ const t = outcomes(mode, (m) => (m === 'T' ? types : grades))!;
+ expect(t.head).toEqual([
+ 'Pacientes',
+ 'Carcinoma ductal infiltrante',
+ 'Sin biopsia',
+ '% maligno',
+ ]);
+ expect(t.rows[0].cells).toEqual(['2', '1', '1', '1/1 (100.0 %)']);
+ expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
+ });
+});
diff --git a/src/app/indicadores/groups.ts b/src/app/indicadores/groups.ts
new file mode 100644
index 0000000..25edd93
--- /dev/null
+++ b/src/app/indicadores/groups.ts
@@ -0,0 +1,231 @@
+import {
+ Bar,
+ Bars,
+ hiddenNote,
+ Mode,
+ NO_PATIENTS,
+ NO_ROUND,
+ NOT_AVAILABLE,
+ patients,
+ pct,
+ Read,
+ reconciles,
+ size,
+ whole,
+ withAggregate,
+} from './bars';
+import { name } from './labels';
+
+/** One category of a group as a bar of 0 to 100 %: its records over the group's. */
+export interface GroupRow {
+ label: string;
+ color: string;
+ sub?: boolean;
+ /** none when the group has no records */
+ percent?: number;
+ /** "2/5 · 40.0 %" */
+ text: string;
+}
+export interface Group {
+ code: string;
+ label: string;
+ total: number;
+ hint?: string;
+ rows: GroupRow[];
+}
+
+/** The subsequent round, split by the form's last screening, drawn in place of that group. */
+const LAST_SCREENING: Record = {
+ within_1_year: 'Detección anterior hace un año o menos',
+ '2_years': 'Detección anterior hace dos años',
+ '3_or_more_years': 'Detección anterior hace tres años o más',
+};
+/** Results counted from 15 years old: their youngest group starts there. */
+const FROM_15 = ['CACU_EU7', 'CACU_VPH_GENOTIPO'];
+
+const cellsOf = (strata: Record>, group: string) =>
+ Object.entries(strata)
+ .filter(([k]) => k.split('|')[0] === group)
+ .map(([k, c]) => [k.split('|')[1], size(c)] as const);
+
+/** The groups of a `grouped` mode, each with a bar per category over its own records. A group
+ * the report leaves out is drawn empty only when the listed ones add up (`complete`). */
+export function grouped(mode: Mode, read: Read): { groups: Group[]; note?: string } | undefined {
+ if (mode.kind !== 'grouped') return undefined;
+ const r = read(mode.measure);
+ const cells = r?.strata[`${mode.stratum}-category`] ?? {};
+ const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
+ if (!patients(r) || !found.length) return undefined;
+ const history = (mode.stratum === 'round' && r?.strata['subsequent_history-category']) || {};
+ const split = Object.keys(history).length > 0;
+ const reconciled = reconciles(Object.values(cells).map(size), patients(r));
+ const codes = [
+ ...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
+ ...found.filter((g) => !mode.order.includes(g)),
+ ].flatMap((g) => (split && g === 'subsequent' ? Object.keys(LAST_SCREENING) : [g]));
+ const count = (g: string) => cellsOf(g in LAST_SCREENING ? history : cells, g);
+ const n = (g: string, code: string) =>
+ count(g).reduce((t, [c, k]) => (c === code ? t + k : t), 0);
+ const total = (g: string) =>
+ mode.ofAll
+ ? count(g).reduce((t, [, k]) => t + k, 0)
+ : mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
+ const row = (label: string, color: string, k: number, of: number): GroupRow => {
+ const percent = of ? (100 * k) / of : undefined;
+ return { label, color, percent, text: `${k}/${of} · ${of ? pct(k, of) : '—'}` };
+ };
+ const groups = codes.map((code): Group => {
+ const of = total(code);
+ const a = mode.aggregate;
+ return {
+ code,
+ label:
+ LAST_SCREENING[code] ??
+ (code === '<25' && mode.stratum === 'age_group' && FROM_15.includes(mode.measure)
+ ? '15-24'
+ : name(code)),
+ total: of,
+ hint: of ? undefined : `Sin ${mode.unit} en el grupo`,
+ rows: withAggregate(
+ mode.catalog.map((c) => row(c.label, c.color, n(code, c.code), of)),
+ mode.catalog.map((c) => c.code),
+ a,
+ () =>
+ row(
+ a!.label,
+ a!.color,
+ a!.codes.reduce((t, c) => t + n(code, c), 0),
+ of,
+ ),
+ (x) => ({ ...x, sub: true }),
+ ),
+ };
+ });
+ const unrounded =
+ mode.complete &&
+ reconciled &&
+ total('no_data') > 0 &&
+ groups.every((g) => g.code === 'no_data' || !g.total);
+ const sentence =
+ mode.complete && !reconciled
+ ? 'Los conteos del informe no concilian con el total: los grupos ausentes no se ' +
+ 'muestran como cero.'
+ : unrounded
+ ? NO_ROUND
+ : undefined;
+ const note = [sentence, hiddenNote(mode, read)].filter(Boolean).join(' ') || undefined;
+ return { groups, note };
+}
+
+/** Why a grouped mode has nothing to draw though its period has records. */
+export function unavailable(mode: Mode, read: Read): string | undefined {
+ if (mode.kind !== 'grouped' && !(mode.kind === 'shares' && mode.complete)) return undefined;
+ const r = read(mode.measure);
+ const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
+ if (!patients(r) || Object.keys(r?.strata[key] ?? {}).length) return undefined;
+ return `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
+}
+
+const RESULT_COLORS = ['#5C42C2', '#C24269', '#9C42C2', '#A8C243', '#2778B8', '#B19525'];
+const GRADES = ['benign', 'in_situ', 'invasive'];
+
+/** Each row's units by result, as one bar in segments, and the malignant share. */
+export function outcomes(mode: Mode, read: Read): Bars | undefined {
+ if (mode.kind !== 'outcomes') return undefined;
+ const r = read(mode.measure);
+ const units = r?.strata[mode.stratum] ?? {};
+ if (!Object.keys(units).length) return undefined;
+ const cells = r?.strata[`${mode.stratum}-category`] ?? {};
+ const fixed = mode.results.map((x) => x.code);
+ const results = [
+ ...Object.keys(r?.strata['category'] ?? {})
+ .filter((code) => !fixed.includes(code))
+ .sort()
+ .map((code, i) => ({ code, label: name(code), color: RESULT_COLORS[i % 6] })),
+ ...mode.results,
+ ];
+ const graded = read(mode.malignancy)?.strata[`${mode.stratum}-category`];
+ const of = (row: string, codes: string[]) =>
+ codes.reduce((t, c) => t + size(graded?.[`${row}|${c}`]), 0);
+ const malignant = (row: string) => {
+ if (!graded) return NOT_AVAILABLE;
+ const [bad, known] = [of(row, mode.malignant), of(row, GRADES)];
+ if (known) return `${bad}/${known} (${pct(bad, known)})`;
+ return size(graded[`${row}|no_data`]) ? 'Sin biopsias clasificables' : 'Sin biopsias';
+ };
+ return {
+ head: ['Pacientes', ...results.map((x) => x.label), '% maligno'],
+ legend: results.map(({ label, color }) => ({ label, color })),
+ rows: mode.rows.map(({ code, label }) => {
+ const n = size(units[code]);
+ const by = results.map((x) => size(cells[`${code}|${x.code}`]));
+ return {
+ label,
+ width: 100,
+ marks: [],
+ hint: n ? undefined : 'Sin pacientes en el periodo',
+ segments: results.map((x, i) => ({
+ width: n ? (100 * by[i]) / n : 0,
+ color: x.color,
+ title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
+ })),
+ cells: n ? [`${n}`, ...by.map(String), malignant(code)] : ['0', ...by.map(() => '—'), '—'],
+ };
+ }),
+ };
+}
+
+/** A proportion by group; complete, every group of the order, as the counts allow. */
+export function shares(mode: Mode, read: Read): Bars | undefined {
+ if (mode.kind !== 'shares') return undefined;
+ const r = read(mode.measure);
+ const cells = r?.strata[mode.stratum] ?? {};
+ const listed = Object.keys(cells);
+ const head = ['n/N', mode.percentLabel ?? 'Porcentaje'];
+ const of = (code: string): Bar => {
+ const [n, total] = [cells[code]?.['numerator'], cells[code]?.['denominator']];
+ const label = name(code);
+ const color = mode.colors?.[code];
+ if (!whole(n) || !whole(total) || n > total)
+ return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
+ return {
+ label,
+ color,
+ hint: total ? undefined : NO_PATIENTS,
+ marks: [],
+ width: total ? (100 * n) / total : 0,
+ cells: [`${n}/${total}`, pct(n, total)],
+ };
+ };
+ if (!mode.complete) {
+ const found = mode.order.filter((c) => cells[c]);
+ return found.length ? { head, rows: found.map(of) } : undefined;
+ }
+ if (!patients(r) || !listed.length) return undefined;
+ const reconciled = reconciles(
+ listed.map((c) => cells[c]['denominator']),
+ patients(r),
+ );
+ const rows = [...mode.order, ...listed.filter((c) => !mode.order.includes(c))].map((code) =>
+ listed.includes(code)
+ ? of(code)
+ : {
+ label: name(code),
+ color: mode.colors?.[code],
+ width: 0,
+ marks: [],
+ ...(reconciled
+ ? { hint: NO_PATIENTS, cells: ['0/0', '—'] }
+ : { hint: NOT_AVAILABLE, cells: ['—', '—'] }),
+ },
+ );
+ const classified = mode.order.filter((c) => c !== 'no_data' && listed.includes(c));
+ const none = classified.every((c) => !cells[c]['denominator']) && listed.includes('no_data');
+ const note = !reconciled
+ ? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no ' +
+ 'se muestran como cero.'
+ : none
+ ? NO_ROUND
+ : undefined;
+ return { head, rows, note };
+}
diff --git a/src/app/indicadores/history.ts b/src/app/indicadores/history.ts
new file mode 100644
index 0000000..d9e4367
--- /dev/null
+++ b/src/app/indicadores/history.ts
@@ -0,0 +1,216 @@
+/** One panel of Trazabilidad (tests/fixtures/reference//ui, tab "Trazabilidad"): a
+ * measure month by month, as stacked counts by category, a percentage with its 95 % interval,
+ * or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
+export interface HistoryPanel {
+ title: string;
+ measure: string;
+ kind: 'stack' | 'percent' | 'median';
+ /** stack: the categories, in the old order, with their names and colours */
+ series?: { code: string; label: string; color: string }[];
+ /** stack: the y axis */
+ axis?: string;
+ group?: string;
+}
+export interface History {
+ panels: HistoryPanel[];
+ /** the line's colour (percent and median) */
+ line: string;
+ /** how many of the latest months the tab opens with (none: from the first with data) */
+ months?: number;
+}
+
+const GREY = '#C9CDD2';
+const stack = (
+ title: string,
+ measure: string,
+ axis: string,
+ series: [string, string, string][],
+): HistoryPanel => ({
+ title,
+ measure,
+ kind: 'stack',
+ axis,
+ series: series.map(([code, label, color]) => ({ code, label, color })),
+});
+const BIRADS_SERIES: [string, string, string][] = [
+ ['4A', 'BI-RADS 4A', '#C24269'],
+ ['4B', 'BI-RADS 4B', '#9C42C2'],
+ ['4C', 'BI-RADS 4C', '#5C42C2'],
+ ['5', 'BI-RADS 5', '#C2429C'],
+ ['6', 'BI-RADS 6', '#8E2F62'],
+ ['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
+];
+
+export const HISTORY: Record = {
+ cacu: {
+ line: '#6A8000',
+ months: 5,
+ panels: [
+ stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
+ ['NILM', 'Normal', '#9DBFE3'],
+ ['ASC-US', 'ASC-US', '#2F6DB3'],
+ ['LSIL', 'LIEBG', '#9C42C2'],
+ ['ASC-H', 'ASC-H', '#5C42C2'],
+ ['HSIL', 'LIEAG', '#C2429C'],
+ ['CIS', 'Carcinoma in situ', '#8E2F62'],
+ ['no_data', 'Sin dato', GREY],
+ ]),
+ { title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
+ { title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
+ stack(
+ 'Resultado de biopsia tras citología de alto grado',
+ 'CACU_CONFIRMACION_CITOLOGIA',
+ 'Pacientes',
+ [
+ ['normal', 'Normal', '#9DBFE3'],
+ ['LSIL', 'LIEBG (CIN 1)', '#69C242'],
+ ['CIN2', 'CIN 2', '#E07A9C'],
+ ['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
+ ['CIN3', 'CIN 3', '#A8325A'],
+ ['CIS', 'Carcinoma in situ', '#9C42C2'],
+ ['carcinoma', 'Carcinoma invasor', '#5C42C2'],
+ ['no_biopsy', 'Sin biopsia aún', GREY],
+ ['no_data', 'Biopsia sin grado', GREY],
+ ],
+ ),
+ {
+ title: 'Días de la toma de la citología a su resultado',
+ measure: 'CACU_EU_TIEMPO_REPORTE',
+ kind: 'median',
+ },
+ {
+ title: 'Tiempo de tamizaje a primer diagnóstico',
+ measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
+ kind: 'median',
+ },
+ {
+ title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
+ measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
+ kind: 'median',
+ },
+ {
+ title: 'Tiempo de tamizaje a tratamiento',
+ measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
+ kind: 'median',
+ },
+ {
+ title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
+ measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
+ kind: 'median',
+ },
+ {
+ title: 'Riesgo CIN2+ por banda',
+ measure: 'CACU_RIESGO_BANDA',
+ kind: 'stack',
+ axis: 'Pacientes',
+ },
+ ],
+ },
+ cama: {
+ line: '#9C42C2',
+ panels: [
+ {
+ title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
+ measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
+ kind: 'median',
+ },
+ {
+ title: 'Días de la toma de la mastografía a su resultado',
+ measure: 'CAMA_EU38A',
+ kind: 'median',
+ },
+ {
+ title: 'Días del resultado de la mastografía al diagnóstico',
+ measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
+ kind: 'median',
+ },
+ {
+ title: 'Tiempo de tamizaje a diagnóstico',
+ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
+ kind: 'median',
+ },
+ {
+ title: 'Tasa de detección histopatológica',
+ measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
+ kind: 'percent',
+ },
+ stack(
+ 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
+ 'CAMA_BIRADS456_MASTOGRAFIA',
+ 'Mastografías',
+ BIRADS_SERIES,
+ ),
+ stack(
+ 'Pacientes con resultado BI-RADS 4, 5 ó 6',
+ 'CAMA_BIRADS456_PACIENTE',
+ 'Pacientes',
+ BIRADS_SERIES,
+ ),
+ stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
+ ['benign', 'Benigno', '#9DBFE3'],
+ ['in_situ', 'Carcinoma in situ', '#C24269'],
+ ['invasive', 'Carcinoma invasor', '#9C42C2'],
+ ['no_biopsy', 'Sin biopsia reportada', GREY],
+ ['no_data', 'Sin dato', GREY],
+ ]),
+ {
+ title: 'Confirmación histopatológica',
+ measure: 'CAMA_CONFIRMACION_BIRADS45',
+ kind: 'percent',
+ },
+ ],
+ },
+ tea: {
+ line: '#9C42C2',
+ panels: [
+ {
+ group: 'Tiempos del tamizaje',
+ title: 'Días de M-CHAT a ADOS-2',
+ measure: 'M26_DIAS_MCHAT_ADOS2',
+ kind: 'median',
+ },
+ {
+ group: 'Tiempos del tamizaje',
+ title: 'Días de ADOS-2 a diagnóstico',
+ measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
+ kind: 'median',
+ },
+ {
+ group: 'Tiempos del tamizaje',
+ title: 'Días de M-CHAT a diagnóstico positivo',
+ measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
+ kind: 'median',
+ },
+ stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
+ ['confirmed', 'Diagnóstico confirmado', '#A8C243'],
+ ['in_process', 'En proceso', '#B8433A'],
+ ]),
+ {
+ title: 'Porcentaje de confirmación diagnóstica',
+ measure: 'M24_CONFIRMACION_DIAGNOSTICO',
+ kind: 'percent',
+ },
+ {
+ title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
+ measure: 'M21_DIAGNOSTICADOS_CON_EEG',
+ kind: 'percent',
+ },
+ {
+ title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
+ measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
+ kind: 'percent',
+ },
+ stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
+ ['mchat_only', 'Solo M-CHAT', '#B8433A'],
+ ['psychology', 'Hasta evaluación psicológica', '#42C29C'],
+ ['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
+ ['eeg', 'Con EEG', '#A8C243'],
+ ]),
+ stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
+ ['good', 'Bueno', '#A8C243'],
+ ['bad', 'No aceptable', '#B8433A'],
+ ['not_analyzed', 'Sin analizar', GREY],
+ ]),
+ ],
+ },
+};
diff --git a/src/app/indicadores/indicadores.ts b/src/app/indicadores/indicadores.ts
index eb103a3..85b2917 100644
--- a/src/app/indicadores/indicadores.ts
+++ b/src/app/indicadores/indicadores.ts
@@ -36,7 +36,7 @@ import { Loading } from '../loading';
Este dominio todavía no tiene indicadores publicados.
} @else {
-
+
@@ -45,7 +45,7 @@ import { Loading } from '../loading';
@if (domain() === 'cacu') {
-
+
@@ -57,7 +57,7 @@ import { Loading } from '../loading';
} @else if (domain() === 'cama') {
-
+
diff --git a/src/app/indicadores/labels.ts b/src/app/indicadores/labels.ts
new file mode 100644
index 0000000..dc13e23
--- /dev/null
+++ b/src/app/indicadores/labels.ts
@@ -0,0 +1,90 @@
+/** Codes as the screens name them. */
+export const LABELS: Record = {
+ NILM: 'Normal (NILM)',
+ LSIL: 'LIEBG',
+ HSIL: 'LIEAG',
+ CIN2: 'CIN 2',
+ CIN3: 'CIN 3',
+ normal: 'Normal',
+ carcinoma: 'Carcinoma',
+ no_data: 'Sin dato',
+ '<25': '<25 años (sin límite inferior)',
+ 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',
+ benign: 'Benigno',
+ in_situ: 'Carcinoma in situ',
+ invasive: 'Carcinoma invasor',
+ cancer: 'Diagnóstico confirmado',
+ pending_biopsy: 'Pendiente de biopsia',
+ biopsy_no_result: 'Biopsia sin resultado',
+ benign_biopsy: 'Biopsia benigna',
+ confirmed: 'Diagnóstico confirmado',
+ in_process: 'En proceso',
+ not_confirmed: 'Sin TEA',
+ mchat_only: 'Solo M-CHAT',
+ psychology: 'Psicología (ADOS-2)',
+ neuropediatrics: 'Neuropediatría',
+ eeg: 'EEG',
+ good: 'Bueno',
+ bad: 'Malo',
+ not_analyzed: 'Sin analizar',
+ initial: 'Detección inicial',
+ subsequent: 'Con detección anterior',
+ positive: 'Positivo',
+ negative: 'Negativo',
+ hpv_16: 'VPH 16',
+ hpv_18: 'VPH 18',
+ ascus_plus: 'ASC-US o mayor',
+ lsil_plus: 'LIEBG o mayor',
+ hsil_plus: 'LIEAG o mayor',
+ cin1_plus: 'Histología LIEBG o mayor',
+ cin2_plus: 'Histología LIEAG o mayor',
+ several: 'Varios códigos',
+ no_result: 'Sin resultado de VPH',
+ positive_incomplete: 'Positivo con genotipificación incompleta',
+ inconsistent: 'Inconsistente',
+ no_grade: 'Sin grado',
+ ...Object.fromEntries(
+ ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
+ ),
+};
+/** A follow-up priority's label. */
+export const PRIORITY: Record = { high: 'Alta', medium: 'Media', low: 'Baja' };
+export const STRATA: Record = {
+ category: 'Categoría',
+ age_group: 'Grupo de edad',
+ follow_up_status: 'Estatus de seguimiento',
+ result: 'Citología de alto grado',
+ birads: 'BI-RADS de la mastografía',
+ diagnosis_code: 'Diagnóstico CIE-10',
+ cytology: 'Citología previa',
+ hpv: 'VPH de la citología previa',
+ level: 'Histología confirmada',
+ round: 'Detección inicial o anterior',
+ hpv_16: 'VPH 16',
+ hpv_18: 'VPH 18',
+};
+/** Breast histologic types (ICD-O-3 morphology) the sites report; any other shows its code. */
+const HISTOLOGIC_TYPES: Record = {
+ '8500/2': 'Carcinoma ductal in situ',
+ '8500/3': 'Carcinoma ductal infiltrante',
+ '8520/2': 'Carcinoma lobulillar in situ',
+ '8520/3': 'Carcinoma lobulillar infiltrante',
+ '8522/3': 'Carcinoma ductal y lobulillar infiltrante',
+ '8480/3': 'Adenocarcinoma mucinoso',
+ '8211/3': 'Carcinoma tubular',
+ '8510/3': 'Carcinoma medular',
+ '8530/3': 'Carcinoma inflamatorio',
+ '8540/3': 'Enfermedad de Paget de la mama',
+ '9010/0': 'Fibroadenoma',
+ '9016/0': 'Fibroadenoma gigante',
+};
+export const name = (value: string) => LABELS[value] ?? HISTOLOGIC_TYPES[value] ?? value;
diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts
index 7d9e304..a971c95 100644
--- a/src/app/indicadores/measures.ts
+++ b/src/app/indicadores/measures.ts
@@ -1,3 +1,4 @@
+import { name } from './labels';
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
import { code, ext } from '../fhir';
import { Figure, PALETTE } from '../plot';
@@ -23,6 +24,13 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
return found;
}
+/** A period's first day ("2026-S2": July 1st; "2026-03": March 1st). */
+export function periodStart(period: string): Date {
+ const [year, part] = period.split('-');
+ const month = part.startsWith('S') ? (part === 'S1' ? 0 : 6) : Number(part) - 1;
+ return new Date(Number(year), month, 1);
+}
+
export function periodLabel(period: string): string {
const [year, part] = period.split('-');
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
@@ -98,78 +106,6 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
};
}
-/** Codes as the screens name them. */
-export const LABELS: Record = {
- 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',
- benign: 'Benigno',
- in_situ: 'Carcinoma in situ',
- invasive: 'Carcinoma invasor',
- cancer: 'Diagnóstico confirmado',
- pending_biopsy: 'Pendiente de biopsia',
- biopsy_no_result: 'Biopsia sin resultado',
- benign_biopsy: 'Biopsia benigna',
- confirmed: 'Diagnóstico confirmado',
- in_process: 'En proceso',
- not_confirmed: 'Sin TEA',
- mchat_only: 'Solo M-CHAT',
- psychology: 'Psicología (ADOS-2)',
- neuropediatrics: 'Neuropediatría',
- eeg: 'EEG',
- good: 'Bueno',
- bad: 'Malo',
- not_analyzed: 'Sin analizar',
- initial: 'Inicial',
- subsequent: 'Subsecuente',
- positive: 'Positivo',
- negative: 'Negativo',
- hpv_16: 'VPH 16',
- hpv_18: 'VPH 18',
- ascus_plus: 'ASC-US o mayor',
- lsil_plus: 'LIEBG o mayor',
- hsil_plus: 'LIEAG o mayor',
- cin1_plus: 'Histología LIEBG o mayor',
- cin2_plus: 'Histología LIEAG o mayor',
- several: 'Varios códigos',
- no_result: 'Sin resultado de VPH',
- inconsistent: 'Inconsistente',
- no_grade: 'Sin grado',
- ...Object.fromEntries(
- ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
- ),
-};
-/** A follow-up priority's label. */
-export const PRIORITY: Record = { high: 'Alta', medium: 'Media', low: 'Baja' };
-export const STRATA: Record = {
- category: 'Categoría',
- age_group: 'Grupo de edad',
- follow_up_status: 'Estatus de seguimiento',
- result: 'Citología de alto grado',
- birads: 'BI-RADS de la mastografía',
- diagnosis_code: 'Diagnóstico CIE-10',
- cytology: 'Citología previa',
- hpv: 'VPH de la citología previa',
- level: 'Histología confirmada',
- round: 'Tamizaje inicial o subsecuente',
- hpv_16: 'VPH 16',
- hpv_18: 'VPH 18',
-};
-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)) {
@@ -182,14 +118,14 @@ export function formatScore(measure: Measure, r: Reading | undefined): string {
}
}
-export function detail(measure: Measure, r: Reading | undefined): string {
+export function detail(measure: Measure, r: Reading | undefined, unit = 'pacientes'): 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)}.`;
+ ? `Sin ${unit} en el periodo.`
+ : `${p['numerator']} de ${p['denominator']} ${unit}. 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.`
diff --git a/src/app/indicadores/pages-cacu.ts b/src/app/indicadores/pages-cacu.ts
index 786533b..44f6633 100644
--- a/src/app/indicadores/pages-cacu.ts
+++ b/src/app/indicadores/pages-cacu.ts
@@ -1,72 +1,112 @@
-import type { Mode } from './bars';
-import type { Catalog, Page, ReadingsCard } from './pages';
+import type { Category, Mode } from './bars';
+import {
+ BIOPSY,
+ CONFIRMED,
+ CYTOLOGY,
+ HPV,
+ LEVEL,
+ PRIOR_CYTOLOGY,
+ ROUND,
+ TINT,
+} from './palette-cacu';
+import type { Page, ReadingsCard } from './pages';
-const OLIVE = '#A8C243';
const ROSE = '#C24269';
+const of = (colors: Record, rows: [string, string][]): Category[] =>
+ rows.map(([code, label]) => ({ code, label, color: colors[code] }));
-/** Bethesda results as the old app grouped and coloured them. */
-const CYTOLOGY: Catalog = {
- groups: [
- { id: 'normal', label: 'Sin anomalía', color: OLIVE },
- { id: 'abnormal', label: 'Anormal', color: ROSE },
- ],
- categories: [
- { code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
- { code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
- { code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
- { code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
- { code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
- { code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
- ],
-};
+/** Bethesda results; the abnormal ones also added up under "Anormal". */
+const RESULTS = of(CYTOLOGY, [
+ ['NILM', 'Normal'],
+ ['ASC-US', 'ASC-US'],
+ ['LSIL', 'LIEBG'],
+ ['ASC-H', 'ASC-H'],
+ ['HSIL', 'LIEAG'],
+ ['CIS', 'Carcinoma in situ'],
+ ['carcinoma', 'Carcinoma epidermoide invasor'],
+]);
+const ABNORMAL = { label: 'Anormal', color: ROSE, codes: RESULTS.slice(1).map((c) => c.code) };
+const GRADES = of(BIOPSY, [
+ ['normal', 'Normal'],
+ ['LSIL', 'LIEBG (CIN 1)'],
+ ['CIN2', 'CIN 2'],
+ ['HSIL', 'LIEAG (CIN 2 y 3)'],
+ ['CIN3', 'CIN 3'],
+ ['CIS', 'Carcinoma in situ'],
+ ['carcinoma', 'Carcinoma invasor'],
+]);
+const GENOTYPES = of(HPV, [
+ ['negative', 'Negativo'],
+ ['positive_16', 'VPH 16'],
+ ['positive_18', 'VPH 18'],
+ ['positive_16_18', 'VPH 16 y 18'],
+ ['positive_other', 'Positivo sin genotipo'],
+]);
+/** HPV categories not drawn: their reports stay in the total and the percentages. */
+const UNDRAWN = { codes: ['positive_incomplete', 'inconsistent', 'no_result'], unit: 'reportes' };
-/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
-const BIOPSY: Catalog = {
- groups: [
- { id: 'low', label: 'Menor que LIEAG', color: OLIVE },
- { id: 'high', label: 'LIEAG o más', color: ROSE },
- ],
- categories: [
- { code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
- { code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
- { code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
- { code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
- { code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
- ],
- faded: ['normal', 'LSIL'],
-};
+const ROUNDS = ['initial', 'subsequent', 'no_data'];
+const BY_ROUND = 'Por detección inicial y anterior';
+const BY_AGE = 'Por grupo de edad';
+const GENERAL = 'General';
-/** HPV reports by genotype, and biopsy requests by what became of them. */
-const HPV = [
- { code: 'negative', label: 'Negativo', color: '#A8C243' },
- { code: 'positive_16', label: 'VPH 16', color: '#C24269' },
- { code: 'positive_18', label: 'VPH 18', color: '#9C42C2' },
- { code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' },
- { code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' },
- { code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' },
-];
-const REQUESTS = [
- { code: 'high_grade', label: 'LIEAG o más', color: '#C24269' },
- { code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' },
- { code: 'pending', label: 'Pendiente', color: '#C9CDD2' },
- { code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' },
-];
+/** A results card's general reading and its readings by age group and by round (one
+ * selector for both cards). */
+function results(measure: string, catalog: Category[], unit: string, more: object): Mode[] {
+ const caption =
+ measure === 'CACU_VPH_GENOTIPO'
+ ? 'Porcentaje de reportes de VPH del grupo por genotipo.'
+ : 'Porcentaje de pacientes del grupo por resultado citológico.';
+ const groups = [
+ {
+ label: BY_AGE,
+ stratum: 'age_group',
+ order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
+ },
+ { label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
+ ];
+ return [
+ {
+ kind: 'counts',
+ label: GENERAL,
+ measure,
+ catalog,
+ unit: unit === 'pacientes' ? 'Pacientes' : 'Reportes',
+ percentLabel:
+ unit === 'pacientes' ? 'Porcentaje de pacientes' : 'Porcentaje de reportes de VPH',
+ ...more,
+ },
+ ...groups.map((g) => ({
+ kind: 'grouped' as const,
+ measure,
+ catalog,
+ unit,
+ caption,
+ ofAll: true,
+ ...g,
+ ...more,
+ })),
+ ];
+}
-/** A PPV's card: the whole, and by each of its stratifiers. */
-const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
+/** A confirmation rate's card: the whole, and by each of its stratifiers. */
+const ppv = (measure: string, title: string, note: string, percentLabel: string): ReadingsCard => ({
kind: 'readings',
title,
headline: measure,
+ footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
- { kind: 'figure', label: 'Total', measure, figure: 'donut' },
+ { kind: 'ratio', label: 'Total', measure, color: CONFIRMED, percentLabel },
{
kind: 'shares',
label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure,
stratum: 'cytology',
+ colors: PRIOR_CYTOLOGY,
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
+ percentLabel: 'Porcentaje de pacientes con esta citología previa',
},
{
kind: 'shares',
@@ -74,23 +114,34 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
caption: 'Los grupos se traslapan.',
measure,
stratum: 'hpv',
+ colors: HPV,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
+ percentLabel: 'Porcentaje de pacientes de cada grupo de VPH previo',
},
{
kind: 'shares',
label: 'Nivel de histología',
measure,
stratum: 'level',
+ colors: LEVEL,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
+ percentLabel: 'Porcentaje de pacientes de cada nivel de histología',
},
{
kind: 'shares',
- label: 'Tamizaje',
+ label: BY_ROUND,
+ caption:
+ 'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección ' +
+ 'inicial (primera vez en la vida), con detección anterior (registrada, o ya con ' +
+ 'colposcopía o tratamiento) o «Sin dato». Un grupo sin pacientes se muestra en cero; ' +
+ 'sin porcentaje.',
measure,
stratum: 'round',
- order: ['initial', 'subsequent', 'no_data'],
+ colors: ROUND,
+ order: ROUNDS,
+ complete: true,
+ percentLabel: 'Porcentaje de pacientes de cada ronda',
},
- ...more,
],
});
@@ -98,8 +149,16 @@ const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
+const days = (label: string, ...steps: [string, string][]): Mode => ({
+ kind: 'days',
+ label,
+ tint: TINT,
+ steps: steps.map(([label, measure]) => ({ label, measure })),
+});
+
export const CACU: Page = {
anchor: 'CACU_EU7',
+ clinicalFirst: true,
kpis: [
{
measure: 'CACU_EU7',
@@ -113,8 +172,8 @@ export const CACU: Page = {
...CACU_DAYS,
},
{
- measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
- title: 'Tiempo de tamizaje a diagnóstico',
+ measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
+ title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS,
},
{
@@ -124,44 +183,44 @@ export const CACU: Page = {
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
- title: 'Tiempo de diagnóstico a tratamiento',
+ title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'readings',
- title: 'Tiempos de la ruta del tamizaje',
+ title: 'Tiempos de tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [
+ days(
+ 'Acumulado desde la toma',
+ ['Resultado de citología', 'CACU_EU_TIEMPO_REPORTE'],
+ ['Resultado de colposcopía', 'CACU_DIAS_TOMA_COLPOSCOPIA'],
+ ['Resultado de biopsia', 'CACU_DIAS_TOMA_BIOPSIA'],
+ ['Diagnóstico tras biopsia', 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA'],
+ ),
{
- kind: 'days',
- label: 'Acumulado desde la toma',
- steps: [
- { label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
- { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
- { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
- { label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
- ],
- },
- {
- kind: 'days',
- label: 'Por pasos',
- caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
- steps: [
- { label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
- { label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
- { label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
- { label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
- ],
- },
- {
- kind: 'days-by',
- label: 'Por CIE-10',
- caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
- measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
- stratum: 'diagnosis_code',
- },
+ ...days(
+ 'Por ventana de tiempo',
+ ['Toma a resultado de citología', 'CACU_EU_TIEMPO_REPORTE'],
+ ['Resultado a colposcopía', 'CACU_DIAS_RESULTADO_COLPOSCOPIA'],
+ ['Colposcopía a biopsia', 'CACU_DIAS_COLPOSCOPIA_BIOPSIA'],
+ ['Biopsia a diagnóstico', 'CACU_DIAS_BIOPSIA_DIAGNOSTICO'],
+ ),
+ staggered: true,
+ caption:
+ 'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus ' +
+ 'propias pacientes: las medianas no se suman.',
+ } as Mode,
+ days('Diagnóstico precolposcópico', [
+ 'Toma a primer diagnóstico',
+ 'CACU_DIAS_TOMA_DIAGNOSTICO',
+ ]),
+ days('Diagnóstico tras biopsia', [
+ 'Toma a diagnóstico tras biopsia',
+ 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
+ ]),
],
},
],
@@ -169,32 +228,22 @@ export const CACU: Page = {
{
kind: 'columns',
title: 'Resultados de citología, VPH y biopsia',
+ viewsLabel: 'Lectura de la distribución citológica y del VPH por genotipo',
+ views: [GENERAL, BY_AGE, BY_ROUND],
sections: [
{
kind: 'readings',
+ follows: true,
title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.',
- modes: [
- {
- kind: 'counts',
- label: 'General',
- measure: 'CACU_EU7',
- catalog: CYTOLOGY.categories,
- },
- {
- kind: 'figure',
- label: 'Por escenario clínico',
- measure: 'CACU_EU7',
- figure: 'scenarios',
- catalog: CYTOLOGY.categories,
- },
- ],
+ modes: results('CACU_EU7', RESULTS, 'pacientes', { aggregate: ABNORMAL }),
},
{
kind: 'readings',
+ follows: true,
title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.',
- modes: [{ kind: 'counts', label: 'General', measure: 'CACU_VPH_GENOTIPO', catalog: HPV }],
+ modes: results('CACU_VPH_GENOTIPO', GENOTYPES, 'reportes', { hidden: UNDRAWN }),
},
{
kind: 'readings',
@@ -203,50 +252,16 @@ export const CACU: Page = {
modes: [
{
kind: 'counts',
- label: 'General',
+ label: GENERAL,
measure: 'CACU_BIOPSIA_RESULTADOS',
- catalog: BIOPSY.categories,
+ catalog: GRADES,
+ unit: 'Reportes',
+ percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
],
},
- {
- kind: 'readings',
- title: 'Pacientes evaluadas por resultado de VPH',
- headline: 'CACU_VPH',
- note: 'Una vez cada paciente, por su última muestra con resultado.',
- modes: [
- { kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' },
- {
- kind: 'positives',
- label: 'Por grupo de edad',
- measure: 'CACU_VPH',
- stratum: 'age_group',
- order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
- },
- {
- kind: 'positives',
- label: 'Por estatus de seguimiento',
- measure: 'CACU_VPH',
- stratum: 'follow_up_status',
- order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
- },
- {
- kind: 'signs',
- label: 'Por genotipo',
- measure: 'CACU_VPH',
- strata: ['hpv_16', 'hpv_18'],
- },
- {
- kind: 'positives',
- label: 'Por tamizaje',
- measure: 'CACU_VPH',
- stratum: 'round',
- order: ['initial', 'subsequent', 'no_data'],
- },
- ],
- },
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
@@ -255,23 +270,18 @@ export const CACU: Page = {
label: 'Colposcopía',
section: ppv(
'CACU_VPP_COLPOSCOPIA',
- 'Valor predictivo positivo de la colposcopía',
+ 'Tasa de confirmación histopatológica de referencia a colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
+ 'Porcentaje de pacientes',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
- 'Valor predictivo positivo de la biopsia',
+ 'Tasa de confirmación histopatológica de referencia a biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
- {
- kind: 'counts',
- label: 'Solicitudes',
- caption: 'Solicitudes de biopsia registradas, según su resultado.',
- measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
- catalog: REQUESTS,
- },
+ 'Porcentaje de biopsias reportadas',
),
},
],
diff --git a/src/app/indicadores/pages-cama.ts b/src/app/indicadores/pages-cama.ts
new file mode 100644
index 0000000..68ec7ba
--- /dev/null
+++ b/src/app/indicadores/pages-cama.ts
@@ -0,0 +1,228 @@
+import type { Catalog, Page } from './pages';
+
+const CAMA_DAYS = {
+ value: '{median} días (mediana)',
+ note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
+};
+
+/** BI-RADS 4 to 6 as the old app named and coloured them. */
+const BIRADS: Catalog = {
+ groups: [],
+ categories: [
+ { code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
+ { code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
+ { code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
+ { code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
+ { code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
+ { code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
+ ],
+};
+/** What a patient without a typed biopsy shows. */
+const NO_TYPE = [
+ { code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
+ { code: 'no_data', label: 'Sin dato', color: '#8C949C' },
+];
+
+/** CaMa's page: the timeliness cards and their route, then the clinical indicators. */
+export const CAMA: Page = {
+ anchor: 'CAMA_BIRADS456_PACIENTE',
+ kpis: [
+ {
+ measure: 'CAMA_BIRADS456_PACIENTE',
+ title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
+ value: '{n} pacientes',
+ note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
+ },
+ {
+ measure: 'CAMA_EU38A',
+ title: 'Tiempo de toma de mastografía a interpretación radiológica',
+ ...CAMA_DAYS,
+ },
+ {
+ measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
+ title: 'Tiempo de interpretación radiológica a diagnóstico',
+ ...CAMA_DAYS,
+ },
+ {
+ measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
+ title: 'Tiempo de interpretación radiológica a resultado de biopsia',
+ ...CAMA_DAYS,
+ },
+ {
+ measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
+ title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
+ ...CAMA_DAYS,
+ },
+ {
+ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
+ title: 'Tiempo de tamizaje a diagnóstico',
+ ...CAMA_DAYS,
+ },
+ ],
+ opportunity: [
+ {
+ kind: 'readings',
+ title: 'Tiempo de tamizaje a diagnóstico y tratamiento',
+ modes: [
+ {
+ kind: 'days',
+ label: 'Por pasos',
+ rowsLabel: 'Paso',
+ staggered: true,
+ scale: true,
+ tint: { bar: '#42A77E', mark: '#17324D' },
+ caption:
+ 'Esquema: cada barra es la mediana de su paso y empieza donde termina el paso del ' +
+ 'que parte. Los pasos pueden corresponder a poblaciones diferentes, por lo que las ' +
+ 'medianas no se suman. Las marcas indican el primer y tercer cuartil.',
+ steps: [
+ { label: 'Toma de mastografía a interpretación radiológica', measure: 'CAMA_EU38A' },
+ {
+ label: 'Interpretación radiológica a diagnóstico',
+ measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
+ },
+ {
+ label: 'Diagnóstico tras biopsia a tratamiento',
+ measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
+ },
+ // from the interpretation, as the diagnosis
+ {
+ label: 'Interpretación radiológica a resultado de biopsia',
+ measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
+ after: 0,
+ },
+ ],
+ },
+ {
+ kind: 'days',
+ label: 'Acumulado desde la toma',
+ rowsLabel: 'Etapa',
+ scale: true,
+ tint: { bar: '#42A77E', mark: '#17324D' },
+ caption:
+ 'Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se ' +
+ 'calcula por separado. Las marcas indican el primer y tercer cuartil.',
+ steps: [
+ { label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
+ {
+ label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
+ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ clinical: [
+ {
+ kind: 'figures',
+ figures: [
+ {
+ kind: 'share-donut',
+ title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
+ measure: 'CAMA_BIRADS456_MASTOGRAFIA',
+ catalog: BIRADS,
+ center: 'mastografías',
+ },
+ {
+ kind: 'share-donut',
+ title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
+ measure: 'CAMA_BIRADS456_PACIENTE',
+ catalog: BIRADS,
+ center: 'pacientes',
+ },
+ ],
+ },
+ {
+ kind: 'readings',
+ title: 'Tipo histológico por categoría BI-RADS',
+ note:
+ 'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave ' +
+ 'reportada, por fecha del examen. Los tipos siguen la clasificación CIE-O-3; «Sin dato» ' +
+ 'incluye tipos ausentes o ' +
+ 'con vínculo ambiguo. El porcentaje maligno conserva la clasificación de la biopsia y ' +
+ 'su denominador de pacientes con clasificación conocida.',
+ modes: [
+ {
+ kind: 'outcomes',
+ label: 'Por categoría BI-RADS',
+ heading: 'Resultados por paciente',
+ caption: '«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.',
+ measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
+ stratum: 'birads',
+ rows: BIRADS.categories,
+ results: NO_TYPE,
+ malignant: ['in_situ', 'invasive'],
+ malignancy: 'CAMA_HISTOPATOLOGIA_BIRADS',
+ },
+ {
+ kind: 'counts',
+ label: 'Todas las categorías',
+ heading: 'Resultados por paciente',
+ measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
+ catalog: [],
+ unit: 'Pacientes',
+ percent: true,
+ percentLabel: 'Porcentaje de pacientes',
+ },
+ ],
+ },
+ {
+ kind: 'choice',
+ title: 'Confirmación histopatológica',
+ card: true,
+ choices: [
+ {
+ label: 'Tipos histológicos',
+ section: {
+ kind: 'readings',
+ title: 'Tipos histológicos',
+ note:
+ 'Biopsias por fecha de reporte, agrupadas por tipo histológico (CIE-O-3). «Sin dato» ' +
+ 'incluye los ' +
+ 'tipos ausentes y los que no pueden vincularse de forma inequívoca. La tasa de ' +
+ 'detección conserva su cálculo de carcinomas entre biopsias con clasificación ' +
+ 'conocida; su denominador puede ser distinto.',
+ modes: [
+ {
+ kind: 'counts',
+ label: 'Tipos histológicos',
+ heading: 'Tipo histológico',
+ measure: 'CAMA_TIPO_HISTOLOGICO',
+ catalog: [],
+ unit: 'Biopsias',
+ percent: true,
+ percentLabel: 'Porcentaje de reportes de biopsia',
+ },
+ ],
+ },
+ },
+ {
+ label: 'Mastografías con biopsia',
+ section: {
+ kind: 'readings',
+ title: 'Mastografías con biopsia',
+ headline: 'CAMA_CONFIRMACION_BIRADS45',
+ unit: 'mastografías',
+ note:
+ 'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: ' +
+ 'cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de ' +
+ 'la biopsia.',
+ modes: [
+ {
+ kind: 'split',
+ label: 'Con y sin biopsia',
+ measure: 'CAMA_CONFIRMACION_BIRADS45',
+ yes: 'Con reporte de biopsia',
+ no: 'Sin reporte de biopsia',
+ colors: ['#A8C243', '#C9CDD2'],
+ unit: 'Mastografías',
+ percentLabel: 'Porcentaje de mastografías',
+ },
+ ],
+ },
+ },
+ ],
+ },
+ ],
+};
diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts
index 7380911..717420b 100644
--- a/src/app/indicadores/pages.ts
+++ b/src/app/indicadores/pages.ts
@@ -1,11 +1,14 @@
import type { Mode } from './bars';
import { CACU } from './pages-cacu';
+import { CAMA } from './pages-cama';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference//ui):
* the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */
export interface Page {
kpis: Kpi[];
+ /** the clinical indicators before the timeliness ones (CaCu) */
+ clinicalFirst?: boolean;
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[];
clinical: Section[];
@@ -25,33 +28,48 @@ export interface ReadingsCard {
kind: 'readings';
title: string;
headline?: string;
+ /** the headline said under the figure, not above it */
+ footnote?: boolean;
+ /** what the headline proportion counts, in the plural (default: pacientes) */
+ unit?: string;
note?: string;
modes: Mode[];
+ /** in `columns` with `views`, the mode its section's selector picks */
+ follows?: boolean;
}
export type Section =
| ReadingsCard
- /** Cards side by side; the last one alone when odd. */
- | { kind: 'columns'; title: string; sections: ReadingsCard[] }
- /** One section at a time. */
- | { kind: 'choice'; title: string; choices: { label: string; section: ReadingsCard }[] }
+ /** Cards side by side, the last one alone when odd; `views`: one selector (its first view
+ * by default) for the cards that follow it */
+ | {
+ kind: 'columns';
+ title: string;
+ sections: ReadingsCard[];
+ views?: string[];
+ viewsLabel?: string;
+ }
+ /** One section at a time; `card`: the title, the toggle and the chosen card in one card */
+ | {
+ kind: 'choice';
+ title: string;
+ choices: { label: string; section: ReadingsCard }[];
+ card?: boolean;
+ }
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
| {
kind: 'boxes';
/** none: the boxes stand alone (TEA) */
title?: string;
cards: { measure?: string; title: string }[];
- /** the measure's own title under each card's (CaMa) */
- subtitles?: boolean;
}
/** Each figure in its own card, titled, two to a row (TEA). */
| { kind: 'grid'; figures: FigureSpec[] }
/** TEA's period summary in words, its numbers from the measures. */
- | { kind: 'tea-summary' }
- | ({ kind: 'card' } & Kpi);
+ | { kind: 'tea-summary' };
/** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec =
| {
- kind: 'donut' | 'share-donut';
+ kind: 'share-donut';
title: string;
measure: string;
catalog: Catalog;
@@ -65,18 +83,6 @@ export type FigureSpec =
measure: string;
/** the numerator's and the rest's names (stack), or the axis (share) */
names: [string, string];
- }
- | {
- kind: 'rates';
- title: string;
- measure: string;
- stratum: string;
- rows: Category[];
- /** each row in its category's colour (else all rose) */
- colored?: boolean;
- /** the categories (of the measure) that count as a positive */
- positive: string[];
- axis: string;
};
export interface Category {
@@ -93,37 +99,6 @@ export interface Catalog {
}
const OLIVE = '#A8C243';
-const ROSE = '#C24269';
-
-const CAMA_DAYS = {
- value: '{median} días (mediana)',
- note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
-};
-const PENDING = 'Indicador no publicado en el catálogo institucional.';
-
-/** BI-RADS 4 to 6 as the old app named and coloured them. */
-const BIRADS: Catalog = {
- groups: [],
- categories: [
- { code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
- { code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
- { code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
- { code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
- { code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
- { code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
- ],
-};
-const BREAST_BIOPSY: Catalog = {
- groups: [
- { id: 'benign', label: 'No maligno', color: '#42C29C' },
- { id: 'malignant', label: 'Maligno', color: ROSE },
- ],
- categories: [
- { code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
- { code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
- { code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
- ],
-};
export const PAGES: Record = {
tea: {
@@ -218,308 +193,6 @@ export const PAGES: Record = {
},
],
},
- cama: {
- anchor: 'CAMA_BIRADS456_PACIENTE',
- kpis: [
- {
- measure: 'CAMA_BIRADS456_PACIENTE',
- title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
- value: '{n} pacientes',
- note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
- },
- {
- measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
- title: 'Tasa de confirmación histopatológica',
- value: '{pct} %',
- note: '{num} de {den} biopsias con riesgo a carcinoma.',
- },
- {
- measure: 'CAMA_EU38A',
- title: 'Tiempo de toma de mastografía a interpretación radiológica',
- ...CAMA_DAYS,
- },
- {
- measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
- title: 'Tiempo de interpretación radiológica a diagnóstico',
- ...CAMA_DAYS,
- },
- {
- title: 'Tiempo de diagnóstico a tratamiento',
- value: 'Indicador no disponible',
- note: PENDING,
- },
- ],
- opportunity: [
- {
- kind: 'boxes',
- title: 'Tiempo de tamizaje a diagnóstico',
- subtitles: true,
- cards: [
- {
- measure: 'CAMA_EU38A',
- title: 'Tiempo de toma de mastografía a interpretación radiológica',
- },
- {
- measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
- title: 'Tiempo de interpretación radiológica a diagnóstico',
- },
- { title: 'Tiempo de interpretación radiológica a resultado de biopsia' },
- { title: 'Tiempo de diagnóstico a tratamiento' },
- { measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
- ],
- },
- ],
- clinical: [
- {
- kind: 'figures',
- figures: [
- {
- kind: 'share-donut',
- title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
- measure: 'CAMA_BIRADS456_MASTOGRAFIA',
- catalog: BIRADS,
- center: 'mastografías',
- },
- {
- kind: 'share-donut',
- title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
- measure: 'CAMA_BIRADS456_PACIENTE',
- catalog: BIRADS,
- center: 'pacientes',
- },
- ],
- },
- {
- kind: 'figures',
- title: 'Resultado histopatológico por categoría BI-RADS',
- figures: [
- {
- kind: 'rates',
- title: 'Por categoría BI-RADS, {p}',
- measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
- stratum: 'birads',
- rows: BIRADS.categories,
- colored: true,
- positive: ['in_situ', 'invasive'],
- axis: 'Porcentaje con resultado maligno',
- },
- {
- kind: 'donut',
- title: 'Resultado de la biopsia, {p}',
- measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
- catalog: BREAST_BIOPSY,
- center: 'con resultado',
- },
- ],
- },
- {
- kind: 'card',
- measure: 'CAMA_CONFIRMACION_BIRADS45',
- title: 'Tasa de confirmación histopatológica',
- value: '{pct} %',
- note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
- },
- ],
- },
+ cama: CAMA,
cacu: CACU,
};
-
-/** One panel of Trazabilidad (tests/fixtures/reference//ui, tab "Trazabilidad"): a
- * measure month by month, as stacked counts by category, a percentage with its 95 % interval,
- * or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
-export interface HistoryPanel {
- title: string;
- measure: string;
- kind: 'stack' | 'percent' | 'median';
- /** stack: the categories, in the old order, with their names and colours */
- series?: { code: string; label: string; color: string }[];
- /** stack: the y axis */
- axis?: string;
- group?: string;
-}
-export interface History {
- panels: HistoryPanel[];
- /** the line's colour (percent and median) */
- line: string;
- /** how many of the latest months the tab opens with (none: from the first with data) */
- months?: number;
-}
-
-const GREY = '#C9CDD2';
-const stack = (
- title: string,
- measure: string,
- axis: string,
- series: [string, string, string][],
-): HistoryPanel => ({
- title,
- measure,
- kind: 'stack',
- axis,
- series: series.map(([code, label, color]) => ({ code, label, color })),
-});
-const BIRADS_SERIES: [string, string, string][] = [
- ['4A', 'BI-RADS 4A', '#C24269'],
- ['4B', 'BI-RADS 4B', '#9C42C2'],
- ['4C', 'BI-RADS 4C', '#5C42C2'],
- ['5', 'BI-RADS 5', '#C2429C'],
- ['6', 'BI-RADS 6', '#8E2F62'],
- ['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
-];
-
-export const HISTORY: Record = {
- cacu: {
- line: '#6A8000',
- months: 5,
- panels: [
- stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
- ['NILM', 'Normal', '#9DBFE3'],
- ['ASC-US', 'ASC-US', '#2F6DB3'],
- ['LSIL', 'LIEBG', '#9C42C2'],
- ['ASC-H', 'ASC-H', '#5C42C2'],
- ['HSIL', 'LIEAG', '#C2429C'],
- ['CIS', 'Carcinoma in situ', '#8E2F62'],
- ['no_data', 'Sin dato', GREY],
- ]),
- { title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
- { title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
- stack(
- 'Resultado de biopsia tras citología de alto grado',
- 'CACU_CONFIRMACION_CITOLOGIA',
- 'Pacientes',
- [
- ['normal', 'Normal', '#9DBFE3'],
- ['LSIL', 'LIEBG (CIN 1)', '#69C242'],
- ['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
- ['CIS', 'Carcinoma in situ', '#9C42C2'],
- ['carcinoma', 'Carcinoma invasor', '#5C42C2'],
- ['no_biopsy', 'Sin biopsia aún', GREY],
- ['no_data', 'Biopsia sin grado', GREY],
- ],
- ),
- {
- title: 'Días de la toma de la citología a su resultado',
- measure: 'CACU_EU_TIEMPO_REPORTE',
- kind: 'median',
- },
- {
- title: 'Tiempo de tamizaje a diagnóstico',
- measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
- kind: 'median',
- },
- {
- title: 'Tiempo de tamizaje a tratamiento',
- measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
- kind: 'median',
- },
- {
- title: 'Tiempo de diagnóstico a tratamiento',
- measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
- kind: 'median',
- },
- {
- title: 'Riesgo CIN2+ por banda',
- measure: 'CACU_RIESGO_BANDA',
- kind: 'stack',
- axis: 'Pacientes',
- },
- ],
- },
- cama: {
- line: '#9C42C2',
- panels: [
- {
- title: 'Días de la toma de la mastografía a su resultado',
- measure: 'CAMA_EU38A',
- kind: 'median',
- },
- {
- title: 'Días del resultado de la mastografía al diagnóstico',
- measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
- kind: 'median',
- },
- {
- title: 'Días de tamizaje a diagnóstico',
- measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
- kind: 'median',
- },
- stack(
- 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
- 'CAMA_BIRADS456_MASTOGRAFIA',
- 'Mastografías',
- BIRADS_SERIES,
- ),
- stack(
- 'Pacientes con resultado BI-RADS 4, 5 ó 6',
- 'CAMA_BIRADS456_PACIENTE',
- 'Pacientes',
- BIRADS_SERIES,
- ),
- stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
- ['benign', 'Benigno', '#9DBFE3'],
- ['in_situ', 'Carcinoma in situ', '#C24269'],
- ['invasive', 'Carcinoma invasor', '#9C42C2'],
- ['no_biopsy', 'Sin biopsia reportada', GREY],
- ['no_data', 'Sin dato', GREY],
- ]),
- {
- title: 'Tasa de confirmación histopatológica',
- measure: 'CAMA_CONFIRMACION_BIRADS45',
- kind: 'percent',
- },
- ],
- },
- tea: {
- line: '#9C42C2',
- panels: [
- {
- group: 'Tiempos del tamizaje',
- title: 'Días de M-CHAT a ADOS-2',
- measure: 'M26_DIAS_MCHAT_ADOS2',
- kind: 'median',
- },
- {
- group: 'Tiempos del tamizaje',
- title: 'Días de ADOS-2 a diagnóstico',
- measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
- kind: 'median',
- },
- {
- group: 'Tiempos del tamizaje',
- title: 'Días de M-CHAT a diagnóstico positivo',
- measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
- kind: 'median',
- },
- stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
- ['confirmed', 'Diagnóstico confirmado', '#A8C243'],
- ['in_process', 'En proceso', '#B8433A'],
- ]),
- {
- title: 'Porcentaje de confirmación diagnóstica',
- measure: 'M24_CONFIRMACION_DIAGNOSTICO',
- kind: 'percent',
- },
- {
- title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
- measure: 'M21_DIAGNOSTICADOS_CON_EEG',
- kind: 'percent',
- },
- {
- title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
- measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
- kind: 'percent',
- },
- stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
- ['mchat_only', 'Solo M-CHAT', '#B8433A'],
- ['psychology', 'Hasta evaluación psicológica', '#42C29C'],
- ['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
- ['eeg', 'Con EEG', '#A8C243'],
- ]),
- stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
- ['good', 'Bueno', '#A8C243'],
- ['bad', 'No aceptable', '#B8433A'],
- ['not_analyzed', 'Sin analizar', GREY],
- ]),
- ],
- },
-};
diff --git a/src/app/indicadores/palette-cacu.ts b/src/app/indicadores/palette-cacu.ts
new file mode 100644
index 0000000..5c38d1a
--- /dev/null
+++ b/src/app/indicadores/palette-cacu.ts
@@ -0,0 +1,69 @@
+/** CaCu's colours, by category: a colour names a category (never a position in a report), so
+ * one category looks the same on every card; greys are what is absent or not classified. */
+export const NEUTRAL = '#C9CDD2';
+export const NEUTRAL_DARK = '#9AA3AB';
+const STEEL = '#5F7F9A';
+const STEEL_MID = '#8FA7BB';
+
+const GREEN = '#408651';
+const BLUE = '#2778B8';
+const OCHRE = '#B19525';
+const VIOLET = '#7955B1';
+const PINK = '#E07A9C';
+const RASPBERRY = '#CE4778';
+const RUBY = '#BC4163';
+const WINE = '#AA394D';
+const PLUM = '#8D4C79';
+
+export const CYTOLOGY: Record = {
+ NILM: GREEN,
+ 'ASC-US': BLUE,
+ LSIL: OCHRE,
+ 'ASC-H': VIOLET,
+ HSIL: RASPBERRY,
+ CIS: WINE,
+ carcinoma: PLUM,
+ no_data: NEUTRAL,
+};
+export const BIOPSY: Record = {
+ normal: GREEN,
+ LSIL: OCHRE,
+ CIN2: PINK,
+ HSIL: RASPBERRY,
+ CIN3: RUBY,
+ CIS: WINE,
+ carcinoma: PLUM,
+ no_data: NEUTRAL,
+};
+/** HPV by genotype; a prior HPV group takes its genotype's colour. */
+export const HPV: Record = {
+ negative: '#42A77E',
+ positive_16: '#DF8640',
+ positive_18: '#C29C42',
+ positive_16_18: '#C24269',
+ positive_other: '#A8C243',
+ positive: '#A8C243',
+ hpv_16: '#DF8640',
+ hpv_18: '#C29C42',
+ no_data: NEUTRAL,
+};
+export const ROUND: Record = {
+ initial: STEEL,
+ subsequent: STEEL_MID,
+ no_data: NEUTRAL,
+};
+/** A PPV's groups: a cytology or histology level takes its category's colour. */
+export const PRIOR_CYTOLOGY: Record = {
+ ascus_plus: BLUE,
+ lsil_plus: OCHRE,
+ hsil_plus: RASPBERRY,
+ no_data: NEUTRAL,
+};
+export const LEVEL: Record = {
+ cin1_plus: OCHRE,
+ cin2_plus: RASPBERRY,
+ carcinoma: PLUM,
+};
+export const CONFIRMED = '#6A8000';
+/** A median's bar and its quartile marks. */
+export const TINT = { bar: '#42A77E', mark: '#17324D' };
diff --git a/src/app/indicadores/readings.html b/src/app/indicadores/readings.html
new file mode 100644
index 0000000..fc46b63
--- /dev/null
+++ b/src/app/indicadores/readings.html
@@ -0,0 +1,132 @@
+@if (!hideTitle()) {
+ {{ title() }}
+}
+@if (headline()) {
+ {{ headline() }}
+}
+@if (note()) {
+ {{ note() }}
+}
+@if (modes().length > 1 && !view()) {
+
+ @for (m of modes(); track m.label) {
+ {{ m.label }}
+ }
+
+}
+@if (mode().caption) {
+ {{ mode().caption }}
+}
+@if (mode().heading) {
+ {{ mode().heading }}
+}
+@if (loading()) {
+
+} @else if (missing(); as why) {
+ {{ why }}
+} @else if (groups(); as g) {
+
+
+
+ @for (t of [0, 25, 50, 75, 100]; track t) {
+ {{ t }} %
+ }
+
+
+
+ @for (group of g.groups; track group.code) {
+
+
+ {{ group.label }} {{ unit() }}: {{ group.total }}
+ @if (group.hint) {
+ {{ group.hint }}
+ }
+
+ @for (row of group.rows; track row.label) {
+
+ {{ row.label }}
+
+
+
+ {{ row.text }}
+
+ }
+
+ }
+ @if (g.note) {
+ {{ g.note }}
+ }
+} @else if (table(); as t) {
+
+
+
+ {{ mode().rowsLabel ?? '' }}
+ @for (h of t.head; track h) {
+ {{ h }}
+ }
+
+
+
+ @for (row of t.rows; track row.label) {
+
+
+ {{ row.label }}
+ @if (row.hint) {
+ {{ row.hint }}
+ }
+ @if (row.none) {
+ {{ row.none }}
+ } @else {
+
+ @for (p of row.segments ?? []; track $index) {
+
+ } @empty {
+
+ }
+ @for (m of row.marks; track $index) {
+
+ }
+
+ }
+
+ @for (c of row.cells; track $index) {
+ {{ c }}
+ }
+
+ }
+
+
+ @if (t.note) {
+ {{ t.note }}
+ }
+ @if (t.legend; as legend) {
+
+ @for (l of legend; track l.label) {
+ {{ l.label }}
+ }
+
+ }
+} @else {
+ Sin datos en el periodo.
+}
+@if (foot()) {
+ {{ foot() }}
+}
diff --git a/src/app/indicadores/readings.scss b/src/app/indicadores/readings.scss
new file mode 100644
index 0000000..1369c7a
--- /dev/null
+++ b/src/app/indicadores/readings.scss
@@ -0,0 +1,156 @@
+:host {
+ --name-width: minmax(9rem, 16rem);
+ --value-width: 8.5rem;
+ display: block;
+ min-width: 0;
+}
+:host(.compact) {
+ overflow-x: auto;
+ .title {
+ font-size: 18px;
+ font-weight: 500;
+ }
+ .state {
+ color: var(--color-text-secondary);
+ font-size: 13px;
+ margin: 8px 0;
+ }
+ table {
+ font-size: 13px;
+ }
+ thead th {
+ font-weight: 500;
+ }
+}
+.title {
+ margin: 0 0 8px;
+}
+.headline {
+ font-weight: 500;
+}
+.heading {
+ font-size: 14px;
+ font-weight: 500;
+ margin: 12px 0 4px;
+}
+mat-button-toggle-group {
+ flex-wrap: wrap;
+ margin: 4px 0;
+}
+table {
+ border-collapse: collapse;
+ width: 100%;
+}
+th,
+td {
+ font-weight: 400;
+ padding: 4px 6px;
+ text-align: right;
+ white-space: nowrap;
+}
+thead th:first-child,
+th[scope='row'] {
+ text-align: left;
+ white-space: normal;
+ width: 60%;
+}
+tr.sub th[scope='row'],
+.row.sub .name {
+ padding-left: 1.25rem;
+}
+.hint {
+ color: var(--color-text-secondary);
+ display: block;
+ font-size: 12px;
+}
+.track {
+ background: rgba(0, 0, 0, 0.06);
+ display: flex;
+ height: 8px;
+ position: relative;
+}
+.bar {
+ background: #a8c243;
+ display: block;
+ flex: none;
+ height: 100%;
+}
+.mark {
+ background: #333;
+ height: 12px;
+ position: absolute;
+ top: -2px;
+ width: 2px;
+}
+.legend {
+ display: flex;
+ flex-wrap: wrap;
+ font-size: 12px;
+ gap: 4px 16px;
+ i {
+ display: inline-block;
+ height: 10px;
+ margin-right: 6px;
+ width: 10px;
+ }
+}
+.axis,
+.row {
+ column-gap: 8px;
+ display: grid;
+ grid-template-columns: var(--name-width) 1fr var(--value-width);
+}
+.axis {
+ font-size: 12px;
+ margin: 12px 0 2px;
+}
+.ticks {
+ height: 1.2em;
+ position: relative;
+ span {
+ position: absolute;
+ transform: translateX(-50%);
+ white-space: nowrap;
+ }
+ span:first-child {
+ transform: none;
+ }
+ span:last-child {
+ transform: translateX(-100%);
+ }
+}
+.group {
+ margin: 6px 0 14px;
+ h4 {
+ font-size: 0.95rem;
+ margin: 0 0 4px;
+ }
+ .n {
+ color: var(--color-text-secondary);
+ font-size: 0.8em;
+ font-weight: 400;
+ margin-left: 8px;
+ }
+}
+.row {
+ align-items: center;
+ font-size: 0.9rem;
+ min-height: 22px;
+ .track {
+ background:
+ linear-gradient(to right, #d8dde1 1px, transparent 1px) 25% 0 / 1px 100% no-repeat,
+ linear-gradient(to right, #d8dde1 1px, transparent 1px) 50% 0 / 1px 100% no-repeat,
+ linear-gradient(to right, #d8dde1 1px, transparent 1px) 75% 0 / 1px 100% no-repeat,
+ rgba(0, 0, 0, 0.06);
+ height: 10px;
+ }
+ .fill {
+ display: block;
+ height: 100%;
+ }
+ .value {
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+ white-space: nowrap;
+ }
+}
diff --git a/src/app/indicadores/readings.ts b/src/app/indicadores/readings.ts
index 8a5985e..1fb1992 100644
--- a/src/app/indicadores/readings.ts
+++ b/src/app/indicadores/readings.ts
@@ -1,144 +1,49 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading';
-import { Figure, Plot } from '../plot';
-import { bars, Mode } from './bars';
-import { Reading } from './measures';
+import { bars, Mode, Read } from './bars';
+import { grouped, outcomes, shares, unavailable } from './groups';
-/** A card read one mode at a time: its title, its headline, the toggle and the bars. */
+/** A card read one mode at a time: its title, its headline, the toggle and the bars (or the
+ * groups of bars). In a section with one selector for several cards, `view` picks the mode. */
@Component({
selector: 'app-readings',
- imports: [Loading, MatButtonToggleModule, Plot],
- template: `
- {{ title() }}
- @if (headline()) {
- {{ headline() }}
- }
- @if (note()) {
- {{ note() }}
- }
- @if (modes().length > 1) {
-
- @for (m of modes(); track m.label) {
- {{ m.label }}
- }
-
- }
- @if (mode().caption) {
- {{ mode().caption }}
- }
- @if (loading()) {
-
- } @else if (figure(); as f) {
-
- } @else if (table(); as t) {
-
-
-
-
- @for (h of t.head; track h) {
- {{ h }}
- }
-
-
-
- @for (row of t.rows; track row.label) {
-
-
- {{ row.label }}
-
-
- @for (m of row.marks; track $index) {
-
- }
-
-
- @for (c of row.cells; track $index) {
- {{ c }}
- }
-
- }
-
-
- } @else {
- Sin datos en el periodo.
- }
- `,
- styles: `
- :host {
- display: block;
- min-width: 0;
- }
- .title {
- margin: 0 0 8px;
- }
- .headline {
- font-weight: 500;
- }
- mat-button-toggle-group {
- flex-wrap: wrap;
- margin: 4px 0;
- }
- table {
- border-collapse: collapse;
- width: 100%;
- }
- th,
- td {
- font-weight: 400;
- padding: 4px 6px;
- text-align: right;
- white-space: nowrap;
- }
- th[scope='row'] {
- text-align: left;
- white-space: normal;
- width: 60%;
- }
- .track {
- background: rgba(0, 0, 0, 0.06);
- display: block;
- height: 8px;
- position: relative;
- }
- .bar {
- background: #a8c243;
- display: block;
- height: 100%;
- }
- .mark {
- background: #333;
- height: 12px;
- position: absolute;
- top: -2px;
- width: 2px;
- }
- `,
+ imports: [Loading, MatButtonToggleModule],
+ host: { '[class.compact]': 'compact()' },
+ templateUrl: './readings.html',
+ styleUrl: './readings.scss',
})
export class Readings {
readonly title = input.required();
+ readonly hideTitle = input(false);
+ /** smaller type, for cards of tables with many columns */
+ readonly compact = input(false);
readonly headline = input('');
+ /** the headline said under the figure instead */
+ readonly foot = input('');
readonly note = input('');
readonly modes = input.required();
+ readonly view = input();
readonly loading = input(false);
- /** A measure's reading in the applied period, and the figure of a mode that has one. */
- readonly read = input.required<(measure: string) => Reading | undefined>();
- readonly draw = input.required<(mode: Mode) => Figure | undefined>();
+ readonly read = input.required();
protected readonly chosen = signal('');
- protected readonly mode = computed(
- () => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0],
- );
- protected readonly table = computed(() => bars(this.mode(), this.read()));
- protected readonly figure = computed(() =>
- this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
+ protected readonly mode = computed(() => {
+ const label = this.view() ?? this.chosen();
+ return this.modes().find((m) => m.label === label) ?? this.modes()[0];
+ });
+ protected readonly missing = computed(() => unavailable(this.mode(), this.read()));
+ protected readonly groups = computed(() => grouped(this.mode(), this.read()));
+ protected readonly table = computed(
+ () =>
+ outcomes(this.mode(), this.read()) ??
+ shares(this.mode(), this.read()) ??
+ bars(this.mode(), this.read()),
);
+ /** "Pacientes", "Reportes": what a group's records are called, capitalised. */
+ protected readonly unit = computed(() => {
+ const m = this.mode();
+ const unit = m.kind === 'grouped' ? m.unit : '';
+ return unit.charAt(0).toUpperCase() + unit.slice(1);
+ });
}
diff --git a/src/app/indicadores/section.ts b/src/app/indicadores/section.ts
index 305a507..4843e06 100644
--- a/src/app/indicadores/section.ts
+++ b/src/app/indicadores/section.ts
@@ -1,11 +1,10 @@
-import { Component, computed, input, signal } from '@angular/core';
+import { NgTemplateOutlet } from '@angular/common';
+import { Component, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure } from 'fhir/r4';
-import { Mode } from './bars';
-import { scenarioBars } from './figures';
-import { detail, donut, formatScore, name, Reading, scoring } from './measures';
-import type { Section } from './pages';
+import { detail, formatScore, Reading, scoring } from './measures';
+import type { ReadingsCard, Section } from './pages';
import { Readings } from './readings';
/** The applied period's readings and the measures they are of. */
@@ -16,45 +15,57 @@ export interface Source {
}
type Shown = Extract;
-/** A card of readings, several side by side, or one of several at a time. */
+/** A card of readings, several side by side (optionally read through one selector), or one of
+ * several at a time (as sections, or as one card). */
@Component({
selector: 'app-section',
- imports: [MatButtonToggleModule, MatCardModule, Readings],
+ imports: [MatButtonToggleModule, MatCardModule, NgTemplateOutlet, Readings],
template: `
@let s = section();
@if (s.kind === 'readings') {
-
+
+
+
+ } @else if (s.kind === 'choice' && s.card) {
+ @let open = chosen() || s.choices[0].label;
+
+
+ {{ s.title }}
+
+ @for (c of s.choices; track c.label) {
+ @if (c.label === open) {
+
+ }
+ }
} @else {
{{ s.title }}
@if (s.kind === 'columns') {
+ @let view = picked() || s.views?.[0];
+ @if (s.views) {
+
+ @for (v of s.views; track v) {
+ {{ v }}
+ }
+
+ }
@for (inner of s.sections; track $index) {
-
+
}
} @else {
@let open = chosen() || s.choices[0].label;
-
- @for (c of s.choices; track c.label) {
- {{ c.label }}
- }
-
+
@for (c of s.choices; track c.label) {
@if (c.label === open) {
@@ -62,13 +73,48 @@ type Shown = Extract;
}
}
}
+
+
+
+ @for (c of s.choices; track c.label) {
+ {{ c.label }}
+ }
+
+
+
+
+
`,
styles: `
:host {
display: block;
- margin-top: 16px;
+ margin-top: 24px;
min-width: 0;
}
+ .title {
+ font-size: 18px;
+ font-weight: 500;
+ margin: 0 0 8px;
+ }
+ mat-button-toggle-group {
+ flex-wrap: wrap;
+ margin: 4px 0 8px;
+ }
.columns {
display: grid;
column-gap: 16px;
@@ -82,24 +128,22 @@ type Shown = Extract;
export class ReadingsSection {
readonly section = input.required();
readonly of = input.required();
+ /** The mode a card following its section's selector takes (its label). */
+ readonly view = input();
+ protected readonly picked = signal('');
protected readonly chosen = signal('');
- protected readonly headline = computed(() => {
- const s = this.section();
- const code = s.kind === 'readings' ? s.headline : undefined;
- const measure = code && this.of().measure(code);
- const r = code && this.of().reading(code);
+ /** A card whose modes say what their rows count reads in smaller type. */
+ protected compact(c: ReadingsCard): boolean {
+ return c.modes.some((m) => !!m.heading);
+ }
+
+ /** A card's headline: its measure's score and its counts, in its own unit. */
+ protected headline(c: ReadingsCard): string {
+ const measure = c.headline && this.of().measure(c.headline);
+ const r = c.headline && this.of().reading(c.headline);
if (!measure || !r) return '';
- const words = detail(measure, r);
+ const words = detail(measure, r, c.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
- });
- protected readonly draw = computed(() => (mode: Mode) => {
- if (mode.kind !== 'figure') return undefined;
- const r = this.of().reading(mode.measure);
- const measure = this.of().measure(mode.measure);
- if (!measure || !r?.populations['initial-population']) return undefined;
- if (mode.figure === 'donut') return donut(measure, r);
- const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
- return scenarioBars(r, { groups: [], categories }, 'follow_up_status', name);
- });
+ }
}
diff --git a/src/app/indicadores/tab-definiciones.ts b/src/app/indicadores/tab-definiciones.ts
index 07523bc..89d35b6 100644
--- a/src/app/indicadores/tab-definiciones.ts
+++ b/src/app/indicadores/tab-definiciones.ts
@@ -3,7 +3,8 @@ import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app';
import type { Domain } from '../api/models/domain';
import { code, label } from '../fhir';
-import { periodTypes, STRATA } from './measures';
+import { STRATA } from './labels';
+import { periodTypes } from './measures';
const SCORING: Record = {
proportion: 'Proporción',
@@ -15,6 +16,29 @@ const IMPROVEMENT: Record = {
decrease: 'Mejor si baja',
};
const PERIODS: Record = { semester: 'Semestral', month: 'Mensual' };
+/** Where the NCI reference risks come from. */
+const NCI = [
+ [
+ 'https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/',
+ 'Egemen y colaboradores: estimaciones que sustentan las guías (2020).',
+ ],
+ [
+ 'https://doi.org/10.1097/LGT.0000000000000528',
+ 'Cheung y colaboradores: métodos de estimación (2020).',
+ ],
+ [
+ 'https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/',
+ 'Perkins y colaboradores: guías de manejo ASCCP 2019.',
+ ],
+ [
+ 'https://data.lhncbc.nlm.nih.gov/public/cervixca/AdditionalTables.zip',
+ 'LHNCBC: libros de tablas adicionales.',
+ ],
+ [
+ 'https://web.archive.org/web/20240710095705/https://lhncbc.nlm.nih.gov/LHC-research/LHC-projects/image-processing/cervixca.html',
+ 'LHNCBC: página archivada de las tablas, 10 de julio de 2024.',
+ ],
+].map(([url, citation]) => ({ url, citation }));
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
* indicator opening to what it is (how it scores, which way is better, its periods and
@@ -31,6 +55,23 @@ const PERIODS: Record = { semester: 'Semestral', month: 'Mensual
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
espécimen fue insatisfactorio.
+ Riesgos de referencia NCI
+
+ Los riesgos de referencia corresponden a la cohorte Kaiser Permanente Northern
+ California (2003–2017, pacientes de 25 a 65 años). Las guías ASCCP deciden la conducta
+ con el riesgo de CIN3+. Los riesgos publicados de CIN2+ y cáncer son resultados
+ complementarios; no son directamente comparables con las estimaciones institucionales
+ porque no están validados para la población de esta plataforma.
+
+
}
@if (available().length) {
Periodicidad disponible: {{ available().join(', ') }}.
@@ -48,6 +89,22 @@ const PERIODS: Record = { semester: 'Semestral', month: 'Mensual
@if (m.description) {
{{ m.description }}
}
+ @if (m.relatedArtifact?.length) {
+ Referencias
+
+ }
Cálculo
{{ scoring[code(m.scoring) ?? ''] }}
@@ -116,6 +173,7 @@ const PERIODS: Record = { semester: 'Semestral', month: 'Mensual
`,
})
export class TabDefiniciones {
+ protected readonly nci = NCI;
readonly domain = input.required();
readonly measures = input.required();
protected readonly scoring = SCORING;
diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html
index 831afcd..c08984e 100644
--- a/src/app/indicadores/tab-indicadores.html
+++ b/src/app/indicadores/tab-indicadores.html
@@ -40,12 +40,19 @@
}
@if (page(); as pg) {
@if (applied(); as period) {
+ @if (pg.clinicalFirst) {
+
+ }
Indicadores de oportunidad
Periodo {{ period }}
-
+
@for (k of pg.kpis; track k.title) {
@@ -73,6 +80,12 @@
}
+ @if (!pg.clinicalFirst) {
+
+ }
+ }
+
+
Indicadores clínicos
@for (section of pg.clinical; track $index) {
@@ -81,7 +94,7 @@
/>
}
- }
+
@switch (section.kind) {
@@ -157,10 +170,6 @@
Sin datos publicados
} @else {
Filtro general aplicado: {{ period }}
- @if (section.subtitles) {
- {{ measureTitle(b.measure) }}
- Figura: Caja de cuartiles
- }
@if (reports.isLoading()) {
} @else if (boxOf(b.measure); as fig) {
@@ -174,21 +183,6 @@
}
}
- @case ('card') {
-
-
- {{ section.title }}
-
- @let w = kpiParts(kpiValue(section));
- {{ w[0] }}
- @if (w[1]) {
- {{ w[1] }}
- }
-
- {{ kpiNote(section) }}
-
-
- }
@default {
diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss
index f641449..a33be93 100644
--- a/src/app/indicadores/tab-indicadores.scss
+++ b/src/app/indicadores/tab-indicadores.scss
@@ -42,13 +42,13 @@ h2 {
@media (min-width: 1000px) {
.kpis {
- grid-template-columns: repeat(3, 1fr);
+ grid-template-columns: repeat(var(--kpi-cols-md, 3), 1fr);
}
}
@media (min-width: 1350px) {
.kpis {
- grid-template-columns: repeat(5, 1fr);
+ grid-template-columns: repeat(var(--kpi-cols-lg, 5), 1fr);
}
}
@@ -221,12 +221,6 @@ h2.box-title {
margin: 0 0 4px;
}
-h2.box-subtitle {
- font-size: 16px;
- font-weight: 500;
- margin: 8px 0 0;
-}
-
.empty-figure {
align-items: center;
border: 1px solid var(--color-border);
@@ -246,10 +240,6 @@ h2.box-subtitle {
font-weight: 500;
}
-.kpi.closing {
- margin-top: 24px;
-}
-
.summary {
margin-bottom: 24px;
diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts
index e6f4127..2330813 100644
--- a/src/app/indicadores/tab-indicadores.ts
+++ b/src/app/indicadores/tab-indicadores.ts
@@ -15,8 +15,6 @@ import {
boxFigure,
countBars,
fill,
- nestedDonut,
- rateDots,
scenarioBars,
shareDonut,
} from './figures';
@@ -26,16 +24,15 @@ import {
donut,
formatScore,
medians,
- name,
periodLabel,
periods,
PeriodType,
reading,
Reading,
scoring,
- STRATA,
strataBars,
} from './measures';
+import { name, STRATA } from './labels';
import { Loading } from '../loading';
import { ReadingsSection, Source } from './section';
@@ -262,8 +259,9 @@ export class TabIndicadores {
unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'),
};
});
- protected measureTitle(code: string | undefined): string {
- return (code && this.byName().get(code)?.title) || '';
+ /** The cards' columns at medium and large widths: all in one row up to five, else in two. */
+ protected kpiColumns(n: number): [number, number] {
+ return [Math.min(n, 3), n <= 5 ? n : Math.ceil(n / 2)];
}
/** What a section of readings is drawn from. */
protected readonly of = computed(() => {
@@ -278,8 +276,6 @@ export class TabIndicadores {
const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
switch (spec.kind) {
- case 'donut':
- return nestedDonut(r, spec.catalog, spec.center);
case 'share-donut':
return shareDonut(r, spec.catalog, spec.center);
case 'counts':
@@ -290,8 +286,6 @@ export class TabIndicadores {
return ageShare(r, spec.names[0]);
case 'scenario-bars':
return scenarioBars(r, spec.catalog, spec.stratum, name);
- case 'rates':
- return rateDots(r, spec);
}
}
}
diff --git a/src/app/indicadores/tab-riesgos-tea.ts b/src/app/indicadores/tab-riesgos-tea.ts
index a51de02..fed57c8 100644
--- a/src/app/indicadores/tab-riesgos-tea.ts
+++ b/src/app/indicadores/tab-riesgos-tea.ts
@@ -11,7 +11,7 @@ import type { Patient } from 'fhir/r4';
import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { ageLabel } from './figures';
-import { name } from './measures';
+import { name } from './labels';
import { matchesSearch, PatientSearch } from './patient-search';
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */
diff --git a/src/app/indicadores/tab-riesgos.ts b/src/app/indicadores/tab-riesgos.ts
index a86d1ff..0e5e6bc 100644
--- a/src/app/indicadores/tab-riesgos.ts
+++ b/src/app/indicadores/tab-riesgos.ts
@@ -22,7 +22,7 @@ import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
-import { name } from './measures';
+import { name } from './labels';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
diff --git a/src/app/indicadores/tab-seguimiento.html b/src/app/indicadores/tab-seguimiento.html
index 66dd6c9..fb18cbe 100644
--- a/src/app/indicadores/tab-seguimiento.html
+++ b/src/app/indicadores/tab-seguimiento.html
@@ -115,4 +115,23 @@
Siguiente
+
+ Exportar Excel
+
+
+ Exportar PDF
+
+@if (saveError()) {
+ {{ saveError() }}
+}
diff --git a/src/app/indicadores/tab-seguimiento.ts b/src/app/indicadores/tab-seguimiento.ts
index c35d163..5e3a404 100644
--- a/src/app/indicadores/tab-seguimiento.ts
+++ b/src/app/indicadores/tab-seguimiento.ts
@@ -7,10 +7,12 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
+import { saveExcel, savePdf } from '../export';
import { camaRows, windowStart } from './follow-up';
+import { camaFollowUpSheet } from './follow-up-sheet';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
-import { name, PRIORITY } from './measures';
+import { name, PRIORITY } from './labels';
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
@@ -47,22 +49,23 @@ export class TabSeguimiento {
protected readonly name = name;
protected readonly priority = (code: string) => PRIORITY[code] ?? code;
+ protected readonly saving = signal(false);
+ protected readonly saveError = signal('');
+ /** The list as it is asked for, whatever the page. */
+ private readonly query = computed(() => ({
+ 'follow-up-window': this.window(),
+ ...patientSearch(this.search()),
+ 'follow-up-cutoff': this.cutoff() || undefined,
+ 'follow-up-status': this.status() || undefined,
+ _revinclude: ['DiagnosticReport:subject'],
+ '_include:iterate': 'DiagnosticReport:result',
+ }));
+
private readonly first = resource({
- params: () => ({
- domain: this.domain(),
- 'follow-up-window': this.window(),
- ...patientSearch(this.search()),
- 'follow-up-cutoff': this.cutoff() || undefined,
- 'follow-up-status': this.status() || undefined,
- _count: this.size(),
- }),
- loader: ({ params: { domain, ...params } }) => {
+ params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
+ loader: ({ params: { domain, query, size } }) => {
this.moved.set(undefined);
- return this.fhir.search(domain, 'Patient', {
- ...params,
- _revinclude: ['DiagnosticReport:subject'],
- '_include:iterate': 'DiagnosticReport:result',
- });
+ return this.fhir.search(domain, 'Patient', { ...query, _count: size });
},
});
protected readonly loading = signal(false);
@@ -91,6 +94,32 @@ export class TabSeguimiento {
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
+ /** The whole list, not the page shown, as a file. */
+ protected async save(kind: 'xlsx' | 'pdf'): Promise {
+ this.saving.set(true);
+ this.saveError.set('');
+ try {
+ const cutoff = this.applied();
+ const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
+ const pages = await this.fhir.all(this.domain(), 'Patient', asked);
+ const sheet = camaFollowUpSheet(
+ pages.flatMap((p) => camaRows(p, cutoff)),
+ [
+ ['Ventana consultada', `${windowStart(cutoff, this.window())} al ${cutoff}`],
+ ['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
+ ['Búsqueda', this.search() || 'Ninguna'],
+ ],
+ this.priority,
+ );
+ if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cama');
+ else await savePdf([sheet], 'seguimiento-cama', true);
+ } catch {
+ this.saveError.set('No se generó el archivo.');
+ } finally {
+ this.saving.set(false);
+ }
+ }
+
protected retry(): void {
this.first.reload();
}
diff --git a/src/app/indicadores/tab-trazabilidad.ts b/src/app/indicadores/tab-trazabilidad.ts
index e108d96..3f7203b 100644
--- a/src/app/indicadores/tab-trazabilidad.ts
+++ b/src/app/indicadores/tab-trazabilidad.ts
@@ -1,12 +1,14 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
+import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { historyFigure } from './figures';
-import { periodLabel, periods, PeriodType, reading } from './measures';
-import { HISTORY, HistoryPanel } from './pages';
+import { periodLabel, periods, periodStart, PeriodType, reading } from './measures';
+import { HISTORY, HistoryPanel } from './history';
interface Drawn {
panel: HistoryPanel;
@@ -19,24 +21,37 @@ interface Drawn {
* each measure period by period. */
@Component({
selector: 'app-tab-trazabilidad',
- imports: [Loading, MatButtonToggleModule, Plot],
+ imports: [Loading, MatButtonModule, MatButtonToggleModule, MatSelectModule, Plot],
template: `
Filtros
Mensual
Semestral
+ @if (domain() !== 'tea') {
+
+ Periodo seleccionado
+
+ @for (p of options(); track p) {
+ {{ p }}
+ }
+
+
+
+ Aplicar
+
+ }
@if (series.isLoading()) {
-
+
} @else if (series.error()) {
- No se pudo cargar la trazabilidad.
+ No se pudo cargar el histórico.
Reintentar
} @else {
@@ -71,6 +86,12 @@ interface Drawn {
padding: 16px 20px;
margin-bottom: 16px;
}
+ .filters {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ }
.filters-title {
font-size: 16px;
font-weight: 500;
@@ -95,13 +116,28 @@ export class TabTrazabilidad {
readonly domain = input.required();
readonly measures = input.required();
protected readonly type = signal('month');
+ protected readonly options = computed(() => periods(this.type()));
+ /** The period the history ends in (CaCu, CaMa): the chosen one, once applied. */
+ protected readonly chosen = signal(periods('month')[0]);
+ protected readonly upTo = signal(periods('month')[0]);
+
+ protected setType(type: PeriodType): void {
+ this.type.set(type);
+ this.chosen.set(this.options()[0]);
+ this.upTo.set(this.options()[0]);
+ }
protected readonly series = resource({
- params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
+ params: () => ({
+ domain: this.domain(),
+ type: this.type(),
+ measures: this.measures(),
+ upTo: this.upTo(),
+ }),
loader: async ({ params }) => {
const history = HISTORY[params.domain];
if (!history) return [];
- const asked = periods(params.type).reverse();
+ const asked = periods(params.type, 6, periodStart(params.upTo)).reverse();
return Promise.all(
history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure);
diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts
index c58101e..ffd1383 100644
--- a/src/app/paciente/paciente.ts
+++ b/src/app/paciente/paciente.ts
@@ -24,7 +24,7 @@ import { recordSheets } from './record-sheets';
import { riskScales, RiskScales } from './risk-scales';
import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
-import { LABELS, name, PRIORITY } from '../indicadores/measures';
+import { LABELS, name, PRIORITY } from '../indicadores/labels';
import {
BIOMARKER_NAMES,
byDeviation,
diff --git a/src/app/revision/revision.ts b/src/app/revision/revision.ts
index 59972e6..7d5a210 100644
--- a/src/app/revision/revision.ts
+++ b/src/app/revision/revision.ts
@@ -32,6 +32,7 @@ const ENTITIES: Record = {
cervical_biopsy: 'Biopsia cervical',
clinical_note: 'Nota médica',
death: 'Defunción',
+ cacu_eligibility_evidence: 'Evidencia de elegibilidad de CaCu',
identity: 'Identidad',
mammography: 'Mastografía',
breast_biopsy: 'Biopsia de mama',