Connect TEA screening views to FHIR
This commit is contained in:
@@ -7,11 +7,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page').
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||
{
|
||||
path: 'indicadores/tea-estatus',
|
||||
title: 'Casos por estatus | ISSSTELEON',
|
||||
path: 'indicadores/tea',
|
||||
title: 'Indicadores TEA | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
||||
data: { workspace: true, breadcrumb: 'Indicadores TEA' },
|
||||
},
|
||||
{ path: 'indicadores/tea-estatus', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
{
|
||||
path: 'conectar',
|
||||
title: 'Conectar datos | ISSSTELEON',
|
||||
@@ -39,7 +40,7 @@ export const routes: Routes = [
|
||||
data: { workspace: true, breadcrumb: 'Indicadores' },
|
||||
},
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({
|
||||
...DOMINIOS.filter(dominio => dominio !== 'tea').map(dominio => ({
|
||||
path: `indicadores/${dominio}`,
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<section class="dashboard">
|
||||
<header><span class="domain">Trastorno del espectro autista, investigación</span><h1>Indicadores</h1><p>Explore la información del tamizaje.</p></header>
|
||||
<nav class="domain-nav" aria-label="Dominios de indicadores"><a routerLink="/indicadores/cacu">Cáncer cervicouterino</a><a routerLink="/indicadores/cama">Cáncer de mama</a><a routerLink="/indicadores/tea" aria-current="page">TEA</a></nav>
|
||||
<nav class="tabs" aria-label="Secciones de TEA">
|
||||
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Resumen</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Histórico</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
|
||||
</nav>
|
||||
@if (section() !== 'seguimiento') {
|
||||
<section aria-label="Consulta de indicadores">
|
||||
<h2>{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}</h2>
|
||||
<form (ngSubmit)="section() === 'resumen' ? loadSummary() : loadHistory()">
|
||||
@if (section() === 'resumen') { <label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1"></label> }
|
||||
@else {
|
||||
<label>Indicador <select name="measure" [(ngModel)]="measureId">@for (m of measures(); track m.id) { <option [value]="m.id">{{ m.title }}</option> }</select></label>
|
||||
<label>Periodos separados por coma <input name="history" [(ngModel)]="historyPeriods" required></label>
|
||||
}
|
||||
<label>Corte de evento <input name="evento" type="date" [(ngModel)]="eventCutoff"></label>
|
||||
<label>Corte de conocimiento <input name="conocimiento" type="datetime-local" [(ngModel)]="knowledgeCutoff"></label>
|
||||
<button type="submit">Consultar</button>
|
||||
</form>
|
||||
@if (measureState() === 'cargando' || measureState() === 'inicial') { <p role="status">Consultando indicadores…</p> }
|
||||
@if (measureState() === 'error') { <p role="alert">{{ measureError() }}</p> }
|
||||
@if (measureState() === 'listo' && reports().length === 0) { <p>No hay indicadores para la selección.</p> }
|
||||
@for (report of reports(); track $index) {
|
||||
@if (measureState() === 'listo') { <article class="card"><h3>{{ title(report) }}</h3><p>{{ report.period?.start }} a {{ report.period?.end }}</p>
|
||||
@if (rows(report).length === 0) { <p>Sin datos para el periodo.</p> }
|
||||
@else { <dl>@for (row of rows(report); track $index) { <div><dt>{{ row.label }}</dt><dd>{{ row.value }}</dd></div> }</dl> }
|
||||
</article> }
|
||||
}
|
||||
</section>
|
||||
}
|
||||
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Seguimiento">
|
||||
<h2>Seguimiento</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
|
||||
<form (ngSubmit)="applyFilters()" class="filters">
|
||||
<label>Desde <input type="date" name="desde" [(ngModel)]="filters.since"></label><label>Fecha de corte <input type="date" name="corte" [(ngModel)]="filters.cutoff"></label>
|
||||
<label>Estado <select name="status" [(ngModel)]="filters.status"><option value="">Todos</option><option value="active">En seguimiento</option><option value="finished">Finalizado</option></select></label>
|
||||
<label>Etapa <select name="stage" [(ngModel)]="filters.stage"><option value="">Todas</option><option value="SOLO_MCHAT">Solo M-CHAT</option><option value="PSICOLOGIA">Psicología</option><option value="NEUROPEDIATRIA">Neuropediatría</option><option value="EEG">EEG</option></select></label>
|
||||
<label>Etapa desde <input type="date" name="stageFrom" [(ngModel)]="filters.stageFrom"></label><label>Etapa hasta <input type="date" name="stageTo" [(ngModel)]="filters.stageTo"></label>
|
||||
<label>Edad al M-CHAT <select name="age" [(ngModel)]="filters.age"><option value="">Todas</option><option value="16_23">16 a 23 meses</option><option value="24_29">24 a 29 meses</option><option value="30_36">30 a 36 meses</option></select></label>
|
||||
<label>M-CHAT mínimo <input type="number" name="mchatMin" [(ngModel)]="filters.mchatMin"></label><label>M-CHAT máximo <input type="number" name="mchatMax" [(ngModel)]="filters.mchatMax"></label>
|
||||
<label>CSS mínimo <input type="number" name="cssMin" [(ngModel)]="filters.cssMin"></label><label>CSS máximo <input type="number" name="cssMax" [(ngModel)]="filters.cssMax"></label>
|
||||
<label>EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
|
||||
@if (alterationsAvailable() && alterationTypes().length) { <label>Alteración <select name="alteration" [(ngModel)]="filters.alteration"><option value="">Todas</option>@for (item of alterationTypes(); track item.code) { <option [value]="item.code">{{ item.display }}</option> }</select></label> }
|
||||
<button type="submit">Aplicar filtros</button>
|
||||
</form>
|
||||
@if (episodeState() === 'cargando') { <p role="status">Consultando seguimiento…</p> }
|
||||
@if (episodeState() === 'error') { <p role="alert">{{ episodeError() }}</p> }
|
||||
@if (episodeState() === 'listo') {
|
||||
<p>{{ episodeTotal() }} episodios</p>
|
||||
@if (episodes().length === 0) { <p>No hay episodios para la selección.</p> }
|
||||
@else { <table><thead><tr><th>Paciente</th><th>Etapa</th><th>Fecha de etapa</th><th>Estado</th><th></th></tr></thead><tbody>
|
||||
@for (e of episodes(); track e.id) { <tr><td>{{ patientId(e) }}</td><td>{{ stage(e) }}</td><td>{{ stageDate(e) }}</td><td>{{ e.status === 'finished' ? 'Finalizado' : 'En seguimiento' }}</td><td><button type="button" [attr.data-patient]="patientId(e)" (click)="openPatient(e)">Abrir ficha</button></td></tr> }
|
||||
</tbody></table> }
|
||||
<div class="paging"><button type="button" [disabled]="page === 0" (click)="page = page - 1; loadEpisodes()">Anterior</button><span>Página {{ page + 1 }}</span><button type="button" [disabled]="(page + 1) * pageSize >= episodeTotal()" (click)="page = page + 1; loadEpisodes()">Siguiente</button></div>
|
||||
}
|
||||
</section>
|
||||
@if (section() === 'seguimiento' && selected()) {
|
||||
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Seguimiento</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
|
||||
@if (patientState() === 'cargando') { <p role="status">Consultando ficha…</p> }
|
||||
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
|
||||
@if (patientState() === 'listo') {
|
||||
<article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article>
|
||||
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
|
||||
@if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> }
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,13 @@
|
||||
.dashboard { max-width: 1200px; margin: 0 auto; padding: 1.5rem; color: #142b3d; }
|
||||
.domain { color: #24735a; font-weight: 600; }
|
||||
.domain-nav, .tabs, form, .paging { display: flex; flex-wrap: wrap; gap: .8rem; align-items: end; margin: 1rem 0; }
|
||||
.domain-nav a { color: #216b56; padding: .5rem; }
|
||||
.tabs { border-bottom: 1px solid #c9d6d1; }
|
||||
button { border: 1px solid #216b56; border-radius: .3rem; background: #fff; color: #165a47; padding: .55rem .8rem; cursor: pointer; }
|
||||
button[aria-current="page"], button[type="submit"] { background: #216b56; color: white; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
label { display: grid; gap: .25rem; font-size: .9rem; }
|
||||
input, select { padding: .45rem; border: 1px solid #8ba09a; border-radius: .25rem; }
|
||||
.card { border: 1px solid #d5e0dc; border-radius: .5rem; padding: 1rem; margin: 1rem 0; background: #fff; }
|
||||
dl div { display: flex; gap: 1rem; justify-content: space-between; border-bottom: 1px solid #edf1ef; padding: .3rem 0; } dd { margin: 0; font-weight: 600; }
|
||||
table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: .55rem; border-bottom: 1px solid #d5e0dc; }
|
||||
@@ -1,24 +1,69 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { TeaStatusPage } from './tea-status-page';
|
||||
|
||||
describe('TeaStatusPage', () => {
|
||||
it('shows the stages in a FHIR report and reports a failed query', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const component = TestBed.createComponent(TeaStatusPage).componentInstance;
|
||||
const tag = { tag: [{ system: 'https://isssteleon.org/fhir/CodeSystem/etiqueta', code: 'simulado' }] };
|
||||
const episode = (id: string) => ({ resourceType: 'EpisodeOfCare', id, meta: tag, patient: { reference: `Patient/${id}` }, type: [{ coding: [{ code: 'SOLO_MCHAT' }] }] });
|
||||
const measure = { resourceType: 'Measure', id: 'M28-casos-por-estado', title: 'Casos por estatus', url: 'https://isssteleon.org/fhir/Measure/M28-casos-por-estado' };
|
||||
const bundle = (...items: any[]) => ({ resourceType: 'Bundle', total: items.length, entry: items.map(resource => ({ resource })) });
|
||||
|
||||
describe('TEA FHIR journey', () => {
|
||||
function setup() {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
const fixture = TestBed.createComponent(TeaStatusPage);
|
||||
const c = fixture.componentInstance;
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
component.consultar();
|
||||
const request = http.expectOne('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure?periodo=2025-S1');
|
||||
request.flush({ group: [{ population: [{ count: 6 }], stratifier: [{ stratum: [
|
||||
{ value: { coding: [{ code: 'SOLO_MCHAT' }] }, population: [{ count: 2 }] },
|
||||
] }] }] });
|
||||
expect(component.total()).toBe(6);
|
||||
expect(component.filas()).toEqual([{ codigo: 'SOLO_MCHAT', nombre: 'M-CHAT', cantidad: 2 }]);
|
||||
component.consultar();
|
||||
http.expectOne('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure?periodo=2025-S1')
|
||||
.flush({}, { status: 404, statusText: 'Not Found' });
|
||||
expect(component.estado()).toBe('error');
|
||||
http.expectOne('/tea/fhir/Measure').flush(bundle(measure));
|
||||
http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] });
|
||||
return { c, http };
|
||||
}
|
||||
it('distinguishes zero, missing and masked values and requests the historical periods', () => {
|
||||
const { c, http } = setup();
|
||||
expect(c.value({ count: 0 }, 'count')).toBe('0');
|
||||
expect(c.value({}, 'count')).toBe('Sin dato');
|
||||
expect(c.value({ _count: { extension: [{ valueCode: 'masked' }] } }, 'count')).toBe('Dato suprimido');
|
||||
c.changeSection('historico');
|
||||
const req = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||
expect(req.request.params.get('periodo')).toBe('2025-01,2025-02,2025-03');
|
||||
req.flush(bundle());
|
||||
expect(c.reports()).toEqual([]);
|
||||
http.verify();
|
||||
});
|
||||
it('retains filters and page and rejects a late patient response', () => {
|
||||
const { c, http } = setup();
|
||||
c.filters.stage = 'PSICOLOGIA'; c.filters.cutoff = '2025-12-31'; c.filters.cssMin = null as unknown as string; c.page = 1; c.changeSection('seguimiento');
|
||||
const list = http.expectOne(r => r.url.endsWith('/EpisodeOfCare'));
|
||||
expect(list.request.params.get('etapa')).toBe('PSICOLOGIA');
|
||||
expect(list.request.params.get('_offset')).toBe('5');
|
||||
expect(list.request.params.has('css')).toBe(false);
|
||||
list.flush({ ...bundle(episode('a'), episode('b')), total: 8 });
|
||||
c.openPatient(episode('a')); const a = http.expectOne(r => r.url.includes('/Patient/a/'));
|
||||
c.openPatient(episode('b')); const b = http.expectOne(r => r.url.includes('/Patient/b/'));
|
||||
b.flush(bundle({ resourceType: 'Patient', id: 'b', meta: tag }));
|
||||
a.flush(bundle({ resourceType: 'Patient', id: 'a', meta: tag }));
|
||||
expect(c.selected()).toBe('b'); expect(c.patientResources()[0].id).toBe('b');
|
||||
c.back(); expect(c.page).toBe(1); expect(c.filters.stage).toBe('PSICOLOGIA');
|
||||
http.verify();
|
||||
});
|
||||
it('rejects an untagged response and shows the OperationOutcome error', () => {
|
||||
const { c, http } = setup();
|
||||
c.changeSection('seguimiento');
|
||||
http.expectOne(r => r.url.endsWith('/EpisodeOfCare')).flush(bundle({ ...episode('a'), meta: {} }));
|
||||
expect(c.episodeState()).toBe('error');
|
||||
c.openPatient(episode('a'));
|
||||
http.expectOne(r => r.url.includes('/Patient/a/')).flush({ issue: [{ diagnostics: 'Paciente no encontrado' }] }, { status: 404, statusText: 'Not Found' });
|
||||
expect(c.patientError()).toBe('Paciente no encontrado');
|
||||
http.verify();
|
||||
});
|
||||
it('shows alteration groups only when the catalog offers M30', () => {
|
||||
const { c, http } = setup();
|
||||
expect(c.alterationsAvailable()).toBe(false);
|
||||
c.measures.set([measure, { id: 'M30-resultado-eeg', url: 'm30', scoring: { coding: [{ code: 'proportion' }] } }]);
|
||||
expect(c.alterationsAvailable()).toBe(true);
|
||||
const rows = c.rows({ measure: 'm30', group: [{ population: [] }, { code: { coding: [{ code: 'ritmo', display: 'Ritmo' }] }, population: [{ code: { coding: [{ code: 'numerator' }] }, count: 0 }] }] });
|
||||
expect(rows).toContainEqual({ label: 'Ritmo — Numerador', value: '0' });
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,53 +1,185 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { Component, ElementRef, inject, OnDestroy, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { forkJoin, Subscription } from 'rxjs';
|
||||
|
||||
interface Population { count?: number }
|
||||
interface Stratum { value?: { coding?: { code?: string; display?: string }[] }; population?: Population[] }
|
||||
interface Report { group?: { population?: Population[]; stratifier?: { stratum?: Stratum[] }[] }[] }
|
||||
type Resource = any;
|
||||
type Section = 'resumen' | 'historico' | 'seguimiento';
|
||||
type State = 'inicial' | 'cargando' | 'listo' | 'error';
|
||||
const stages: Record<string, string> = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' };
|
||||
const populations: Record<string, string> = { 'initial-population': 'Total', numerator: 'Numerador', denominator: 'Denominador', 'denominator-exclusion': 'Excluidos del denominador', 'measure-observation': 'Con valor', 'measure-population-exclusion': 'Sin valor' };
|
||||
const code = (value: Resource) => value?.coding?.[0]?.code ?? '';
|
||||
const text = (value: Resource) => value?.coding?.[0]?.display ?? value?.text ?? code(value);
|
||||
const resources = (bundle: Resource): Resource[] => (bundle?.entry ?? []).map((entry: Resource) => entry.resource);
|
||||
const simulated = (resource: Resource) => resource?.meta?.tag?.some((tag: Resource) => tag.system === 'https://isssteleon.org/fhir/CodeSystem/etiqueta' && tag.code === 'simulado');
|
||||
|
||||
@Component({
|
||||
selector: 'app-tea-status-page',
|
||||
imports: [FormsModule],
|
||||
template: `
|
||||
<h1>Casos por estatus</h1>
|
||||
<p>Consulte la etapa alcanzada por las niñas y los niños en el periodo seleccionado.</p>
|
||||
<form (ngSubmit)="consultar()">
|
||||
<label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1" /></label>
|
||||
<button type="submit" [disabled]="estado() === 'cargando'">Consultar</button>
|
||||
</form>
|
||||
@if (estado() === 'cargando') { <p role="status">Consultando información…</p> }
|
||||
@if (estado() === 'error') { <p role="alert">No fue posible consultar el periodo. Verifique el periodo e intente de nuevo.</p> }
|
||||
@if (estado() === 'listo') {
|
||||
<p>Total: {{ total() }}</p>
|
||||
@if (filas().length === 0) { <p>No hay casos para este periodo.</p> }
|
||||
@else { <ul>@for (fila of filas(); track fila.codigo) { <li>{{ fila.nombre }}: {{ fila.cantidad }}</li> }</ul> }
|
||||
}
|
||||
`,
|
||||
imports: [FormsModule, RouterLink],
|
||||
templateUrl: './tea-status-page.html',
|
||||
styleUrl: './tea-status-page.scss',
|
||||
})
|
||||
export class TeaStatusPage {
|
||||
export class TeaStatusPage implements OnDestroy {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private requests: Subscription[] = [];
|
||||
private revision = { measures: 0, episodes: 0, patient: 0 };
|
||||
readonly section = signal<Section>('resumen');
|
||||
readonly measures = signal<Resource[]>([]);
|
||||
readonly alterationTypes = signal<Resource[]>([]);
|
||||
readonly reports = signal<Resource[]>([]);
|
||||
readonly measureState = signal<State>('inicial');
|
||||
readonly measureError = signal('');
|
||||
readonly episodes = signal<Resource[]>([]);
|
||||
readonly episodeTotal = signal(0);
|
||||
readonly episodeState = signal<State>('inicial');
|
||||
readonly episodeError = signal('');
|
||||
readonly selected = signal<string | null>(null);
|
||||
readonly patientResources = signal<Resource[]>([]);
|
||||
readonly patientState = signal<State>('inicial');
|
||||
readonly patientError = signal('');
|
||||
periodo = '2025-S1';
|
||||
readonly estado = signal<'inicial' | 'cargando' | 'listo' | 'error'>('inicial');
|
||||
readonly total = signal(0);
|
||||
readonly filas = signal<{ codigo: string; nombre: string; cantidad: number }[]>([]);
|
||||
historyPeriods = '2025-01,2025-02,2025-03';
|
||||
measureId = 'M28-casos-por-estado';
|
||||
eventCutoff = '';
|
||||
knowledgeCutoff = '';
|
||||
page = 0;
|
||||
pageSize = 5;
|
||||
filters = { since: '', cutoff: '', status: '', stage: '', stageFrom: '', stageTo: '', age: '', mchatMin: '', mchatMax: '', cssMin: '', cssMax: '', eeg: '', alteration: '' };
|
||||
readonly stages = stages;
|
||||
|
||||
consultar() {
|
||||
this.estado.set('cargando');
|
||||
this.http.get<Report>('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure', {
|
||||
params: new HttpParams().set('periodo', this.periodo),
|
||||
}).subscribe({
|
||||
next: report => {
|
||||
const group = report.group?.[0];
|
||||
this.total.set(group?.population?.[0]?.count ?? 0);
|
||||
const nombres: Record<string, string> = { SOLO_MCHAT: 'M-CHAT', PSICOLOGIA: 'Psicología', NEUROPEDIATRIA: 'Neuropediatría', EEG: 'EEG' };
|
||||
this.filas.set((group?.stratifier?.[0]?.stratum ?? []).map(s => {
|
||||
const codigo = s.value?.coding?.[0]?.code ?? '';
|
||||
return { codigo, nombre: nombres[codigo] ?? s.value?.coding?.[0]?.display ?? codigo, cantidad: s.population?.[0]?.count ?? 0 };
|
||||
}));
|
||||
this.estado.set('listo');
|
||||
constructor() {
|
||||
this.requests.push(this.http.get<Resource>('/tea/fhir/Measure').subscribe({
|
||||
next: bundle => {
|
||||
this.measures.set(resources(bundle).filter(m => /^M(2[1-9]|30)-/.test(m.id)));
|
||||
if (this.alterationsAvailable()) this.requests.push(this.http.get<Resource>('/tea/fhir/CodeSystem/tea-eeg-metrica').subscribe({ next: system => this.alterationTypes.set(system.concept ?? []), error: () => this.alterationTypes.set([]) }));
|
||||
this.loadSummary();
|
||||
},
|
||||
error: () => this.estado.set('error'),
|
||||
});
|
||||
error: () => { this.measureState.set('error'); this.measureError.set('No fue posible cargar los indicadores.'); },
|
||||
}));
|
||||
}
|
||||
ngOnDestroy() { this.requests.forEach(s => s.unsubscribe()); }
|
||||
changeSection(section: Section) {
|
||||
this.section.set(section);
|
||||
if (section === 'resumen') this.loadSummary();
|
||||
if (section === 'historico') this.loadHistory();
|
||||
if (section === 'seguimiento' && this.episodeState() === 'inicial') this.loadEpisodes();
|
||||
}
|
||||
private cutoffs(params: HttpParams): HttpParams {
|
||||
if (this.eventCutoff) params = params.set('corte_evento', this.eventCutoff);
|
||||
if (this.knowledgeCutoff) params = params.set('corte_conocimiento', new Date(this.knowledgeCutoff).toISOString());
|
||||
return params;
|
||||
}
|
||||
loadSummary() {
|
||||
const token = ++this.revision.measures;
|
||||
const measures = this.measures();
|
||||
if (!measures.length) { this.measureState.set('listo'); this.reports.set([]); return; }
|
||||
this.measureState.set('cargando');
|
||||
const params = this.cutoffs(new HttpParams().set('periodo', this.periodo));
|
||||
this.requests.push(forkJoin(measures.map(m => this.http.get<Resource>(`/tea/fhir/Measure/${encodeURIComponent(m.id)}/$evaluate-measure`, { params }))).subscribe({
|
||||
next: reports => { if (token === this.revision.measures) { this.reports.set(reports); this.measureState.set('listo'); } },
|
||||
error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } },
|
||||
}));
|
||||
}
|
||||
loadHistory() {
|
||||
const token = ++this.revision.measures;
|
||||
const measure = this.measures().find(m => m.id === this.measureId);
|
||||
if (!measure) { this.measureState.set('error'); this.measureError.set('Seleccione un indicador disponible.'); return; }
|
||||
this.measureState.set('cargando');
|
||||
const params = this.cutoffs(new HttpParams().set('measure', measure.url).set('periodo', this.historyPeriods.replace(/\s/g, '')).set('_count', 200));
|
||||
this.requests.push(this.http.get<Resource>('/tea/fhir/MeasureReport', { params }).subscribe({
|
||||
next: bundle => { if (token === this.revision.measures) { const found = resources(bundle); if (bundle.total > found.length) { this.measureError.set('Seleccione como máximo 200 periodos.'); this.measureState.set('error'); return; } this.reports.set(found); this.measureState.set('listo'); } },
|
||||
error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } },
|
||||
}));
|
||||
}
|
||||
title(report: Resource) { return this.measures().find(m => report.measure?.split('|')[0] === m.url)?.title ?? report.measure; }
|
||||
rows(report: Resource): { label: string; value: string }[] {
|
||||
const group = report.group?.[0];
|
||||
if (!group) return [];
|
||||
const rows = (group.population ?? []).map((p: Resource) => ({ label: populations[code(p.code)] ?? text(p.code), value: this.value(p, 'count') }));
|
||||
const measure = this.measures().find(m => report.measure?.split('|')[0] === m.url);
|
||||
if (code(measure?.scoring) !== 'cohort') rows.push({ label: 'Resultado', value: group.measureScore ? this.score(group.measureScore) : 'Sin dato' });
|
||||
for (const extension of group.measureScore?.extension ?? []) {
|
||||
if (extension.url?.endsWith('/q1') || extension.url?.endsWith('/q3')) rows.push({ label: extension.url.endsWith('/q1') ? 'Primer cuartil' : 'Tercer cuartil', value: `${extension.valueDecimal} días` });
|
||||
}
|
||||
for (const stratum of group.stratifier?.[0]?.stratum ?? []) {
|
||||
const name = code(stratum.value);
|
||||
const label = stages[name] ?? ({ '16_23': '16 a 23 meses', '24_29': '24 a 29 meses', '30_36': '30 a 36 meses' } as Record<string, string>)[name] ?? text(stratum.value);
|
||||
if (code(measure?.scoring) === 'cohort') rows.push({ label, value: this.value(stratum.population?.[0], 'count') });
|
||||
else {
|
||||
for (const p of stratum.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') });
|
||||
rows.push({ label: `${label} — resultado`, value: stratum.measureScore ? this.score(stratum.measureScore) : 'Sin dato' });
|
||||
}
|
||||
}
|
||||
for (const extra of report.group?.slice(1) ?? []) {
|
||||
const label = text(extra.code) || 'Grupo';
|
||||
for (const p of extra.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') });
|
||||
rows.push({ label: `${label} — resultado`, value: extra.measureScore ? this.score(extra.measureScore) : 'Sin dato' });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
value(value: Resource, field: string): string {
|
||||
if (value?.[`_${field}`]?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido';
|
||||
return value?.[field] == null ? 'Sin dato' : String(value[field]);
|
||||
}
|
||||
score(score: Resource): string {
|
||||
if (score?._value?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido';
|
||||
if (score?.value == null) return 'Sin dato';
|
||||
return score.unit === 'd' ? `${score.value} días` : `${(100 * score.value).toFixed(1)} %`;
|
||||
}
|
||||
private errorText(error: Resource) { return error?.error?.issue?.[0]?.diagnostics ?? 'No fue posible consultar la información. Intente de nuevo.'; }
|
||||
applyFilters() { this.page = 0; this.loadEpisodes(); }
|
||||
loadEpisodes() {
|
||||
const token = ++this.revision.episodes;
|
||||
this.episodeState.set('cargando');
|
||||
let p = new HttpParams().set('_count', this.pageSize).set('_offset', this.page * this.pageSize).set('_include', '*');
|
||||
const f = this.filters;
|
||||
for (const [key, val] of [['status', f.status], ['etapa', f.stage], ['grupo-edad', f.age], ['resultado-eeg', f.eeg]] as const) if (val) p = p.set(key, val);
|
||||
if (this.alterationsAvailable() && f.alteration) p = p.set('alteracion', f.alteration);
|
||||
for (const [key, prefix, val] of [['date', 'ge', f.since], ['date', 'le', f.cutoff], ['fecha-etapa', 'ge', f.stageFrom], ['fecha-etapa', 'le', f.stageTo], ['mchat', 'ge', f.mchatMin], ['mchat', 'le', f.mchatMax], ['css', 'ge', f.cssMin], ['css', 'le', f.cssMax]] as const) if (val != null && val !== '') p = p.append(key, prefix + val);
|
||||
this.requests.push(this.http.get<Resource>('/tea/fhir/EpisodeOfCare', { params: p }).subscribe({
|
||||
next: bundle => {
|
||||
if (token !== this.revision.episodes) return;
|
||||
const found = resources(bundle);
|
||||
if (found.some(r => !simulated(r))) { this.episodeError.set('La información recibida no está identificada como datos simulados.'); this.episodeState.set('error'); return; }
|
||||
this.episodes.set(found.filter(r => r.resourceType === 'EpisodeOfCare')); this.episodeTotal.set(bundle.total ?? 0); this.episodeState.set('listo');
|
||||
},
|
||||
error: e => { if (token === this.revision.episodes) { this.episodeError.set(this.errorText(e)); this.episodeState.set('error'); } },
|
||||
}));
|
||||
}
|
||||
stage(e: Resource) { const value = code(e.type?.[0]); return stages[value] ?? value ?? 'Sin dato'; }
|
||||
stageDate(e: Resource) { return e.extension?.find((x: Resource) => x.url.endsWith('/fecha-etapa'))?.valueDate ?? 'Sin dato'; }
|
||||
patientId(e: Resource): string { return e.patient?.reference?.startsWith('Patient/') ? e.patient.reference.slice(8) : ''; }
|
||||
openPatient(e: Resource) {
|
||||
const id = this.patientId(e);
|
||||
if (!id) { this.episodeError.set('El episodio no identifica a un paciente.'); this.episodeState.set('error'); return; }
|
||||
const token = ++this.revision.patient;
|
||||
this.selected.set(id); this.patientState.set('cargando'); this.patientResources.set([]);
|
||||
this.requests.push(this.http.get<Resource>(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`).subscribe({
|
||||
next: bundle => {
|
||||
if (token !== this.revision.patient || this.selected() !== id) return;
|
||||
const found = resources(bundle);
|
||||
if (!found.some(r => r.resourceType === 'Patient' && r.id === id) || found.some(r => !simulated(r) || (r.resourceType === 'Patient' && r.id !== id) || (r.subject?.reference && r.subject.reference !== `Patient/${id}`))) {
|
||||
this.patientError.set('No se pudo verificar la identidad o el origen de la ficha.'); this.patientState.set('error'); return;
|
||||
}
|
||||
this.patientResources.set(found); this.patientState.set('listo');
|
||||
},
|
||||
error: e => { if (token === this.revision.patient && this.selected() === id) { this.patientError.set(this.errorText(e)); this.patientState.set('error'); } },
|
||||
}));
|
||||
}
|
||||
back() {
|
||||
const id = this.selected(); ++this.revision.patient; this.selected.set(null);
|
||||
setTimeout(() => this.element.nativeElement.querySelector<HTMLButtonElement>(`[data-patient="${id}"]`)?.focus());
|
||||
}
|
||||
ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); }
|
||||
eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); }
|
||||
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : 'Sin dato'; }
|
||||
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
|
||||
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : 'sin dato'; }
|
||||
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && code(r.code).startsWith('eeg.calidad_')); }
|
||||
alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); }
|
||||
alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); }
|
||||
componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); }
|
||||
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}` : 'Sin dato'); }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user