diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index feed61d..9857d72 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -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 }, diff --git a/src/app/features/indicadores/tea-status-page.html b/src/app/features/indicadores/tea-status-page.html new file mode 100644 index 0000000..74e5ea1 --- /dev/null +++ b/src/app/features/indicadores/tea-status-page.html @@ -0,0 +1,69 @@ +
+
Trastorno del espectro autista, investigación

Indicadores

Explore la información del tamizaje.

+ + + @if (section() !== 'seguimiento') { +
+

{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}

+
+ @if (section() === 'resumen') { } + @else { + + + } + + + +
+ @if (measureState() === 'cargando' || measureState() === 'inicial') {

Consultando indicadores…

} + @if (measureState() === 'error') {

{{ measureError() }}

} + @if (measureState() === 'listo' && reports().length === 0) {

No hay indicadores para la selección.

} + @for (report of reports(); track $index) { + @if (measureState() === 'listo') {

{{ title(report) }}

{{ report.period?.start }} a {{ report.period?.end }}

+ @if (rows(report).length === 0) {

Sin datos para el periodo.

} + @else {
@for (row of rows(report); track $index) {
{{ row.label }}
{{ row.value }}
}
} +
} + } +
+ } +
+

Seguimiento

Consulte los episodios según la fecha de corte y los filtros seleccionados.

+
+ + + + + + + + + @if (alterationsAvailable() && alterationTypes().length) { } + +
+ @if (episodeState() === 'cargando') {

Consultando seguimiento…

} + @if (episodeState() === 'error') {

{{ episodeError() }}

} + @if (episodeState() === 'listo') { +

{{ episodeTotal() }} episodios

+ @if (episodes().length === 0) {

No hay episodios para la selección.

} + @else { + @for (e of episodes(); track e.id) { } +
PacienteEtapaFecha de etapaEstado
{{ patientId(e) }}{{ stage(e) }}{{ stageDate(e) }}{{ e.status === 'finished' ? 'Finalizado' : 'En seguimiento' }}
} +
Página {{ page + 1 }}
+ } +
+ @if (section() === 'seguimiento' && selected()) { +

Ficha del paciente

{{ selected() }}

La ficha muestra la información disponible a la fecha actual.

+ @if (patientState() === 'cargando') {

Consultando ficha…

} + @if (patientState() === 'error') {

{{ patientError() }}

} + @if (patientState() === 'listo') { +

ADOS-2

@if (ados(); as ados) {

Fecha: {{ ados.effectiveDateTime }}

@for (c of ados.component; track $index) {
{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}
{{ componentValue(c) }}
}
} @else {

Sin información de ADOS-2.

}
+

EEG del estudio

@if (eeg(); as eeg) {

Fecha: {{ eeg.effectiveDateTime }}

Calidad: {{ eegQuality() }}

Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.

@if (eeg.conclusion) {

{{ eeg.conclusion }}

}
@for (o of quality(); track o.id) {
{{ o.code.coding?.[0]?.display }}
{{ observationValue(o) }} ({{ qualityStatus(o) }})
}
} @else {

Sin información de EEG.

}
+ @if (alterationsAvailable() && alterations().length) {

Métricas del EEG

@for (o of alterations(); track o.id) {
{{ o.code.coding?.[0]?.display }}
{{ observationValue(o) }}
}
} + } +
+ } +
diff --git a/src/app/features/indicadores/tea-status-page.scss b/src/app/features/indicadores/tea-status-page.scss new file mode 100644 index 0000000..4e56781 --- /dev/null +++ b/src/app/features/indicadores/tea-status-page.scss @@ -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; } diff --git a/src/app/features/indicadores/tea-status-page.spec.ts b/src/app/features/indicadores/tea-status-page.spec.ts index 74ac0c0..9f23683 100644 --- a/src/app/features/indicadores/tea-status-page.spec.ts +++ b/src/app/features/indicadores/tea-status-page.spec.ts @@ -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(); }); }); diff --git a/src/app/features/indicadores/tea-status-page.ts b/src/app/features/indicadores/tea-status-page.ts index 99b7b31..b6927ab 100644 --- a/src/app/features/indicadores/tea-status-page.ts +++ b/src/app/features/indicadores/tea-status-page.ts @@ -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 = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' }; +const populations: Record = { '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: ` -

Casos por estatus

-

Consulte la etapa alcanzada por las niñas y los niños en el periodo seleccionado.

-
- - -
- @if (estado() === 'cargando') {

Consultando información…

} - @if (estado() === 'error') {

No fue posible consultar el periodo. Verifique el periodo e intente de nuevo.

} - @if (estado() === 'listo') { -

Total: {{ total() }}

- @if (filas().length === 0) {

No hay casos para este periodo.

} - @else { } - } - `, + 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); + private requests: Subscription[] = []; + private revision = { measures: 0, episodes: 0, patient: 0 }; + readonly section = signal
('resumen'); + readonly measures = signal([]); + readonly alterationTypes = signal([]); + readonly reports = signal([]); + readonly measureState = signal('inicial'); + readonly measureError = signal(''); + readonly episodes = signal([]); + readonly episodeTotal = signal(0); + readonly episodeState = signal('inicial'); + readonly episodeError = signal(''); + readonly selected = signal(null); + readonly patientResources = signal([]); + readonly patientState = signal('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('/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 = { 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('/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('/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(`/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('/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)[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('/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(`/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(`[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'); } }