Compare commits

..

1 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 749afe765d CaMa: present diagnostic pathway and biopsy results 2026-12-01 12:27:16 -06:00
22 changed files with 772 additions and 354 deletions
+23 -1
View File
@@ -210,7 +210,29 @@ for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page, page,
}) => { }) => {
const old = captured(domain); const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores'); const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
-113
View File
@@ -979,48 +979,6 @@
"title": "Join", "title": "Join",
"type": "object" "type": "object"
}, },
"LanguageModel": {
"properties": {
"available": {
"title": "Available",
"type": "boolean"
},
"model": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Model"
},
"reason": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Reason"
},
"vision": {
"title": "Vision",
"type": "boolean"
}
},
"required": [
"available",
"model",
"vision",
"reason"
],
"title": "LanguageModel",
"type": "object"
},
"Link": { "Link": {
"additionalProperties": false, "additionalProperties": false,
"description": "Identity rows from every input, grouped into persons (Splink).\n\nTwo records are the same person when any rule holds (Splink's SQL rule syntax, `l.`\nand `r.` for the two records); persons are the connected groups. A person whose\nrecords disagree on birth date or sex is held for review as a whole. Pairs Splink\nscores above `review` that ended up apart are queued as possible matches.", "description": "Identity rows from every input, grouped into persons (Splink).\n\nTwo records are the same person when any rule holds (Splink's SQL rule syntax, `l.`\nand `r.` for the two records); persons are the connected groups. A person whose\nrecords disagree on birth date or sex is held for review as a whole. Pairs Splink\nscores above `review` that ended up apart are queued as possible matches.",
@@ -3009,28 +2967,6 @@
] ]
} }
}, },
"/ingest/llm": {
"get": {
"description": "The site's language model (LLM_URL): whether it answers, which, and whether it\nreads images. Autom\u00e1tico needs it; extract nodes use their patterns without it.",
"operationId": "language_model",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/LanguageModel"
}
}
},
"description": "Successful Response"
}
},
"summary": "Language Model",
"tags": [
"ingest"
]
}
},
"/ingest/pipelines": { "/ingest/pipelines": {
"get": { "get": {
"operationId": "pipelines", "operationId": "pipelines",
@@ -3175,55 +3111,6 @@
] ]
} }
}, },
"/ingest/pipelines/{pipeline_id}/draft": {
"post": {
"description": "Autom\u00e1tico: starts the `draft` job, which draws the whole pipeline from its saved\nsources (the only nodes it may hold), saves it as a new version and runs it; follow it\nat /runs/{run_id}.",
"operationId": "start_draft",
"parameters": [
{
"in": "path",
"name": "pipeline_id",
"required": true,
"schema": {
"maxLength": 40,
"pattern": "^[a-z][a-z0-9_]*$",
"title": "Pipeline Id",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Start Draft",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Start Draft",
"tags": [
"ingest"
]
}
},
"/ingest/pipelines/{pipeline_id}/nodes/{node_id}/rows": { "/ingest/pipelines/{pipeline_id}/nodes/{node_id}/rows": {
"get": { "get": {
"description": "What a node produced in the last run (empty if it produced nothing yet).", "description": "What a node produced in the last run (empty if it produced nothing yet).",
-30
View File
@@ -1,30 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { LanguageModel } from '../../models/language-model';
export interface LanguageModel$Params {
}
export function languageModel(http: HttpClient, rootUrl: string, params?: LanguageModel$Params, context?: HttpContext): Observable<StrictHttpResponse<LanguageModel>> {
const rb = new RequestBuilder(rootUrl, languageModel.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<LanguageModel>;
})
);
}
languageModel.PATH = '/ingest/llm';
-35
View File
@@ -1,35 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface StartDraft$Params {
pipeline_id: string;
}
export function startDraft(http: HttpClient, rootUrl: string, params: StartDraft$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, startDraft.PATH, 'post');
if (params) {
rb.path('pipeline_id', params.pipeline_id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
startDraft.PATH = '/ingest/pipelines/{pipeline_id}/draft';
-4
View File
@@ -15,16 +15,12 @@ export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/g
export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map'; export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map';
export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map'; export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map';
export { saveConceptMap as saveConceptMap } from './fn/ingest/save-concept-map'; export { saveConceptMap as saveConceptMap } from './fn/ingest/save-concept-map';
export type { LanguageModel$Params as LanguageModel$Params } from './fn/ingest/language-model';
export { languageModel as languageModel } from './fn/ingest/language-model';
export type { Pipelines$Params as Pipelines$Params } from './fn/ingest/pipelines'; export type { Pipelines$Params as Pipelines$Params } from './fn/ingest/pipelines';
export { pipelines as pipelines } from './fn/ingest/pipelines'; export { pipelines as pipelines } from './fn/ingest/pipelines';
export type { Pipeline$Params as Pipeline$Params } from './fn/ingest/pipeline'; export type { Pipeline$Params as Pipeline$Params } from './fn/ingest/pipeline';
export { pipeline as pipeline } from './fn/ingest/pipeline'; export { pipeline as pipeline } from './fn/ingest/pipeline';
export type { SavePipeline$Params as SavePipeline$Params } from './fn/ingest/save-pipeline'; export type { SavePipeline$Params as SavePipeline$Params } from './fn/ingest/save-pipeline';
export { savePipeline as savePipeline } from './fn/ingest/save-pipeline'; export { savePipeline as savePipeline } from './fn/ingest/save-pipeline';
export type { StartDraft$Params as StartDraft$Params } from './fn/ingest/start-draft';
export { startDraft as startDraft } from './fn/ingest/start-draft';
export type { NodeRows$Params as NodeRows$Params } from './fn/ingest/node-rows'; export type { NodeRows$Params as NodeRows$Params } from './fn/ingest/node-rows';
export { nodeRows as nodeRows } from './fn/ingest/node-rows'; export { nodeRows as nodeRows } from './fn/ingest/node-rows';
export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run'; export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
-1
View File
@@ -19,7 +19,6 @@ export type { Group } from './models/group';
export type { Guided } from './models/guided'; export type { Guided } from './models/guided';
export type { HttpValidationError } from './models/http-validation-error'; export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join'; export type { Join } from './models/join';
export type { LanguageModel } from './models/language-model';
export type { Link } from './models/link'; export type { Link } from './models/link';
export type { Listing } from './models/listing'; export type { Listing } from './models/listing';
export type { Login } from './models/login'; export type { Login } from './models/login';
-9
View File
@@ -1,9 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface LanguageModel {
available: boolean;
model: (string | null);
reason: (string | null);
vision: boolean;
}
-18
View File
@@ -36,24 +36,6 @@
<span class="spacer"></span> <span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button> <button mat-stroked-button (click)="save()">Guardar</button>
<button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button> <button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button>
@if (onlySources()) {
<span
[matTooltip]="
llm.value()?.available
? 'El modelo de lenguaje del sitio arma toda la canalización a partir de estas fuentes y la ejecuta.'
: 'No disponible: ' +
(llm.value()?.reason ?? 'no hay modelo de lenguaje configurado')
"
>
<button
mat-flat-button
(click)="automatic()"
[disabled]="running() || !llm.value()?.available"
>
<mat-icon>auto_awesome</mat-icon>Armar automáticamente
</button>
</span>
}
} }
</div> </div>
@if (message()) { @if (message()) {
+4 -36
View File
@@ -23,14 +23,12 @@ import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material'; import { withFormlyMaterial } from '@ngx-formly/material';
import { Connection, NodeChange, Vflow } from 'ngx-vflow'; import { Connection, NodeChange, Vflow } from 'ngx-vflow';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { languageModel } from '../api/fn/ingest/language-model';
import { nodeRows } from '../api/fn/ingest/node-rows'; import { nodeRows } from '../api/fn/ingest/node-rows';
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline'; import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
import { pipelines } from '../api/fn/ingest/pipelines'; import { pipelines } from '../api/fn/ingest/pipelines';
import { savePipeline } from '../api/fn/ingest/save-pipeline'; import { savePipeline } from '../api/fn/ingest/save-pipeline';
import { schema } from '../api/fn/ingest/schema'; import { schema } from '../api/fn/ingest/schema';
import { sourcePreview } from '../api/fn/ingest/source-preview'; import { sourcePreview } from '../api/fn/ingest/source-preview';
import { startDraft } from '../api/fn/ingest/start-draft';
import { startRun } from '../api/fn/ingest/start-run'; import { startRun } from '../api/fn/ingest/start-run';
import { runStatus } from '../api/fn/runs/run-status'; import { runStatus } from '../api/fn/runs/run-status';
import type { Pipeline } from '../api/models/pipeline'; import type { Pipeline } from '../api/models/pipeline';
@@ -122,8 +120,6 @@ export class Conectar {
protected readonly rawError = signal(''); protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) }); protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
/** The site's language model: Automático needs it. */
protected readonly llm = resource({ loader: () => this.api.invoke(languageModel) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) }); private readonly schema = resource({ loader: () => this.api.invoke(schema) });
protected readonly pipelineId = signal<string | undefined>(undefined); protected readonly pipelineId = signal<string | undefined>(undefined);
@@ -140,10 +136,6 @@ export class Conectar {
protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected())); protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected()));
protected readonly message = signal(''); protected readonly message = signal('');
protected readonly run = signal<{ id: string; status: string } | undefined>(undefined); protected readonly run = signal<{ id: string; status: string } | undefined>(undefined);
/** Automático drafts a pipeline that holds its sources only. */
protected readonly onlySources = computed(
() => this.docs().length > 0 && this.docs().every((d) => d.kind === 'source'),
);
protected readonly running = computed(() => { protected readonly running = computed(() => {
const run = this.run(); const run = this.run();
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
@@ -403,34 +395,7 @@ export class Conectar {
const id = this.pipelineId(); const id = this.pipelineId();
if (!id || !(await this.save())) return; if (!id || !(await this.save())) return;
try { try {
await this.follow((await this.api.invoke(startRun, { pipeline_id: id, body: {} }))['run_id']); const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
} catch (e) {
this.message.set(problem(e));
}
}
/** "Armar automáticamente": saves the sources, starts the `draft` job (the site's model
* draws the whole pipeline, saves it as a new version and runs it) and, once it ends,
* shows the version drawn. */
protected async automatic(): Promise<void> {
const id = this.pipelineId();
if (!id || !(await this.save())) return;
try {
this.message.set('Armando la canalización: se leen los documentos y el modelo los revisa.');
await this.follow((await this.api.invoke(startDraft, { pipeline_id: id }))['run_id']);
if (this.run()?.status === 'SUCCESS') {
await this.open(id);
this.message.set(
`Versión ${this.version()} armada y ejecutada. Revise lo que queda en Revisión.`,
);
this.list.reload();
}
} catch (e) {
this.message.set(problem(e));
}
}
private async follow(run_id: string): Promise<void> {
this.run.set({ id: run_id, status: 'STARTING' }); this.run.set({ id: run_id, status: 'STARTING' });
while (this.running()) { while (this.running()) {
await new Promise((r) => setTimeout(r, 2000)); await new Promise((r) => setTimeout(r, 2000));
@@ -439,6 +404,9 @@ export class Conectar {
status: (await this.api.invoke(runStatus, { run_id }))['status'], status: (await this.api.invoke(runStatus, { run_id }))['status'],
}); });
} }
} catch (e) {
this.message.set(problem(e));
}
} }
/** What the node gives: a source's first rows, or what any other node gave in the last run. */ /** What the node gives: a source's first rows, or what any other node gave in the last run. */
+87
View File
@@ -24,4 +24,91 @@ describe('bars', () => {
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] }; const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']); expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
}); });
it('a proportion split into its parts shows both in units and shares', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const t = bars({ kind: 'split', label: 'x', measure: 'M', yes: 'Con', no: 'Sin' }, () => r)!;
expect(t.rows.map((x) => [x.label, ...x.cells])).toEqual([
['Con', '1', '25.0 %'],
['Sin', '3', '75.0 %'],
]);
});
it('rows with patients and no biopsy are not rows with no patients; malignant counts only graded', () => {
const r: Reading = {
populations: {},
strata: {
birads: {
'4A': { 'initial-population': 3 },
'5': { 'initial-population': 4 },
'6': { 'initial-population': 2 },
},
'birads-category': {
'4A|no_biopsy': { 'initial-population': 3 },
'5|benign': { 'initial-population': 1 },
'5|invasive': { 'initial-population': 1 },
'5|no_data': { 'initial-population': 2 },
'6|no_data': { 'initial-population': 2 },
},
},
};
const results = [
{ code: 'benign', label: 'Benigno', color: '#1' },
{ code: 'invasive', label: 'Invasor', color: '#2' },
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#3' },
{ code: 'no_data', label: 'Sin dato', color: '#4' },
];
const rows = ['4A', '5', '6', '4B'].map((code) => ({ code, label: code, color: '#0' }));
const mode = {
kind: 'outcomes',
label: 'x',
measure: 'M',
stratum: 'birads',
rows,
results,
malignant: ['invasive'],
};
const t = bars(mode as any, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '0', '0', '3', '0', 'Sin biopsias'],
['4', '1', '1', '0', '2', '1/2 (50.0 %)'],
['2', '0', '0', '0', '2', 'Sin biopsias clasificables'],
['0', '—', '—', '—', '—', '—'],
]);
expect(t.rows.map((x) => x.none)).toEqual([
undefined,
undefined,
undefined,
'Sin pacientes en el periodo',
]);
expect(t.rows[1].segments!.map((x) => x.width)).toEqual([25, 25, 0, 50]);
});
it('bars on a percent scale are as long as the shares shown', () => {
const r: Reading = {
populations: {},
strata: { category: { a: { 'initial-population': 1 }, b: { 'initial-population': 3 } } },
};
const catalog = [
{ code: 'a', label: 'A', color: '#0' },
{ code: 'b', label: 'B', color: '#1' },
{ code: 'c', label: 'C', color: '#2' },
];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, percent: true }, () => r)!;
expect(t.rows.map((x) => x.width)).toEqual([25, 75, 0]);
expect(t.rows.map((x) => x.cells)).toEqual([
['1', '25.0 %'],
['3', '75.0 %'],
['0', '0.0 %'],
]);
});
it('a split takes the colours it is given', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const mode = {
kind: 'split',
label: 'x',
measure: 'M',
yes: 'Con',
no: 'Sin',
colors: ['#a', '#b'],
};
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
});
}); });
+89 -4
View File
@@ -5,15 +5,34 @@ import { name, Reading } from './measures';
export type Category = { code: string; label: string; color: string }; export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */ /** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = { label: string; caption?: string } & ( export type Mode = {
| { kind: 'counts'; measure: string; catalog: Category[] } label: string;
caption?: string;
/** said above the table: what its rows count (patients, reported biopsies…) */
heading?: string;
} &
/** `percent`: every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
(
| { kind: 'counts'; measure: string; catalog: Category[]; percent?: boolean }
| { kind: 'shares'; measure: string; stratum: string; order: string[] } | { kind: 'shares'; measure: string; stratum: string; order: string[] }
| { kind: 'positives'; measure: string; stratum: string; order: string[] } | { kind: 'positives'; measure: string; stratum: string; order: string[] }
| { kind: 'signs'; measure: string; strata: string[] } | { kind: 'signs'; measure: string; strata: string[] }
| { kind: 'days'; steps: { label: string; measure: string }[] } | { kind: 'days'; steps: { label: string; measure: string }[] }
| { kind: 'days-by'; measure: string; stratum: string } | { kind: 'days-by'; measure: string; stratum: string }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
/** Each row's units by result (a bar in segments), and the share of the row's units with a
* result that are `malignant`; a row with units and no result is not a row with none */
| {
kind: 'outcomes';
measure: string;
stratum: string;
rows: Category[];
results: Category[];
malignant: string[];
}
| { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] } | { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] }
); );
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */ /** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar { export interface Bar {
@@ -22,10 +41,16 @@ export interface Bar {
width: number; width: number;
marks: number[]; marks: number[];
cells: string[]; cells: string[];
/** the bar in parts (in % of the bar), each with what it says when hovered */
segments?: { width: number; color: string; title: string }[];
/** said in place of the bar (a row with nothing to draw) */
none?: string;
} }
export interface Bars { export interface Bars {
head: string[]; head: string[];
rows: Bar[]; rows: Bar[];
/** the colours of the segments */
legend?: { label: string; color: string }[];
} }
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—'); const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
@@ -46,7 +71,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
...mode.catalog, ...mode.catalog,
...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })), ...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
]; ];
const most = Math.max(...Object.values(cells).map(size)); const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return { return {
head: ['n', '%'], head: ['n', '%'],
rows: all.map(({ code, label, color }) => { rows: all.map(({ code, label, color }) => {
@@ -107,6 +132,66 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
.sort((a, b) => b.n - a.n), .sort((a, b) => b.n - a.n),
); );
} }
case 'split': {
const { numerator = 0, denominator = 0 } = of(mode.measure)?.populations ?? {};
if (!denominator) return undefined;
const parts: [string, number][] = [
[mode.yes, numerator],
[mode.no, denominator - numerator],
];
return {
head: ['n', '%'],
rows: parts.map(([label, n], i) => ({
label,
color: mode.colors?.[i],
width: (100 * n) / denominator,
marks: [],
cells: [`${n}`, pct(n, denominator)],
})),
};
}
case 'outcomes': {
const r = of(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
return {
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'],
legend: mode.results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]);
const by = mode.results.map((x) => size(cells[`${code}|${x.code}`]));
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0);
const bad = by.reduce(
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0),
0,
);
return {
label,
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: mode.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}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? den
? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')]
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
}),
};
}
default: default:
return undefined; return undefined;
} }
+55
View File
@@ -0,0 +1,55 @@
import { durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
describe('durationRows', () => {
const reads: Record<string, Reading> = {
A: reading(0, 3, 0, 1),
B: reading(6, 20, 4, 8),
C: reading(undefined, 0),
};
const rows = durationRows(
[
{ label: 'zero', measure: 'A' },
{ label: 'value', measure: 'B' },
{ label: 'nothing measured', measure: 'C' },
{ label: 'no report', measure: 'D' },
{ label: 'not in the catalog', measure: 'E' },
{ label: 'no measure' },
],
(m) => reads[m],
(m) => m !== 'E',
);
it('keeps a real zero as a value', () => {
expect(rows[0]).toEqual({
label: 'zero',
status: 'value',
median: 0,
observations: 3,
low: 0,
high: 1,
});
});
it('tells no measurements from an unpublished measure', () => {
expect(rows.map((r) => r.status)).toEqual([
'value',
'value',
'empty',
'empty',
'unpublished',
'unpublished',
]);
});
it('scales from zero to the largest median or third quartile', () => {
expect(durationMax(rows)).toBe(8);
expect(durationMax([])).toBe(0);
});
});
+46
View File
@@ -0,0 +1,46 @@
import { Reading } from './measures';
/** One step of a route: its name and the measure that times it. A step with no measure is
* not published yet. */
export interface RouteStep {
label: string;
measure?: string;
}
/** One row of a duration table: the median days, how many measurements and the quartiles.
* `empty` (published, nothing measured in the period) is not `unpublished` (no measure), and
* neither is a zero: a median of 0 days is a value. */
export interface DurationRow {
label: string;
status: 'value' | 'empty' | 'unpublished';
median?: number;
observations?: number;
low?: number;
high?: number;
}
/** The rows of a route in one reading; every step keeps its row. `published` says which
* measures the catalog has. */
export function durationRows(
steps: RouteStep[],
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' };
const r = read(measure);
if (r?.score === undefined) return { label, status: 'empty' };
return {
label,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
low: r.low,
high: r.high,
};
});
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
+3 -3
View File
@@ -182,14 +182,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 ''; if (!r) return '';
const p = r.populations; const p = r.populations;
switch (scoring(measure)) { switch (scoring(measure)) {
case 'proportion': case 'proportion':
return r.score === undefined return r.score === undefined
? 'Sin pacientes en el periodo.' ? `Sin ${unit} en el periodo.`
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`; : `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable': case 'continuous-variable':
return r.score === undefined return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.` ? `${p['initial-population'] ?? 0} sin medición en el periodo.`
+107 -38
View File
@@ -1,5 +1,6 @@
import type { Mode } from './bars'; import type { Mode } from './bars';
import { CACU } from './pages-cacu'; import { CACU } from './pages-cacu';
import type { RouteStep } from './durations';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui): /** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures. * the timeliness cards with their own words, then the clinical sections and their figures.
@@ -25,15 +26,28 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string;
note?: string; note?: string;
modes: Mode[]; modes: Mode[];
} }
export type Section = export type Section =
| ReadingsCard | ReadingsCard
/** A screening route as one compact card: a bar per step with its median, observations and
* quartiles. `sample` reads each step from the sample (its own measure, never a sum of
* medians); `step` reads each from the previous step. A reading with no steps is not offered. */
| { kind: 'route'; title: string; sample: RouteStep[]; step: RouteStep[] }
/** Cards side by side; the last one alone when odd. */ /** Cards side by side; the last one alone when odd. */
| { kind: 'columns'; title: string; sections: ReadingsCard[] } | { kind: 'columns'; title: string; sections: ReadingsCard[] }
/** One section at a time. */ /** One section at a time. */
| { kind: 'choice'; title: string; choices: { label: string; section: ReadingsCard }[] } /** `card`: the title, the tabs and the chosen reading in one card (the reading's own title is
* left out: its tab names it) */
| {
kind: 'choice';
title: string;
choices: { label: string; section: ReadingsCard }[];
card?: boolean;
}
| { kind: 'figures'; title?: string; figures: FigureSpec[] } | { kind: 'figures'; title?: string; figures: FigureSpec[] }
| { | {
kind: 'boxes'; kind: 'boxes';
@@ -113,17 +127,22 @@ const BIRADS: Catalog = {
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' }, { code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
], ],
}; };
const BREAST_BIOPSY: Catalog = {
groups: [ /** A breast biopsy's grades, and what stands in their place when there is none. */
{ id: 'benign', label: 'No maligno', color: '#42C29C' }, const BIOPSY_GRADES = [
{ id: 'malignant', label: 'Maligno', color: ROSE }, { code: 'benign', label: 'Benigno', color: '#A8C243' },
], { code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2' },
categories: [ { code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2' },
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' }, ];
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' }, /** What «Sin biopsia» says, whatever the contract's category is called. */
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' }, const NO_BIOPSY_MEANS =
], '«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.';
}; const INSTITUTIONAL = '#A8C243';
const NEUTRAL = '#C9CDD2';
const NO_RESULT = [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
];
export const PAGES: Record<string, Page> = { export const PAGES: Record<string, Page> = {
tea: { tea: {
@@ -229,9 +248,9 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de confirmación histopatológica', title: 'Tasa de detección histopatológica',
value: '{pct} %', value: '{pct} %',
note: '{num} de {den} biopsias con riesgo a carcinoma.', note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
}, },
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
@@ -251,21 +270,27 @@ export const PAGES: Record<string, Page> = {
], ],
opportunity: [ opportunity: [
{ {
kind: 'boxes', kind: 'route',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Tiempo de tamizaje a diagnóstico',
subtitles: true, // from the mammography: only the two measures that start at it
cards: [ sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
measure: 'CAMA_EU38A', label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
title: 'Tiempo de toma de mastografía a interpretación radiológica', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
}, },
],
step: [
{ 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', 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' }, label: 'Interpretación radiológica a resultado de biopsia',
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' }, measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
},
{ label: 'Diagnóstico a tratamiento' },
], ],
}, },
], ],
@@ -290,34 +315,78 @@ export const PAGES: Record<string, Page> = {
], ],
}, },
{ {
kind: 'figures', kind: 'readings',
title: 'Resultado histopatológico por categoría BI-RADS', title: 'Resultado histopatológico por categoría BI-RADS',
figures: [ 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. El porcentaje maligno se calcula solo sobre las pacientes con biopsia con grado.',
modes: [
{ {
kind: 'rates', kind: 'outcomes',
title: 'Por categoría BI-RADS, {p}', label: 'Por categoría BI-RADS',
heading: 'Resultados por paciente',
caption: NO_BIOPSY_MEANS,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads', stratum: 'birads',
rows: BIRADS.categories, rows: BIRADS.categories,
colored: true, results: [...BIOPSY_GRADES, ...NO_RESULT],
positive: ['in_situ', 'invasive'], malignant: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
}, },
{ {
kind: 'donut', kind: 'counts',
title: 'Resultado de la biopsia, {p}', label: 'Todas las categorías',
heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: BREAST_BIOPSY, catalog: [...BIOPSY_GRADES, ...NO_RESULT],
center: 'con resultado', percent: true,
}, },
], ],
}, },
{ {
kind: 'card', kind: 'choice',
title: 'Confirmación histopatológica',
card: true,
choices: [
{
label: 'Resultado de biopsias',
section: {
kind: 'readings',
title: 'Resultado de biopsias',
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
unit: 'biopsias',
note: 'Biopsias con resultado reportado, por fecha del reporte (no son pacientes ni mastografías). La tasa divide los carcinomas (in situ o invasor) entre biopsias con grado conocido. Los porcentajes de la distribución incluyen todas las biopsias reportadas, también «Sin dato» (sin grado), por lo que sus denominadores pueden ser distintos.',
modes: [
{
kind: 'counts',
label: 'Biopsias reportadas',
heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
percent: true,
},
],
},
},
{
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; no es equivalente a la tasa de detección.',
modes: [
{
kind: 'split',
label: 'Con y sin biopsia',
measure: 'CAMA_CONFIRMACION_BIRADS45', measure: 'CAMA_CONFIRMACION_BIRADS45',
title: 'Tasa de confirmación histopatológica', yes: 'Con reporte de biopsia',
value: '{pct} %', no: 'Sin reporte de biopsia',
note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.', colors: [INSTITUTIONAL, NEUTRAL],
},
],
},
},
],
}, },
], ],
}, },
+80 -1
View File
@@ -8,9 +8,12 @@ import { Reading } from './measures';
/** 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. */
@Component({ @Component({
selector: 'app-readings', selector: 'app-readings',
host: { '[class.cama]': 'camaStyle()' },
imports: [Loading, MatButtonToggleModule, Plot], imports: [Loading, MatButtonToggleModule, Plot],
template: ` template: `
@if (!hideTitle()) {
<h3 class="title">{{ title() }}</h3> <h3 class="title">{{ title() }}</h3>
}
@if (headline()) { @if (headline()) {
<p class="headline">{{ headline() }}</p> <p class="headline">{{ headline() }}</p>
} }
@@ -28,6 +31,9 @@ import { Reading } from './measures';
} }
</mat-button-toggle-group> </mat-button-toggle-group>
} }
@if (mode().heading) {
<h4 class="heading">{{ mode().heading }}</h4>
}
@if (mode().caption) { @if (mode().caption) {
<p class="state">{{ mode().caption }}</p> <p class="state">{{ mode().caption }}</p>
} }
@@ -50,16 +56,31 @@ import { Reading } from './measures';
<tr> <tr>
<th scope="row"> <th scope="row">
{{ row.label }} {{ row.label }}
<span class="track" aria-hidden="true"> @if (row.none) {
<span class="none">{{ row.none }}</span>
} @else {
<span class="track" [class.parts]="!!row.segments" aria-hidden="true">
@if (row.segments; as parts) {
@for (p of parts; track $index) {
<span
class="bar"
[style.width.%]="p.width"
[style.background]="p.color"
[attr.title]="p.title"
></span>
}
} @else {
<span <span
class="bar" class="bar"
[style.width.%]="row.width" [style.width.%]="row.width"
[style.background]="row.color" [style.background]="row.color"
></span> ></span>
}
@for (m of row.marks; track $index) { @for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m"></span> <span class="mark" [style.left.%]="m"></span>
} }
</span> </span>
}
</th> </th>
@for (c of row.cells; track $index) { @for (c of row.cells; track $index) {
<td>{{ c }}</td> <td>{{ c }}</td>
@@ -68,6 +89,13 @@ import { Reading } from './measures';
} }
</tbody> </tbody>
</table> </table>
@if (t.legend; as legend) {
<p class="legend">
@for (l of legend; track l.label) {
<span><i [style.background]="l.color"></i>{{ l.label }}</span>
}
</p>
}
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@@ -77,12 +105,32 @@ import { Reading } from './measures';
display: block; display: block;
min-width: 0; min-width: 0;
} }
:host(.cama) {
overflow-x: auto;
}
.title { .title {
margin: 0 0 8px; margin: 0 0 8px;
} }
:host(.cama) .title {
font-size: 18px;
font-weight: 500;
}
.heading {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
.headline { .headline {
font-weight: 500; font-weight: 500;
} }
:host(.cama) .headline {
margin: 8px 0;
}
:host(.cama) .state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
mat-button-toggle-group { mat-button-toggle-group {
flex-wrap: wrap; flex-wrap: wrap;
margin: 4px 0; margin: 4px 0;
@@ -91,6 +139,12 @@ import { Reading } from './measures';
border-collapse: collapse; border-collapse: collapse;
width: 100%; width: 100%;
} }
:host(.cama) table {
font-size: 13px;
}
:host(.cama) thead th {
font-weight: 500;
}
th, th,
td { td {
font-weight: 400; font-weight: 400;
@@ -114,6 +168,28 @@ import { Reading } from './measures';
display: block; display: block;
height: 100%; height: 100%;
} }
.parts {
display: flex;
}
.none {
color: rgba(0, 0, 0, 0.6);
display: block;
font-size: 12px;
font-weight: 400;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 16px;
margin: 8px 0 0;
}
.legend i {
display: inline-block;
height: 10px;
margin-right: 6px;
width: 10px;
}
.mark { .mark {
background: #333; background: #333;
height: 12px; height: 12px;
@@ -127,6 +203,9 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false);
readonly camaStyle = input(false);
readonly modes = input.required<Mode[]>(); readonly modes = input.required<Mode[]>();
readonly loading = input(false); readonly loading = input(false);
/** A measure's reading in the applied period, and the figure of a mode that has one. */ /** A measure's reading in the applied period, and the figure of a mode that has one. */
+183
View File
@@ -0,0 +1,183 @@
import { Component, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading';
import { DurationRow, durationMax } from './durations';
/** A screening route as one compact card: a bar per step with its median, its observations
* and its quartiles, read step by step or cumulatively from the sample. A step that is not
* published, or has no measurements in the period, keeps its row and says so. */
@Component({
selector: 'app-route-card',
imports: [Loading, MatButtonToggleModule, MatCardModule],
template: `
<mat-card appearance="outlined">
<mat-card-content>
<div class="head">
<h3>{{ title() }}</h3>
@if (sample().length && step().length) {
<mat-button-toggle-group
aria-label="Lectura de los tiempos"
[value]="mode()"
(change)="mode.set($event.value)"
>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (loading()) {
<app-loading what="los tiempos" [figure]="true" />
} @else {
@let rows = mode() === 'sample' ? sample() : step();
@let max = scale(rows);
<p class="state">
@if (mode() === 'sample') {
Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se
calcula por separado.
} @else {
Cada barra es la mediana de su paso, desde cero y por separado; los pasos pueden
corresponder a poblaciones diferentes, por lo que las medianas no se suman.
}
Las marcas indican el primer y tercer cuartil.
@if (max) {
Escala: 0 a {{ max }} días.
}
</p>
<table [attr.aria-label]="title()">
<thead>
<tr>
<th>{{ mode() === 'sample' ? 'Etapa' : 'Paso' }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr [attr.data-status]="row.status">
<th scope="row">
{{ row.label }}
@if (row.status === 'value') {
<span class="track" aria-hidden="true">
<span
class="bar"
[style.width.%]="max ? (100 * row.median!) / max : 0"
></span>
@if (row.low !== undefined && row.high !== undefined) {
<span
class="mark"
[style.left.%]="max ? (100 * row.low) / max : 0"
></span>
<span
class="mark"
[style.left.%]="max ? (100 * row.high) / max : 0"
></span>
}
</span>
} @else {
<span class="none">
{{
row.status === 'empty'
? 'Sin mediciones en el periodo'
: 'Indicador no publicado'
}}
</span>
}
</th>
<td>{{ row.status === 'value' ? row.median + ' días' : '—' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{
row.low === undefined || row.high === undefined
? '—'
: row.low + '–' + row.high
}}
</td>
</tr>
}
</tbody>
</table>
}
</mat-card-content>
</mat-card>
`,
styles: `
:host {
display: block;
margin-top: 24px;
}
.head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
h3 {
font-size: 18px;
font-weight: 500;
margin: 0;
}
.state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
table {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
th {
font-weight: 500;
text-align: left;
}
th[scope='row'] {
padding: 5px 0;
}
td,
thead th:not(:first-child) {
font-variant-numeric: tabular-nums;
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
position: relative;
}
.bar {
background: #42a77e;
display: block;
height: 100%;
}
.mark {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.none {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
`,
})
export class RouteCard {
readonly title = input.required<string>();
/** The rows from the sample, and the rows step by step. */
readonly sample = input.required<DurationRow[]>();
readonly step = input.required<DurationRow[]>();
readonly loading = input(false);
protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax;
}
+52 -8
View File
@@ -5,7 +5,7 @@ import type { Measure } from 'fhir/r4';
import { Mode } from './bars'; import { Mode } from './bars';
import { scenarioBars } from './figures'; import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures'; import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { Section } from './pages'; import type { ReadingsCard, Section } from './pages';
import { Readings } from './readings'; import { Readings } from './readings';
/** The applied period's readings and the measures they are of. */ /** The applied period's readings and the measures they are of. */
@@ -27,7 +27,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
<mat-card-content> <mat-card-content>
<app-readings <app-readings
[title]="s.title" [title]="s.title"
[headline]="headline()" [camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)"
[note]="s.note ?? ''" [note]="s.note ?? ''"
[modes]="s.modes" [modes]="s.modes"
[loading]="of().loading" [loading]="of().loading"
@@ -36,6 +37,37 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
/> />
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} @else if (s.kind === 'choice' && s.card) {
@let open = chosen() || s.choices[0].label;
<mat-card appearance="outlined" class="choice-card">
<mat-card-content>
<h3 class="title">{{ s.title }}</h3>
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-readings
[title]="c.section.title"
[hideTitle]="true"
[camaStyle]="true"
[headline]="headlineOf(c.section)"
[note]="c.section.note ?? ''"
[modes]="c.section.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
}
}
</mat-card-content>
</mat-card>
} @else { } @else {
<h2>{{ s.title }}</h2> <h2>{{ s.title }}</h2>
@if (s.kind === 'columns') { @if (s.kind === 'columns') {
@@ -66,9 +98,17 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
styles: ` styles: `
:host { :host {
display: block; display: block;
margin-top: 16px; margin-top: 24px;
min-width: 0; min-width: 0;
} }
.title {
font-size: 18px;
font-weight: 500;
margin: 0 0 8px;
}
.choice-card app-readings {
margin-top: 8px;
}
.columns { .columns {
display: grid; display: grid;
column-gap: 16px; column-gap: 16px;
@@ -84,15 +124,19 @@ export class ReadingsSection {
readonly of = input.required<Source>(); readonly of = input.required<Source>();
protected readonly chosen = signal(''); protected readonly chosen = signal('');
protected readonly headline = computed(() => { protected hasCamaHeading(s: ReadingsCard): boolean {
const s = this.section(); return s.modes.some((mode) => !!mode.heading);
const code = s.kind === 'readings' ? s.headline : undefined; }
/** A reading card's headline: its measure's score and its counts, in its own units. */
protected headlineOf(s: ReadingsCard): string {
const code = s.headline;
const measure = code && this.of().measure(code); const measure = code && this.of().measure(code);
const r = code && this.of().reading(code); const r = code && this.of().reading(code);
if (!measure || !r) return ''; if (!measure || !r) return '';
const words = detail(measure, r); const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
}); }
protected readonly draw = computed(() => (mode: Mode) => { protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined; if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure); const r = this.of().reading(mode.measure);
+8
View File
@@ -90,6 +90,14 @@
@case ('choice') { @case ('choice') {
<app-section [section]="section" [of]="of()" /> <app-section [section]="section" [of]="of()" />
} }
@case ('route') {
<app-route-card
[title]="section.title"
[sample]="stepRows(section, 'sample')"
[step]="stepRows(section, 'step')"
[loading]="reports.isLoading()"
/>
}
@case ('tea-summary') { @case ('tea-summary') {
@if (teaSummary(); as t) { @if (teaSummary(); as t) {
<mat-card appearance="outlined" class="summary"> <mat-card appearance="outlined" class="summary">
+12
View File
@@ -8,6 +8,7 @@ import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4'; import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { DurationRow, durationRows } from './durations';
import { LAYOUTS } from './layout'; import { LAYOUTS } from './layout';
import { import {
ageShare, ageShare,
@@ -37,6 +38,7 @@ import {
strataBars, strataBars,
} from './measures'; } from './measures';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { RouteCard } from './route-card';
import { ReadingsSection, Source } from './section'; import { ReadingsSection, Source } from './section';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per /** The period's indicators: the timeliness KPIs, the screening route, and a card per
@@ -53,6 +55,7 @@ import { ReadingsSection, Source } from './section';
MatSelectModule, MatSelectModule,
Plot, Plot,
ReadingsSection, ReadingsSection,
RouteCard,
], ],
templateUrl: './tab-indicadores.html', templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss', styleUrl: './tab-indicadores.scss',
@@ -194,6 +197,15 @@ export class TabIndicadores {
} }
protected readonly name = name; protected readonly name = name;
protected stepRows(section: Section, mode: 'sample' | 'step'): DurationRow[] {
if (section.kind !== 'route') return [];
return durationRows(
section[mode],
(code) => this.rd(code),
(code) => this.byName().has(code),
);
}
/** A measure's reading in the applied period, by code. */ /** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined { protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code); return this.loaded()?.get(code);
+1 -24
View File
@@ -219,20 +219,8 @@
@if (c['probability'] !== null) { @if (c['probability'] !== null) {
· p = {{ $any(c['probability']) | number: '1.2-2' }} · p = {{ $any(c['probability']) | number: '1.2-2' }}
} }
</span> </span></span
@if ($any(c['suggestion']); as s) {
<span class="suggestion"
>Sugerencia del modelo:
{{
s.same === true
? 'misma paciente'
: s.same === false
? 'distintas'
: 'no se puede saber'
}}. {{ s.reason }}</span
> >
}
</span>
<button <button
mat-stroked-button mat-stroked-button
[disabled]="decided().has(entry['person'] + '|' + c['candidate'])" [disabled]="decided().has(entry['person'] + '|' + c['candidate'])"
@@ -257,17 +245,6 @@
<h2>Registros que no coinciden en fecha de nacimiento o sexo ({{ p['torn'].length }})</h2> <h2>Registros que no coinciden en fecha de nacimiento o sexo ({{ p['torn'].length }})</h2>
@for (entry of p['torn']; track entry['person']) { @for (entry of p['torn']; track entry['person']) {
<div class="card person"> <div class="card person">
@if ($any(entry['suggestion']); as s) {
<p class="suggestion">
Sugerencia del modelo:
@if (s.record) {
el registro <code>{{ text(s.record).slice(0, 10) }}</code> parece de otra persona.
} @else {
no se puede saber cuál registro es de otra persona.
}
{{ s.reason }}
</p>
}
@for (r of records(entry); track $index) { @for (r of records(entry); track $index) {
<div class="candidate"> <div class="candidate">
<span class="values"> <span class="values">
-7
View File
@@ -54,10 +54,3 @@ h2 {
white-space: pre-wrap; white-space: pre-wrap;
font-size: 12px; font-size: 12px;
} }
.suggestion {
display: block;
color: var(--mat-sys-tertiary, #4a5d6b);
font-size: 0.85rem;
margin-top: 2px;
}