Files
WebApp/src/app/indicadores/tab-riesgos.ts
T
2026-12-03 10:23:42 -06:00

191 lines
7.2 KiB
TypeScript

import { DecimalPipe } from '@angular/common';
import {
Component,
computed,
inject,
input,
resource,
signal,
WritableSignal,
} 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 { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { Stages } from '../paciente/stages';
import { saveFollowUp } from './follow-up-export';
import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
import { name } from './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status,
* results and current risks, in the order asked for. */
@Component({
selector: 'app-tab-riesgos',
imports: [
PatientSearch,
DecimalPipe,
FormsModule,
Loading,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
RouterLink,
Stages,
],
templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss',
})
export class TabRiesgos {
private readonly fhir = inject(Fhir);
readonly domain = input.required<string>();
protected readonly cutoff = signal<string>('');
protected readonly window = signal(3);
protected readonly status = signal<string>('');
protected readonly horizon = signal(5);
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
/** Completed years at the cut-off (none: no limit). */
protected readonly ageFrom = signal<number | null>(null);
protected readonly ageTo = signal<number | null>(null);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** Whose stages are shown in full. */
protected readonly opened = signal<string | undefined>(undefined);
/** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES;
protected readonly name = name;
protected readonly result = cytologyResult;
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
birthdate: bornFor(this.cutoff(), this.ageFrom(), this.ageTo()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
loader: ({ params: { domain, query, size } }) => {
this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
},
});
protected readonly loading = signal(false);
protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
});
protected readonly offset = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? Number(new URL(self).searchParams.get('_offset') ?? 0) : 0;
});
protected readonly rows = computed(() => {
const page = this.page();
const cutoff = this.applied();
return page && cutoff
? rows(page, windowStart(cutoff, this.window()), cutoff, this.horizon())
: [];
});
protected readonly error = computed(() => this.first.error());
/** "Ventana consultada": the window's first day for the applied cut-off. */
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
/** "Estudio más reciente": her latest cytology or HPV sample. */
protected latest(row: Row): string | undefined {
return [row.cytology?.date, row.hpv?.date]
.filter((d) => !!d)
.sort()
.at(-1)
?.slice(0, 10);
}
protected retry(): void {
this.first.reload();
}
/** Ages are told at the cut-off: the one shown becomes the one asked for. */
protected setAge(age: WritableSignal<number | null>, years: number | null): void {
if (!this.cutoff()) this.cutoff.set(this.applied());
age.set(years);
}
/** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true);
this.saveError.set('');
try {
await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) => {
const cutoffYear = Number(query.cutoff.slice(0, 4));
// bornFor encodes the minimum with le and the maximum with gt at one year earlier.
const lower = query.birthdates.find((value) => value.startsWith('le'));
const upper = query.birthdates.find((value) => value.startsWith('gt'));
const minimum = lower ? `${cutoffYear - Number(lower.slice(2, 6))}` : 'Sin límite';
const maximum = upper ? `${cutoffYear - Number(upper.slice(2, 6)) - 1}` : 'Sin límite';
const all = pages.flatMap((p) => rows(p, query.start, query.cutoff, query.horizon));
return followUpSheet(all, [
['Ventana consultada', query.window],
['Estatus de seguimiento', query.status],
['Edad mínima', minimum],
['Edad máxima', maximum],
['Búsqueda', query.search],
['Horizonte de la probabilidad (años)', `${query.horizon}`],
]);
});
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected toggle(row: Row): void {
this.opened.set(this.opened() === row.patient.id ? undefined : row.patient.id);
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}
protected async go(relation: 'next' | 'previous'): Promise<void> {
const page = this.page();
const next = page && this.fhir.follow(this.domain(), page, relation);
if (!next) return;
this.loading.set(true);
try {
this.moved.set(await next);
} finally {
this.loading.set(false);
}
}
}