Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e0a3be26eb | |||
| 52d00409a0 |
@@ -1,6 +1,4 @@
|
||||
export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia';
|
||||
export type OrdenSeguimiento = 'reciente' | ProbabilidadClave;
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
@@ -11,20 +9,13 @@ export interface SeguimientoPaciente {
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
/** CaCu: her latest biopsy reported by the cut-off, with its grade. */
|
||||
ultima_biopsia?: { fecha: string; grado: string | null } | null;
|
||||
/** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */
|
||||
probabilidades?: Partial<Record<ProbabilidadClave, ProbabilidadHorizonte[]>> | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
}
|
||||
export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; }
|
||||
export interface SeguimientoResponse {
|
||||
simulado: boolean;
|
||||
corte: string;
|
||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number };
|
||||
/** The horizons the models give, in years, for ordering and showing the probabilities. */
|
||||
horizontes_disponibles?: number[];
|
||||
filtros: { estatus: string | null };
|
||||
estatus_disponibles: SeguimientoStatus[];
|
||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||
@@ -38,15 +29,3 @@ export function isoDate(value: unknown): value is string {
|
||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||
}
|
||||
/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */
|
||||
export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined {
|
||||
return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte);
|
||||
}
|
||||
/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival).
|
||||
* Every patient or an unknown status shows none: each scenario has its own models. */
|
||||
export const COLUMNAS_DE_PROBABILIDAD: Readonly<Record<string, readonly ProbabilidadClave[]>> = {
|
||||
CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'],
|
||||
};
|
||||
export const ETIQUETA_PROBABILIDAD: Readonly<Record<ProbabilidadClave, string>> = {
|
||||
lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia',
|
||||
};
|
||||
|
||||
@@ -7,14 +7,6 @@ import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia'];
|
||||
const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
||||
const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates.
|
||||
const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string');
|
||||
const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) =>
|
||||
['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad'])
|
||||
&& (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto']))));
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
|
||||
}
|
||||
@@ -25,8 +17,6 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string))
|
||||
|| (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios)))
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
@@ -35,8 +25,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']))
|
||||
&& biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']);
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@@ -48,8 +37,6 @@ export class CacuSeguimientoService {
|
||||
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.estatus) params = params.set('estatus', query.estatus);
|
||||
if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden);
|
||||
if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte);
|
||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9);
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
@@ -97,50 +97,4 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
// Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the
|
||||
// horizon stop reaching the API (the list is paginated, so ordering happens there).
|
||||
it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' },
|
||||
probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }],
|
||||
cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] },
|
||||
} : item);
|
||||
const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const fila = root.querySelector('tbody tr')!;
|
||||
expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %');
|
||||
expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)');
|
||||
expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']);
|
||||
|
||||
fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1;
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1');
|
||||
req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges();
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)');
|
||||
});
|
||||
|
||||
// Fails if the columns stop following the status filtered: each scenario has its own models.
|
||||
it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' },
|
||||
probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item);
|
||||
const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim());
|
||||
expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)');
|
||||
expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false);
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)');
|
||||
expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']);
|
||||
|
||||
fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia';
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.has('orden')).toBe(false);
|
||||
req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges();
|
||||
expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false);
|
||||
expect(root.querySelector('select[name="orden"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 9,
|
||||
"total": 7,
|
||||
"link": [
|
||||
{
|
||||
"relation": "self",
|
||||
@@ -297,123 +297,6 @@
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/figuras",
|
||||
"valueString": "fig_c3r_caja"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"version": "0.1.0",
|
||||
"name": "cacu_dias_diagnostico_tratamiento",
|
||||
"title": "Tiempo de diagnóstico a tratamiento",
|
||||
"status": "active",
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.",
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-DIAGNOSTICO",
|
||||
"resource": {
|
||||
@@ -531,123 +414,6 @@
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/figuras",
|
||||
"valueString": "fig_c3r_caja"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"version": "0.1.0",
|
||||
"name": "cacu_dias_toma_tratamiento",
|
||||
"title": "Tiempo de tamizaje a tratamiento",
|
||||
"status": "active",
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del realizado.",
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-EU-TIEMPO-REPORTE",
|
||||
"resource": {
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
}
|
||||
@if (model(); as m) {
|
||||
<div class="controls">
|
||||
@if (m.period) { <p class="period">Periodo: {{ periodLabel(m.period) }}</p> }
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo</mat-label>
|
||||
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
|
||||
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||
@@ -17,17 +22,15 @@
|
||||
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||
@else if (figure(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||
<details class="how-to-read"><summary>Cómo leer</summary>
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él.
|
||||
El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos,
|
||||
y las medianas de los tramos no suman el acumulado.
|
||||
}
|
||||
</p>
|
||||
</details>
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento.
|
||||
El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos.
|
||||
Las medianas de los tramos no tienen que sumar el tiempo acumulado.
|
||||
}
|
||||
</p>
|
||||
}
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||
.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); }
|
||||
.note { color: var(--issste-text-secondary); max-width: 70ch; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
|
||||
@@ -64,10 +64,8 @@ describe('Ruta del tamizaje: componente', () => {
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||
// the period follows the page's filter, with no request of its own
|
||||
f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges();
|
||||
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
|
||||
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||
expect(f.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||
http.expectNone(() => true);
|
||||
@@ -81,17 +79,6 @@ describe('Ruta del tamizaje: componente', () => {
|
||||
expect(text).toContain('mediana 35.7');
|
||||
expect(text).toContain('Suprimido');
|
||||
});
|
||||
it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => {
|
||||
// Fails if the reading note goes back to an open paragraph under the chart.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id));
|
||||
const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement;
|
||||
expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer');
|
||||
expect(guia.open).toBe(false);
|
||||
expect(guia.textContent).toContain('bigote: Q1 a Q3');
|
||||
expect(f.nativeElement.querySelector('section > p.note')).toBeNull();
|
||||
});
|
||||
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
// Fails if an empty route draws a chart or hides the reason.
|
||||
f.detectChanges();
|
||||
|
||||
@@ -3,7 +3,9 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||
@@ -14,7 +16,7 @@ import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, ro
|
||||
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||
@Component({
|
||||
selector: 'app-indicador-screening-route',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
templateUrl: './indicador-screening-route.html',
|
||||
styleUrl: './indicador-screening-route.scss',
|
||||
})
|
||||
@@ -22,18 +24,17 @@ export class IndicadorScreeningRoute {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly tipo = input<TipoPeriodo>('semestre');
|
||||
/** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */
|
||||
readonly periodos = input<readonly string[] | undefined>(undefined);
|
||||
/** The measures load once the region is visible. */
|
||||
readonly visible = input(true);
|
||||
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly message = signal('');
|
||||
readonly view = signal<RouteView>('cumulative');
|
||||
readonly requestedPeriod = signal<string | undefined>(undefined);
|
||||
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||
readonly model = computed(() => {
|
||||
const data = this.payloads();
|
||||
return data ? routeModel(data, this.tipo(), this.periodos()) : undefined;
|
||||
return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined;
|
||||
});
|
||||
readonly figure = computed(() => {
|
||||
const model = this.model();
|
||||
@@ -55,6 +56,7 @@ export class IndicadorScreeningRoute {
|
||||
}
|
||||
|
||||
retry() { this.load(this.dominio(), this.tipo()); }
|
||||
selectPeriod(period: string) { this.requestedPeriod.set(period); }
|
||||
selectView(view: RouteView) { this.view.set(view); }
|
||||
|
||||
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||
@@ -65,7 +67,7 @@ export class IndicadorScreeningRoute {
|
||||
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: data => {
|
||||
try {
|
||||
const model = routeModel(data, tipo, this.periodos());
|
||||
const model = routeModel(data, tipo, this.requestedPeriod());
|
||||
this.payloads.set(data);
|
||||
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
|
||||
@@ -107,14 +107,13 @@ const reporteDe = (m: Measure, conteos: number[]): Report => ({
|
||||
|
||||
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
|
||||
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
|
||||
// Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none
|
||||
// Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none
|
||||
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
|
||||
// checked against the renderer.
|
||||
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
|
||||
expect(figuras).toEqual({
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_riesgo_banda: [], ind1: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Covers how the Indicadores tab arranges CaCu's figures: the five times of «Tiempo de tamizaje a diagnóstico» under
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures. Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures with the
|
||||
// pending «Progresión por grupo de riesgo». Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
@@ -39,21 +40,27 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||
|
||||
it('las figuras disponibles conservan su orden sin reservas vacías', () => {
|
||||
it('las cinco figuras conservan su orden y las ausentes quedan como pendientes', () => {
|
||||
// Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose
|
||||
// the names of the request.
|
||||
abrir(CACU);
|
||||
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
});
|
||||
|
||||
it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => {
|
||||
// Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it.
|
||||
it('con la ruta del tamizaje la gráfica dibuja colposcopía y biopsia y no hay una segunda tarjeta ni una pendiente', () => {
|
||||
// Fails if the measures only the route chart draws get a card (or a «pendiente» slot) next to it, which the route
|
||||
// chart's own page spec forbids.
|
||||
abrir([...CACU, ...RUTA]);
|
||||
expect(root().querySelector('.subsection-title')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([]);
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
expect(root().querySelector('app-indicador-screening-route')).not.toBeNull();
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
@@ -65,6 +72,7 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(root().querySelector('app-indicador-screening-route')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
@@ -78,9 +86,9 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(titulosKpi).not.toContain('Días de toma a resultado');
|
||||
});
|
||||
|
||||
it('los indicadores clínicos son los dos pedidos, sin tarjetas vacías ni figuras pendientes', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card, or if a pending
|
||||
// figure («Progresión por grupo de riesgo», withdrawn) comes back.
|
||||
it('los indicadores clínicos son los dos pedidos, sin una reserva de progresión sin datos', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card or if the pending
|
||||
// figure is not drawn as such.
|
||||
abrir(CACU);
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
|
||||
@@ -28,7 +28,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function load(items = [item('a'), item('b')], domain = 'tea') {
|
||||
function load(items = [item('M23_pacientes_evaluados'), item('M24_confirmacion_diagnostico')], domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
}
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
@@ -55,7 +55,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s sin KPI no publicados ni HTTP inicial', domain => {
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
|
||||
load(undefined, domain);
|
||||
load([item('sin_kpi')], domain);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
expect(sections[0].querySelector('#global-filters-title')!.textContent!.trim()).toBe('Filtros');
|
||||
@@ -73,7 +73,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar actualiza todas las activadas sin abrir pendientes ni KPI', () => {
|
||||
load([item('a'), item('b'), item('c')]); open(0); open(1); respond();
|
||||
load([item('M23_pacientes_evaluados'), item('M24_confirmacion_diagnostico'), item('M21_diagnosticados_con_eeg')]); open(0); open(1); respond();
|
||||
const before = cards(); draft('semestre', ['2025-S1']); apply();
|
||||
expect(cards()).toEqual(before); expect(cards()[2].visible).toBe(false);
|
||||
const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2);
|
||||
@@ -91,28 +91,28 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
it('tarjeta activada después recibe el último aplicado y solo su primera consulta', () => {
|
||||
load(); draft('semestre', ['2025-S2']); apply(); http.expectNone(() => true);
|
||||
cards()[1].setVisible(true); fixture.detectChanges();
|
||||
const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} });
|
||||
const r = request('M24_confirmacion_diagnostico'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} });
|
||||
cards()[1].setVisible(true); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it('fuera del viewport difiere aplicado y al volver usa revisión vigente', () => {
|
||||
load(); open(); respond(); const panel = panels()[0];
|
||||
cards()[0].setVisible(false); fixture.detectChanges(); draft('semestre', ['2025-S1']); apply();
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); expect(panel.result().status).toBe('deferred'); http.expectNone(() => true);
|
||||
open(); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
open(); const r = request('M23_pacientes_evaluados'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('restaurada abierta espera visibilidad y usa revisión vigente al activarse', () => {
|
||||
load(); open(); respond(); page.changeDominio('cacu'); load(undefined, 'cacu');
|
||||
page.changeDominio('tea'); load();
|
||||
expect(cards()[0].visible).toBe(false); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true);
|
||||
cards()[0].setVisible(true); fixture.detectChanges();
|
||||
expect(panels()[0].applied.revision).toBe(1); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
expect(panels()[0].applied.revision).toBe(1); const r = request('M23_pacientes_evaluados'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('mensual compartido consulta compatibles y retira resultado anterior del incompatible', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(0); open(1); respond();
|
||||
load([item('M23_pacientes_evaluados', ['semestre']), item('M24_confirmacion_diagnostico')]); open(0); open(1); respond();
|
||||
const panel = panels()[0], host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('mes', ['2025-01']); apply();
|
||||
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
|
||||
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
|
||||
http.expectNone(r => r.url.includes('/M23_pacientes_evaluados/figuras/')); const r = request('M24_confirmacion_diagnostico');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de análisis mensual');
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
@@ -120,28 +120,28 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
});
|
||||
it('incompatibilidad cancela solicitud pendiente y no queda cargando', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(); const old = request('a');
|
||||
load([item('M23_pacientes_evaluados', ['semestre']), item('M24_confirmacion_diagnostico')]); open(); const old = request('M23_pacientes_evaluados');
|
||||
draft('mes', ['2025-01']); apply(); expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('incompatible');
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); http.expectNone(() => true);
|
||||
});
|
||||
it('dos revisiones cancelan respuestas anteriores y carga oculta resultado previo conservando host', () => {
|
||||
load(); open(); respond(); const host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('semestre', ['2025-S1']); apply(); const old = request('a');
|
||||
draft('semestre', ['2025-S1']); apply(); const old = request('M23_pacientes_evaluados');
|
||||
expect(panels()[0].result().figure).toBeUndefined(); expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); apply(); const current = request('a');
|
||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); apply(); const current = request('M23_pacientes_evaluados');
|
||||
expect(old.cancelled).toBe(true); current.flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].result().figure!.data[0]['y']).toEqual([7]); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host);
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(false);
|
||||
});
|
||||
it('404 y reintento individual usan aplicado vigente y conservan borrador y otra figura', () => {
|
||||
load(); open(0); open(1); respond(); draft('semestre', ['2025-S1']); apply();
|
||||
request('a').flush('private', { status: 404, statusText: 'Not Found' }); request('b').flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
request('M23_pacientes_evaluados').flush('private', { status: 404, statusText: 'Not Found' }); request('M24_confirmacion_diagnostico').flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const other = panels()[1].result(); editor().select([]); panels()[0].requestFigure();
|
||||
const retry = request('a'); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
const retry = request('M23_pacientes_evaluados'); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} }); expect(panels()[1].result()).toBe(other); expect(editor().entry.draft.mode).toBe('empty');
|
||||
});
|
||||
it('dominio durante carga cancela saliente y restaura borrador separado del aplicado', () => {
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('a');
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('M23_pacientes_evaluados');
|
||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
|
||||
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
|
||||
@@ -152,15 +152,15 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
});
|
||||
it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => {
|
||||
load(); draft('mes', ['2025-01']); apply(); open(); respond();
|
||||
page.retryCatalog(); fixture.detectChanges(); load([item('a', ['semestre'])]);
|
||||
page.retryCatalog(); fixture.detectChanges(); load([item('M23_pacientes_evaluados', ['semestre'])]);
|
||||
expect(page.filters!.applied.tipo).toBe('mes'); expect(page.filters!.applied.revision).toBe(1);
|
||||
cards()[0].setVisible(true); fixture.detectChanges();
|
||||
expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
editor().changeTipo('semestre'); apply(); request('a').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2);
|
||||
editor().changeTipo('semestre'); apply(); request('M23_pacientes_evaluados').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2);
|
||||
});
|
||||
it('orden del catálogo no permite simular Todos mensual', () => {
|
||||
load([item('a', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
draft('mes', ['2025-01']); apply(); request('a').flush({ data: [], layout: {} });
|
||||
load([item('M23_pacientes_evaluados', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
draft('mes', ['2025-01']); apply(); request('M23_pacientes_evaluados').flush({ data: [], layout: {} });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,16 +96,20 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
// the page gives it, and with the contract the panel expects.
|
||||
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
|
||||
const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']);
|
||||
for (const panel of activos) {
|
||||
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
|
||||
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||
}
|
||||
});
|
||||
it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => {
|
||||
// Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure.
|
||||
expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]);
|
||||
it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => {
|
||||
const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo);
|
||||
expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([
|
||||
['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'C3r'],
|
||||
['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'],
|
||||
['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'],
|
||||
]);
|
||||
// The risk bands are in the catalog and stay reserved.
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,9 +19,8 @@ const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStar
|
||||
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
|
||||
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const RESERVADOS: string[] = [];
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
|
||||
const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||
@@ -96,21 +95,21 @@ describe('Histórico de CaCu', () => {
|
||||
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||
});
|
||||
it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => {
|
||||
it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
const reservados = paneles().slice(ACTIVOS.length);
|
||||
expect(graficas()).toHaveLength(6);
|
||||
const reservados = paneles().slice(6);
|
||||
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||
expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual(
|
||||
HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
HISTORICO_CACU.slice(6).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
});
|
||||
it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => {
|
||||
// Pins down: the state of a reserved panel comes from the config alone.
|
||||
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||
montar(catalogo, true); responder();
|
||||
expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo'));
|
||||
expect(paneles().slice(6).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(3).fill('Trabajo en desarrollo'));
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
});
|
||||
@@ -123,7 +122,7 @@ describe('Histórico de CaCu', () => {
|
||||
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
@@ -131,7 +130,7 @@ describe('Histórico de CaCu', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
@@ -177,7 +176,7 @@ describe('Histórico de CaCu', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||
@@ -189,7 +188,7 @@ describe('Histórico de CaCu', () => {
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo');
|
||||
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
});
|
||||
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||
montar(CATALOGO, true);
|
||||
@@ -197,17 +196,17 @@ describe('Histórico de CaCu', () => {
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('private');
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||
reintentar.click(); fixture.detectChanges(); responder();
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
expect(graficas()).toHaveLength(6);
|
||||
});
|
||||
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
|
||||
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
|
||||
const panel = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
});
|
||||
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
|
||||
@@ -227,7 +226,7 @@ describe('Histórico de CaCu', () => {
|
||||
}
|
||||
});
|
||||
it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
||||
montar(RESERVADOS.map(item), true);
|
||||
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
|
||||
@@ -42,7 +42,7 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
];
|
||||
|
||||
// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask.
|
||||
// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved.
|
||||
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
@@ -50,9 +50,12 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana',
|
||||
enDesarrollo: true, fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'] },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana',
|
||||
enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas',
|
||||
enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
|
||||
@@ -142,21 +142,16 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe('');
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total');
|
||||
});
|
||||
it('M30 dibuja EEG anormal y EEG normal como dos líneas complementarias', () => {
|
||||
// Fails if the normal line stops mirroring the abnormal one over the same denominator, or if a period without
|
||||
// evaluable children is drawn as normal (it stays a gap), or if the caption changes.
|
||||
it('M30 dibuja solo la línea de EEG anormal publicada', () => {
|
||||
const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }),
|
||||
fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos);
|
||||
const f = m30.figure as unknown as Fig;
|
||||
const lineas = f.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal', 'EEG normal']);
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal']);
|
||||
expect(lineas[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(lineas[1]['y']).toEqual([37.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8');
|
||||
expect(JSON.stringify(lineas[1]['text'])).toContain('3 de 8');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]);
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza (normal)')!['y']).toEqual([69.4, 13.7]);
|
||||
expect(m30.comoLeer).toBe('La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.');
|
||||
expect(m30.comoLeer).toBe('Línea de EEG anormal: se detecta alguna alteración.');
|
||||
expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
|
||||
@@ -102,12 +102,10 @@ function colorDeLinea(id: string, tema: Tema) {
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
// Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions.
|
||||
const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0];
|
||||
|
||||
const PIE_PORCENTAJE: Readonly<Record<string, string>> = {
|
||||
cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.',
|
||||
[M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
[M30_RESULTADO_EEG]: 'Línea de EEG anormal: se detecta alguna alteración.',
|
||||
};
|
||||
const PIE_MEDIANA: Readonly<Record<string, string>> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id,
|
||||
'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.']));
|
||||
@@ -119,19 +117,9 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje');
|
||||
const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
const resultadoEeg = data.id === M30_RESULTADO_EEG;
|
||||
const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje';
|
||||
const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10);
|
||||
// EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval.
|
||||
const normal = data.id === M30_RESULTADO_EEG ? [
|
||||
banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false,
|
||||
line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG },
|
||||
text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} %<br>%{text}<extra></extra>' },
|
||||
] : [];
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
@@ -142,7 +130,6 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
...normal,
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}),
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('Pestaña Histórico', () => {
|
||||
it('TEA tiene Trazabilidad y Análisis de Riesgo', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => {
|
||||
|
||||
@@ -105,17 +105,17 @@ describe('Figuras de histórico', () => {
|
||||
describe('Pestaña Histórico', () => {
|
||||
let http: HttpTestingController;
|
||||
let fixture: ComponentFixture<IndicadoresHistorico>;
|
||||
const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||
const periodos = { id: 'm1', version: '1', periodos: [
|
||||
const catalog: Indicador[] = [{ id: 'M24_confirmacion_diagnostico', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||
const periodos = { id: 'M24_confirmacion_diagnostico', version: '1', periodos: [
|
||||
{ periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
|
||||
{ periodo: '2024-02', tipo: 'mes', report_id: 2, periodo_inicio: '2024-02-01', periodo_fin: '2024-03-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
|
||||
{ periodo: '2024-S1', tipo: 'semestre', report_id: 3, periodo_inicio: '2024-01-01', periodo_fin: '2024-07-01', fecha_corte: '2024-08-01', generado_en: '2024-08-01T00:00:00+00:00' },
|
||||
] };
|
||||
const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
|
||||
const datosUrl = '/tea/indicadores/m1/datos';
|
||||
const datos = (tipo: string, ps: string[]) => ({ id: 'M24_confirmacion_diagnostico', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
|
||||
const datosUrl = '/tea/indicadores/M24_confirmacion_diagnostico/datos';
|
||||
const render = () => { TestBed.tick(); fixture.detectChanges(); };
|
||||
const datos_ = (tipo: string, ps: string[]) => datos(tipo, ps);
|
||||
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
|
||||
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
@@ -129,9 +129,25 @@ describe('Pestaña Histórico', () => {
|
||||
afterEach(() => http.verify());
|
||||
const abrir = () => {
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
http.expectOne('/tea/indicadores/m1/periodos').flush(periodos);
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush(periodos);
|
||||
};
|
||||
|
||||
it('ignora periodos y consultas de indicadores TEA ocultos', () => {
|
||||
fixture.componentRef.setInput('catalog', [
|
||||
{ ...catalog[0], tipos_periodo: ['semestre'] },
|
||||
{ id: 'oculto', titulo: 'Oculto', contrato: 'C1', figuras: [], tipos_periodo: ['mes'] },
|
||||
]);
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
expect(fixture.componentInstance.tipos()).toEqual(['semestre']);
|
||||
expect(fixture.componentInstance.tipo()).toBe('semestre');
|
||||
http.expectNone('/tea/indicadores/oculto/periodos');
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush(periodos);
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', ['2024-S1'])); render();
|
||||
expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M24_confirmacion_diagnostico']);
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toContain('2024 S1');
|
||||
http.expectNone(r => r.url.includes('/oculto/'));
|
||||
});
|
||||
|
||||
it('no consulta hasta abrir la pestaña y entonces pide todos los periodos de una vez', () => {
|
||||
http.expectNone(() => true);
|
||||
abrir();
|
||||
@@ -157,7 +173,7 @@ describe('Pestaña Histórico', () => {
|
||||
const meses = Array.from({ length: 12 }, (_, i) => '2024-' + String(i + 1).padStart(2, '0'));
|
||||
const semestres = ['2020-S1', '2020-S2', '2021-S1', '2021-S2', '2022-S1', '2022-S2'];
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush({ id: 'M24_confirmacion_diagnostico', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render();
|
||||
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)', 'Personalizado…']);
|
||||
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)');
|
||||
@@ -206,19 +222,18 @@ describe('Pestaña Histórico', () => {
|
||||
const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||
expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos);
|
||||
// The notes live in the round help, not as text under the chart.
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')).toBeNull();
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')?.textContent?.trim()).toBe('Línea de EEG anormal: se detecta alguna alteración.');
|
||||
const ayuda = (fixture.nativeElement as HTMLElement).querySelector('.panel:last-child app-indicador-ayuda') as HTMLElement;
|
||||
ayuda.querySelector('button')!.click(); fixture.detectChanges();
|
||||
expect(ayuda.querySelector('.ayuda-texto')!.textContent).toContain('Resultado experimental.');
|
||||
});
|
||||
it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => {
|
||||
it('TEA muestra solamente los paneles solicitados en orden', () => {
|
||||
// Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped.
|
||||
const ids = ['M30_resultado_eeg', 'M29_calidad_eeg', 'otro', 'M28_casos_por_estado', 'M22_diagnosticados_sin_eeg', 'M21_diagnosticados_con_eeg', 'M24_confirmacion_diagnostico', 'M23_pacientes_evaluados'];
|
||||
fixture.componentRef.setInput('catalog', ids.map(id => ({ id, titulo: id, contrato: 'C2', figuras: [], tipos_periodo: ['mes'] })));
|
||||
render();
|
||||
expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg', 'otro']);
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg']);
|
||||
});
|
||||
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
|
||||
const c = fixture.componentInstance;
|
||||
@@ -256,7 +271,7 @@ describe('Pestaña Histórico', () => {
|
||||
});
|
||||
it('un indicador sin reportes del intervalo lo dice sin consultar sus datos', () => {
|
||||
fixture.componentRef.setInput('active', true); render();
|
||||
http.expectOne('/tea/indicadores/m1/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
|
||||
http.expectOne('/tea/indicadores/M24_confirmacion_diagnostico/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
|
||||
http.expectNone(r => r.url === datosUrl);
|
||||
expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados');
|
||||
});
|
||||
|
||||
@@ -86,7 +86,7 @@ export function resaltarSerie(figura: PlotlyFigure, elegida: string): PlotlyFigu
|
||||
return { ...figura, data };
|
||||
}
|
||||
|
||||
// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them.
|
||||
// TEA's requested panels in display order.
|
||||
const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG];
|
||||
function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; };
|
||||
@@ -161,7 +161,7 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
||||
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.comoLeer && (dominio() !== 'tea' || panel.item.id === 'M30_resultado_eeg')) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
@@ -262,7 +262,7 @@ export class IndicadoresHistorico {
|
||||
const config = this.config();
|
||||
return config
|
||||
? config.paneles.filter(entrada => !entrada.enDesarrollo).flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))
|
||||
: this.catalog();
|
||||
: this.dominio() === 'tea' ? this.catalog().filter(item => ORDEN_TEA.includes(item.id)) : this.catalog();
|
||||
});
|
||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
|
||||
@@ -365,9 +365,9 @@ export class IndicadoresHistorico {
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||
const items = this.publicados().filter(item => item.tipos_periodo.includes(tipo));
|
||||
if (this.dominio() !== 'tea') return items.map(panelDe);
|
||||
const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
const paneles = items.filter(item => ORDEN_TEA.includes(item.id)).map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
return agruparTiempos(ordenar(paneles, ORDEN_TEA));
|
||||
});
|
||||
|
||||
|
||||
@@ -78,9 +78,8 @@ describe('KPI de tratamiento de CaCu', () => {
|
||||
expect(cards[0].querySelector('.value')).toBeNull();
|
||||
expect(cards[1].querySelector('.value')?.firstChild?.textContent).toBe('7.75');
|
||||
expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD);
|
||||
// the cards carry no provisional notice: what the measure is lives in its technical sheet
|
||||
expect(cards[1].textContent).not.toContain('Indicador provisional');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')).toBeNull();
|
||||
expect(cards[1].textContent).toContain('El evento de tratamiento se infiere de notas clínicas');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')?.textContent).not.toContain('diagnóstico a tratamiento');
|
||||
expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally {
|
||||
|
||||
@@ -22,6 +22,7 @@ const CACU_TRATAMIENTO_C3R = {
|
||||
unit: 'días (mediana)',
|
||||
requiresObservations: true,
|
||||
c3rInfo: (n, q1, q3) => `${n} ${n === 1 ? 'observación' : 'observaciones'}. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`,
|
||||
note: 'Indicador provisional. El evento de tratamiento se infiere de notas clínicas, sin confirmación de que se realizó.',
|
||||
} satisfies Omit<KpiDefinition, 'id' | 'title'>;
|
||||
|
||||
export const CACU_TRATAMIENTO_KPIS: readonly KpiDefinition[] = [
|
||||
@@ -65,15 +66,17 @@ export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg'];
|
||||
// CaCu's available figures in display order; titles are assigned when the catalog publishes them.
|
||||
// CaCu's figures under «Indicadores de oportunidad» (section «Tiempo de tamizaje a diagnóstico») in display order. A slot
|
||||
// with no `id` has no published indicator yet and draws as pending; `titulo` is the name the page gives the figure.
|
||||
export interface FiguraOportunidad { id?: string; titulo: string; }
|
||||
export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' },
|
||||
{ titulo: 'Tiempo de toma de muestra a resultado de VPH' },
|
||||
{ id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' },
|
||||
{ id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' },
|
||||
];
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. Same rules as CaCu's: an entry
|
||||
// with no `id` has no published indicator yet and draws as pending.
|
||||
export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cama_eu38a', titulo: 'Tiempo de toma de mastografía a interpretación radiológica' },
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
return RouterTestingHarness.create();
|
||||
}
|
||||
function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]);
|
||||
http.expectOne('/' + domain + '/indicadores').flush(domain === 'tea' ? [{ ...syntheticCatalogs.tea[0], id: 'M23_pacientes_evaluados' }] : syntheticCatalogs[domain]);
|
||||
harness.detectChanges();
|
||||
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
|
||||
@@ -126,7 +126,7 @@
|
||||
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
|
||||
</div>
|
||||
}
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" [tipo]="filters?.applied?.tipo ?? 'semestre'" [periodos]="periodosDelFiltro()" /> }
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" /> }
|
||||
<div class="catalog-grid">
|
||||
@for (item of clinicosItems(); track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -20,15 +20,15 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] };
|
||||
const item: Indicador = { id: 'M23_pacientes_evaluados', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const second: Indicador = { ...item, id: 'M24_confirmacion_diagnostico', titulo: 'Dos', figuras: ['g'] };
|
||||
describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
@@ -46,7 +46,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; }
|
||||
|
||||
it('no presenta destacados retirados del catálogo ni consulta sus datos', () => {
|
||||
load();
|
||||
load([{ ...item, id: 'retirado' }]);
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')).map(h => (h as HTMLElement).textContent))
|
||||
.toEqual([]);
|
||||
@@ -90,7 +90,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(grid.children).toHaveLength(2);
|
||||
expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true);
|
||||
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']);
|
||||
// Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página.
|
||||
expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
|
||||
@@ -161,7 +161,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it.each([0, 1, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => {
|
||||
const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i }));
|
||||
load(items);
|
||||
http.expectOne('/tea/indicadores'); page.changeDominio('cacu'); load(items, 'cacu');
|
||||
expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
|
||||
expect(cards().every(c => !c.visible)).toBe(true);
|
||||
expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/'));
|
||||
@@ -232,7 +232,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
http.expectOne(r => r.url === '/tea/indicadores/i1/metadatos').flush({});
|
||||
http.expectOne(r => r.url === '/tea/indicadores/M23_pacientes_evaluados/metadatos').flush({});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false');
|
||||
@@ -278,13 +278,13 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(cards()[0].visible).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true);
|
||||
});
|
||||
it('identidades estables conservan componentes al reordenar el catálogo', () => {
|
||||
load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0];
|
||||
http.expectOne('/tea/indicadores'); page.changeDominio('cacu'); load([item, second], 'cacu'); toggle(); flushAll(); const card = cards()[0], panel = panels()[0];
|
||||
page.catalog.set([second, item]); fixture.detectChanges();
|
||||
expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
||||
});
|
||||
it('identidad eliminada no se monta aunque exista preferencia anterior', () => {
|
||||
TestBed.inject(IndicadoresMemory).rememberFigure('tea', 'removed', 'f1');
|
||||
load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll();
|
||||
load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['M24_confirmacion_diagnostico']); flushAll();
|
||||
});
|
||||
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
|
||||
load(); toggle(); flushAll();
|
||||
@@ -316,8 +316,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(page.catalogError()).toContain('error interno'); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
page.retryCatalog(); load([]); expect(panels()).toHaveLength(0);
|
||||
});
|
||||
it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => {
|
||||
load(syntheticCatalogs.tea);
|
||||
it.each(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => {
|
||||
load([item, second]);
|
||||
const index = cards().findIndex(c => c.indicador.id === id);
|
||||
toggle(index); flushAll();
|
||||
const c = control(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||
@@ -344,8 +344,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
it('IDs distintos con el mismo título y figura conservan paneles y etiquetas independientes', () => {
|
||||
load([{ ...item, figuras: ['f1'] }, { ...second, titulo: item.titulo, figuras: ['f1'] }]);
|
||||
toggle(0); toggle(1);
|
||||
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
|
||||
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
|
||||
const a = http.expectOne(r => r.url.endsWith('/M23_pacientes_evaluados/figuras/f1'));
|
||||
const b = http.expectOne(r => r.url.endsWith('/M24_confirmacion_diagnostico/figuras/f1'));
|
||||
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
|
||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
|
||||
|
||||
@@ -47,7 +47,7 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
];
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_TEA: typeof SECTIONS = [
|
||||
{ id: 'resumen', label: 'Resumen' }, { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
];
|
||||
const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
@@ -351,12 +351,6 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
/** The periods the page's filter applies, for the charts that follow it with no filter of their own (the screening
|
||||
* route); `undefined` when it applies every period. */
|
||||
periodosDelFiltro(): readonly string[] | undefined {
|
||||
const seleccion = this.filters?.applied.selection;
|
||||
return seleccion?.mode === 'explicit' ? seleccion.periodos : undefined;
|
||||
}
|
||||
// CaCu's screening route chart, once the catalog publishes every measure it reads.
|
||||
get screeningRouteAvailable() {
|
||||
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
|
||||
@@ -413,9 +407,8 @@ export class IndicadoresPage {
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
|
||||
});
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary and CaMa's times, each a pending
|
||||
// slot while the catalog does not publish its indicator; CaCu's, only when its screening route chart isn't shown. The
|
||||
// rest are the clinical ones.
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary, and CaCu's five times, each a
|
||||
// pending slot while the catalog does not publish its indicator. The rest are the clinical ones.
|
||||
// The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for.
|
||||
readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => {
|
||||
const items = this.searchResults().items;
|
||||
@@ -430,12 +423,13 @@ export class IndicadoresPage {
|
||||
return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo };
|
||||
});
|
||||
}
|
||||
// With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to
|
||||
// each event. Without it, each time the catalog publishes with a figure keeps its own.
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => {
|
||||
const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0);
|
||||
return item ? [{ item, titulo: item.titulo }] : [];
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length) return [];
|
||||
// The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while
|
||||
// it is shown, so those slots are left to the chart instead of drawn twice or as pending.
|
||||
const delaRuta = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.filter(figura => !figura.id || !delaRuta.includes(figura.id)).map(figura => {
|
||||
const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined;
|
||||
return item ? { item, titulo: item.titulo } : { titulo: figura.titulo };
|
||||
});
|
||||
});
|
||||
readonly clinicosItems = computed(() => {
|
||||
@@ -446,7 +440,7 @@ export class IndicadoresPage {
|
||||
&& !CACU_FIGURAS_OPORTUNIDAD.some(figura => figura.id === item.id));
|
||||
return [...CACU_FIGURAS_CLINICAS.flatMap(id => clinicos.filter(item => item.id === id)), ...clinicos.filter(item => !CACU_FIGURAS_CLINICAS.includes(item.id))];
|
||||
}
|
||||
return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items;
|
||||
return this.dominio === 'tea' ? items.filter(item => TEA_FIGURAS_CLINICAS.includes(item.id)) : items;
|
||||
});
|
||||
// CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it.
|
||||
readonly confirmacionCama = CAMA_CONFIRMACION_KPI;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
@@ -13,7 +13,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
const items: Indicador[] = ['Edad', 'Evaluación inicial', 'Sexo', 'Seguimiento', 'Evaluación final'].map((titulo, i) => ({
|
||||
id: 'i' + i, titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'],
|
||||
id: ["M23_pacientes_evaluados","M24_confirmacion_diagnostico","M21_diagnosticados_con_eeg","M22_diagnosticados_sin_eeg","M28_casos_por_estado"][i], titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'],
|
||||
}));
|
||||
|
||||
describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
@@ -25,7 +25,7 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined);
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider,
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
create(); load();
|
||||
});
|
||||
@@ -41,78 +41,78 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
|
||||
it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
|
||||
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||
await pin('i3');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
|
||||
await pin('M22_diagnosticados_sin_eeg');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(true);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i3');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
|
||||
await pin('M22_diagnosticados_sin_eeg');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(false);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('varios fijados no alteran el orden del catálogo', async () => {
|
||||
const original = page.catalog(), snapshot = JSON.stringify(original);
|
||||
await pin('i4'); await pin('i2'); await pin('i0');
|
||||
await pin('M28_casos_por_estado'); await pin('M21_diagnosticados_con_eeg'); await pin('M23_pacientes_evaluados');
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('M21_diagnosticados_con_eeg'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
||||
});
|
||||
it('la selección de indicadores conserva el orden del catálogo', async () => {
|
||||
await pin('i3'); await pin('i4');
|
||||
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||
await pin('M22_diagnosticados_sin_eeg'); await pin('M28_casos_por_estado');
|
||||
page.changeIndicatorSelection(['M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado']);
|
||||
await pin('M24_confirmacion_diagnostico'); expect(ids()).toEqual(['M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado']);
|
||||
expect(cards()).toHaveLength(3); http.expectNone(() => true);
|
||||
});
|
||||
it('Mostrar todos restaura el catálogo en su orden', async () => {
|
||||
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i0']);
|
||||
await pin('M22_diagnosticados_sin_eeg'); page.changeIndicatorSelection(['M23_pacientes_evaluados']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['M23_pacientes_evaluados']);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
page.showAllIndicators(); fixture.detectChanges(); await settle();
|
||||
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
|
||||
});
|
||||
it('un fijado sin seleccionar no se muestra', async () => {
|
||||
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true);
|
||||
await pin('M21_diagnosticados_con_eeg'); page.changeIndicatorSelection(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico']); http.expectNone(() => true);
|
||||
});
|
||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('M22_diagnosticados_sin_eeg'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('M24_confirmacion_diagnostico'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
const memory = TestBed.inject(IndicadoresMemory);
|
||||
expect(memory.isPinned('cacu', 'i1')).toBe(true);
|
||||
expect(memory.isPinned('tea', 'i3')).toBe(true);
|
||||
expect(memory.isPinned('cama', 'i1')).toBe(false);
|
||||
expect(memory.isPinned('cacu', 'M24_confirmacion_diagnostico')).toBe(true);
|
||||
expect(memory.isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(true);
|
||||
expect(memory.isPinned('cama', 'M24_confirmacion_diagnostico')).toBe(false);
|
||||
page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
page.changeDominio('tea'); load(); expect(ids()).toEqual(items.map(i => i.id));
|
||||
fixture.destroy(); create(); load();
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M22_diagnosticados_sin_eeg')).toBe(true);
|
||||
expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
|
||||
});
|
||||
it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
|
||||
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
|
||||
await pin('i2'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i2')).toBe(true);
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
|
||||
await pin('M21_diagnosticados_con_eeg'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'M21_diagnosticados_con_eeg')).toBe(true);
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'M21_diagnosticados_con_eeg')).toBe(false);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
it('fijar no mueve la tarjeta ni pide figuras', async () => {
|
||||
const before = cards();
|
||||
await pin('i4');
|
||||
await pin('M28_casos_por_estado');
|
||||
expect(cards()).toEqual(before);
|
||||
await pin('i4');
|
||||
await pin('M28_casos_por_estado');
|
||||
expect(cards()).toEqual(before); http.expectNone(() => true);
|
||||
});
|
||||
it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => {
|
||||
card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle();
|
||||
card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle();
|
||||
card('M22_diagnosticados_sin_eeg').setVisible(true); fixture.detectChanges(); respond(); await settle();
|
||||
card('M22_diagnosticados_sin_eeg').selectFigure('g'); fixture.detectChanges(); respond(); await settle();
|
||||
|
||||
const before = cards(), panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance;
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied;
|
||||
const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length;
|
||||
for (const id of ['i3', 'i1', 'i3']) {
|
||||
for (const id of ['M22_diagnosticados_sin_eeg', 'M24_confirmacion_diagnostico', 'M22_diagnosticados_sin_eeg']) {
|
||||
await pin(id);
|
||||
for (const c of before) expect(card(c.indicador.id)).toBe(c);
|
||||
expect(card('i3').visible).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').visible).toBe(true);
|
||||
expect(card('i1').visible).toBe(false);
|
||||
expect(card('M22_diagnosticados_sin_eeg').visible).toBe(true); expect(card('M22_diagnosticados_sin_eeg').selectedFigure).toBe('g'); expect(card('M22_diagnosticados_sin_eeg').visible).toBe(true);
|
||||
expect(card('M24_confirmacion_diagnostico').visible).toBe(false);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart);
|
||||
expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied);
|
||||
@@ -121,9 +121,9 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges);
|
||||
});
|
||||
it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => {
|
||||
card('i4').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f'));
|
||||
card('M28_casos_por_estado').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/M28_casos_por_estado/figuras/f'));
|
||||
const panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance;
|
||||
await pin('i4'); expect(request.cancelled).toBe(false);
|
||||
await pin('M28_casos_por_estado'); expect(request.cancelled).toBe(false);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); http.expectNone(() => true);
|
||||
request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]);
|
||||
});
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'j', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'M23_pacientes_evaluados', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'M24_confirmacion_diagnostico', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]);
|
||||
fixture.detectChanges();
|
||||
for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).setVisible(true);
|
||||
fixture.detectChanges();
|
||||
@@ -42,8 +42,8 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, i, f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea, j, g');
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, M23_pacientes_evaluados, f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea, M24_confirmacion_diagnostico, g');
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(hosts[0]);
|
||||
@@ -59,7 +59,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
card.selectFigure('g'); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(outgoing); expect(runtime.purge).not.toHaveBeenCalledWith(other);
|
||||
http.expectOne(r => r.url.endsWith('/i/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
||||
http.expectOne(r => r.url.endsWith('/M23_pacientes_evaluados/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
||||
const current = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(current[0].componentInstance.host.nativeElement).not.toBe(outgoing);
|
||||
expect(current[1].componentInstance.host.nativeElement).toBe(other);
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
dominio === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
dominio === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
|
||||
@@ -33,14 +33,14 @@ describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
|
||||
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
|
||||
|
||||
it('con las siete medidas publicadas aparece la gráfica y ninguna de sus medidas tiene tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of every time it draws, the cytology's and the diagnosis' included (the
|
||||
// «Tiempo de tamizaje a diagnóstico» figures). Fails if the chart stops appearing, or a time it draws also shows as
|
||||
// a card.
|
||||
it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis'
|
||||
// keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).not.toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_IDS) expect(ids).not.toContain(id);
|
||||
for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu_tiempo_reporte');
|
||||
expect(ids).toContain('cacu_eu7');
|
||||
});
|
||||
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
|
||||
|
||||
@@ -11,11 +11,11 @@ import { Indicador } from './indicadores.models';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
const items: Indicador[] = [
|
||||
{ id: 'A01', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'B02', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M02_sexo', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'D04', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M23_pacientes_evaluados', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M24_confirmacion_diagnostico', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M21_diagnosticados_con_eeg', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
{ id: 'M28_casos_por_estado', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||
];
|
||||
|
||||
describe('Selección de indicadores gráficos', () => {
|
||||
@@ -42,7 +42,7 @@ describe('Selección de indicadores gráficos', () => {
|
||||
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
|
||||
|
||||
it.each([0, 1, 2, 5])('no ofrece buscador y muestra el catálogo completo: %i indicadores', count => {
|
||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
|
||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: items[i].id })));
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
expect(cards()).toHaveLength(count);
|
||||
http.expectNone(() => true);
|
||||
@@ -57,12 +57,12 @@ describe('Selección de indicadores gráficos', () => {
|
||||
});
|
||||
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
|
||||
load(); const before = cards(), original = page.catalog();
|
||||
choose(['B02', 'E05']);
|
||||
expect(ids()).toEqual(['B02', 'E05']);
|
||||
choose(['M24_confirmacion_diagnostico', 'M28_casos_por_estado']);
|
||||
expect(ids()).toEqual(['M24_confirmacion_diagnostico', 'M28_casos_por_estado']);
|
||||
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
|
||||
expect(page.selectionSummary()).toBe('2 indicadores');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
|
||||
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||
choose(['M21_diagnosticados_con_eeg']); expect(ids()).toEqual(['M21_diagnosticados_con_eeg']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||
expect(page.catalog()).toBe(original);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -75,25 +75,25 @@ describe('Selección de indicadores gráficos', () => {
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('marcar todos equivale a no filtrar', () => {
|
||||
load(); choose(['A01']); choose(items.map(i => i.id));
|
||||
load(); choose(['M23_pacientes_evaluados']); choose(items.map(i => i.id));
|
||||
expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores');
|
||||
});
|
||||
it('los indicadores destacados no dependen de la selección', () => {
|
||||
load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'));
|
||||
choose(['A01']);
|
||||
choose(['M23_pacientes_evaluados']);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
|
||||
});
|
||||
it('ir a un indicador oculto lo vuelve a mostrar y desplaza hasta su tarjeta', async () => {
|
||||
const scroll = vi.fn();
|
||||
Element.prototype.scrollIntoView = scroll;
|
||||
load(); choose(['A01']);
|
||||
load(); choose(['M23_pacientes_evaluados']);
|
||||
expect(document.querySelector('.indicator-select-panel')).toBeNull();
|
||||
page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||
page.goToIndicator('M22_diagnosticados_sin_eeg'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['M23_pacientes_evaluados', 'M22_diagnosticados_sin_eeg']);
|
||||
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); });
|
||||
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
|
||||
page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||
page.goToIndicator('M23_pacientes_evaluados'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['M23_pacientes_evaluados', 'M22_diagnosticados_sin_eeg']);
|
||||
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(2); });
|
||||
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
|
||||
});
|
||||
@@ -103,7 +103,7 @@ describe('Selección de indicadores gráficos', () => {
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('cambiar de dominio restablece la selección', () => {
|
||||
load(); choose(['A01']);
|
||||
load(); choose(['M23_pacientes_evaluados']);
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull();
|
||||
load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
});
|
||||
|
||||
@@ -39,7 +39,7 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
const esperadas = domain === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
const esperadas = domain === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
|
||||
@@ -36,8 +36,7 @@ describe('Seguimiento de CaMa: ficha del paciente', () => {
|
||||
// Fails if the export buttons leave the title row or come back under the table.
|
||||
it('has the export buttons in the row of the section title, and nothing after the pagination', () => {
|
||||
const row = root().querySelector('.title-row')!;
|
||||
// Fails if the section heading goes back to «Seguimiento de …» instead of the name of the section tab.
|
||||
expect(row.querySelector('h2')!.textContent).toBe('Análisis de riesgos');
|
||||
expect(row.querySelector('h2')!.textContent).toContain('Seguimiento de');
|
||||
expect([...row.querySelectorAll('button')].map(b => b.textContent!.trim())).toEqual(['Exportar Excel (.xlsx)', 'Exportar PDF']);
|
||||
expect(root().querySelector('nav')!.nextElementSibling).toBeNull();
|
||||
expect(root().textContent).not.toContain('Exportar resultados');
|
||||
|
||||
@@ -48,7 +48,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
}
|
||||
<div [hidden]="!!ficha()">
|
||||
<div class="title-row">
|
||||
<h2>Análisis de riesgos</h2>
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
@if (data(); as respuesta) {
|
||||
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
|
||||
}
|
||||
|
||||
@@ -73,12 +73,12 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
expect(root().querySelector('app-tea-resumen-periodo')).toBeNull();
|
||||
});
|
||||
|
||||
it('la primera pestaña se llama Resumen en TEA e Indicadores en CaCu y CaMa', () => {
|
||||
it('la primera pestaña se llama Indicadores en todos los dominios', () => {
|
||||
// Fails if TEA's first tab loses its name, if CaCu or CaMa take it, or if the section id changes.
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) {
|
||||
open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]);
|
||||
const first = root().querySelector('[role="tab"]') as HTMLElement;
|
||||
expect(first.textContent?.trim()).toBe(domain === 'tea' ? 'Resumen' : 'Indicadores');
|
||||
expect(first.textContent?.trim()).toBe('Indicadores');
|
||||
expect(first.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -55,18 +55,6 @@
|
||||
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Horizonte de la probabilidad <select name="horizonte" [(ngModel)]="draft.horizonte">
|
||||
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Ordenar por <select name="orden" [(ngModel)]="draft.orden">
|
||||
@for (o of ordenes(); track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@@ -127,18 +115,16 @@
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Última biopsia</th>@for (c of columnasProbabilidad(); track c) {<th scope="col">{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)</th>}<th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track identidad(item).id) {
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}<small>Fecha: {{ b.fecha }}</small> } @else { No disponible }</td>
|
||||
@for (c of columnasProbabilidad(); track c) { <td class="probabilidad">{{ probabilidad(item, c) ?? 'No disponible' }}</td> }
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
} @empty { <tr><td [attr.colspan]="9 + columnasProbabilidad().length">No hay registros para los filtros aplicados.</td></tr> }
|
||||
} @empty { <tr><td colspan="8">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -5,8 +5,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
@@ -68,28 +67,6 @@ export class IndicadoresTracking implements OnChanges {
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
/** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */
|
||||
horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; }
|
||||
horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; }
|
||||
readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD;
|
||||
/** The probability columns of a follow-up status (its scenario's models); none for every patient. */
|
||||
columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] {
|
||||
return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||
}
|
||||
/** The probability columns of the list shown: those of the status it was filtered by. */
|
||||
columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); }
|
||||
/** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */
|
||||
ordenes(): { codigo: string; etiqueta: string }[] {
|
||||
return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' },
|
||||
...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))];
|
||||
}
|
||||
/** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */
|
||||
probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null {
|
||||
const h = probabilidadAl(item, clave, this.horizonteMostrado());
|
||||
if (!h) return null;
|
||||
const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : '';
|
||||
return `${porcentaje(h.probabilidad)} %${ic}`;
|
||||
}
|
||||
private applied: SeguimientoQuery = { ...this.draft };
|
||||
readonly latestStudy = latestStudy;
|
||||
readonly gruposEdad = GRUPOS_EDAD_TEA;
|
||||
@@ -113,7 +90,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.statuses = data.estatus_disponibles;
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied };
|
||||
if (!this.metadataLoaded) {
|
||||
this.metadataLoaded = true;
|
||||
@@ -159,12 +136,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() {
|
||||
this.draft.page_size = acotarTamano(this.draft.page_size);
|
||||
// an order by a column the chosen status doesn't show goes back to the most recent study
|
||||
if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente';
|
||||
this.load({ ...this.draft, page: 1 });
|
||||
}
|
||||
apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); }
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
|
||||
@@ -18,7 +18,7 @@ import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
|
||||
id: ["M23_pacientes_evaluados","M24_confirmacion_diagnostico","M21_diagnosticados_con_eeg","M22_diagnosticados_sin_eeg","M28_casos_por_estado"][i], titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
|
||||
}));
|
||||
|
||||
// jsdom geometry and browser notifications are explicit, independent inputs.
|
||||
@@ -104,9 +104,9 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
expect(frames.size).toBe(0);
|
||||
}
|
||||
|
||||
it.each([{ domain: 'tea', count: 18 }, { domain: 'cacu', count: 8 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => {
|
||||
it.each([{ domain: 'tea', count: 5 }, { domain: 'cacu', count: 18 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => {
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
|
||||
await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'i' + i })), domain);
|
||||
await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: domain === 'tea' ? items[i].id : 'i' + i })), domain);
|
||||
await idle(); expect(cards()).toHaveLength(count); expect(panels()).toHaveLength(count);
|
||||
expect(panels().every(p => p.result().status === 'deferred')).toBe(true); http.expectNone(() => true);
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button')).toHaveLength(0);
|
||||
@@ -159,13 +159,13 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
|
||||
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
|
||||
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
|
||||
const request = http.expectOne(r => r.url.includes('/M23_pacientes_evaluados/figuras/'));
|
||||
expect(request.request.params.get('periodos')).toBe('2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
|
||||
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
|
||||
await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
|
||||
const old = http.expectOne(r => r.url.includes('/i0/figuras/'));
|
||||
const old = http.expectOne(r => r.url.includes('/M23_pacientes_evaluados/figuras/'));
|
||||
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll'));
|
||||
page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; page.applyFilters(); await render();
|
||||
expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('deferred'); http.expectNone(() => true);
|
||||
@@ -189,7 +189,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
// Pins no longer reorder; the selected indicators keep catalog order and their components.
|
||||
expect(cards()).toEqual([before[3], before[4]]);
|
||||
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
|
||||
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
|
||||
http.expectOne(r => r.url.includes('/M22_diagnosticados_sin_eeg/figuras/')).flush({ data: [], layout: {} }); await render();
|
||||
expect(cards()[0].selectedFigure).toBe('f');
|
||||
});
|
||||
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
|
||||
|
||||
+9
-4
@@ -4,11 +4,16 @@
|
||||
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
|
||||
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
|
||||
@if (r) {
|
||||
@if (escenarios().length === 0) { <p role="status">La paciente no cumple las condiciones de ningún escenario clínico de recurrencia.</p> }
|
||||
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Cohorte
|
||||
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
|
||||
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario() ? clave(escenario()!) : ''" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track clave(f)) { <option [value]="clave(f)" [selected]="f === escenario()">{{ f.escenario }} ({{ f.cohorte_nombre }})</option> }
|
||||
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
|
||||
@@ -17,7 +22,7 @@
|
||||
</section>
|
||||
<section aria-labelledby="factores-recurrencia-titulo">
|
||||
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
|
||||
@if (escenario()) {
|
||||
@if (r && r.escenarios.length) {
|
||||
<label class="selector horizons">Horizonte
|
||||
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
|
||||
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
|
||||
|
||||
+18
-16
@@ -4,14 +4,15 @@ import { switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
|
||||
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
|
||||
export const HORIZONTE_PREDETERMINADO = 60;
|
||||
|
||||
/**
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo» for one patient: the clinical scenarios her own age, tumor size, grade and
|
||||
* receptors place her in, from either external cohort (METABRIC or SCAN-B, named with each scenario and never mixed in one figure).
|
||||
* The scenario chosen decides the curve and the label at once; the label has a horizon (12, 36 or 60 months, 60 by default).
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
|
||||
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
|
||||
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-recurrencia',
|
||||
@@ -22,28 +23,29 @@ export const HORIZONTE_PREDETERMINADO = 60;
|
||||
export class CamaAnalisisRecurrencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaRecurrenciaService);
|
||||
readonly cohortes = COHORTES;
|
||||
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
|
||||
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
private readonly cohorteElegida = signal<string | null>(null);
|
||||
private readonly escenarioElegido = signal<string | null>(null);
|
||||
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
|
||||
/** The figures of her scenarios, in the order the server ranked them. */
|
||||
readonly escenarios = computed(() => {
|
||||
const r = this.respuesta();
|
||||
if (!r) return [];
|
||||
return r.deLaPaciente.map(s => r.escenarios.find(f => f.cohorte === s.cohorte && f.escenario === s.escenario))
|
||||
.filter((f): f is FiguraRecurrencia => !!f);
|
||||
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
|
||||
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
|
||||
/** The scenarios of the cohort chosen, from the list of that cohort only. */
|
||||
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
|
||||
readonly escenario = computed(() => {
|
||||
const lista = this.escenarios();
|
||||
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
|
||||
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
|
||||
});
|
||||
readonly escenario = computed(() => this.escenarios().find(f => clave(f) === this.elegido()) ?? this.escenarios()[0] ?? null);
|
||||
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
|
||||
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
|
||||
readonly factores = computed(() => {
|
||||
const f = this.escenario();
|
||||
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
|
||||
});
|
||||
readonly clave = clave;
|
||||
|
||||
elegirEscenario(valor: string): void { this.elegido.set(valor); }
|
||||
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
|
||||
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
|
||||
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
|
||||
}
|
||||
|
||||
function clave(f: FiguraRecurrencia): string { return `${f.cohorte}|${f.escenario}`; }
|
||||
|
||||
+6
-9
@@ -4,16 +4,13 @@
|
||||
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
|
||||
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
|
||||
@if (m) {
|
||||
@if (opciones().length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@else {
|
||||
@if (opciones().length === 1) { <p class="selector">Escenario clínico de la paciente: <strong>{{ escenario() }}</strong></p> }
|
||||
@else {
|
||||
<label class="selector">Escenarios clínicos de la paciente
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of opciones(); track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
}
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@let l = lectura();
|
||||
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
|
||||
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
|
||||
|
||||
+3
-5
@@ -9,9 +9,9 @@ import { figuraSupervivencia } from './cama-supervivencia-figura';
|
||||
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores };
|
||||
|
||||
/**
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo» of the clinical scenario the patient's own data place her in; when they place
|
||||
* her in several, a menu of those. The scenario decides the curve and the label at once, computed from the data ingested so far with the
|
||||
* model in production.
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label
|
||||
* at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on
|
||||
* the scenario the patient belongs to.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-supervivencia',
|
||||
@@ -25,8 +25,6 @@ export class CamaAnalisisSupervivencia {
|
||||
/** The menu; `undefined` while it loads, `null` when there is no model in production. */
|
||||
readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
/** Her scenarios; every scenario only if the server could not place her. */
|
||||
readonly opciones = computed(() => { const m = this.menu(); return m ? (m.deLaPaciente.length ? m.deLaPaciente : m.escenarios) : []; });
|
||||
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
|
||||
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
|
||||
map((datos): Lectura => ({ tipo: 'lista', datos })),
|
||||
|
||||
+16
-36
@@ -78,8 +78,7 @@ describe('Análisis de supervivencia', () => {
|
||||
beforeEach(() => {
|
||||
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }, { nombre: 'Estadio IV', n: 30 }],
|
||||
deLaPaciente: [{ nombre: 'Estadio I', n: 80 }, { nombre: '< 45 años', n: 100 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
@@ -90,12 +89,12 @@ describe('Análisis de supervivencia', () => {
|
||||
return f;
|
||||
};
|
||||
|
||||
// Fails if the menu does not open on the patient's scenario, or offers a scenario her data do not place her in.
|
||||
it('opens on the patient\'s scenario and offers only hers', () => {
|
||||
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
|
||||
it('opens on the patient\'s scenario with the menu the API gave', () => {
|
||||
const f = montar();
|
||||
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
|
||||
|
||||
expect(opciones).toEqual(['Estadio I', '< 45 años']);
|
||||
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
|
||||
});
|
||||
@@ -105,7 +104,7 @@ describe('Análisis de supervivencia', () => {
|
||||
const f = montar();
|
||||
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
|
||||
|
||||
elegir(f, 'Escenarios clínicos de la paciente', '< 45 años');
|
||||
elegir(f, 'Escenario clínico', '< 45 años');
|
||||
|
||||
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
|
||||
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
|
||||
@@ -113,25 +112,6 @@ describe('Análisis de supervivencia', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de supervivencia de una paciente con un solo escenario', () => {
|
||||
// Fails if a patient whose data place her in one scenario is asked to choose: the scenario is named and drawn, with no menu.
|
||||
it('names her one scenario and draws it without a menu', () => {
|
||||
const consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: null }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }],
|
||||
deLaPaciente: [{ nombre: 'Toda la cohorte', n: 500 }], predeterminado: 'Toda la cohorte' }), consulta } }] });
|
||||
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
||||
f.componentRef.setInput('pacId', '9');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
|
||||
expect((f.nativeElement as HTMLElement).querySelector('select')).toBeNull();
|
||||
expect(texto(f)).toContain('Escenario clínico de la paciente: Toda la cohorte');
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Toda la cohorte');
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de recurrencia', () => {
|
||||
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
|
||||
it('scales the y axis to the months it draws', () => {
|
||||
@@ -150,8 +130,7 @@ describe('Análisis de recurrencia', () => {
|
||||
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
|
||||
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
|
||||
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' },
|
||||
de_la_paciente: [{ cohorte: 'scanb', escenario: 'Grado 3' }, { cohorte: 'metabric', escenario: '< 45 años' }] });
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
@@ -164,23 +143,24 @@ describe('Análisis de recurrencia', () => {
|
||||
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
|
||||
.querySelectorAll('option');
|
||||
|
||||
// Fails if the menu offers a cohort selector or scenarios the patient's covariates do not place her in, or does not open on the first.
|
||||
it('offers only the patient\'s scenarios, each with its cohort, and opens on the first', () => {
|
||||
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
|
||||
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
|
||||
const f = montar();
|
||||
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].some(l => l.textContent!.includes('Cohorte'))).toBe(false);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['Grado 3 (SCAN-B)', '< 45 años (METABRIC)']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her first scenario, the label at 60 months
|
||||
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
|
||||
});
|
||||
|
||||
// Fails if choosing another of her scenarios leaves the previous curve or label on screen: the cohorts are never mixed.
|
||||
it('changes the curve and the label together when she has another scenario chosen, and keeps one curve', () => {
|
||||
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
|
||||
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
|
||||
const f = montar();
|
||||
|
||||
elegir(f, 'Escenario clínico', 'metabric|< 45 años');
|
||||
elegir(f, 'Cohorte', 'metabric');
|
||||
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
|
||||
expect(texto(f)).toContain('Marca=metabric-60');
|
||||
expect(texto(f)).not.toContain('Marca=scanb');
|
||||
expect(texto(f)).not.toContain('scanb');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export interface CurvasSupervivencia {
|
||||
n: number; events: number; median_follow_up_months: number;
|
||||
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
km_adjusted?: { months: number[]; S: number[] };
|
||||
km_adjusted: { months: number[]; S: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
|
||||
@@ -50,7 +50,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
|
||||
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|
||||
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
|
||||
if (adjusted !== undefined && (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length))) invalid();
|
||||
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
|
||||
for (const curve of [weibull, fractional]) {
|
||||
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
|
||||
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
|
||||
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
|
||||
km: km as CurvasSupervivencia['km'], ...(adjusted !== undefined ? { km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'] } : {}),
|
||||
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
|
||||
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
|
||||
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
|
||||
},
|
||||
@@ -87,7 +87,7 @@ export function filaFactores(v: unknown): FilaFactores {
|
||||
}
|
||||
|
||||
/** The scenarios the menu offers, and the one the patient belongs to first. */
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; deLaPaciente: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
/** A scenario's figure with its risk factors (`null`: it has no summary row). */
|
||||
export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; }
|
||||
/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */
|
||||
@@ -97,13 +97,13 @@ export class SeleccionRechazada extends Error {}
|
||||
export class CamaCurvasService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios the menu offers, the patient's own and her default, or `null` when there is no model in production or no cohort yet. */
|
||||
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
|
||||
escenarios(pacId: string): Observable<MenuEscenarios | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
|
||||
map(r => {
|
||||
if (!record(r) || !Array.isArray(r['escenarios'])) invalid();
|
||||
const leer = (v: unknown) => (Array.isArray(v) ? v : []).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: leer(r['escenarios']), deLaPaciente: leer(r['de_la_paciente']), predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
}),
|
||||
catchError(() => of(null)),
|
||||
);
|
||||
|
||||
@@ -20,8 +20,6 @@ export interface RespuestaRecurrencia {
|
||||
resumen: FilaFactores[];
|
||||
/** The cohort and scenario the patient's own covariates place her in first, if any. */
|
||||
predeterminado: { cohorte: string; escenario: string } | null;
|
||||
/** Every scenario her covariates place her in, the larger first within each cohort; empty when none or no patient was asked. */
|
||||
deLaPaciente: { cohorte: string; escenario: string }[];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
@@ -50,12 +48,9 @@ export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
|
||||
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
|
||||
if (!Array.isArray(v['resumen'])) invalid();
|
||||
const d = v['predeterminado'];
|
||||
const suyos = Array.isArray(v['de_la_paciente']) ? (v['de_la_paciente'] as unknown[]) : [];
|
||||
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
|
||||
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null,
|
||||
deLaPaciente: suyos.filter((e): e is Record<string, string> => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')
|
||||
.map(e => ({ cohorte: e['cohorte'], escenario: e['escenario'] })) };
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
</mat-card>
|
||||
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
|
||||
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" [estatus]="estatusCodigo" /></mat-card-content>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ export interface PacienteResumen {
|
||||
identidad: IdentidadPaciente;
|
||||
grupoEdad: string | null;
|
||||
estatus: string | null;
|
||||
/** The follow-up status code (`CASO`, `PRE_COLPOSCOPIA`…): it decides which probabilities the record shows. */
|
||||
estatusCodigo: string | null;
|
||||
corte: string;
|
||||
origen: 'seguimiento-demostracion';
|
||||
citologia: { fecha: string; resultado: string | null; calidad: string | null } | null;
|
||||
|
||||
@@ -45,7 +45,6 @@ export class PacienteDetalleState {
|
||||
identidad,
|
||||
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
|
||||
estatus: paciente.estatus.etiqueta,
|
||||
estatusCodigo: paciente.estatus.codigo,
|
||||
corte,
|
||||
origen: 'seguimiento-demostracion',
|
||||
citologia: paciente.ultima_citologia ? {
|
||||
|
||||
@@ -34,7 +34,6 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
|
||||
|
||||
get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; }
|
||||
/** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */
|
||||
get estatusCodigo() { return this.estado.tipo !== 'cerrado' ? this.estado.resumen.estatusCodigo : null; }
|
||||
get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; }
|
||||
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ describe('Riesgo individual de la paciente CaMa', () => {
|
||||
expect(text).toContain('17.8 %');
|
||||
expect(text).toContain('25.1 %');
|
||||
expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/);
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('table.risk tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
|
||||
});
|
||||
|
||||
// Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace.
|
||||
|
||||
@@ -5,14 +5,14 @@ import { of } from 'rxjs';
|
||||
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { conIntervalo, covariables, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
|
||||
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
// What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons.
|
||||
describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
function setup(data: unknown, estatus: string | null = null) {
|
||||
function setup(data: unknown) {
|
||||
const react = vi.fn(() => Promise.resolve());
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } },
|
||||
@@ -20,7 +20,6 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
addFrames: vi.fn(), deleteFrames: vi.fn() }) }] });
|
||||
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
fixture.componentRef.setInput('pacId', '42');
|
||||
fixture.componentRef.setInput('estatus', estatus);
|
||||
fixture.detectChanges();
|
||||
fixture.detectChanges();
|
||||
return { fixture, root: fixture.nativeElement as HTMLElement };
|
||||
@@ -28,8 +27,8 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
|
||||
it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => {
|
||||
expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({
|
||||
quantity: 'Probabilidad', description: 'Probabilidad de CIN2+ antes de cada horizonte.',
|
||||
outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', covariates: 'VPH y citología índice' });
|
||||
quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.',
|
||||
outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' });
|
||||
expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista());
|
||||
});
|
||||
|
||||
@@ -41,7 +40,7 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
|
||||
it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => {
|
||||
const { root } = setup(riesgoCacuConEstimando());
|
||||
expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim()))
|
||||
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo');
|
||||
for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) {
|
||||
@@ -53,7 +52,7 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
it('dibuja la curva solo al abrir su sección', async () => {
|
||||
const { fixture, root } = setup(riesgoCacuConEstimando());
|
||||
const details = root.querySelector('details.risk-curve') as HTMLDetailsElement;
|
||||
expect(details.querySelector('summary')!.textContent).toContain('Curva de probabilidad');
|
||||
expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado');
|
||||
expect(root.querySelector('app-plotly-chart')).toBeNull();
|
||||
details.open = true;
|
||||
details.dispatchEvent(new Event('toggle'));
|
||||
@@ -67,7 +66,7 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
expect(banda.data).toHaveLength(3);
|
||||
expect(banda.data[2]['y']).toEqual([8, 21, 34]);
|
||||
expect(banda.data[1]['y']).toEqual([5, 15, 26]);
|
||||
expect((banda.layout['yaxis'] as any).title.text).toBe('Probabilidad (%)');
|
||||
expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)');
|
||||
|
||||
const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) };
|
||||
const barras = figuraRiesgoPaciente([parcial]);
|
||||
@@ -77,9 +76,9 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
|
||||
it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => {
|
||||
const { root } = setup(riesgoCacuDosDesenlaces());
|
||||
expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim()))
|
||||
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
const fila = [...root.querySelectorAll('table.risk tbody tr')][2];
|
||||
const fila = [...root.querySelectorAll('tbody tr')][2];
|
||||
expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim()))
|
||||
.toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']);
|
||||
});
|
||||
@@ -87,8 +86,8 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']);
|
||||
expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen una probabilidad '
|
||||
+ 'a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), '
|
||||
expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo '
|
||||
+ 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), '
|
||||
+ 'respectivamente.');
|
||||
expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull();
|
||||
});
|
||||
@@ -114,19 +113,19 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' };
|
||||
expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01');
|
||||
expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) '
|
||||
+ 'tienen una probabilidad a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).');
|
||||
+ 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).');
|
||||
});
|
||||
|
||||
it('sin modelo de un desenlace su columna dice No disponible', () => {
|
||||
const { root } = setup(riesgoCacuConEstimando());
|
||||
const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']);
|
||||
});
|
||||
|
||||
it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => {
|
||||
const data = riesgoCacuCancerSinEstimar();
|
||||
const { root } = setup(data);
|
||||
const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']);
|
||||
expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población');
|
||||
const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!;
|
||||
@@ -135,61 +134,4 @@ describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers'))
|
||||
.toHaveLength(1);
|
||||
});
|
||||
|
||||
it('una supervivencia se muestra como 1 − la probabilidad de morir, con el IC invertido, y es 1 a los 0 años', () => {
|
||||
const data = riesgoCacuConEstimando();
|
||||
const r = data.entry[0].resource;
|
||||
r.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' });
|
||||
r.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; });
|
||||
const lote = riesgoPacienteResponse(data, '42')!.riesgo;
|
||||
// at the index date every patient is alive
|
||||
expect(lote.horizontes[0]).toEqual({ horizonte_anios: 0, probabilidad: 1, ic_bajo: 1, ic_alto: 1 });
|
||||
expect(lote.horizontes[1]).toMatchObject({ horizonte_anios: 1 });
|
||||
expect(lote.horizontes[1].probabilidad).toBeCloseTo(0.92);
|
||||
expect(lote.horizontes[1].ic_bajo).toBeCloseTo(0.88);
|
||||
expect(lote.horizontes[1].ic_alto).toBeCloseTo(0.95);
|
||||
expect(encabezado(lote)).toBe('Probabilidad de supervivencia');
|
||||
});
|
||||
|
||||
it('pone las covariables al pie de la tabla y el detalle en una fila por modelo, sin versión ni estado', () => {
|
||||
const { root } = setup(riesgoCacuDosDesenlaces());
|
||||
expect(root.querySelector('.covariates-note')!.textContent).toBe('Covariables: VPH y citología índice.');
|
||||
expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(2);
|
||||
expect(root.textContent).not.toMatch(/Versión del modelo|Estado del lote/);
|
||||
expect(root.querySelector('caption')!.textContent).toContain('Probabilidad en porcentaje (0 a 100 %)');
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
riesgos[1].estimando = { ...riesgos[1].estimando, covariates: 'otras' };
|
||||
expect(covariables(riesgos)).toBe('Covariables: Probabilidad a LIEAG+: VPH y citología índice; Probabilidad a cáncer: otras.');
|
||||
});
|
||||
|
||||
/** The Bundle of a patient scored by the CIN2+, cancer and survival models (survival first). */
|
||||
function conSupervivencia() {
|
||||
const data = riesgoCacuDosDesenlaces();
|
||||
const muerte = structuredClone(data.entry[1].resource);
|
||||
muerte.id = '14-42';
|
||||
muerte.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' });
|
||||
muerte.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; });
|
||||
data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/14-42', resource: muerte });
|
||||
data.total = 3;
|
||||
return data;
|
||||
}
|
||||
const encabezados = (root: HTMLElement) => [...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim());
|
||||
|
||||
it('a un caso solo le muestra su supervivencia, sin LIEAG+ ni cáncer, también en el detalle', () => {
|
||||
// Fails if the record stops following the follow-up status, or shows a case the risk of a disease she already has.
|
||||
const { root } = setup(conSupervivencia(), 'CASO');
|
||||
expect(encabezados(root)).toEqual(['Horizonte (años)', 'Probabilidad de supervivencia (%)']);
|
||||
expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('antes de la colposcopia muestra LIEAG+ y cáncer; después, solo LIEAG+; sin estatus, todo', () => {
|
||||
// Fails if a status shows another set of columns than the follow-up table's, or no status hides a column.
|
||||
expect(encabezados(setup(conSupervivencia(), 'PRE_COLPOSCOPIA').root))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
TestBed.resetTestingModule();
|
||||
expect(encabezados(setup(conSupervivencia(), 'POST_COLPOSCOPIA').root)).toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)']);
|
||||
TestBed.resetTestingModule();
|
||||
expect(encabezados(setup(conSupervivencia()).root)).toEqual(
|
||||
['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)', 'Probabilidad de supervivencia (%)']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,15 +8,15 @@
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
@let todos = lectura.datos.riesgos;
|
||||
@let riesgos = conRiesgo(delEstatus(todos));
|
||||
@let riesgo = riesgos[0] ?? lectura.datos.riesgo;
|
||||
@let riesgos = conRiesgo(todos);
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
@let columnas = columnasDe(todos);
|
||||
@let filas = filasDe(lotesDe(columnas));
|
||||
@if (filas.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Riesgos por horizonte, tabla desplazable" tabindex="0">
|
||||
<table class="risk">
|
||||
<caption>Probabilidad en porcentaje (0 a 100 %) por horizonte desde la fecha índice
|
||||
({{ riesgo.fecha_indice }}), con su intervalo de confianza de 95 % entre paréntesis</caption>
|
||||
<table>
|
||||
<caption>{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice
|
||||
({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis</caption>
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }})</th>
|
||||
@for (c of columnas; track c.encabezado) { <th scope="col">{{ c.encabezado }} (%)</th> }
|
||||
@@ -36,31 +36,25 @@
|
||||
@for (c of columnas; track c.encabezado) {
|
||||
@if (c.lote?.sin_estimacion; as motivo) { <p class="unavailable-note">{{ c.encabezado }}: {{ motivo }}.</p> }
|
||||
}
|
||||
@if (covariables(riesgos); as texto) { <p class="covariates-note">{{ texto }}</p> }
|
||||
<details class="risk-details">
|
||||
<summary>Detalle del modelo</summary>
|
||||
<div class="risk-scroll" role="region" aria-label="Modelos de la ficha, tabla desplazable" tabindex="0">
|
||||
<table class="models">
|
||||
<thead><tr>
|
||||
<th scope="col">Probabilidad</th><th scope="col">Modelo</th><th scope="col">Qué se estima</th>
|
||||
<th scope="col">Desenlace</th><th scope="col">Desde</th><th scope="col">Fecha índice</th>
|
||||
<th scope="col">Evaluado en</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (r of riesgos; track r.id) {
|
||||
<tr>
|
||||
<th scope="row">{{ encabezado(r) }}</th>
|
||||
<td>{{ r.modelo_nombre }}</td>
|
||||
<td>{{ r.estimando?.description ?? '—' }}</td>
|
||||
<td>{{ r.estimando?.outcome ?? r.desenlace_texto ?? r.desenlace }}</td>
|
||||
<td>{{ r.estimando?.index_date ?? '—' }}</td>
|
||||
<td>{{ r.fecha_indice }}</td>
|
||||
<td><time [attr.datetime]="r.evaluado_en">{{ instante(r.evaluado_en) }}</time></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@for (r of riesgos; track r.id) {
|
||||
@if (riesgos.length > 1) { <h6>{{ encabezado(r) }}</h6> }
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ r.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ r.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ r.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ r.desenlace_texto ?? r.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en</dt><dd><time [attr.datetime]="r.evaluado_en">{{ instante(r.evaluado_en) }}</time></dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ r.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
@if (r.estimando; as e) {
|
||||
@if (e.quantity) { <div><dt>Qué se estima</dt><dd>{{ e.quantity }}@if (e.description) {: {{ e.description }}}</dd></div> }
|
||||
@if (e.outcome) { <div><dt>Desenlace del modelo</dt><dd>{{ e.outcome }}</dd></div> }
|
||||
@if (e.index_date) { <div><dt>Desde</dt><dd>{{ e.index_date }}</dd></div> }
|
||||
@if (e.horizons_unit) { <div><dt>Horizontes en</dt><dd>{{ e.horizons_unit }}</dd></div> }
|
||||
}
|
||||
</dl>
|
||||
}
|
||||
</details>
|
||||
@if (filas.length > 1) {
|
||||
<details class="risk-curve" (toggle)="curvaAbierta.set($any($event.target).open)">
|
||||
@@ -68,7 +62,7 @@
|
||||
@if (frase(riesgos); as texto) { <p class="risk-sentence">{{ texto }}</p> }
|
||||
@if (curvaAbierta()) {
|
||||
<app-plotly-chart [style.--plot-height]="'300px'" [showNotes]="false" [figure]="figura(riesgos)"
|
||||
[label]="'Curvas de probabilidad individual ' + rotulo() + ' por horizonte'" />
|
||||
[label]="'Curvas de riesgo individual ' + rotulo() + ' por horizonte'" />
|
||||
}
|
||||
</details>
|
||||
}
|
||||
|
||||
@@ -24,5 +24,3 @@ tbody tr:last-child > * { border-bottom: 0; }
|
||||
.risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; }
|
||||
.unavailable { color: var(--issste-text-secondary); }
|
||||
.unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; }
|
||||
.covariates-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; }
|
||||
table.models { min-width: 48rem; }
|
||||
|
||||
@@ -3,7 +3,7 @@ import { LowerCasePipe } from '@angular/common';
|
||||
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../indicadores.models';
|
||||
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
|
||||
import { ColumnaRiesgo, columnasRiesgo, conRiesgo, delEstatus, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { ColumnaRiesgo, columnasRiesgo, conRiesgo, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
@@ -26,8 +26,6 @@ export class PacienteRiesgoTabla {
|
||||
readonly pacId = input.required<string | null>();
|
||||
/** The domain whose model scored her: CaCu unless said otherwise. */
|
||||
readonly dominio = input<DominioRiesgo>('cacu');
|
||||
/** Her follow-up status code: the table shows only the probabilities that status follows (a case, her survival). */
|
||||
readonly estatus = input<string | null>(null);
|
||||
readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu');
|
||||
private readonly state = inject(PacienteRiesgoState);
|
||||
readonly estado = this.state.estado;
|
||||
@@ -41,9 +39,7 @@ export class PacienteRiesgoTabla {
|
||||
readonly frase = fraseRiesgo;
|
||||
readonly filasDe = filasRiesgo;
|
||||
readonly conRiesgo = conRiesgo;
|
||||
readonly covariables = covariables;
|
||||
columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio(), this.estatus()); }
|
||||
delEstatus(riesgos: LoteRiesgoCacu[]): LoteRiesgoCacu[] { return delEstatus(riesgos, this.estatus()); }
|
||||
columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); }
|
||||
lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); }
|
||||
private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure };
|
||||
figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
|
||||
|
||||
@@ -16,17 +16,13 @@ export interface HorizonteRiesgoCacu {
|
||||
|
||||
/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */
|
||||
export interface EstimandoRiesgo {
|
||||
/** e.g. "Probabilidad"; also `method.text`. */
|
||||
/** e.g. "Riesgo acumulado"; also `method.text`. */
|
||||
quantity?: string;
|
||||
description?: string;
|
||||
outcome?: string;
|
||||
index_date?: string;
|
||||
/** The unit the horizons are counted in, e.g. "años". */
|
||||
horizons_unit?: string;
|
||||
/** The variables the model uses, in words, as the record writes them under the table. */
|
||||
covariates?: string;
|
||||
/** `supervivencia`: the model gives the probability of the outcome (dying) and the record shows its complement. */
|
||||
complement?: string;
|
||||
}
|
||||
|
||||
/** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ProbabilidadClave } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
@@ -6,7 +5,7 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
export function etiquetaDesenlace(lote: LoteRiesgoCacu): string {
|
||||
if (lote.desenlace.startsWith('cin2')) return 'LIEAG+';
|
||||
if (lote.desenlace === 'cancer') return 'cáncer';
|
||||
if (lote.desenlace === 'muerte') return lote.estimando?.complement === 'supervivencia' ? 'supervivencia' : 'muerte';
|
||||
if (lote.desenlace === 'muerte') return 'muerte';
|
||||
return lote.desenlace_texto ?? lote.desenlace;
|
||||
}
|
||||
|
||||
@@ -14,8 +13,7 @@ export function etiquetaDesenlace(lote: LoteRiesgoCacu): string {
|
||||
* `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */
|
||||
export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string {
|
||||
const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : '';
|
||||
const etiqueta = etiquetaDesenlace(lote);
|
||||
return `${etiqueta === 'supervivencia' ? 'Probabilidad de supervivencia' : `Probabilidad a ${etiqueta}`}${desde}`;
|
||||
return `Probabilidad a ${etiquetaDesenlace(lote)}${desde}`;
|
||||
}
|
||||
|
||||
/** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8",
|
||||
@@ -40,20 +38,6 @@ const COLUMNAS_FIJAS: Record<string, { desenlace: string; etiqueta: string }[]>
|
||||
const esDe = (lote: LoteRiesgoCacu, desenlace: string) =>
|
||||
desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace;
|
||||
|
||||
/** The outcomes the record shows for each follow-up status, the same as the follow-up table's columns: a case
|
||||
* already has the disease, so only her survival; a patient before colposcopy, LIEAG+ and cancer; after it, LIEAG+. */
|
||||
const DESENLACE_DE_LA_COLUMNA: Record<ProbabilidadClave, string> = { lieag: 'cin2', cancer: 'cancer', supervivencia: 'muerte' };
|
||||
export function desenlacesDelEstatus(estatus: string | null | undefined): string[] | null {
|
||||
const columnas = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] : undefined;
|
||||
return columnas ? columnas.map(c => DESENLACE_DE_LA_COLUMNA[c]) : null;
|
||||
}
|
||||
|
||||
/** The risks of the outcomes her follow-up status shows; all of them when the status names none. */
|
||||
export function delEstatus(riesgos: LoteRiesgoCacu[], estatus: string | null | undefined): LoteRiesgoCacu[] {
|
||||
const desenlaces = desenlacesDelEstatus(estatus);
|
||||
return desenlaces ? riesgos.filter(r => desenlaces.some(d => esDe(r, d))) : riesgos;
|
||||
}
|
||||
|
||||
export interface ColumnaRiesgo {
|
||||
encabezado: string;
|
||||
/** Its model's risks; `null` when no model of the outcome is current. */
|
||||
@@ -64,11 +48,9 @@ export interface ColumnaRiesgo {
|
||||
|
||||
/** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any
|
||||
* other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */
|
||||
export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu', estatus: string | null = null): ColumnaRiesgo[] {
|
||||
riesgos = delEstatus(riesgos, estatus);
|
||||
export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu'): ColumnaRiesgo[] {
|
||||
const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null;
|
||||
const desenlaces = desenlacesDelEstatus(estatus);
|
||||
const fijas = (COLUMNAS_FIJAS[dominio] ?? []).filter(f => !desenlaces || desenlaces.includes(f.desenlace));
|
||||
const fijas = COLUMNAS_FIJAS[dominio] ?? [];
|
||||
const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => {
|
||||
const lote = riesgos.find(r => esDe(r, desenlace)) ?? null;
|
||||
if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' };
|
||||
@@ -128,15 +110,6 @@ export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null {
|
||||
const desenlaces = junta(riesgos.map(etiquetaDesenlace));
|
||||
const valores = junta(ultima.celdas.map(c => conIntervalo(c!)));
|
||||
const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`;
|
||||
return `${inicio} (${fecha}) tienen una probabilidad a ${anios} de estar presente o de aparecer ${desenlaces} `
|
||||
return `${inicio} (${fecha}) tienen un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} `
|
||||
+ `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`;
|
||||
}
|
||||
|
||||
/** The covariates under the table: each model's, by its column, or once when every model uses the same ones. */
|
||||
export function covariables(riesgos: LoteRiesgoCacu[]): string | null {
|
||||
const con = riesgos.filter(r => r.estimando?.covariates);
|
||||
if (!con.length) return null;
|
||||
const textos = [...new Set(con.map(r => r.estimando!.covariates!))];
|
||||
if (textos.length === 1) return `Covariables: ${textos[0]}.`;
|
||||
return `Covariables: ${con.map(r => `${encabezado(r)}: ${r.estimando!.covariates}`).join('; ')}.`;
|
||||
}
|
||||
|
||||
@@ -45,14 +45,13 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
// horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval
|
||||
expect(root.querySelectorAll('table.risk thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('table.risk thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('table.risk tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)');
|
||||
// the record names the model, its index date and outcome, not its version nor the batch's state
|
||||
expect(root.textContent).not.toMatch(/Final \(final\)|2\.1\.0/);
|
||||
for (const value of ['modelo-cacu', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
@@ -74,7 +73,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(getComputedStyle(scroll).overflow).toBe('auto');
|
||||
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
|
||||
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
|
||||
expect(getComputedStyle(root.querySelector('table.risk thead th')!).position).toBe('sticky');
|
||||
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
|
||||
});
|
||||
|
||||
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
|
||||
@@ -86,10 +85,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
prediccion(0.00123, '2026-06-01', '2038-09-01'),
|
||||
];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('table.risk tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']);
|
||||
expect(root.textContent).not.toContain('Preliminar (preliminary)');
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
|
||||
@@ -57,10 +57,9 @@ export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
export function riesgoCacuConEstimando(): any {
|
||||
const data = riesgoCacuEjemplo();
|
||||
const resource = data.entry[0].resource;
|
||||
resource.method.text = 'Probabilidad';
|
||||
resource.method.text = 'Riesgo acumulado';
|
||||
resource.extension = [{ url: ESTIMANDO, extension: [
|
||||
{ url: 'quantity', valueString: 'Probabilidad' },
|
||||
{ url: 'covariates', valueString: 'VPH y citología índice' },
|
||||
{ url: 'quantity', valueString: 'Riesgo acumulado' },
|
||||
{ url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' },
|
||||
{ url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' },
|
||||
{ url: 'horizons_unit', valueString: 'años' },
|
||||
|
||||
@@ -13,7 +13,7 @@ const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
|
||||
const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
|
||||
const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
|
||||
const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph'];
|
||||
const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'covariates', 'complement'];
|
||||
const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit'];
|
||||
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
return typeof v === 'string'
|
||||
@@ -138,22 +138,6 @@ function simulated(resource: Record<string, unknown>): boolean {
|
||||
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
|
||||
}
|
||||
|
||||
/** A model whose estimand asks for its complement (survival from a probability of dying): each horizon becomes
|
||||
* 1 − p, and its interval 1 − high to 1 − low; survival at 0 years is 1. */
|
||||
function complemento(lote: LoteRiesgoCacu): void {
|
||||
if (lote.estimando?.complement !== 'supervivencia') return;
|
||||
const horizontes = lote.horizontes.map(h => ({
|
||||
...h, probabilidad: 1 - h.probabilidad,
|
||||
ic_bajo: h.ic_alto == null ? h.ic_alto ?? null : 1 - h.ic_alto,
|
||||
ic_alto: h.ic_bajo == null ? h.ic_bajo ?? null : 1 - h.ic_bajo,
|
||||
}));
|
||||
// At its index date every patient is alive: survival at 0 years is 1, whether or not the model gives it.
|
||||
if (horizontes.length && !horizontes.some(h => h.horizonte_anios === 0)) {
|
||||
horizontes.unshift({ horizonte_anios: 0, probabilidad: 1, ic_bajo: 1, ic_alto: 1 });
|
||||
}
|
||||
lote.horizontes = horizontes;
|
||||
}
|
||||
|
||||
/** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */
|
||||
export function ordenDesenlace(desenlace: string): number {
|
||||
return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2;
|
||||
@@ -173,7 +157,6 @@ export function riesgoPacienteResponse(v: unknown, pacId: string | null = null):
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return riskAssessment(structuredClone(resource), pacId);
|
||||
});
|
||||
riesgos.forEach(complemento);
|
||||
riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace));
|
||||
return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos };
|
||||
}
|
||||
|
||||
@@ -49,17 +49,6 @@ describe('Ruta del tamizaje: modelo', () => {
|
||||
expect(routeModel(data, 'semestre').period).toBe('2025-S2');
|
||||
expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1');
|
||||
});
|
||||
it('con los periodos del filtro de la página se usa el más reciente de ellos con cajas publicadas', () => {
|
||||
// Fails if the chart, which has no period filter of its own, ignores the page's periods or opens on an empty one of
|
||||
// them while an earlier one it was given has data.
|
||||
const vacio = (id: string) => payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id]),
|
||||
row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S1', '2025-S2', '2026-S1']);
|
||||
const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)]));
|
||||
expect(routeModel(data, 'semestre', ['2025-S1', '2026-S1', '2025-S2']).period).toBe('2025-S2');
|
||||
expect(routeModel(data, 'semestre', ['2025-S1']).period).toBe('2025-S1');
|
||||
expect(routeModel(data, 'semestre', ['2026-S1']).period).toBe('2026-S1');
|
||||
expect(routeModel(data, 'semestre', ['2023-S1']).period).toBe('2025-S2');
|
||||
});
|
||||
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
|
||||
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
|
||||
// becomes a bar or leaves a gap in the chain.
|
||||
|
||||
@@ -47,8 +47,7 @@ const fail = (message: string): never => { throw new RouteIncompatible(message);
|
||||
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
|
||||
|
||||
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo,
|
||||
requested?: string | readonly string[]): RouteModel {
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
|
||||
const boxes: Record<string, Record<string, Caja>> = {};
|
||||
for (const id of ROUTE_IDS) {
|
||||
const d = data[id];
|
||||
@@ -67,12 +66,9 @@ export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPerio
|
||||
}
|
||||
}
|
||||
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
|
||||
// The newest of the requested periods (the page's filter) that has a published box, else the newest requested one;
|
||||
// without a valid request, the newest period that has a published box: a semester that has just begun is empty.
|
||||
// Without a valid request the newest period that has a published box: a semester that has just begun is empty.
|
||||
const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado');
|
||||
const pedidos = (typeof requested === 'string' ? [requested] : [...(requested ?? [])])
|
||||
.filter(p => periods.includes(p)).sort().reverse();
|
||||
const period = pedidos.length ? pedidos.find(hasData) ?? pedidos[0] : periods.find(hasData) ?? periods[0];
|
||||
const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0];
|
||||
let cursor = 0;
|
||||
const rows = ROUTE_STEPS.map((step): RouteRow => {
|
||||
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
|
||||
@@ -34,13 +34,15 @@ describe('Resumen TEA por periodo', () => {
|
||||
// or if a median is cut (22.5 stays 22.5).
|
||||
const root: HTMLElement = render(completos()).nativeElement;
|
||||
const text = texto(root);
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños de la cohorte de tamizaje; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('La cohorte incluye a niños de 16 a 36 meses al primer M-CHAT y a niños sin edad registrada.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes en tamizaje con diagnóstico confirmado o en proceso tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico positivo fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad.');
|
||||
expect(text).toContain('De los 80 estudios de EEG realizados a niños de la cohorte en el periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('*tomando la mediana de los tiempos');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']);
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '80', '25.0%']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
expect(root.querySelector('h2')!.textContent).toBe('Resumen');
|
||||
});
|
||||
@@ -56,8 +58,10 @@ describe('Resumen TEA por periodo', () => {
|
||||
const periodo = '2026-03';
|
||||
for (const p of paneles) p.result.set({ ...p.result(), period: periodo });
|
||||
const text = texto(render(paneles, periodo).nativeElement);
|
||||
expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('Al cierre del periodo 2026-03, se evaluaron 3 niños de la cohorte de tamizaje; 1 únicamente tienen M-CHAT');
|
||||
expect(text).toContain('54.5 días de M-CHAT (psicología) a ADOS-2, 9 días de ADOS-2 a diagnóstico.');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad.');
|
||||
expect(text).toContain('De los 4 estudios de EEG realizados a niños de la cohorte en el periodo, 25.0% tienen buena calidad.');
|
||||
for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo);
|
||||
});
|
||||
|
||||
@@ -67,16 +71,15 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57));
|
||||
paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. No se registraron estudios de EEG en el periodo.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0');
|
||||
});
|
||||
|
||||
it('incluye los estudios sin analizar en el total de EEG del periodo', () => {
|
||||
// Fails if the share of good quality leaves the unanalysed studies out of its denominator.
|
||||
const paneles = completos();
|
||||
paneles[7].result.set({ ...listo(6), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 6 } });
|
||||
expect(texto(render(paneles).nativeElement))
|
||||
.toContain('estudios de EEG, 0.0% tienen buena calidad.');
|
||||
.toContain('De los 6 estudios de EEG realizados a niños de la cohorte en el periodo, 0.0% tienen buena calidad.');
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
@@ -94,7 +97,7 @@ describe('Resumen TEA por periodo', () => {
|
||||
const paneles = completos();
|
||||
paneles[4].result.set({ ...c1('28.1', 16, 58), period: '2025-S1' });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG');
|
||||
expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad');
|
||||
expect(root.querySelector('.dato.sin-dato')?.getAttribute('title')).toBe('Sin datos para el periodo seleccionado');
|
||||
});
|
||||
|
||||
@@ -104,7 +107,7 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[4].result.set(c1('28.1', 16, 58));
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title')))
|
||||
.toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
.toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
});
|
||||
|
||||
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||
|
||||
@@ -19,23 +19,40 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
<article class="resumen" [attr.aria-busy]="cargando" aria-labelledby="tea-resumen-titulo">
|
||||
<h2 id="tea-resumen-titulo">Resumen</h2>
|
||||
<p>
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños entre 16 y 36 meses;
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños de la cohorte de tamizaje;
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> únicamente tienen M-CHAT,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['PSICOLOGIA']) }" /> hasta la evaluación psicológica y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(conNeuropediatria) }" /> presentan evaluación neuropediátrica.
|
||||
</p>
|
||||
<p class="nota">La cohorte incluye a niños de 16 a 36 meses al primer M-CHAT y a niños sin edad registrada.</p>
|
||||
<p>
|
||||
En este periodo el <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', '%') }" />
|
||||
de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).
|
||||
de los pacientes en tamizaje con diagnóstico confirmado o en proceso tiene diagnóstico confirmado de TEA (CIE-10 F84.0).
|
||||
</p>
|
||||
<p>
|
||||
Las ventanas de tiempo<sup>*</sup> de tamizaje son: <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" /> de M-CHAT (psicología) a ADOS-2,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" /> de ADOS-2 a diagnóstico.
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
<br>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado en este periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> presentan estudio de EEG y faltan
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> por realizarlo.
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> estudios de EEG,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
</p>
|
||||
<p>
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico positivo fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
</p>
|
||||
<p>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado al cierre del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> tienen un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> aún no cuentan con uno de esa calidad.
|
||||
</p>
|
||||
@let estudios = valor('M29_calidad_eeg', '');
|
||||
@if (estudios.estado !== 'listo') {
|
||||
<p>Estudios de EEG del periodo: <ng-container *ngTemplateOutlet="dato; context: { $implicit: estudios }" />.</p>
|
||||
} @else if (estudios.texto === '0') {
|
||||
<p>No se registraron estudios de EEG en el periodo.</p>
|
||||
} @else {
|
||||
<p>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: estudios }" /> estudios de EEG realizados a niños de la cohorte en el periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
</p>
|
||||
}
|
||||
<p class="nota">*tomando la mediana de los tiempos</p>
|
||||
@if (conError.length) {
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||
|
||||
Reference in New Issue
Block a user