Merge dashboard-test: the CaMa dashboard's presentation over the FHIR measures, with TEA's history and summary kept

This commit is contained in:
Roberto Treviño Cervantes
2026-11-15 05:37:15 -06:00
133 changed files with 9936 additions and 290 deletions
@@ -0,0 +1,47 @@
@let p = summary();
<div class="toolbar">
<button class="back-button" mat-stroked-button type="button" (click)="back.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
<button class="export-button" mat-stroked-button type="button" [disabled]="generating()" (click)="exportPdf()"><mat-icon aria-hidden="true">picture_as_pdf</mat-icon><span>Exportar ficha PDF</span></button>
@if (generating()) { <p class="toolbar-message" role="status">Generando PDF…</p> }
@if (failed()) { <p class="toolbar-message" role="alert">No se pudo generar el PDF. Intenta nuevamente.</p> }
</div>
<header>
<h2 #title tabindex="-1">Paciente {{ p.patientId }}</h2>
<p>Fecha de corte: {{ p.cutoff }}.</p>
<dl class="summary">
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
</dl>
</header>
<div class="detail-grid">
<mat-card class="mammography-card" appearance="outlined" aria-labelledby="mastografia-title">
<mat-card-header><h3 id="mastografia-title">Mastografía</h3></mat-card-header>
<mat-card-content>
<ul>
<li><strong>Última mastografía</strong><span>Categoría BI-RADS: {{ p.birads ?? notAvailable }}</span><span>Fecha: {{ p.mammographyDate ?? notAvailable }}</span></li>
</ul>
</mat-card-content>
</mat-card>
<mat-card class="histopathology-card" appearance="outlined" aria-labelledby="histopatologia-title">
<mat-card-header><h3 id="histopatologia-title">Histopatología</h3></mat-card-header>
<mat-card-content>
<ul>
<li><strong>Resultado histopatológico</strong><span>Resultado: {{ p.histopathology ?? notAvailable }}</span><span>{{ p.biopsyDateLabel ?? 'Fecha de biopsia' }}: {{ p.biopsyDate ?? notAvailable }}</span></li>
</ul>
</mat-card-content>
</mat-card>
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
<mat-card-content>
<ul>
@for (item of placeholders; track item.key) {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
}
</ul>
<p class="availability">{{ recommendationsUnavailable }}</p>
</mat-card-content>
</mat-card>
</div>
@@ -0,0 +1,26 @@
:host { display: block; min-width: 0; color: var(--issste-text); overflow-wrap: anywhere; }
header { margin-block: 1.5rem; }
h2 { margin-block: .5rem 1rem; font-size: 1.65rem; }
h3 { margin-block: 0 1rem; font-size: 1.2rem; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem 1rem; }
.toolbar-message { flex: 0 0 100%; margin: 0; }
.export-button { margin-inline-start: auto; }
.back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; }
.back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; }
.availability { margin-block: .75rem; color: var(--issste-text-secondary); }
.summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; }
dt { color: var(--issste-text-secondary); font-size: .9rem; }
dd { margin: .4rem 0 0; font-weight: 600; }
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "mammography histopathology" "prognosis prognosis"; gap: 1rem; align-items: start; }
mat-card { min-width: 0; background: var(--issste-surface); color: inherit; border-color: var(--issste-border); }
.mammography-card { grid-area: mammography; }
.histopathology-card { grid-area: histopathology; }
.prognosis-card { grid-area: prognosis; }
ul { list-style: none; padding: 0; margin: 0; }
li { padding-block: .75rem; border-top: 1px solid var(--issste-border); }
li:first-child { border-top: 0; }
li span { display: block; margin-top: .4rem; }
button { min-height: 44px; color: var(--issste-text); border-color: var(--issste-border); }
@media (max-width: 48rem) {
.detail-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "mammography" "histopathology" "prognosis"; }
}
@@ -0,0 +1,129 @@
// Covers CaMa's individual record: how a follow-up row becomes its summary, what the card shows (only fields the list
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { CamaPatientCard } from './cama-patient-card';
import { CamaPatientSummary, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
const complete = () => rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!;
const incomplete = () => rows().find(r => r['biopsia'] === null)!;
describe('Ficha CaMa: resumen', () => {
// Fails if a field of the row is mapped to another one or lost on the way to the card.
it('reads every field the follow-up row carries', () => {
const row = complete();
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
});
});
// Fails if a missing value is turned into text or a number (for example 0 days), which would read as clinical data.
it('keeps a missing value as null', () => {
const summary = toCamaPatientSummary(incomplete(), '2026-10-20')!;
expect(summary.histopathology).toBeNull();
expect(summary.daysMammographyToDiagnosis).toBeNull();
});
// Fails if a row without an identifier opens a record for nobody.
it('has no summary for a row without an identifier', () => {
expect(toCamaPatientSummary({ ...complete(), id_seudonimo: null }, '2026-10-20')).toBeNull();
expect(toCamaPatientSummary({ ...complete(), id_seudonimo: '' }, '2026-10-20')).toBeNull();
});
});
describe('Ficha CaMa: componente', () => {
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
const root = () => fixture.nativeElement as HTMLElement;
function montar(summary: CamaPatientSummary) {
fixture = TestBed.createComponent(CamaPatientCard);
fixture.componentRef.setInput('summary', summary);
fixture.detectChanges();
}
afterEach(() => fixture?.destroy());
// Fails if a note or warning line comes back to the record.
it('has no note or warning line', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
expect(root().querySelector('.note, [role="note"]')).toBeNull();
expect(root().textContent).not.toContain('Documento de consulta');
});
// Fails if the card shows something other than what the list carried, or hides the identifier and cut-off.
it('shows the summary, the mammography and the histopathology of the row', () => {
const row = complete();
montar(toCamaPatientSummary(row, '2026-10-20')!);
const text = root().textContent!.replace(/\s+/g, ' ');
for (const value of [`Paciente ${row['id_seudonimo']}`, 'Fecha de corte: 2026-10-20', String(row['estatus']), String(row['prioridad']), String(row['birads']),
String(row['mastografia_fecha']), String(row['biopsia']), String(row['biopsia_fecha']), String(row['dias_mastografia_diagnostico'])]) expect(text).toContain(value);
});
// Fails if a missing value is left blank or invented instead of reading "No disponible".
it('reads each missing value as "No disponible"', () => {
montar(toCamaPatientSummary(incomplete(), '2026-10-20')!);
const text = root().textContent!;
expect(text).toContain('Resultado: No disponible');
expect(text).toContain('Fecha de biopsia: No disponible');
expect(text).toContain('Días de mastografía a diagnóstico');
});
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const items = [...root().querySelectorAll('[data-pronostico]')];
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']);
for (const item of items) {
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
expect(item.textContent).not.toMatch(/\d/);
}
expect(root().textContent).toContain(RECOMMENDATIONS_UNAVAILABLE);
});
// Fails if the record opens without moving focus to its title, which strands keyboard and screen-reader users.
it('moves focus to its title when it opens', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
expect(document.activeElement).toBe(root().querySelector('h2'));
});
// Fails if the PDF button stops downloading, or the file name starts carrying the patient identifier.
it('downloads the record as a PDF named without the patient', async () => {
const downloads: string[] = [];
vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { downloads.push(this.download); });
const summary = toCamaPatientSummary(complete(), '2026-10-20')!;
montar(summary);
[...root().querySelectorAll('button')].find(b => b.textContent!.includes('Exportar ficha PDF'))!.click();
for (let i = 0; i < 100 && !downloads.length; i++) await new Promise(r => setTimeout(r, 50));
expect(downloads).toHaveLength(1);
expect(downloads[0]).toMatch(/^ficha-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.pdf$/);
expect(downloads[0]).not.toContain(summary.patientId);
vi.restoreAllMocks();
}, 30000);
// Fails if the two buttons leave the row above the title: back on the left, the PDF export on the right.
it('puts "Regresar" first and "Exportar ficha PDF" last in one row above the identifier', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const row = root().querySelector('.toolbar')!;
const buttons = [...row.querySelectorAll('button')];
expect(buttons).toHaveLength(2);
expect(buttons[0].textContent).toContain('Regresar');
expect(buttons[1].textContent).toContain('Exportar ficha PDF');
expect(row.compareDocumentPosition(root().querySelector('h2')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(root().querySelector('header')!.querySelector('button')).toBeNull();
});
// Fails if the back button stops telling the list to return.
it('emits back when "Regresar" is pressed', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
let backs = 0;
fixture.componentInstance.back.subscribe(() => backs++);
[...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click();
expect(backs).toBe(1);
});
});
@@ -0,0 +1,48 @@
import { AfterViewInit, Component, ElementRef, input, output, signal, viewChild } from '@angular/core';
import { downloadBlob, exportFilename } from '../../export/download-file';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
/**
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
* survival and prognostic factors are placeholders until a validated model supplies them.
*/
@Component({
selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule],
templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss',
})
export class CamaPatientCard implements AfterViewInit {
readonly summary = input.required<CamaPatientSummary>();
readonly back = output<void>();
readonly notAvailable = NOT_AVAILABLE;
readonly placeholders = PROGNOSIS_PLACEHOLDERS;
readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE;
readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE;
private readonly title = viewChild<ElementRef<HTMLElement>>('title');
readonly generating = signal(false);
readonly failed = signal(false);
ngAfterViewInit() { this.title()?.nativeElement.focus(); }
/** Downloads the record as a PDF. The file name carries the report and the cut-off, never the patient. */
async exportPdf() {
if (this.generating()) return;
this.generating.set(true); this.failed.set(false);
try {
const patient = this.summary();
// The PDF library downloads only when the button is used.
const blob = await (await import('./cama-patient-pdf')).buildCamaPatientPdf(patient);
downloadBlob(blob, exportFilename('ficha-cancer-de-mama', patient.cutoff, 'pdf'));
} catch {
this.failed.set(true);
} finally {
this.generating.set(false);
}
}
}
@@ -0,0 +1,69 @@
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
// the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { PDF_CONFIDENTIAL } from '../../export/pdf-template';
import { buildCamaPatientPdf, camaPatientDocument, PATIENT_TITLE } from './cama-patient-pdf';
import { PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
const NOW = new Date(Date.UTC(2026, 10, 12, 21, 30));
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
const complete = () => toCamaPatientSummary(rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!, '2026-10-20')!;
const incomplete = () => toCamaPatientSummary(rows().find(r => r['biopsia'] === null)!, '2026-10-20')!;
const definition = (p = complete(), logo?: string) => camaPatientDocument(p, NOW, logo) as Record<string, any>;
function texts(node: unknown, out: string[] = []): string[] {
if (typeof node === 'string') out.push(node);
else if (Array.isArray(node)) node.forEach(n => texts(n, out));
else if (node && typeof node === 'object') Object.values(node).forEach(n => texts(n, out));
return out;
}
describe('Ficha CaMa: PDF individual', () => {
// Fails if the record stops sharing the report's frame (header, footer, properties) or leaves portrait.
it('uses the institutional frame in portrait, with the title in the header and the confidentiality line in the footer', () => {
const d = definition(complete(), 'data:image/png;base64,AAAA');
expect(d['pageOrientation']).toBe('portrait');
expect(d['info']).toMatchObject({ title: PATIENT_TITLE, author: 'ISSSTELEON' });
expect(texts(d['header']())).toEqual(expect.arrayContaining([PATIENT_TITLE]));
expect(JSON.stringify(d['header']())).toContain('"image":"logo"');
expect(texts(d['footer'](1, 1))).toEqual(expect.arrayContaining(['Página 1 de 1', PDF_CONFIDENTIAL]));
});
// Fails if a field of the record is left out of the document or printed under another label.
it('prints each field of the record under its label', () => {
const p = complete();
const found = texts(definition(p)['content']);
for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia', 'Días de mastografía a diagnóstico']) expect(found).toContain(t);
});
// Fails if a missing value is printed as something other than "No disponible".
it('prints a missing value as "No disponible"', () => {
const found = texts(definition(incomplete())['content']);
expect(found.filter(t => t === 'No disponible').length).toBeGreaterThanOrEqual(2);
});
// Fails if a placeholder gains a figure or an explanation other than "unavailable".
it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => {
const found = texts(definition()['content']);
for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3);
});
// Fails if the document carries a platform identifier field.
it('contains no platform identifier', () => {
const p = complete();
expect(texts(definition(p)['info'])).not.toContain('pac_id');
});
// Fails if the document no longer renders to a real PDF file.
it('renders a PDF file', async () => {
const blob = await buildCamaPatientPdf(complete(), NOW);
const bytes = new TextDecoder('latin1').decode(new Uint8Array(await blob.arrayBuffer()));
expect(bytes.startsWith('%PDF-')).toBe(true);
expect(bytes.trimEnd().endsWith('%%EOF')).toBe(true);
expect((bytes.match(/\/Type \/Page\b/g) ?? []).length).toBe(1);
}, 30000);
});
@@ -0,0 +1,41 @@
import { renderPdf, PdfDefinition } from '../../export/pdf-engine';
import { COLORS, institutionalDocument, loadLogo } from '../../export/pdf-template';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
export const PATIENT_TITLE = 'Ficha de paciente — Cáncer de mama';
const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 };
const value = (v: string | number | null) => (v === null ? { text: NOT_AVAILABLE, italics: true, color: COLORS.muted } : { text: String(v) });
const section = (title: string, rows: [string, string | number | null][]) => [
{ text: title, style: 'h2' },
{ table: { widths: [170, '*'], body: rows.map(([label, v]) => [{ text: label, bold: true }, value(v)]) }, layout: rule },
];
/** The document definition of one patient's record. Exported so its content can be checked without rendering. */
export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo?: string): PdfDefinition {
return institutionalDocument({ title: PATIENT_TITLE, logo, now, orientation: 'portrait' }, [
{ text: `Paciente ${patient.patientId}`, style: 'h1' },
{ text: `Fecha de corte: ${patient.cutoff}`, style: 'muted' },
...section('Resumen', [
[patient.idLabel, patient.patientId],
['Grupo de edad', patient.ageGroup],
['Estatus de seguimiento', patient.status],
['Prioridad', patient.priority],
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
]),
...section('Mastografía', [['Categoría BI-RADS', patient.birads], ['Fecha de la mastografía', patient.mammographyDate]]),
...section('Histopatología', [['Resultado histopatológico', patient.histopathology], [patient.biopsyDateLabel ?? 'Fecha de biopsia', patient.biopsyDate]]),
...section('Pronóstico y recomendaciones', [
...PROGNOSIS_PLACEHOLDERS.map(p => [p.label, PROGNOSIS_UNAVAILABLE] as [string, string]),
['Recomendaciones', RECOMMENDATIONS_UNAVAILABLE],
]),
{ text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] },
]);
}
/** A one-patient PDF with the same frame as the follow-up report. */
export async function buildCamaPatientPdf(patient: CamaPatientSummary, now = new Date(), logo?: string): Promise<Blob> {
return renderPdf(camaPatientDocument(patient, now, logo ?? await loadLogo()));
}
@@ -0,0 +1,63 @@
import { TrackingRow } from '../../export/tracking-export.models';
import { CampoIdentidad, ETIQUETA_IDENTIDAD, identidadDe } from '../../paciente-identidad';
export const NOT_AVAILABLE = 'No disponible';
/**
* What the CaMa follow-up list says about one patient, read from the row that was clicked. `patientId` is the
* identifier the row carries (`idField` says which field); the record only shows it.
*/
export interface CamaPatientSummary {
patientId: string;
idField: CampoIdentidad;
/** What the identifier is called on screen and in the file. */
idLabel: string;
cutoff: string;
ageGroup: string | null;
status: string | null;
priority: string | null;
birads: string | null;
mammographyDate: string | null;
histopathology: string | null;
biopsyDate: string | null;
/** What the list calls that date: the cohort's list gives the date of the biopsy report, which can be known before its result is. */
biopsyDateLabel?: string;
daysMammographyToDiagnosis: number | null;
}
/** Placeholders for results that exist only once a validated model and its clinical definition do. */
export const PROGNOSIS_PLACEHOLDERS = [
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
{ key: 'survival', label: 'Supervivencia' },
{ key: 'factors', label: 'Factores pronóstico' },
] as const;
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
export const RECOMMENDATIONS_UNAVAILABLE = 'Recomendaciones no disponibles.';
const text = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : null);
/**
* The patient summary of a follow-up row, or `null` when the row has no identity that can be trusted. `columnas` are the ones the
* list announced: the label it gives to the biopsy date is kept, so the record says the same as the list.
*/
export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: readonly { clave: string; detalles?: readonly { clave: string; etiqueta: string }[] }[] = []): CamaPatientSummary | null {
const identity = identidadDe(row);
if (!identity) return null;
const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta;
const days = row['dias_mastografia_diagnostico'];
return {
patientId: identity.id,
idField: identity.campo,
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
cutoff,
ageGroup: text(row['grupo_edad']),
status: text(row['estatus']),
priority: text(row['prioridad']),
birads: text(row['birads']),
mammographyDate: text(row['mastografia_fecha']),
histopathology: text(row['biopsia']),
biopsyDate: text(row['biopsia_fecha']),
...(etiquetaFecha ? { biopsyDateLabel: etiquetaFecha } : {}),
daysMammographyToDiagnosis: typeof days === 'number' && Number.isFinite(days) ? days : null,
};
}
@@ -1,10 +1,10 @@
@if (estado.tipo !== 'cerrado') {
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
<header>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.id_seudonimo }}</h2>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.identidad.id }}</h2>
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
<dl class="summary">
<div><dt>Identificador seudónimo</dt><dd>{{ estado.resumen.id_seudonimo }}</dd></div>
<div><dt>{{ etiquetaIdentidad }}</dt><dd>{{ estado.resumen.identidad.id }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
@@ -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 /></mat-card-content>
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
</mat-card>
</div>
}
@@ -1,8 +1,9 @@
import { Observable } from 'rxjs';
import { IdentidadPaciente } from '../paciente-identidad';
/** Snapshot of the received row, independent of the Seguimiento transport contract. */
export interface PacienteResumen {
id_seudonimo: string;
identidad: IdentidadPaciente;
grupoEdad: string | null;
estatus: string | null;
corte: string;
@@ -27,7 +28,8 @@ export interface PacienteDetalle {
}
export interface PacienteDetalleProvider {
obtener(idSeudonimo: string): Observable<PacienteDetalle | null>;
/** `id` is the patient identifier of the row; a patient the provider does not know is `null`. */
obtener(id: string): Observable<PacienteDetalle | null>;
}
export type PacienteDetalleEstado =
@@ -5,9 +5,9 @@ import { PacienteDetalleProvider } from './paciente-detalle.models';
@Injectable({ providedIn: 'root' })
export class PacienteDetalleMockProvider implements PacienteDetalleProvider {
obtener(idSeudonimo: string) {
obtener(id: string) {
return defer(() => {
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo);
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === id);
// Each read owns its data; consumers cannot mutate another selection or the fixtures.
return of(detalle ? structuredClone(detalle) : null);
});
@@ -3,6 +3,7 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Subject, of, throwError } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
@@ -10,9 +11,9 @@ import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.mod
import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
describe('Proveedor de detalle sintético', () => {
it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => {
@@ -59,7 +60,7 @@ describe('Estado de selección del paciente', () => {
const estado = state.estado();
expect(estado.tipo).toBe('no-disponible');
if (estado.tipo !== 'cerrado') {
expect(estado.resumen.id_seudonimo).toBe('001');
expect(estado.resumen.identidad.id).toBe('001');
expect(estado.resumen.vph?.resultado).toBe('NEGATIVO');
expect(estado.resumen.vph?.genotipo16y18).toBeNull();
expect(estado.resumen.diasTomaDiagnostico).toBe(0);
@@ -108,7 +109,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
let root: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
fixture = TestBed.createComponent(IndicadoresTracking);
root = fixture.nativeElement;
http = TestBed.inject(HttpTestingController);
@@ -166,7 +168,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
fixture.detectChanges();
const estado = fixture.componentInstance.pacienteDetalle.estado();
expect(estado.tipo).toBe('disponible');
if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo);
if (estado.tipo === 'disponible') expect(estado.resumen.identidad.id).toBe(pacientes[1].id_seudonimo);
volver();
expect(row).toBe(document.activeElement);
http.expectNone(() => true);
@@ -238,20 +240,15 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
http.expectNone(() => true);
});
it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => {
// Fails if a row that only has id_seudonimo asks the risk route (which takes a pac_id) or leaves no «no disponible» state.
it('una ficha de un renglón con solo id_seudonimo no consulta el riesgo y lo declara no disponible', () => {
const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
const obtener = vi.spyOn(provider, 'obtener');
try {
const detail = abrir();
const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Información simulada');
expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
expect(obtener).toHaveBeenCalledExactlyOnceWith();
volver();
const otra = abrir(1);
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
const tarjeta = abrir().querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(tarjeta.querySelector('table')).toBeNull();
expect(obtener).not.toHaveBeenCalled();
http.expectNone(() => true);
} finally { obtener.mockRestore(); }
});
@@ -2,6 +2,7 @@ import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core'
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, catchError, defer, map, of, switchMap } from 'rxjs';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { identidadDe } from '../paciente-identidad';
import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models';
import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider';
import { AltaRegistroTemporal } from './paciente-registro.models';
@@ -17,14 +18,14 @@ export class PacienteDetalleState {
readonly estado = this.actual.asReadonly();
readonly registrosTemporales = computed(() => {
const estado = this.actual();
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo);
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.identidad.id);
});
constructor() {
this.seleccion.pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.identidad.id)).pipe(
map(detalle => {
if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) {
if (detalle && (detalle.id_seudonimo !== resumen.identidad.id || detalle.origen !== 'sintetico')) {
throw new Error('Detalle incompatible con la selección');
}
return detalle
@@ -38,8 +39,10 @@ export class PacienteDetalleState {
}
abrir(paciente: SeguimientoPaciente, corte: string) {
const identidad = identidadDe(paciente);
if (!identidad) return;
const resumen: PacienteResumen = {
id_seudonimo: paciente.id_seudonimo,
identidad,
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
estatus: paciente.estatus.etiqueta,
corte,
@@ -65,7 +68,7 @@ export class PacienteDetalleState {
agregarRegistro(alta: AltaRegistroTemporal) {
const estado = this.actual();
if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false;
return this.sesion.agregar(alta.id_seudonimo, alta.registro);
if (estado.tipo === 'cerrado' || estado.resumen.identidad.id !== alta.paciente.id) return false;
return this.sesion.agregar(alta.paciente.id, alta.registro);
}
}
@@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente } from '../paciente-identidad';
import { PacienteDetalleEstado } from './paciente-detalle.models';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
@@ -31,19 +32,22 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
ngOnDestroy() { this.dialogoActivo?.close(); }
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 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); }
abrirRegistro(tipo: TipoRegistroTemporal) {
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
const id_seudonimo = this.estado.resumen.id_seudonimo;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; id_seudonimo: string }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
const paciente = this.estado.resumen.identidad;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, paciente }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false,
});
this.dialogoActivo = ref;
ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => {
this.dialogoActivo = undefined;
if (registro) this.registroAgregado.emit({ id_seudonimo, registro });
if (registro) this.registroAgregado.emit({ paciente, registro });
});
}
etiquetaCitologia(resultado: string | null, calidad: string | null) {
@@ -1,7 +1,7 @@
<h2 mat-dialog-title>{{ titulo }}</h2>
<form [formGroup]="form" (ngSubmit)="agregar()">
<mat-dialog-content>
<p>Paciente {{ data.id_seudonimo }}</p>
<p>Paciente {{ data.paciente.id }}</p>
<div class="fields">
<mat-form-field appearance="outline">
<mat-label>{{ etiquetaTipo }}</mat-label>
@@ -1,4 +1,5 @@
import { Component, DestroyRef, inject } from '@angular/core';
import { IdentidadPaciente } from '../paciente-identidad';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -10,7 +11,7 @@ import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO,
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; }
export interface RegistroDialogData { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente; }
const opcionValida = (catalogo: Readonly<Record<string, string>>): ValidatorFn =>
control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true };
@@ -7,17 +7,21 @@ import { MatSelectHarness } from '@angular/material/select/testing';
import { MatInputHarness } from '@angular/material/input/testing';
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
import { MatDialog } from '@angular/material/dialog';
import { firstValueFrom } from 'rxjs';
import { firstValueFrom, of } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
import { TipoRegistroTemporal } from './paciente-registro.models';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
@@ -31,7 +35,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
let dialog: MatDialog;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
http = TestBed.inject(HttpTestingController);
dialog = TestBed.inject(MatDialog);
montarTracking();
@@ -130,7 +135,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo);
expect(almacenado.paciente).toBe(pacientes[0].id_seudonimo);
expect(almacenado.origen).toBe('sesion-demostracion');
expect(almacenado.fecha).toBe('2026-10-26');
http.expectNone(() => true);
@@ -274,7 +279,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
const a = primero.get(PacienteDetalleState);
const b = segundo.get(PacienteDetalleState);
a.abrir(pacientes[0], fixtureData.corte);
expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
expect(a.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
a.cerrar();
expect(a.registrosTemporales()).toEqual([]);
primero.destroy();
@@ -282,7 +287,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
expect(b.registrosTemporales()).toHaveLength(1);
b.abrir(pacientes[1], fixtureData.corte);
expect(b.registrosTemporales()).toEqual([]);
expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
expect(b.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
} finally {
if (!primero.destroyed) primero.destroy();
segundo.destroy();
@@ -1,3 +1,4 @@
import { IdentidadPaciente } from '../paciente-identidad';
import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos';
type ResultadoDemo = {
@@ -14,11 +15,12 @@ export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo'];
/** Independiente del resumen recibido y del historial inicial del proveedor. */
export type RegistroTemporal = Readonly<NuevoRegistroTemporal & {
id: number;
id_seudonimo: string;
/** Identifier of the patient the record was added to. */
paciente: string;
origen: 'sesion-demostracion';
}>;
export interface AltaRegistroTemporal {
id_seudonimo: string;
paciente: IdentidadPaciente;
registro: NuevoRegistroTemporal;
}
@@ -5,6 +5,7 @@ import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
describe('Fecha de calendario de registros temporales', () => {
it('acepta días reales, incluyendo años bisiestos y límites de año', () => {
@@ -35,7 +36,7 @@ describe.each(casos)('Formulario de $tipo', caso => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, paciente: identidadDe({ id_seudonimo: '001' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -82,7 +83,7 @@ describe('Resultados dependientes del estudio', () => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', paciente: identidadDe({ id_seudonimo: 'A' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
const fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -132,7 +133,7 @@ describe('Memoria de registros temporales', () => {
const sesion = TestBed.inject(PacienteRegistrosSesion);
for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true);
expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']);
expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true);
expect(sesion.paraPaciente('001').every(r => r.paciente === '001' && r.origen === 'sesion-demostracion')).toBe(true);
for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]);
sesion.agregar('toString', casos[0].registro);
expect(sesion.paraPaciente('toString')).toHaveLength(1);
@@ -11,21 +11,21 @@ export class PacienteRegistrosSesion {
private readonly registros = signal<ReadonlyMap<string, readonly RegistroTemporal[]>>(new Map());
private siguienteId = 0;
paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] {
return this.registros().get(idSeudonimo) ?? SIN_REGISTROS;
paraPaciente(id: string): readonly RegistroTemporal[] {
return this.registros().get(id) ?? SIN_REGISTROS;
}
agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean {
if (!idSeudonimo || !nuevo) return false;
agregar(id: string, nuevo: NuevoRegistroTemporal): boolean {
if (!id || !nuevo) return false;
const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion
: nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio;
const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : '');
if (!validado) return false;
const registro: RegistroTemporal = Object.freeze({
...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion',
...validado, id: ++this.siguienteId, paciente: id, origen: 'sesion-demostracion',
});
this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([
...(actual.get(idSeudonimo) ?? []), registro,
this.registros.update(actual => new Map(actual).set(id, Object.freeze([
...(actual.get(id) ?? []), registro,
])));
return true;
}
@@ -4,7 +4,6 @@
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@case ('no-disponible') {
<p role="status">Riesgo individual no disponible para esta paciente.</p>
<p class="availability">La consulta de riesgo individual aún no está habilitada.</p>
}
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
@@ -1,4 +1,4 @@
import { Component, inject } from '@angular/core';
import { Component, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@@ -11,6 +11,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
styleUrl: './paciente-riesgo-tabla.scss',
})
export class PacienteRiesgoTabla {
readonly estado = inject(PacienteRiesgoState).estado;
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>();
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
constructor() {
effect(() => this.state.pacId.set(this.pacId()));
}
}
@@ -40,9 +40,9 @@ export interface RiesgoPacienteCacu {
riesgo: LoteRiesgoCacu | null;
}
/** Deliberately no patient argument until secure identity resolution is authorized. */
/** `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(): Observable<unknown>;
obtener(pacId: string): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -1,8 +1,16 @@
import { InjectionToken } from '@angular/core';
import { of } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
},
});
@@ -12,6 +12,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
fixture.componentRef.setInput('pacId', '42');
fixture.detectChanges();
fixture.detectChanges();
return fixture;
}
@@ -20,14 +22,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify();
});
it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
const f = setup(), root: HTMLElement = f.nativeElement;
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
f.detectChanges();
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('aún no está habilitada');
expect(root.textContent).toContain('Recomendaciones no disponibles');
expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/);
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull());
});
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
@@ -35,7 +38,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith();
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
expect(root.querySelectorAll('thead th')).toHaveLength(4);
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
@@ -134,7 +137,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
expect(otra.nativeElement.querySelector('table')).toBeNull();
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
@@ -1,16 +1,23 @@
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of } from 'rxjs';
import { Injectable, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' };
@Injectable()
export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
// `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
), { initialValue: CARGANDO });
}