diff --git a/src/app/indicadores/period-selection.spec.ts b/src/app/indicadores/period-selection.spec.ts new file mode 100644 index 0000000..747fb01 --- /dev/null +++ b/src/app/indicadores/period-selection.spec.ts @@ -0,0 +1,71 @@ +import { + ALL_PERIODS, + chosenLabel, + chronological, + CUSTOM_PERIODS, + initialWindow, + periodsByYear, + visiblePeriods, + windowOptions, +} from './period-selection'; + +const months = Array.from({ length: 12 }, (_, i) => `2024-${String(i + 1).padStart(2, '0')}`); +const none = { window: ALL_PERIODS, custom: [] }; + +describe('period selection', () => { + it('starts on the declared window only when there are more periods than it', () => { + expect(initialWindow(5, 12)).toBe(5); + expect(initialWindow(5, 5)).toBe(ALL_PERIODS); + expect(initialWindow(5, 3)).toBe(ALL_PERIODS); + expect(initialWindow(5, 0)).toBe(5); + expect(initialWindow(0, 12)).toBe(ALL_PERIODS); + }); + + it('shows the latest periods, all of them, or the chosen ones, oldest first', () => { + const shuffled = [...months].reverse(); + expect(visiblePeriods(shuffled, { window: 5, custom: [] })).toEqual(months.slice(-5)); + expect(visiblePeriods(shuffled, none)).toEqual(months); + expect( + visiblePeriods(shuffled, { window: CUSTOM_PERIODS, custom: ['2024-09', '2024-02'] }), + ).toEqual(['2024-02', '2024-09']); + expect(visiblePeriods(months, { window: 50, custom: [] })).toEqual(months); + }); + + it('offers steps of five up to the total, all of them and a custom choice', () => { + expect(windowOptions('month', 12, none).map((o) => o.label)).toEqual([ + 'Últimos 5 meses', + 'Últimos 10 meses', + 'Todos (12 meses)', + 'Personalizado…', + ]); + expect(windowOptions('semester', 6, none).map((o) => o.label)).toEqual([ + 'Últimos 5 semestres', + 'Todos (6 semestres)', + 'Personalizado…', + ]); + expect(windowOptions('month', 0, none).map((o) => o.label)).toEqual(['Todos']); + }); + + it('counts the chosen periods in the custom option only while it is active', () => { + const custom = { window: CUSTOM_PERIODS, custom: ['2024-02'] }; + expect(windowOptions('month', 12, custom).at(-1)?.label).toBe('Personalizado (1 mes)'); + expect(windowOptions('month', 12, { ...custom, window: 5 }).at(-1)?.label).toBe( + 'Personalizado…', + ); + }); + + it('groups the periods by year in chronological order', () => { + expect(periodsByYear(['2024-01', '2023-12', '2024-02'])).toEqual([ + { year: '2023', periods: ['2023-12'] }, + { year: '2024', periods: ['2024-01', '2024-02'] }, + ]); + expect(chronological(['2024-S2', '2024-S1', '2024-S1'])).toEqual(['2024-S1', '2024-S2']); + }); + + it('words the count of chosen periods by unit', () => { + expect(chosenLabel('month', 1)).toBe('1 mes elegido'); + expect(chosenLabel('month', 3)).toBe('3 meses elegidos'); + expect(chosenLabel('semester', 1)).toBe('1 semestre elegido'); + expect(chosenLabel('semester', 2)).toBe('2 semestres elegidos'); + }); +}); diff --git a/src/app/indicadores/period-selection.ts b/src/app/indicadores/period-selection.ts new file mode 100644 index 0000000..429121b --- /dev/null +++ b/src/app/indicadores/period-selection.ts @@ -0,0 +1,70 @@ +import { PeriodType } from './measures'; + +export const ALL_PERIODS = 0; +export const CUSTOM_PERIODS = -1; +const STEP = 5; + +export interface PeriodChoice { + window: number; + custom: readonly string[]; +} + +export interface WindowOption { + value: number; + label: string; +} + +export function unitName(type: PeriodType, count: number): string { + if (type === 'month') return count === 1 ? 'mes' : 'meses'; + return count === 1 ? 'semestre' : 'semestres'; +} + +export function chosenLabel(type: PeriodType, count: number): string { + return count === 1 + ? `1 ${unitName(type, 1)} elegido` + : `${count} ${unitName(type, count)} elegidos`; +} + +export function initialWindow(initial: number, total: number): number { + return initial && (!total || total > initial) ? initial : ALL_PERIODS; +} + +export function chronological(periods: Iterable): string[] { + return [...new Set(periods)].sort(); +} + +export function visiblePeriods(available: readonly string[], choice: PeriodChoice): string[] { + const ordered = chronological(available); + if (choice.window === CUSTOM_PERIODS) return ordered.filter((p) => choice.custom.includes(p)); + return choice.window === ALL_PERIODS ? ordered : ordered.slice(-choice.window); +} + +export function windowOptions( + type: PeriodType, + total: number, + choice: PeriodChoice, +): WindowOption[] { + const latest: WindowOption[] = []; + for (let n = STEP; n < total; n += STEP) { + latest.push({ value: n, label: `Últimos ${n} ${unitName(type, n)}` }); + } + const all = { + value: ALL_PERIODS, + label: total ? `Todos (${total} ${unitName(type, total)})` : 'Todos', + }; + if (!total) return [...latest, all]; + const picked = choice.window === CUSTOM_PERIODS ? choice.custom.length : 0; + const custom = { + value: CUSTOM_PERIODS, + label: picked ? `Personalizado (${picked} ${unitName(type, picked)})` : 'Personalizado…', + }; + return [...latest, all, custom]; +} + +export function periodsByYear(periods: readonly string[]): { year: string; periods: string[] }[] { + const ordered = chronological(periods); + return [...new Set(ordered.map((p) => p.slice(0, 4)))].map((year) => ({ + year, + periods: ordered.filter((p) => p.startsWith(year)), + })); +} diff --git a/src/app/indicadores/periods-dialog.ts b/src/app/indicadores/periods-dialog.ts new file mode 100644 index 0000000..94baba6 --- /dev/null +++ b/src/app/indicadores/periods-dialog.ts @@ -0,0 +1,86 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { periodLabel, PeriodType } from './measures'; +import { chosenLabel, chronological, periodsByYear } from './period-selection'; + +export interface PeriodsDialogData { + type: PeriodType; + periods: readonly string[]; + chosen: readonly string[]; +} + +@Component({ + selector: 'app-periods-dialog', + imports: [MatButtonModule, MatCheckboxModule, MatDialogModule], + template: ` +

Elegir {{ data.type === 'month' ? 'meses' : 'semestres' }}

+ +
+ + +
+ @for (group of years; track group.year) { +
+ {{ group.year }} + @for (period of group.periods; track period) { + + {{ label(period) }} + + } +
+ } +
+ + {{ count() }} + + + + `, + styles: ` + .bulk { + display: flex; + gap: 8px; + margin-bottom: 8px; + } + fieldset { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); + gap: 0 8px; + margin: 0 0 12px; + padding: 4px 8px; + border: 1px solid var(--mat-sys-outline-variant); + border-radius: 8px; + } + legend { + padding-inline: 4px; + font-weight: 600; + } + .count { + margin-inline-end: auto; + padding-inline-start: 12px; + } + `, +}) +export class PeriodsDialog { + protected readonly data = inject(MAT_DIALOG_DATA); + private readonly ref = inject>(MatDialogRef); + protected readonly label = periodLabel; + protected readonly all = chronological(this.data.periods); + protected readonly years = periodsByYear(this.all); + protected readonly chosen = signal(this.data.chosen); + protected readonly count = computed(() => chosenLabel(this.data.type, this.chosen().length)); + + protected toggle(period: string): void { + this.chosen.update((now) => + now.includes(period) ? now.filter((p) => p !== period) : [...now, period], + ); + } + + protected apply(): void { + this.ref.close(this.all.filter((p) => this.chosen().includes(p))); + } +} diff --git a/src/app/indicadores/tab-trazabilidad.ts b/src/app/indicadores/tab-trazabilidad.ts index 21e03ea..0c296be 100644 --- a/src/app/indicadores/tab-trazabilidad.ts +++ b/src/app/indicadores/tab-trazabilidad.ts @@ -1,12 +1,33 @@ 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 } from './measures'; +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; @@ -16,18 +37,38 @@ interface Drawn { @Component({ selector: 'app-tab-trazabilidad', - imports: [Loading, MatButtonToggleModule, Plot], + imports: [ + Loading, + MatButtonModule, + MatButtonToggleModule, + MatFormFieldModule, + MatSelectModule, + Plot, + ], template: `

Filtros

- - Mensual - Semestral - +
+ + Mensual + Semestral + + + Periodos a mostrar + + @for (option of options(); track option.value) { + {{ option.label }} + } + + + @if (choice().window === customPeriods) { + + } +
@if (series.isLoading()) { @@ -68,6 +109,12 @@ interface Drawn { 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; @@ -91,7 +138,11 @@ 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() }), @@ -114,22 +165,77 @@ export class TabTrazabilidad { }, }); + 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 has = (p: (typeof points)[number]) => (p.r?.populations['initial-population'] ?? 0) > 0; - const first = points.findIndex(has); - if (first < 0 || !history) return { panel, heading }; - const last = points.length - 1 - [...points].reverse().findIndex(has); - const shown = - history.months && this.type() === 'month' - ? points.slice(Math.max(first, last + 1 - history.months), last + 1) - : points.slice(first, last + 1); + 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) }; });