Files
WebApp/src/app/indicadores/tab-indicadores.ts
T
alberto 72d5d07d67 F2a: TEA indicators after the 3 Dec review
Changed:
- Summary: the time sentences say "La mediana de..." and the footnote is gone (nothing else used it); "se evaluaron" is now "se registraron en el tamizaje".
- boxFigure: the median, Q3 and Q1 are text annotations to the right of the box; the hover is off so nothing else is labelled.
- M23 is titled "Pacientes en tamizaje por resultado diagnostico" on the page and in Trazabilidad.
- M21/M22 ageShare: the bar text is "p % (n/N)" from numerator and denominator of strata.age_sex, and the hover reuses it.
- M28 Sankey: every node label ends with its count ("M-CHAT · 18"), the "Se quedo en..." nodes included; link labels stay without it.
- M31: the bars plot the rate per 10,000 for the selected period, one bar per sex, with the rate as bar text and confirmed of total children in the hover. The card shows a headline number that follows the sex toggle (total when both sexes). Trazabilidad plots the rate as a line per sex plus the total (new 'rate' panel kind replaces the stacked counts).
- reading() carries the per-stratum measureScore as Reading.rates; the group measureScore is the total rate.

Choices the spec left open:
- Q3, median and Q1 sit at a fixed 56 px right of the box, anchored top/middle/bottom so they do not overlap when the three values are equal.
- Headline detail line: "por 10 000 niños · n confirmados de N niños".
- The selected-sex outline on the M31 bars is black, since the bars are one trace now.
- e2e pages.spec.ts:23 already expects no toggle on the M23 card, which is what the page renders, so it stays; it now also asserts the new M23 heading.
2026-12-03 13:55:14 -06:00

215 lines
7.7 KiB
TypeScript

import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import {
ageShare,
ageStack,
boxFigure,
countBars,
fill,
nestedDonut,
prevalenceHeadline,
rateDots,
routeFigure,
scenarioBars,
shareDonut,
sexCountBars,
teaAlterations,
teaSankey,
teaSexBars,
} from './figures';
import { FigureSpec, Kpi, PAGES, Section } from './pages';
import { name, periods, PeriodType, reading, Reading } from './measures';
import { Loading } from '../loading';
@Component({
selector: 'app-tab-indicadores',
imports: [
Loading,
NgTemplateOutlet,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatSelectModule,
Plot,
],
templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss',
})
export class TabIndicadores {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('semester');
protected readonly options = computed(() => periods(this.type()));
protected readonly chosen = signal<string | undefined>(undefined);
protected readonly prevalenceSex = signal<string | undefined>(undefined);
protected readonly applied = signal<string | undefined>(undefined);
protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
private readonly latest = resource({
params: () => ({
domain: this.domain(),
anchor: this.byName().get(this.page()?.anchor ?? '') ?? this.measures()[0],
all: this.options(),
}),
loader: async ({ params }) => {
const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: params.anchor.id!,
'reporting-period': params.all.join(','),
});
const found = resources<MeasureReport>(pages, 'MeasureReport');
const index = found.findIndex(
(r) => (reading(r)?.populations['initial-population'] ?? 0) > 0,
);
return params.all[Math.max(index, 0)];
},
});
protected readonly reports = resource({
params: () => ({ domain: this.domain(), period: this.applied(), measures: this.measures() }),
loader: async ({ params }) => {
if (!params.period) return new Map<string, Reading | undefined>();
const found = await Promise.all(
params.measures.map(async (m) => {
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
}),
);
return new Map(found);
},
});
protected loaded(): Map<string, Reading | undefined> | undefined {
return this.reports.hasValue() ? this.reports.value() : undefined;
}
constructor() {
effect(() => {
const latest = this.latest.value();
if (latest && !this.applied()) {
this.chosen.set(latest);
this.applied.set(latest);
}
});
}
protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
protected setType(type: PeriodType): void {
this.type.set(type);
this.chosen.set(this.options()[0]);
}
protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code);
}
protected kpiParts(text: string): [string, string] {
const found = /^(.*?)\s*(\([^)]*\))$/.exec(text);
return found ? [found[1], found[2]] : [text, ''];
}
protected kpiValue(k: Kpi): string {
if (!k.measure) return k.value ?? '';
const r = this.rd(k.measure);
return r && r.score !== undefined && k.value ? fill(k.value, r) : '';
}
protected kpiNote(k: Kpi): string {
if (!k.measure) return k.note ?? '';
const r = this.rd(k.measure);
if (!r || r.score === undefined) return 'Sin valor disponible';
return k.note ? fill(k.note, r) : '';
}
protected titled(title: string): string {
return title.replace('{p}', this.applied() ?? '');
}
protected boxOf(measure: string | undefined): Figure | undefined {
const r = measure ? this.rd(measure) : undefined;
return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined;
}
protected prevalenceOf(spec: FigureSpec) {
const r = this.rd(spec.measure);
return r ? prevalenceHeadline(r, this.prevalenceSex()) : undefined;
}
protected readonly teaSummary = computed(() => {
const rd = (c: string) => this.loaded()?.get(c);
const status = rd('M28_CASOS_POR_ESTADO');
if (!status) return undefined;
const n = (r: Reading | undefined, pop: string) => r?.populations[pop] ?? 0;
const cat = (r: Reading | undefined, c: string) =>
r?.strata['category']?.[c]?.['initial-population'] ?? 0;
const days = (c: string) => {
const v = rd(c)?.score;
return v === undefined
? '—'
: `${v.toLocaleString('es-MX', { maximumFractionDigits: 1 })} días`;
};
const confirmed = rd('M24_CONFIRMACION_DIAGNOSTICO')?.score;
const withEeg = rd('M21_DIAGNOSTICADOS_CON_EEG');
return {
evaluated: n(status, 'initial-population'),
mchatOnly: cat(status, 'mchat_only'),
psychology: cat(status, 'psychology'),
neuropediatrics: cat(status, 'neuropediatrics') + cat(status, 'eeg'),
confirmed:
confirmed === undefined
? '—'
: `${(confirmed * 100).toLocaleString('es-MX', { maximumFractionDigits: 1 })}%`,
toAdos: days('M26_DIAS_MCHAT_ADOS2'),
toDiagnosis: days('M27_DIAS_ADOS2_DIAGNOSTICO'),
whole: days('M25_DIAS_MCHAT_DIAGNOSTICO'),
diagnosed: n(withEeg, 'denominator'),
eeg: n(withEeg, 'numerator'),
missing: n(rd('M22_DIAGNOSTICADOS_SIN_EEG'), 'numerator'),
unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'),
};
});
protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || '';
}
protected routeOf(section: Section): Figure | undefined {
if (section.kind !== 'route') return undefined;
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) }));
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined;
}
protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
switch (spec.kind) {
case 'donut':
return nestedDonut(r, spec.catalog, spec.center);
case 'share-donut':
return shareDonut(r, spec.catalog, spec.center);
case 'counts':
return countBars(r, spec.catalog, spec.axis, this.applied() ?? '');
case 'sex-counts':
return sexCountBars(r, spec.catalog, spec.axis, this.applied() ?? '');
case 'sankey':
return teaSankey(r);
case 'sex-bars':
return teaSexBars(r, this.prevalenceSex());
case 'alterations':
return teaAlterations(r);
case 'age-stack':
return ageStack(r, spec.names);
case 'age-share':
return ageShare(r, spec.names[0]);
case 'scenario-bars':
return scenarioBars(r, spec.catalog, spec.stratum, name);
case 'rates':
return rateDots(r, spec);
}
}
}