import { HttpClient } from '@angular/common/http'; import { Component, computed, inject, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { RouterLink } from '@angular/router'; import type { Parameters } from 'fhir/r4'; import { firstValueFrom } from 'rxjs'; import { ApiConfiguration } from '../api/api-configuration'; import { Fhir } from '../fhir'; import { Loading } from '../loading'; import { windowStart } from './follow-up'; import { name } from './measures'; import { Pager } from './pager'; import { PatientSearch } from './patient-search'; import { ageMonths, ASSOCIATION_LABELS, associationRows, DEFAULT_ASSOCIATION_FILTER, exportTea, fetchTeaRows, formatIc, formatOr, formatProbability, formatQ, matchesTeaSearch, parameters, SCORE_FILTERS, teaParams, TOKEN_FILTERS, type AssociationFilter, type TeaFilters, } from './tea-rows'; @Component({ selector: 'app-tab-riesgos-tea', imports: [ FormsModule, Loading, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule, PatientSearch, Pager, RouterLink, ], templateUrl: './tab-riesgos-tea.html', styleUrls: ['./tab-seguimiento-tea.scss', './tab-riesgos-tea.scss'], }) export class TabRiesgosTea { private readonly fhir = inject(Fhir); private readonly http = inject(HttpClient); private readonly root = inject(ApiConfiguration).rootUrl; protected readonly filters = signal({ window: 3 }); protected readonly tokenFilters = TOKEN_FILTERS; protected readonly scoreFilters = SCORE_FILTERS; protected readonly name = name; protected readonly ageMonths = ageMonths; protected readonly formatOr = formatOr; protected readonly formatIc = formatIc; protected readonly formatQ = formatQ; protected readonly formatProbability = formatProbability; protected readonly search = signal(''); protected readonly association = signal(DEFAULT_ASSOCIATION_FILTER); protected readonly associationLabels = ASSOCIATION_LABELS; protected readonly associationOptions = ['all', 'with', 'without'] as const; protected readonly size = signal(20); protected readonly index = signal(0); protected readonly exporting = signal(false); protected readonly actionError = signal(''); private readonly serverFilters = computed(() => teaParams(this.filters())); private readonly results = resource({ params: () => this.serverFilters(), loader: ({ params, abortSignal }) => fetchTeaRows(this.fhir, params, abortSignal), }); private readonly summaryResult = resource({ params: () => Object.fromEntries( Object.entries(this.serverFilters()).filter(([, value]) => value !== undefined), ) as Record, loader: ({ params }) => firstValueFrom( this.http.get(`${this.root}/tea/fhir/Patient/$eeg-summary`, { params }), ), }); protected readonly summary = computed(() => { if (!this.summaryResult.hasValue()) return undefined; const entries = this.summaryResult.value().parameter ?? []; const count = (key: string) => entries.find((entry) => entry.name === key)?.valueInteger ?? 0; return { normal: count('normal'), abnormal: count('abnormal'), notValid: count('not_valid'), alterations: entries .filter((entry) => entry.name === 'by_alteration') .map(({ part }) => ({ code: part?.find((entry) => entry.name === 'alteration')?.valueCode ?? '', patients: part?.find((entry) => entry.name === 'patients')?.valueInteger ?? 0, })), }; }); protected readonly summaryError = this.summaryResult.error; protected readonly loading = this.results.isLoading; protected readonly error = this.results.error; private readonly applied = computed(() => parameters(this.results.hasValue() ? this.results.value().first : undefined), ); protected readonly cutoff = computed(() => this.applied()['follow-up-cutoff'] ?? ''); protected readonly start = computed( () => this.filters().start || (this.cutoff() ? windowStart(this.cutoff(), this.filters().window ?? 3) : ''), ); protected readonly filtered = computed(() => associationRows( this.results.hasValue() ? this.results.value().rows : [], this.association(), ).filter((row) => matchesTeaSearch(row, this.search())), ); protected readonly rows = computed(() => this.filtered().slice(this.index() * this.size(), (this.index() + 1) * this.size()), ); protected readonly pageCount = computed(() => Math.max(1, Math.ceil(this.filtered().length / this.size())), ); protected setFilter(key: K, value: TeaFilters[K]): void { this.index.set(0); this.filters.update((filters) => ({ ...filters, [key]: value })); } protected async export(): Promise { this.exporting.set(true); this.actionError.set(''); try { await exportTea( this.filtered(), { ...this.applied(), ...(this.search() ? { Búsqueda: this.search() } : {}), 'Modelo de asociación': ASSOCIATION_LABELS[this.association()], }, true, ); } catch { this.actionError.set('No se pudo exportar el archivo.'); } finally { this.exporting.set(false); } } }