import { Component, computed, effect, inject, input, resource, signal } from '@angular/core'; import { NgTemplateOutlet } from '@angular/common'; import { FormsModule } from '@angular/forms'; 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 { LAYOUTS } from './layout'; import { ageShare, ageStack, boxFigure, countBars, fill, nestedDonut, rateDots, routeFigure, scenarioBars, shareDonut, } from './figures'; import { FigureSpec, Kpi, PAGES, Section } from './pages'; import { detail, donut, formatScore, medians, name, periodLabel, periods, PeriodType, reading, Reading, scoring, STRATA, strataBars, } from './measures'; import { Loading } from '../loading'; /** The period's indicators: the timeliness KPIs, the screening route, and a card per * clinical measure with its figures. */ @Component({ selector: 'app-tab-indicadores', imports: [ Loading, FormsModule, 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(); readonly measures = input.required(); protected readonly type = signal('semester'); protected readonly options = computed(() => periods(this.type())); protected readonly chosen = signal(undefined); /** The period the figures show (set by Aplicar). */ protected readonly applied = signal(undefined); protected readonly routeView = signal<'sample' | 'step'>('sample'); protected readonly layout = computed( () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, ); protected readonly pending = 'Indicador no publicado en el catálogo institucional.'; /** The old app's page for this domain, when it is rebuilt as it was (else today's). */ protected readonly page = computed(() => PAGES[this.domain()]); private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m]))); protected readonly kpis = computed(() => this.layout() .kpis.map((n) => this.byName().get(n)) .filter((m) => !!m), ); protected readonly clinical = computed(() => { const placed = new Set([ ...this.layout().kpis, ...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]), ]); return this.measures().filter((m) => !placed.has(m.name!)); }); /** The latest period with data, the default. */ private readonly latest = resource({ params: () => ({ domain: this.domain(), anchor: this.byName().get(this.page()?.anchor ?? this.layout().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(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(); 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(page, 'MeasureReport')[0])] as const; }), ); return new Map(found); }, }); /** The period's readings; none while they load or when reading them failed (an errored * resource throws on `value()`). */ protected loaded(): Map | 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 label = periodLabel; protected readonly strataNames = STRATA; protected r(m: Measure): Reading | undefined { return this.loaded()?.get(m.name!); } protected score(m: Measure): string { return formatScore(m, this.r(m)); } protected detail(m: Measure): string { return detail(m, this.r(m)); } protected setType(type: PeriodType): void { this.type.set(type); this.chosen.set(this.options()[0]); } protected readonly route = computed
(() => { const view = this.routeView(); return medians( this.layout().route.map((s) => { const m = this.byName().get(view === 'sample' ? s.fromSample : s.fromStep); return { label: view === 'sample' ? s.label : s.step, r: m && this.r(m) }; }), ); }); /** Each clinical card's figures, built once per loaded period. */ protected readonly figureSets = computed( () => new Map(this.clinical().map((m) => [m.name!, this.build(m, this.loaded()?.get(m.name!))])), ); /** A clinical card's figures: the overall split, then one per stratum. */ private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] { if (!r || !(r.populations['initial-population'] ?? 0)) return []; const strata = Object.keys(r.strata).filter( (s) => s !== 'category' && !s.includes('-') && Object.keys(r.strata[s]).length, ); const kind = scoring(m); if (kind === 'continuous-variable') return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }]; return [ { title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) }, ...strata.map((s) => ({ title: `Por ${STRATA[s]?.toLowerCase() ?? s}`, figure: strataBars(m, r, s), })), ]; } protected readonly name = name; /** A measure's reading in the applied period, by code. */ protected rd(code: string): Reading | undefined { return this.loaded()?.get(code); } protected kpi(code: string): Measure | undefined { return this.byName().get(code); } /** A card's value and note, from its templates (a card with no measure: its words). */ /** "27 días (mediana)" as the value and its qualifier, shown smaller beneath it. */ 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) : ''; } /** A figure's title, with the applied period in it. */ protected titled(title: string): string { return title.replace('{p}', this.applied() ?? ''); } /** A duration's box, or nothing to draw. */ protected boxOf(measure: string | undefined): Figure | undefined { const r = measure ? this.rd(measure) : undefined; return r && r.score !== undefined ? boxFigure(r, this.applied() ?? '') : undefined; } /** TEA's summary of the period: its numbers from the measures (none: no summary). */ 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) || ''; } /** A clinical section's route or figures, drawn from the applied period's reports. */ 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 '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); } } }