Agrupar las tarjetas de CaMa y elegir el periodo en Trazabilidad

This commit is contained in:
2026-12-03 22:21:59 -06:00
parent 84769cb0f4
commit 2a84eb56ca
12 changed files with 142 additions and 120 deletions
+5 -9
View File
@@ -226,12 +226,7 @@ for (const domain of ['cama', 'tea']) {
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico', (i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
); );
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos'); 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 // The histopathology figures are two cards: the result by BI-RADS and the confirmation.
// 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( const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS', (i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
); );
@@ -241,7 +236,7 @@ for (const domain of ['cama', 'tea']) {
]; ];
const old = const old =
domain === 'cama' domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards] ? [...all.slice(0, route + 1), ...all.slice(clinical, results), ...cards]
: all; : 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');
@@ -255,12 +250,13 @@ for (const domain of ['cama', 'tea']) {
const ordered = [ const ordered = [
'Tiempo de toma de mastografía a interpretación radiológica', '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 diagnóstico',
'Tiempo de interpretación radiológica a resultado de biopsia',
'Tiempo de diagnóstico a tratamiento',
'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a diagnóstico',
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'Resultado histopatológico por categoría BI-RADS', 'Resultado histopatológico por categoría BI-RADS',
'Confirmación histopatológica', 'Confirmación histopatológica',
'Tasa de detección histopatológica',
]; ];
let last = -1; let last = -1;
for (const title of ordered) { for (const title of ordered) {
+2 -21
View File
@@ -1,4 +1,4 @@
import { bars, grouped, hiddenNote, Mode, subsequentHistory, unavailable } from './bars'; import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { scenarioBars } from './figures'; import { scenarioBars } from './figures';
import { Reading } from './measures'; import { Reading } from './measures';
@@ -51,25 +51,6 @@ describe('bars', () => {
)!; )!;
expect(g.groups[0].rows[1].text).toBe('3/10 · 30.0 %'); expect(g.groups[0].rows[1].text).toBe('3/10 · 30.0 %');
}); });
it('shows the form history within subsequent screening without treating missing answers as a category', () => {
const r: Reading = {
populations: {},
strata: {
round: { subsequent: { 'initial-population': 5 } },
subsequent_history: {
within_1_year: { 'initial-population': 1 },
'3_or_more_years': { 'initial-population': 2 },
no_data: { 'initial-population': 2 },
},
},
};
expect(subsequentHistory(r)).toEqual([
{ label: 'Un año o menos', text: '1/5 · 20.0 %' },
{ label: 'Dos años', text: '0/5 · 0.0 %' },
{ label: 'Tres o más años', text: '2/5 · 40.0 %' },
]);
expect(subsequentHistory({ populations: {}, strata: {} })).toBeUndefined();
});
it('a group with no patients has no rate', () => { it('a group with no patients has no rate', () => {
const r: Reading = { const r: Reading = {
populations: {}, populations: {},
@@ -353,7 +334,7 @@ describe('independent bars by group', () => {
['0/0 · —', undefined], ['0/0 · —', undefined],
['0/0 · —', undefined], ['0/0 · —', undefined],
]); ]);
expect(empty.note).toContain('una categoría en cero significa'); expect(empty.note).toBeUndefined();
const unreconciled = grouped(mode({ complete: true }), () => const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5), reading({ 'subsequent|NILM': 2 }, 5),
)!; )!;
+3 -29
View File
@@ -172,8 +172,6 @@ export interface Bars {
export const NOT_AVAILABLE = 'No disponible'; export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo'; export const NO_PATIENTS = 'Sin pacientes en el periodo';
const EMPTY_ROUND =
'Hay pacientes sin clasificación de ronda («Sin dato»): una categoría en cero significa que no hay pacientes clasificadas en esa ronda según la información disponible.';
const NO_ROUND = const NO_ROUND =
'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.'; 'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
@@ -448,24 +446,6 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
} }
} }
/** Reported form answers within the subsequent round, over that round's own total. */
export function subsequentHistory(reading?: Reading) {
const values = reading?.strata['subsequent_history'];
const den = reading?.strata['round']?.['subsequent']?.['initial-population'] ?? 0;
if (!values) return undefined;
return [
['within_1_year', 'Un año o menos'],
['2_years', 'Dos años'],
['3_or_more_years', 'Tres o más años'],
].map(([code, label]) => {
const count = values[code]?.['initial-population'] ?? 0;
return {
label,
text: `${count}/${den} · ${den ? ((100 * count) / den).toFixed(1) + ' %' : '—'}`,
};
});
}
/** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with /** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with
* one independent bar per category over the group's own records. A group the report leaves out is * one independent bar per category over the group's own records. A group the report leaves out is
* drawn empty only when the listed ones add up to every record of the period (`complete`). */ * drawn empty only when the listed ones add up to every record of the period (`complete`). */
@@ -501,7 +481,7 @@ export function grouped(
mode.stratum === 'age_group' && mode.stratum === 'age_group' &&
code === '<25' && code === '<25' &&
['CACU_EU7', 'CACU_VPH_GENOTIPO'].includes(mode.measure) ['CACU_EU7', 'CACU_VPH_GENOTIPO'].includes(mode.measure)
? '14 años y 10 meses a menos de 25 años' ? '15-24'
: name(code), : name(code),
total: den, total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`, hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
@@ -543,9 +523,7 @@ export function grouped(
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.' ? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
: none && unclassified : none && unclassified
? NO_ROUND ? NO_ROUND
: unclassified && classified.some((g) => !g.total) : undefined;
? EMPTY_ROUND
: undefined;
note = [sentence, note].filter(Boolean).join(' ') || undefined; note = [sentence, note].filter(Boolean).join(' ') || undefined;
} }
return { groups, note }; return { groups, note };
@@ -586,7 +564,6 @@ function complete(
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c)); const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0)); const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length; const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0;
return { return {
head: ['n/N', percentLabel], head: ['n/N', percentLabel],
rows, rows,
@@ -594,10 +571,7 @@ function complete(
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.' ? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
: none && listed.includes('no_data') : none && listed.includes('no_data')
? NO_ROUND ? NO_ROUND
: unclassified && : undefined,
(empty.length || order.some((c) => !listed.includes(c) && c !== 'no_data'))
? EMPTY_ROUND
: undefined,
}; };
} }
+11 -1
View File
@@ -1,6 +1,6 @@
import type { RiskAssessment } from 'fhir/r4'; import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up'; import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures'; import { historyPeriods, periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
it('starts the window the day after the same day months before (core.follow_up)', () => { it('starts the window the day after the same day months before (core.follow_up)', () => {
@@ -36,6 +36,16 @@ describe('follow-up list', () => {
expect(currentRisk(risks, 'cin2', 3)).toBeUndefined(); expect(currentRisk(risks, 'cin2', 3)).toBeUndefined();
}); });
it('ends history at the selected complete period for months and semesters', () => {
const monthly = historyPeriods('month', '2025-03');
expect(monthly.slice(-3)).toEqual(['2025-01', '2025-02', '2025-03']);
expect(monthly).toHaveLength(72);
const firstSemester = historyPeriods('semester', '2025-S1');
expect(firstSemester.slice(-3)).toEqual(['2024-S1', '2024-S2', '2025-S1']);
const secondSemester = historyPeriods('semester', '2025-S2');
expect(secondSemester.slice(-2)).toEqual(['2025-S1', '2025-S2']);
});
it('lists periods most recent first', () => { it('lists periods most recent first', () => {
expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']); expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']);
expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([ expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([
-1
View File
@@ -51,7 +51,6 @@ export const LAYOUTS: Record<string, Layout> = {
'CAMA_EU38A', 'CAMA_EU38A',
'CAMA_DIAS_TOMA_DIAGNOSTICO', 'CAMA_DIAS_TOMA_DIAGNOSTICO',
'CAMA_CONFIRMACION_BIRADS45', 'CAMA_CONFIRMACION_BIRADS45',
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
], ],
route: [ route: [
{ {
+7
View File
@@ -23,6 +23,13 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
return found; return found;
} }
/** Historical periods ending in the selected month or semester, oldest first. */
export function historyPeriods(type: PeriodType, selected: string): string[] {
const [year, part] = selected.split('-');
const month = type === 'semester' ? (part === 'S1' ? 0 : 6) : Number(part) - 1;
return periods(type, 6, new Date(Number(year), month, 1)).reverse();
}
export function periodLabel(period: string): string { export function periodLabel(period: string): string {
const [year, part] = period.split('-'); const [year, part] = period.split('-');
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`; if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
+1 -1
View File
@@ -199,7 +199,7 @@ export const CACU: Page = {
}, },
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento', title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
], ],
+20 -12
View File
@@ -249,6 +249,7 @@ export const PAGES: Record<string, Page> = {
}, },
cama: { cama: {
anchor: 'CAMA_BIRADS456_PACIENTE', anchor: 'CAMA_BIRADS456_PACIENTE',
// every single-number card, together at the start, in the order asked for
kpis: [ kpis: [
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
@@ -260,18 +261,27 @@ export const PAGES: Record<string, Page> = {
title: 'Tiempo de interpretación radiológica a diagnóstico', title: 'Tiempo de interpretación radiológica a diagnóstico',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
title: 'Tiempo de interpretación radiológica a resultado de biopsia',
...CAMA_DAYS,
},
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: 'Indicador no publicado en el catálogo institucional.',
},
{
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CAMA_DAYS,
},
{ {
measure: 'CAMA_BIRADS456_PACIENTE', measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
value: '{n} pacientes', value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.', note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
}, },
{
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de detección histopatológica',
value: '{pct} %',
note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
},
], ],
opportunity: [ opportunity: [
{ {
@@ -356,9 +366,7 @@ export const PAGES: Record<string, Page> = {
section: { section: {
kind: 'readings', kind: 'readings',
title: 'Resultado de biopsias', title: 'Resultado de biopsias',
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', note: 'Biopsias con resultado reportado, por fecha del reporte (no son pacientes ni mastografías). Los porcentajes incluyen todas las biopsias reportadas, también «Sin dato» (sin grado).',
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: [ modes: [
{ {
kind: 'counts', kind: 'counts',
@@ -380,7 +388,7 @@ export const PAGES: Record<string, Page> = {
title: 'Mastografías con biopsia', title: 'Mastografías con biopsia',
headline: 'CAMA_CONFIRMACION_BIRADS45', headline: 'CAMA_CONFIRMACION_BIRADS45',
unit: 'mastografías', 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.', 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: [ modes: [
{ {
kind: 'split', kind: 'split',
@@ -496,7 +504,7 @@ export const HISTORY: Record<string, History> = {
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
@@ -546,7 +554,7 @@ export const HISTORY: Record<string, History> = {
['no_data', 'Sin dato', GREY], ['no_data', 'Sin dato', GREY],
]), ]),
{ {
title: 'Tasa de confirmación histopatológica', title: 'Confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45', measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent', kind: 'percent',
}, },
+1 -21
View File
@@ -2,7 +2,7 @@ import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { bars, grouped, hiddenNote, Mode, subsequentHistory, unavailable } from './bars'; import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { Reading } from './measures'; 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. */
@@ -77,21 +77,6 @@ import { Reading } from './measures';
@if (g.note) { @if (g.note) {
<p class="state">{{ g.note }}</p> <p class="state">{{ g.note }}</p>
} }
@if (historyBreakdown(); as history) {
<section aria-label="Antecedente declarado en detección subsecuente">
<h4>Dentro de detección subsecuente: antecedente declarado</h4>
<p class="state">
Las categorías son respuestas del formulario; el denominador es el total de la ronda
subsecuente. La diferencia incluye valores no registrados o primera vez declarada con
procedimientos previos.
</p>
<ul>
@for (item of history; track item.label) {
<li>{{ item.label }}: {{ item.text }}</li>
}
</ul>
</section>
}
} @else if (figure(); as f) { } @else if (figure(); as f) {
<app-plot [figure]="f" [height]="height()" /> <app-plot [figure]="f" [height]="height()" />
@if (hidden(); as why) { @if (hidden(); as why) {
@@ -388,11 +373,6 @@ export class Readings {
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0], () => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
); );
protected readonly groups = computed(() => grouped(this.mode(), this.read())); protected readonly groups = computed(() => grouped(this.mode(), this.read()));
protected readonly historyBreakdown = computed(() => {
const mode = this.mode();
if (mode.kind !== 'grouped' || mode.stratum !== 'round') return undefined;
return subsequentHistory(this.read()(mode.measure));
});
protected readonly table = computed(() => bars(this.mode(), this.read())); protected readonly table = computed(() => bars(this.mode(), this.read()));
/** The bars of a scenarios figure need more room than a donut. */ /** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => { protected readonly height = computed(() => {
+2 -10
View File
@@ -46,8 +46,8 @@
<h2 id="opportunity-title">Indicadores de oportunidad</h2> <h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span> <span class="period">Periodo {{ period }}</span>
</div> </div>
<div class="kpis" style="--kpi-cols-md: 2; --kpi-cols-lg: 2"> <div class="kpis" style="--kpi-cols-md: 3; --kpi-cols-lg: 3">
@for (k of pg.kpis.slice(0, 2); track k.title) { @for (k of pg.kpis; track k.title) {
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" /> <ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
} }
</div> </div>
@@ -63,15 +63,7 @@
<ng-container <ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }" *ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/> />
@if ($index === 0) {
<div class="kpis">
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: pg.kpis[2] }" />
</div>
}
} }
<div class="kpis">
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: pg.kpis[3] }" />
</div>
</section> </section>
} @else { } @else {
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
@@ -0,0 +1,51 @@
import { TestBed } from '@angular/core/testing';
import type { Measure } from 'fhir/r4';
import { Fhir } from '../fhir';
import { HISTORY } from './pages';
import { TabTrazabilidad } from './tab-trazabilidad';
describe('Trazabilidad: periodo seleccionado', () => {
for (const domain of ['cama', 'cacu']) {
it(`applies a monthly and semester period to the ${domain} queries`, async () => {
const requests: Record<string, string>[] = [];
await TestBed.configureTestingModule({
imports: [TabTrazabilidad],
providers: [
{
provide: Fhir,
useValue: {
all: async (_domain: string, _resource: string, params: Record<string, string>) => {
requests.push(params);
return [{ resourceType: 'Bundle', type: 'searchset', entry: [] }];
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(TabTrazabilidad);
fixture.componentRef.setInput('domain', domain);
fixture.componentRef.setInput('measures', [
{ resourceType: 'Measure', id: 'test', name: HISTORY[domain].panels[0].measure },
] as Measure[]);
fixture.detectChanges();
await fixture.whenStable();
const component = fixture.componentInstance as any;
component.chosen.set('2025-03');
fixture.detectChanges();
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2025-03');
expect(requests.at(-1)?.['as-of']).toBeUndefined();
component.setType('semester');
fixture.detectChanges();
await fixture.whenStable();
component.chosen.set('2024-S1');
fixture.detectChanges();
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2024-S1');
});
}
});
+39 -15
View File
@@ -1,11 +1,13 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
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 { Loading } from '../loading'; import { Loading } from '../loading';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { historyFigure } from './figures'; import { historyFigure } from './figures';
import { periodLabel, periods, PeriodType, reading } from './measures'; import { historyPeriods, periodLabel, periods, PeriodType, reading } from './measures';
import { HISTORY, HistoryPanel } from './pages'; import { HISTORY, HistoryPanel } from './pages';
interface Drawn { interface Drawn {
@@ -19,21 +21,30 @@ interface Drawn {
* each measure period by period. */ * each measure period by period. */
@Component({ @Component({
selector: 'app-tab-trazabilidad', selector: 'app-tab-trazabilidad',
imports: [Loading, MatButtonToggleModule, Plot], imports: [Loading, MatButtonModule, MatButtonToggleModule, MatSelectModule, Plot],
template: ` template: `
<section class="card filters" aria-labelledby="history-filters"> <section class="card filters" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2> <h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group <mat-button-toggle-group
[value]="type()" [value]="type()"
(change)="type.set($event.value)" (change)="setType($event.value)"
aria-label="Intervalo de análisis" aria-label="Intervalo de análisis"
> >
<mat-button-toggle value="month">Mensual</mat-button-toggle> <mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle> <mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group> </mat-button-toggle-group>
@if (domain() === 'cama' || domain() === 'cacu') { @if (domain() === 'cama' || domain() === 'cacu') {
<label>Fecha de corte <input type="date" [value]="chosenCutoff()" (input)="chosenCutoff.set($any($event.target).value)" /></label> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<button type="button" (click)="cutoff.set(chosenCutoff())">Aplicar</button> <mat-label>Periodo seleccionado</mat-label>
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
@for (p of options(); track p) {
<mat-option [value]="p">{{ p }}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-flat-button (click)="applied.set(chosen())" [disabled]="chosen() === applied()">
Aplicar
</button>
} }
</section> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
@@ -75,6 +86,12 @@ interface Drawn {
padding: 16px 20px; padding: 16px 20px;
margin-bottom: 16px; margin-bottom: 16px;
} }
.filters {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
}
.filters-title { .filters-title {
font-size: 16px; font-size: 16px;
font-weight: 500; font-weight: 500;
@@ -99,16 +116,28 @@ export class TabTrazabilidad {
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('month'); protected readonly type = signal<PeriodType>('month');
protected readonly chosenCutoff = signal(''); protected readonly options = computed(() => periods(this.type()));
protected readonly cutoff = signal(''); protected readonly chosen = signal(periods('month')[0]);
protected readonly applied = signal(periods('month')[0]);
protected setType(type: PeriodType): void {
this.type.set(type);
const latest = this.options()[0];
this.chosen.set(latest);
this.applied.set(latest);
}
protected readonly series = resource({ protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures(), cutoff: this.cutoff() }), params: () => ({
domain: this.domain(),
type: this.type(),
measures: this.measures(),
period: this.applied(),
}),
loader: async ({ params }) => { loader: async ({ params }) => {
const history = HISTORY[params.domain]; const history = HISTORY[params.domain];
if (!history) return []; if (!history) return [];
const day = params.cutoff ? new Date(`${params.cutoff}T12:00:00`) : new Date(); const asked = historyPeriods(params.type, params.period);
const asked = periods(params.type, 6, day).reverse();
return Promise.all( return Promise.all(
history.panels.map(async (panel) => { history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure); const measure = params.measures.find((m) => m.name === panel.measure);
@@ -116,11 +145,6 @@ export class TabTrazabilidad {
const pages = await this.fhir.all(params.domain, 'MeasureReport', { const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!, measure: measure.id!,
'reporting-period': asked.join(','), 'reporting-period': asked.join(','),
...(params.cutoff ? {
'as-of': `${params.cutoff}T23:59:59.999999Z`,
'event-cutoff': params.cutoff,
'period-cutoff': params.cutoff,
} : {}),
}); });
// One report per period asked, in the order asked. // One report per period asked, in the order asked.
const found = resources<MeasureReport>(pages, 'MeasureReport'); const found = resources<MeasureReport>(pages, 'MeasureReport');