164 lines
11 KiB
TypeScript
164 lines
11 KiB
TypeScript
import { inject, Injectable } from '@angular/core';
|
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
|
import { map } from 'rxjs';
|
|
import { isoDate } from './cacu-seguimiento.models';
|
|
import { identidadesDe } from './paciente-identidad';
|
|
import { etiquetaDeFiltro } from './etiquetas-cohorte';
|
|
import { clasificacionHistologica } from './mapeo-histologico';
|
|
import { Dominio, requireDominio } from './indicadores.models';
|
|
|
|
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
|
|
// domain, or per source: the answer can be rebuilt from another source without changing this client.
|
|
export type SeguimientoValor = string | number | null;
|
|
export interface SeguimientoOpcion { codigo: string; etiqueta: string; }
|
|
// `detalles` are shown under the value, each with its label (for example the date of a result).
|
|
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[]; }
|
|
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoOpcion[]; }
|
|
// What a list of a cohort quotes back so that it opens the cohort that was counted: the cohort, its scenario and the
|
|
// revision of its rows. They are not filters; the answer repeats them, and a list that does not is not the one asked for.
|
|
export interface ContextoLista { cohorte: string; escenario: string; revision: string; }
|
|
export const CLAVES_CONTEXTO = ['cohorte', 'escenario', 'revision'] as const;
|
|
export interface SeguimientoTablaQuery {
|
|
corte?: string; meses: MesesVentana; page: number; page_size: number;
|
|
// The filters the list announces in `filtros_disponibles`, by key; an empty value is no filter.
|
|
filtros?: Record<string, string | undefined>;
|
|
contexto?: ContextoLista;
|
|
}
|
|
export interface SeguimientoTablaResponse extends Partial<ContextoLista> {
|
|
simulado: true;
|
|
corte: string;
|
|
ventana: { meses: MesesVentana; desde: string; hasta: string };
|
|
filtros: Record<string, string | null>;
|
|
filtros_disponibles: SeguimientoFiltro[];
|
|
columnas: SeguimientoColumna[];
|
|
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
|
// Every item names its patient (`pac_id`, or the legacy `id_seudonimo`); the rest are the columns' keys and their details.
|
|
items: Record<string, SeguimientoValor>[];
|
|
}
|
|
export class SeguimientoInvalido extends Error {}
|
|
|
|
// 0 is the whole list, without a time window: what a curve or a heatmap cell of the analysis opens. The list offers
|
|
// it only while such a selection is active.
|
|
export const MESES_VENTANA = [1, 3, 6, 12, 0] as const;
|
|
export type MesesVentana = typeof MESES_VENTANA[number];
|
|
/** What the window is called on screen and in the files: the whole cohort or a number of months. */
|
|
export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`;
|
|
export const PAGE_SIZE_MAX = 200;
|
|
const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO];
|
|
|
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
const integer = (v: unknown, min = 0): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
|
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
|
const valor = (v: unknown) => v === null || typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v));
|
|
// Keys travel as query parameters, so they are restricted to what cannot collide with the shared ones.
|
|
const clave = (v: unknown): v is string => text(v) && /^[a-z][a-z0-9_]*$/.test(v) && !RESERVADAS.includes(v);
|
|
const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiqueta']);
|
|
|
|
export function validQuery(q: SeguimientoTablaQuery) {
|
|
return (!q.corte || isoDate(q.corte)) && (MESES_VENTANA as readonly number[]).includes(q.meses) && integer(q.page, 1)
|
|
&& integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX && Object.keys(q.filtros ?? {}).every(clave)
|
|
// A cohort's list needs a cut-off: the revision belongs to it.
|
|
&& (!q.contexto || (!!q.corte && CLAVES_CONTEXTO.every(k => text(q.contexto![k]))));
|
|
}
|
|
|
|
/**
|
|
* Whether an answer says it applied the window and the filters that were asked for (and the cut-off, when one was
|
|
* asked, and the cohort, scenario and revision of a cohort's list). A list or a file must not show rows of another
|
|
* query under the title of this one.
|
|
*/
|
|
export function consultaAplicada(query: SeguimientoTablaQuery, answer: SeguimientoTablaResponse): boolean {
|
|
const entries = (filters: Record<string, string | null | undefined>) =>
|
|
JSON.stringify(Object.entries(filters).filter(([, v]) => !!v).sort(([a], [b]) => a.localeCompare(b)));
|
|
return answer.ventana.meses === query.meses && (!query.corte || answer.corte === query.corte)
|
|
&& entries(query.filtros ?? {}) === entries(answer.filtros)
|
|
&& (!query.contexto || CLAVES_CONTEXTO.every(k => answer[k] === query.contexto![k]));
|
|
}
|
|
|
|
/** The cohort an answer belongs to, when it names one: what the next pages and the files must quote back. */
|
|
export function contextoDe(answer: SeguimientoTablaResponse): ContextoLista | undefined {
|
|
return answer.cohorte && answer.escenario && answer.revision ? { cohorte: answer.cohorte, escenario: answer.escenario, revision: answer.revision } : undefined;
|
|
}
|
|
|
|
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|
|
// The current authorization covers demonstration records only: validated before any item reaches the view.
|
|
if (!record(v) || v['simulado'] !== true) throw new SeguimientoInvalido('El seguimiento no cumple el contrato esperado.');
|
|
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'], available = v['filtros_disponibles'], columns = v['columnas'];
|
|
const filtrosOk = Array.isArray(available) && available.every(f => record(f) && clave(f['clave']) && text(f['etiqueta'])
|
|
&& Array.isArray(f['opciones']) && f['opciones'].every(opcion)) && new Set(available.map(f => (f as Record<string, unknown>)['clave'])).size === available.length;
|
|
const columnasOk = Array.isArray(columns) && columns.length > 0 && columns.every(c => record(c) && text(c['clave']) && text(c['etiqueta'])
|
|
&& (c['detalles'] === undefined || (Array.isArray(c['detalles']) && c['detalles'].every(d => record(d) && text(d['clave']) && text(d['etiqueta'])))));
|
|
if (CLAVES_CONTEXTO.some(k => v[k] !== undefined && !text(v[k]))) throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
|
|
if (!isoDate(v['corte']) || !record(window) || !(MESES_VENTANA as readonly number[]).includes(window['meses'] as number)
|
|
|| !isoDate(window['desde']) || !isoDate(window['hasta'])
|
|
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || p['page_size'] > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
|
|| !filtrosOk || !columnasOk
|
|
|| !record(filters) || !Object.entries(filters).every(([k, f]) => (f === null || typeof f === 'string') && (available as Record<string, unknown>[]).some(a => a['clave'] === k))
|
|
|| !Array.isArray(v['items']) || v['items'].length > p['page_size']
|
|
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
|
|
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
|
|
}
|
|
const respuesta = clasificarHistologia(v as unknown as SeguimientoTablaResponse);
|
|
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
|
|
}
|
|
|
|
const TIPO_HISTOLOGICO = 'tipo_histologico';
|
|
const CLASIFICACION_HISTOLOGICA = 'clasificacion_histologica';
|
|
|
|
/**
|
|
* A list that carries the histologic type of each patient (`tipo_histologico`) also shows its classification, computed
|
|
* from that same value in the same row, in a column placed after the type's (or after the biopsy result when the type
|
|
* has no column). Rows without a type, and lists without the field, are left as received.
|
|
*/
|
|
export function clasificarHistologia(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
|
|
if (!r.items.some(item => typeof item[TIPO_HISTOLOGICO] === 'string') || r.columnas.some(c => c.clave === CLASIFICACION_HISTOLOGICA)) return r;
|
|
const columnas = [...r.columnas];
|
|
const despuesDe = [TIPO_HISTOLOGICO, 'biopsia'].map(k => columnas.findIndex(c => c.clave === k)).find(i => i >= 0) ?? columnas.length - 1;
|
|
columnas.splice(despuesDe + 1, 0, { clave: CLASIFICACION_HISTOLOGICA, etiqueta: 'Clasificación histológica' });
|
|
return {
|
|
...r,
|
|
columnas,
|
|
items: r.items.map(item => {
|
|
const tipo = item[TIPO_HISTOLOGICO];
|
|
return typeof tipo === 'string' ? { ...item, [CLASIFICACION_HISTOLOGICA]: clasificacionHistologica(tipo) } : item;
|
|
}),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
|
|
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays
|
|
* in `<clave>_codigo` and in the filters' options, which are what the requests send.
|
|
*/
|
|
export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
|
|
const claves = Object.keys(ETIQUETADAS);
|
|
return {
|
|
...r,
|
|
filtros_disponibles: r.filtros_disponibles.map(f => claves.includes(f.clave)
|
|
? { ...f, opciones: f.opciones.map(o => o.etiqueta === o.codigo ? { ...o, etiqueta: etiquetaDeFiltro(f.clave, o.codigo) } : o) } : f),
|
|
items: r.items.map(item => {
|
|
const nuevo = { ...item };
|
|
for (const k of claves) {
|
|
const valor = item[k];
|
|
if (typeof valor !== 'string' || etiquetaDeFiltro(k, valor) === valor) continue;
|
|
if (nuevo[k + '_codigo'] === undefined) nuevo[k + '_codigo'] = valor;
|
|
nuevo[k] = etiquetaDeFiltro(k, valor);
|
|
}
|
|
return nuevo;
|
|
}),
|
|
};
|
|
}
|
|
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true };
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class SeguimientoTablaService {
|
|
private readonly http = inject(HttpClient);
|
|
consultar(dominio: Dominio, query: SeguimientoTablaQuery) {
|
|
if (!validQuery(query)) throw new SeguimientoInvalido('Parámetros de seguimiento inválidos');
|
|
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
|
if (query.corte) params = params.set('corte', query.corte);
|
|
if (query.contexto) for (const k of CLAVES_CONTEXTO) params = params.set(k, query.contexto[k]);
|
|
for (const [k, v] of Object.entries(query.filtros ?? {})) if (v) params = params.set(k, v);
|
|
return this.http.get<unknown>(`/${requireDominio(dominio)}/seguimiento`, { params }).pipe(map(seguimientoTablaResponse));
|
|
}
|
|
}
|