Trazabilidad, Datos y definiciones and the risk lists as the old app: declared panels, old labels and order; page tests against the capture

This commit is contained in:
Roberto Treviño
2026-11-28 17:24:29 -06:00
parent cbec0d431e
commit 6ea54d6e6d
11 changed files with 654 additions and 120 deletions
+56
View File
@@ -227,3 +227,59 @@ for (const domain of ['cacu', 'cama', 'tea']) {
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
+64 -3
View File
@@ -1,6 +1,6 @@
import type { Figure } from '../plot';
import type { Reading } from './measures';
import type { Catalog, Category } from './pages';
import { type Figure, PALETTE } from '../plot';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
@@ -415,3 +415,64 @@ export function ageShare(r: Reading, axis: string): Figure {
},
};
}
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
* closed shape. */
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
return {
data: named.map((c) => ({
type: 'bar',
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
})),
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
mode: 'lines',
fill: 'toself',
fillcolor: line + '33',
line: { width: 0 },
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => at(s.r?.score)),
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
};
}
+1 -1
View File
@@ -65,7 +65,7 @@ import { Loading } from '../loading';
}
<mat-tab label="Datos y definiciones">
<ng-template matTabContent>
<app-tab-definiciones [measures]="measures.value()!" />
<app-tab-definiciones [domain]="domain()" [measures]="measures.value()!" />
</ng-template>
</mat-tab>
</mat-tab-group>
+200
View File
@@ -428,3 +428,203 @@ export const PAGES: Record<string, Page> = {
],
},
};
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
export interface HistoryPanel {
title: string;
measure: string;
kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string;
group?: string;
}
export interface History {
panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number;
}
const GREY = '#C9CDD2';
const stack = (
title: string,
measure: string,
axis: string,
series: [string, string, string][],
): HistoryPanel => ({
title,
measure,
kind: 'stack',
axis,
series: series.map(([code, label, color]) => ({ code, label, color })),
});
const BIRADS_SERIES: [string, string, string][] = [
['4A', 'BI-RADS 4A', '#C24269'],
['4B', 'BI-RADS 4B', '#9C42C2'],
['4C', 'BI-RADS 4C', '#5C42C2'],
['5', 'BI-RADS 5', '#C2429C'],
['6', 'BI-RADS 6', '#8E2F62'],
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
];
export const HISTORY: Record<string, History> = {
cacu: {
line: '#6A8000',
months: 5,
panels: [
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
['NILM', 'Normal', '#9DBFE3'],
['ASC-US', 'ASC-US', '#2F6DB3'],
['LSIL', 'LIEBG', '#9C42C2'],
['ASC-H', 'ASC-H', '#5C42C2'],
['HSIL', 'LIEAG', '#C2429C'],
['CIS', 'Carcinoma in situ', '#8E2F62'],
['no_data', 'Sin dato', GREY],
]),
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
stack(
'Resultado de biopsia tras citología de alto grado',
'CACU_CONFIRMACION_CITOLOGIA',
'Pacientes',
[
['normal', 'Normal', '#9DBFE3'],
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
['CIS', 'Carcinoma in situ', '#9C42C2'],
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
['no_biopsy', 'Sin biopsia aún', GREY],
['no_data', 'Biopsia sin grado', GREY],
],
),
{
title: 'Días de la toma de la citología a su resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median',
},
{
title: 'Tiempo de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
{
title: 'Riesgo CIN2+ por banda',
measure: 'CACU_RIESGO_BANDA',
kind: 'stack',
axis: 'Pacientes',
},
],
},
cama: {
line: '#9C42C2',
panels: [
{
title: 'Días de la toma de la mastografía a su resultado',
measure: 'CAMA_EU38A',
kind: 'median',
},
{
title: 'Días del resultado de la mastografía al diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Días de tamizaje a diagnóstico',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
stack(
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_MASTOGRAFIA',
'Mastografías',
BIRADS_SERIES,
),
stack(
'Pacientes con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_PACIENTE',
'Pacientes',
BIRADS_SERIES,
),
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
['benign', 'Benigno', '#9DBFE3'],
['in_situ', 'Carcinoma in situ', '#C24269'],
['invasive', 'Carcinoma invasor', '#9C42C2'],
['no_biopsy', 'Sin biopsia reportada', GREY],
['no_data', 'Sin dato', GREY],
]),
{
title: 'Tasa de confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent',
},
],
},
tea: {
line: '#9C42C2',
panels: [
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a ADOS-2',
measure: 'M26_DIAS_MCHAT_ADOS2',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de ADOS-2 a diagnóstico',
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a diagnóstico positivo',
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
kind: 'median',
},
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
['in_process', 'En proceso', '#B8433A'],
]),
{
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
kind: 'percent',
},
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
['mchat_only', 'Solo M-CHAT', '#B8433A'],
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
['eeg', 'Con EEG', '#A8C243'],
]),
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
['good', 'Bueno', '#A8C243'],
['bad', 'No aceptable', '#B8433A'],
['not_analyzed', 'Sin analizar', GREY],
]),
],
},
};
+106 -32
View File
@@ -1,5 +1,7 @@
import { Component, input } from '@angular/core';
import { Component, computed, input } from '@angular/core';
import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app';
import type { Domain } from '../api/models/domain';
import { code, label } from '../fhir';
import { periodTypes, STRATA } from './measures';
@@ -14,48 +16,120 @@ const IMPROVEMENT: Record<string, string> = {
};
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** What each measure is: how it scores, which way is better, its periods and strata. */
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
* indicator opening to what it is (how it scores, which way is better, its periods and
* strata). */
@Component({
selector: 'app-tab-definiciones',
template: `
<table class="plain card">
<thead>
<tr>
<th>Indicador</th>
<th>Clave</th>
<th>Cálculo</th>
<th>Mejora</th>
<th>Periodos</th>
<th>Estratos</th>
</tr>
</thead>
<tbody>
@for (m of measures(); track m.id) {
<tr>
<td>{{ m.title }}</td>
<td>
<code>{{ m.name }}</code> v{{ m.version }}
</td>
<td>{{ scoring[code(m.scoring) ?? ''] }}</td>
<td>{{ improvement[code(m.improvementNotation) ?? ''] ?? '—' }}</td>
<td>{{ types(m) }}</td>
<td>{{ strata(m) }}</td>
</tr>
<section class="card">
<h2>Datos y definiciones de {{ domainName() }}</h2>
<section aria-labelledby="domain-info-title">
<h3 id="domain-info-title">Información del dominio</h3>
@if (domain() === 'cacu') {
<p>
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
espécimen fue insatisfactorio.
</p>
}
</tbody>
</table>
@if (available().length) {
<p>Periodicidad disponible: {{ available().join(', ') }}.</p>
} @else {
<p>Periodicidad: pendiente de información.</p>
}
</section>
<section aria-labelledby="definitions-catalog-title">
<h3 id="definitions-catalog-title">Catálogo de indicadores</h3>
<p>Consulta las gráficas disponibles y la periodicidad de cada indicador.</p>
@for (m of measures(); track m.id) {
<details>
<summary>{{ m.title || 'Nombre pendiente de publicación' }}</summary>
<div class="indicator-detail">
@if (m.description) {
<p>{{ m.description }}</p>
}
<h4>Cálculo</h4>
<p>
{{ scoring[code(m.scoring) ?? ''] }}
@if (improvement[code(m.improvementNotation) ?? '']; as better) {
· {{ better }}
}
</p>
<h4>Tipos de periodo admitidos</h4>
@if (types(m).length) {
<ul>
@for (t of types(m); track t) {
<li>{{ t }}</li>
}
</ul>
} @else {
<p>Pendiente de información.</p>
}
<h4>Estratos</h4>
<p>{{ strata(m) }}</p>
<p class="muted">
Clave <code>{{ m.name }}</code> · versión {{ m.version }}
</p>
</div>
</details>
} @empty {
<p role="status">
No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de
información.
</p>
}
</section>
</section>
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
}
h2,
h3 {
font-size: 20px;
font-weight: 500;
}
h4 {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
details {
border-bottom: 1px solid var(--mat-sys-outline-variant);
padding: 8px 0;
}
summary {
cursor: pointer;
font-weight: 500;
}
.indicator-detail {
padding: 4px 0 8px 16px;
}
`,
styles: ':host { display: block; padding-top: 16px; overflow-x: auto; }',
})
export class TabDefiniciones {
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly scoring = SCORING;
protected readonly improvement = IMPROVEMENT;
protected readonly code = code;
protected types(m: Measure): string {
return periodTypes(m)
.map((p) => PERIODS[p] ?? p)
.join(', ');
protected readonly domainName = computed(
() => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(),
);
/** The periodicities any of its indicators admits. */
protected readonly available = computed(() =>
[...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p),
);
protected types(m: Measure): string[] {
return periodTypes(m).map((p) => PERIODS[p] ?? p);
}
protected strata(m: Measure): string {
const names = (m.group?.[0]?.stratifier ?? []).map((s) => code(s.code) ?? label(s.code));
+54 -26
View File
@@ -10,7 +10,7 @@
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label>
<mat-label>Ventana de meses</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@for (m of [1, 3, 6, 12]; track m) {
<mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option>
@@ -18,7 +18,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label>
<mat-label>Estatus de seguimiento</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option>
@for (s of statuses; track s) {
@@ -27,7 +27,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Horizonte</mat-label>
<mat-label>Horizonte de la probabilidad</mat-label>
<mat-select [value]="horizon()" (selectionChange)="horizon.set($event.value)">
@for (h of [1, 2, 3, 4, 5]; track h) {
<mat-option [value]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</mat-option>
@@ -35,7 +35,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Orden</mat-label>
<mat-label>Ordenar por</mat-label>
<mat-select [value]="sort()" (selectionChange)="sort.set($event.value)">
<mat-option value="-recent">Estudio más reciente</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option>
@@ -43,7 +43,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label>
<mat-label>Registros por página</mat-label>
<mat-select [value]="size()" (selectionChange)="size.set($event.value)">
@for (n of [20, 50, 100]; track n) {
<mat-option [value]="n">{{ n }}</mat-option>
@@ -53,22 +53,33 @@
</form>
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
<p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
<button mat-button type="button" (click)="retry()">Reintentar seguimiento</button>
</p>
} @else if (!page() || loading()) {
<app-loading what="seguimiento" />
} @else if (applied()) {
<p class="muted window">Ventana consultada: {{ start() }} al {{ applied() }}.</p>
}
<div class="table-wrap card">
<table class="plain worklist">
<caption>
Resultados disponibles por paciente
</caption>
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Estatus</th>
<th>Estatus de seguimiento</th>
<th>Última citología</th>
<th>VPH</th>
<th>Biopsia</th>
<th>Riesgo LIEAG+ ({{ horizon() }} a)</th>
<th>Riesgo cáncer ({{ horizon() }} a)</th>
<th>Días toma → diagnóstico</th>
<th>Último resultado de VPH</th>
<th>Última biopsia</th>
<th>Probabilidad a LIEAG+ a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Probabilidad a cáncer a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Estudio más reciente</th>
<th>Días de toma a diagnóstico</th>
</tr>
</thead>
<tbody>
@@ -86,7 +97,6 @@
<td>{{ name(row.status) }}</td>
<td>
@if (row.cytology; as c) {
{{ c.date }} ·
{{
c.result
? name(c.result)
@@ -94,39 +104,58 @@
? 'Insatisfactoria'
: 'Pendiente'
}}
<small>Fecha: {{ c.date }}</small>
<small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
} @else {
—
No disponible
}
</td>
<td>
@if (row.hpv; as h) {
{{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }}
{{ h.positive ? 'Positivo' : 'Negativo' }}
<small>Fecha: {{ h.date }}</small>
<small
>Genotipo 16/18:
{{
h.types1618 === undefined
? 'No disponible'
: h.types1618
? 'Presente'
: 'No detectado'
}}</small
>
} @else {
—
No disponible
}
</td>
<td>
@if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }}
{{ name(b.histology ?? '') || 'Sin grado' }}
<small>Fecha: {{ b.date }}</small>
} @else {
—
No disponible
}
</td>
<td class="num">
{{ row.risk.cin2 === undefined ? '—' : (row.risk.cin2 * 100 | number: '1.1-1') + ' %' }}
{{
row.risk.cin2 === undefined
? 'No disponible'
: (row.risk.cin2 * 100 | number: '1.1-1') + ' %'
}}
</td>
<td class="num">
{{
row.risk.cancer === undefined ? '—' : (row.risk.cancer * 100 | number: '1.1-1') + ' %'
row.risk.cancer === undefined
? 'No disponible'
: (row.risk.cancer * 100 | number: '1.1-1') + ' %'
}}
</td>
<td class="num">{{ row.daysToDiagnosis ?? '—' }}</td>
<td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr>
} @empty {
<tr>
<td colspan="9" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
</tbody>
@@ -136,8 +165,7 @@
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte
{{ applied() }}
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
+14
View File
@@ -40,3 +40,17 @@ a {
.pager .muted {
margin-right: auto;
}
.worklist td small {
display: block;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
.worklist caption {
text-align: left;
font-weight: 500;
padding: 8px 0;
}
.window {
margin: 4px 0 8px;
}
+26 -2
View File
@@ -8,7 +8,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { rows, windowStart } from './follow-up';
import { Row, rows, windowStart } from './follow-up';
import { Loading } from '../loading';
import { name } from './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
@@ -20,6 +21,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
imports: [
DecimalPipe,
FormsModule,
Loading,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
@@ -65,7 +67,9 @@ export class TabRiesgos {
},
});
protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value());
protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
@@ -84,6 +88,26 @@ export class TabRiesgos {
});
protected readonly error = computed(() => this.first.error());
/** "Ventana consultada": the window's first day for the applied cut-off. */
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
/** "Estudio más reciente": her latest cytology or HPV sample. */
protected latest(row: Row): string | undefined {
return [row.cytology?.date, row.hpv?.date]
.filter((d) => !!d)
.sort()
.at(-1)
?.slice(0, 10);
}
protected retry(): void {
this.first.reload();
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
+26 -15
View File
@@ -10,7 +10,7 @@
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label>
<mat-label>Ventana de meses</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@for (m of [1, 3, 6, 12]; track m) {
<mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option>
@@ -18,7 +18,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label>
<mat-label>Estatus de seguimiento</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option>
@for (s of statuses; track s) {
@@ -27,7 +27,7 @@
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label>
<mat-label>Registros por página</mat-label>
<mat-select [value]="size()" (selectionChange)="size.set($event.value)">
@for (n of [20, 50, 100]; track n) {
<mat-option [value]="n">{{ n }}</mat-option>
@@ -37,18 +37,28 @@
</form>
@if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
<p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
<button mat-button type="button" (click)="retry()">Reintentar seguimiento</button>
</p>
} @else if (!page() || loading()) {
<app-loading what="seguimiento" />
} @else if (applied()) {
<p class="muted window">Ventana consultada: {{ start() }} al {{ applied() }}.</p>
}
<div class="table-wrap card">
<table class="plain worklist">
<caption>
Resultados disponibles por paciente
</caption>
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Mastografía</th>
<th>Biopsia</th>
<th>Estatus</th>
<th>Última mastografía</th>
<th>Última biopsia</th>
<th>Estatus de seguimiento</th>
<th>Prioridad</th>
</tr>
</thead>
@@ -64,12 +74,16 @@
}
</td>
<td>{{ row.ageGroup }}</td>
<td>{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }}</td>
<td>
{{ name(row.mammogram.birads ?? '') || 'Sin dato' }}
<small>Fecha: {{ row.mammogram.date }}</small>
</td>
<td>
@if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }}
{{ name(b.histology ?? '') || 'Sin resultado' }}
<small>Fecha: {{ b.date }}</small>
} @else {
—
No disponible
}
</td>
<td>{{ name(row.status) }}</td>
@@ -77,9 +91,7 @@
</tr>
} @empty {
<tr>
<td colspan="6" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td>
<td colspan="6" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
</tbody>
@@ -89,8 +101,7 @@
<div class="pager">
<span class="muted">
@if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte
{{ applied() }}
Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
}
</span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
+17 -2
View File
@@ -7,7 +7,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { camaRows } from './follow-up';
import { camaRows, windowStart } from './follow-up';
import { Loading } from '../loading';
import { name, PRIORITY } from './measures';
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
@@ -18,6 +19,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy
selector: 'app-tab-seguimiento',
imports: [
FormsModule,
Loading,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
@@ -59,7 +61,9 @@ export class TabSeguimiento {
},
});
protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value());
protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
@@ -75,6 +79,17 @@ export class TabSeguimiento {
});
protected readonly error = computed(() => this.first.error());
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
protected retry(): void {
this.first.reload();
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
+90 -39
View File
@@ -1,58 +1,92 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { history, periods, PeriodType, periodTypes, reading } from './measures';
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';
/** Each measure over time: every period of the chosen kind, oldest first. */
interface Drawn {
panel: HistoryPanel;
/** the group's heading, on the first panel of its run */
heading?: string;
figure?: Figure;
}
/** Trazabilidad as the old tab: the domain's declared panels (pages.HISTORY), in their order,
* each measure period by period. */
@Component({
selector: 'app-tab-trazabilidad',
imports: [Loading, MatButtonToggleModule, MatCardModule, Plot],
imports: [Loading, MatButtonToggleModule, Plot],
template: `
<div class="bar">
<section class="card filters" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group
[value]="type()"
(change)="type.set($event.value)"
aria-label="Intervalo"
aria-label="Intervalo de análisis"
>
<mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group>
</div>
</section>
@if (series.isLoading()) {
<app-loading what="las series" text="Calculando las series del periodo…" />
}
<div class="grid">
@for (item of figures(); track item.measure.id) {
<mat-card appearance="outlined" [attr.data-measure]="item.measure.name">
<mat-card-header
><mat-card-title>{{ item.measure.title }}</mat-card-title></mat-card-header
>
<mat-card-content><app-plot [figure]="item.figure" [height]="280" /></mat-card-content>
</mat-card>
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" />
} @else if (series.error()) {
<p class="muted" role="alert">
No se pudo cargar la trazabilidad.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p>
} @else {
@for (d of drawn(); track d.panel.measure) {
@if (d.heading) {
<h2 class="group-title">{{ d.heading }}</h2>
}
<section class="card panel" [attr.data-measure]="d.panel.measure">
@if (d.panel.group) {
<h3 class="panel-title">{{ d.panel.title }}</h3>
} @else {
<h2 class="panel-title">{{ d.panel.title }}</h2>
}
@if (d.figure) {
<app-plot [figure]="d.figure" [height]="320" />
} @else {
<p class="muted">Sin datos para el periodo.</p>
}
</section>
}
</div>
}
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.bar {
.card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
margin-bottom: 16px;
}
.grid {
display: grid;
gap: 16px;
grid-template-columns: 1fr;
.filters-title {
font-size: 16px;
font-weight: 500;
margin: 0 0 12px;
}
@media (min-width: 1304px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
.panel-title,
.group-title {
font-size: 20px;
font-weight: 700;
margin: 0 0 8px;
}
h3.panel-title {
font-size: 16px;
}
.group-title {
margin: 24px 0 12px;
}
`,
})
@@ -60,31 +94,48 @@ export class TabTrazabilidad {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('semester');
protected readonly type = signal<PeriodType>('month');
protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
loader: async ({ params }) => {
const history = HISTORY[params.domain];
if (!history) return [];
const asked = periods(params.type).reverse();
const shown = params.measures.filter((m) => periodTypes(m).includes(params.type));
return Promise.all(
shown.map(async (measure) => {
history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure);
if (!measure) return { panel, points: [] };
const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!,
'reporting-period': asked.join(','),
});
// One report per period asked, in the order asked.
const found = resources<MeasureReport>(pages, 'MeasureReport');
return { measure, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
return { panel, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
}),
);
},
});
protected readonly figures = computed<{ measure: Measure; figure: Figure }[]>(() =>
(this.series.value() ?? []).map(({ measure, points }) => {
// From the first period with data on.
const first = points.findIndex((p) => (p.r?.populations['initial-population'] ?? 0) > 0);
return { measure, figure: history(measure, first < 0 ? [] : points.slice(first)) };
}),
);
protected readonly drawn = computed<Drawn[]>(() => {
const history = HISTORY[this.domain()];
const xTitle = this.type() === 'month' ? 'Mes y año' : 'Semestre';
let group: string | undefined;
if (!this.series.hasValue()) return [];
return this.series.value().map(({ panel, points }) => {
const heading = panel.group && panel.group !== group ? panel.group : undefined;
group = panel.group;
const has = (p: (typeof points)[number]) => (p.r?.populations['initial-population'] ?? 0) > 0;
const first = points.findIndex(has);
if (first < 0 || !history) return { panel, heading };
const last = points.length - 1 - [...points].reverse().findIndex(has);
const shown =
history.months && this.type() === 'month'
? points.slice(Math.max(first, last + 1 - history.months), last + 1)
: points.slice(first, last + 1);
const series = shown.map((p) => ({ label: periodLabel(p.period), r: p.r }));
return { panel, heading, figure: historyFigure(panel, series, history.line, xTitle) };
});
});
}