114 lines
6.6 KiB
TypeScript
114 lines
6.6 KiB
TypeScript
import { Injectable, signal } from '@angular/core';
|
|
import { Dominio, Indicador, parsePeriodos, Tema, TipoPeriodo } from './indicadores.models';
|
|
|
|
export type PeriodDraft =
|
|
| { mode: 'todos' }
|
|
| { mode: 'empty' }
|
|
| { mode: 'explicit'; periodos: [string, ...string[]] };
|
|
export type AppliedPeriods = Exclude<PeriodDraft, { mode: 'empty' }>;
|
|
export interface PeriodEditor { added: string[]; draft: PeriodDraft; }
|
|
export interface FilterState {
|
|
tipo: TipoPeriodo;
|
|
editors: Partial<Record<TipoPeriodo, PeriodEditor>>;
|
|
applied?: { tipo: TipoPeriodo; selection: AppliedPeriods };
|
|
}
|
|
export interface GlobalApplied { tipo: TipoPeriodo; selection: AppliedPeriods; revision: number; }
|
|
export interface GlobalFilterState extends FilterState { applied: GlobalApplied; }
|
|
export function newEditor(tipo: TipoPeriodo, first: TipoPeriodo): PeriodEditor {
|
|
return { added: [], draft: tipo === 'semestre' && tipo === first ? { mode: 'todos' } : { mode: 'empty' } };
|
|
}
|
|
export function validDraft(draft: PeriodDraft, tipo: TipoPeriodo, types: TipoPeriodo[]): draft is AppliedPeriods {
|
|
if (!types.includes(tipo) || draft.mode === 'empty') return false;
|
|
if (draft.mode === 'todos') return tipo === 'semestre' && tipo === types[0];
|
|
const parsed = parsePeriodos(draft.periodos.join(','), tipo);
|
|
return parsed !== null && parsed.length === draft.periodos.length
|
|
&& parsed.every((p, i) => p === draft.periodos[i]);
|
|
}
|
|
export function describePeriods(tipo: TipoPeriodo, draft: PeriodDraft): string {
|
|
return draft.mode === 'todos' ? 'Todos con reporte (semestres)'
|
|
: draft.mode === 'empty' ? 'Sin periodos seleccionados' : draft.periodos.join(', ');
|
|
}
|
|
export function selectionKey(applied: Pick<GlobalApplied, 'tipo' | 'selection'>): string {
|
|
return JSON.stringify([applied.tipo, applied.selection.mode,
|
|
applied.selection.mode === 'explicit' ? [...applied.selection.periodos].sort() : []]);
|
|
}
|
|
export function pending(state: FilterState): boolean {
|
|
const draft = state.editors[state.tipo]?.draft;
|
|
return !state.applied || !draft || draft.mode === 'empty'
|
|
|| selectionKey(state.applied) !== selectionKey({ tipo: state.tipo, selection: draft });
|
|
}
|
|
export function domainTypes(items: readonly Indicador[]): TipoPeriodo[] {
|
|
return (['semestre', 'mes'] as const).filter(tipo => items.some(item => item.tipos_periodo.includes(tipo)));
|
|
}
|
|
export type Compatibility = { compatible: true } | { compatible: false; reason: string };
|
|
// Published capabilities only; this adapter never changes a selection or probes HTTP.
|
|
// Future consumers may use the same capability list without defining a KPI contract here.
|
|
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
|
|
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
|
|
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
|
|
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de análisis ' + (applied.tipo === 'mes' ? 'mensual' : 'semestral') + ' del filtro general.' };
|
|
const mode = applied.selection.mode;
|
|
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
|
|
? 'Todos con reporte requiere semestre como primer intervalo de análisis publicado. Para meses elige un periodo.'
|
|
: 'Los periodos del filtro general no son válidos para este intervalo de análisis.' };
|
|
return { compatible: true };
|
|
}
|
|
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
|
const draft = state.editors[state.tipo]?.draft;
|
|
if (!draft || !validDraft(draft, state.tipo, types) || !pending(state)) return false;
|
|
state.applied = { tipo: state.tipo, selection: structuredClone(draft), revision: state.applied.revision + 1 };
|
|
return true;
|
|
}
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class IndicadoresMemory {
|
|
private readonly manuallyApplied = new Set<Dominio>();
|
|
initialKpiPresentation(domain: Dominio) { return !this.manuallyApplied.has(domain); }
|
|
finishInitialKpiPresentation(domain: Dominio) { this.manuallyApplied.add(domain); }
|
|
private readonly pinnedIndicators = signal<ReadonlySet<string>>(new Set());
|
|
isPinned(domain: Dominio, indicador: string) {
|
|
return this.pinnedIndicators().has(JSON.stringify([domain, indicador]));
|
|
}
|
|
togglePinned(domain: Dominio, indicador: string) {
|
|
const key = JSON.stringify([domain, indicador]);
|
|
this.pinnedIndicators.update(current => {
|
|
const next = new Set(current);
|
|
if (next.has(key)) next.delete(key); else next.add(key);
|
|
return next;
|
|
});
|
|
}
|
|
private readonly themes = new Map<Dominio, Tema>();
|
|
private readonly figures = new Map<string, string>();
|
|
figure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); }
|
|
rememberFigure(domain: Dominio, indicador: string, figure: string) {
|
|
this.figures.set(JSON.stringify([domain, indicador]), figure);
|
|
}
|
|
private readonly filters = new Map<Dominio, GlobalFilterState>();
|
|
theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; }
|
|
rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); }
|
|
saveGlobal(domain: Dominio, state: GlobalFilterState) {
|
|
this.filters.set(domain, structuredClone(state));
|
|
}
|
|
restoreGlobal(domain: Dominio, types: TipoPeriodo[]): GlobalFilterState {
|
|
const stored = this.filters.get(domain);
|
|
const state: GlobalFilterState = stored ? structuredClone(stored) : {
|
|
tipo: 'semestre', editors: { semestre: newEditor('semestre', 'semestre') },
|
|
applied: { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 },
|
|
};
|
|
for (const tipo of types) state.editors[tipo] ??= newEditor(tipo, 'semestre');
|
|
// Legacy CaMa selections can contain several periods although its editor now shows one.
|
|
if (domain === 'cama' && stored) {
|
|
for (const editor of Object.values(state.editors)) {
|
|
if (editor?.draft.mode === 'explicit' && editor.draft.periodos.length > 1)
|
|
editor.draft = { mode: 'explicit', periodos: [editor.draft.periodos[0]] };
|
|
}
|
|
const selection = state.applied.selection;
|
|
if (selection.mode === 'explicit' && selection.periodos.length > 1)
|
|
state.applied = { ...state.applied, selection: { mode: 'explicit', periodos: [selection.periodos[0]] }, revision: state.applied.revision + 1 };
|
|
}
|
|
// Preserve an application whose capabilities changed: consumers explain incompatibility,
|
|
// rather than silently replacing or trimming the user's temporal selection.
|
|
return state;
|
|
}
|
|
}
|