import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatDialog } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { historyFigure } from './figures';
import { periodLabel, periods, PeriodType, Reading, reading } from './measures';
import { HISTORY, HistoryPanel } from './pages';
import {
chronological,
CUSTOM_PERIODS,
initialWindow,
PeriodChoice,
visiblePeriods,
windowOptions,
} from './period-selection';
import { PeriodsDialog, PeriodsDialogData } from './periods-dialog';
interface Point {
period: string;
r: Reading | undefined;
}
const hasPopulation = (p: Point) => (p.r?.populations['initial-population'] ?? 0) > 0;
interface Drawn {
panel: HistoryPanel;
heading?: string;
figure?: Figure;
}
@Component({
selector: 'app-tab-trazabilidad',
imports: [
Loading,
MatButtonModule,
MatButtonToggleModule,
MatFormFieldModule,
MatSelectModule,
Plot,
],
template: `
Filtros
Mensual
Semestral
Periodos a mostrar
@for (option of options(); track option.value) {
{{ option.label }}
}
@if (choice().window === customPeriods) {
}
@if (series.isLoading()) {
} @else if (series.error()) {
No se pudo cargar la trazabilidad.
} @else {
@for (d of drawn(); track d.panel.measure) {
@if (d.heading) {
{{ d.heading }}
}
@if (d.panel.group) {
{{ d.panel.title }}
} @else {
{{ d.panel.title }}
}
@if (d.figure) {
} @else {
Sin datos para el periodo.
}
}
}
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
margin-bottom: 16px;
}
.filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
}
.filters-title {
font-size: 16px;
font-weight: 500;
margin: 0 0 12px;
}
.panel-title,
.group-title {
font-size: 20px;
font-weight: 700;
margin: 0 0 8px;
}
h3.panel-title {
font-size: 16px;
}
.group-title {
margin: 24px 0 12px;
}
`,
})
export class TabTrazabilidad {
private readonly fhir = inject(Fhir);
readonly domain = input.required();
readonly measures = input.required();
private readonly dialog = inject(MatDialog);
protected readonly type = signal('month');
protected readonly customPeriods = CUSTOM_PERIODS;
private readonly choices = signal>>({});
private readonly picking = signal(false);
protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
loader: async ({ params }) => {
const history = HISTORY[params.domain];
if (!history) return [];
const asked = periods(params.type).reverse();
return Promise.all(
history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure);
if (!measure) return { panel, points: [] };
const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!,
'reporting-period': asked.join(','),
});
const found = resources(pages, 'MeasureReport');
return { panel, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
}),
);
},
});
private readonly available = computed(() => {
if (!this.series.hasValue()) return [];
const withData = this.series
.value()
.flatMap(({ points }) => points.filter(hasPopulation).map((p) => p.period));
return chronological(withData);
});
protected readonly choice = computed(() => {
const type = this.type();
const initial = type === 'month' ? (HISTORY[this.domain()]?.months ?? 0) : 0;
return (
this.choices()[type] ?? {
window: initialWindow(initial, this.available().length),
custom: [],
}
);
});
protected readonly options = computed(() =>
windowOptions(this.type(), this.available().length, this.choice()),
);
protected readonly selected = computed(() =>
this.picking() ? CUSTOM_PERIODS : this.choice().window,
);
protected choose(window: number): void {
if (window === CUSTOM_PERIODS) {
void this.pick();
return;
}
this.choices.update((all) => ({
...all,
[this.type()]: { ...this.choice(), window },
}));
}
protected async pick(): Promise {
const type = this.type();
const periods = this.available();
const data: PeriodsDialogData = {
type,
periods,
chosen: visiblePeriods(periods, this.choice()),
};
this.picking.set(true);
const ref = this.dialog.open(PeriodsDialog, {
data,
width: '640px',
maxWidth: '92vw',
maxHeight: '85vh',
});
const custom = await firstValueFrom(ref.afterClosed());
this.picking.set(false);
if (custom?.length) {
this.choices.update((all) => ({ ...all, [type]: { window: CUSTOM_PERIODS, custom } }));
}
}
protected readonly drawn = computed(() => {
const history = HISTORY[this.domain()];
const xTitle = this.type() === 'month' ? 'Mes y año' : 'Semestre';
const visible = new Set(visiblePeriods(this.available(), this.choice()));
let group: string | undefined;
if (!this.series.hasValue()) return [];
return this.series.value().map(({ panel, points }) => {
const heading = panel.group && panel.group !== group ? panel.group : undefined;
group = panel.group;
const shown = points.filter((p) => visible.has(p.period));
if (!history || !shown.some(hasPopulation)) return { panel, heading };
const series = shown.map((p) => ({ label: periodLabel(p.period), r: p.r }));
return { panel, heading, figure: historyFigure(panel, series, history.line, xTitle) };
});
});
}