CaCu's page by readings, screening stages, ages and exports

This commit is contained in:
Roberto Treviño
2026-11-30 23:31:58 -06:00
parent 053679c817
commit fe4dd55452
29 changed files with 1831 additions and 212 deletions
+21
View File
@@ -21,6 +21,12 @@
<dt>Fecha de nacimiento</dt>
<dd>{{ p.birthDate ?? 'Sin dato' }}</dd>
</div>
@if (stages()) {
<div>
<dt>Edad</dt>
<dd>{{ age() ?? 'Sin dato' }}</dd>
</div>
}
<div>
<dt>Sexo</dt>
<dd>
@@ -101,6 +107,20 @@
</mat-card-content>
</mat-card>
}
@if (stages(); as s) {
<mat-card appearance="outlined" class="wide" data-section="etapas">
<mat-card-header><mat-card-title>Etapas del tamizaje</mat-card-title></mat-card-header>
<mat-card-content>
<app-stages [stages]="s" [detail]="true" />
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
</mat-card-content>
</mat-card>
}
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content>
@@ -169,6 +189,7 @@
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
<app-risk-scales [scales]="scales()" />
@if (models().length) {
<table class="plain">
<thead>
+53 -1
View File
@@ -19,7 +19,11 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { savePdf } from '../export';
import { recordSheets } from './record-sheets';
import { riskScales, RiskScales } from './risk-scales';
import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
import {
BIOMARKER_NAMES,
@@ -60,6 +64,8 @@ function shown(o: Observation): string {
MatIconModule,
RouterLink,
Plot,
RiskScales,
Stages,
],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
@@ -72,6 +78,8 @@ export class Paciente {
/** The follow-up list she was opened from: its window (months) and cut-off. */
readonly ventana = input<string>();
readonly corte = input<string>();
/** CaCu: the day of the cytology the list showed of her. */
readonly citologia = input<string>();
private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }),
@@ -119,6 +127,50 @@ export class Paciente {
})),
].sort((a, b) => b.date.localeCompare(a.date));
});
private readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
protected readonly stages = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
(r) => code(r.code) === 'cervical_cytology',
);
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
});
protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.models()) : [],
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** CaCu: her record as a PDF. */
protected async save(): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
const { name: who, curp, numbers } = this.identity();
const facts: [string, string | undefined][] = [
['Nombre', who],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', this.patient()?.birthDate],
['Edad', this.age()?.toString()],
['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()],
];
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
+59
View File
@@ -0,0 +1,59 @@
import type { Sheet } from '../export';
import type { RiskScale } from './risk-scales';
import { Stage, STATES } from './stages';
const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
interface Event {
date: string;
kind: string;
text: string;
}
interface Test {
date: string;
kind: string;
reported?: string;
results: string[];
}
/** A patient's record as the tables of her PDF, in the page's order. */
export function recordSheets(
facts: [string, string | undefined][],
stages: Stage[],
history: Event[],
tests: Test[],
scales: RiskScale[],
): Sheet[] {
return [
{
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Etapas del tamizaje',
head: ['Etapa', 'Estado', 'Fecha'],
rows: stages.map((s) => [s.label, STATES[s.state], s.day ?? '']),
},
{
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados'],
rows: tests.map((t) => [t.date, t.kind, t.reported ?? 'Pendiente', t.results.join(' · ')]),
},
{
title: 'Riesgos',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [
label,
risk ? percent(risk.p) : NONE,
risk?.low === undefined ? NONE : `${percent(risk.low)} a ${percent(risk.high!)}`,
]),
},
];
}
+75
View File
@@ -0,0 +1,75 @@
import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core';
interface Prediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface RiskScale {
label: string;
risk?: Prediction;
}
/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) =>
[0, 5].map((years) => ({
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`,
risk: m.predictions.find((p) => p.years === years),
})),
);
}
@Component({
selector: 'app-risk-scales',
imports: [DecimalPipe],
template: `
@for (s of scales(); track s.label) {
<div class="scale">
<span>{{ s.label }}</span>
<div class="line">
@if (s.risk; as r) {
<span class="mark" [style.left.%]="r.p * 100"></span>
}
</div>
@if (s.risk; as r) {
<strong>{{ r.p * 100 | number: '1.1-2' }} %</strong>
@if (r.low !== undefined) {
<span>
IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high! * 100 | number: '1.1-2' }} %
</span>
}
} @else {
<strong>No disponible</strong>
}
</div>
}
`,
styles: `
.scale {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 8px;
}
.line {
background: linear-gradient(to right, #a8c243, #c24269);
flex: 1 1 200px;
height: 8px;
position: relative;
}
.mark {
background: #333;
height: 16px;
position: absolute;
top: -4px;
width: 3px;
}
`,
})
export class RiskScales {
readonly scales = input.required<RiskScale[]>();
}
+26
View File
@@ -0,0 +1,26 @@
import { EXT } from '../fhir';
import { route } from './stages';
const ext = (name: string, value: object) => ({ url: EXT + name, ...value });
const cytology = (...extension: object[]): any => ({ effectiveDateTime: '2026-01-10', extension });
describe('the route of a cytology', () => {
it('says what is recorded, inferred, pending and unknown, by the cut-off', () => {
const report = cytology(
ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-date', { valueDate: '2026-03-01' }),
ext('biopsy-link', { valueCode: 'recorded' }),
);
const states = (cutoff: string) => route(report, cutoff).map((s) => s.state);
expect(states('2026-12-31')).toEqual([
'recorded',
'unknown',
'inferred',
'recorded',
'unknown',
]);
expect(states('2026-02-15')[3]).toBe('pending');
expect(states('2026-01-15').slice(2)).toEqual(['unknown', 'unknown', 'unknown']);
});
});
+121
View File
@@ -0,0 +1,121 @@
import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4';
import { ext } from '../fhir';
/** A step of the route that a cytology starts. A day with no state is unknown. */
export interface Stage {
label: string;
day?: string;
state: 'recorded' | 'inferred' | 'pending' | 'unknown';
}
export const STATES: Record<Stage['state'], string> = {
recorded: 'Registrada',
inferred: 'Inferida por fechas',
pending: 'Pendiente',
unknown: 'Sin dato',
};
/** The route of one cytology, as its report says it, by `cutoff`. */
export function route(cytology: DiagnosticReport | undefined, cutoff: string): Stage[] {
const by = (day?: string) => (day && day.slice(0, 10) <= cutoff ? day.slice(0, 10) : undefined);
const at = (name: string) => by(ext(cytology, name)?.valueDate);
const step = (label: string, day: string | undefined, known: Stage['state']): Stage => ({
label,
day,
state: day ? known : 'unknown',
});
const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded' ? 'recorded' : 'inferred';
const biopsy = step('Reporte de biopsia', at('biopsy-date'), linked);
if (!biopsy.day && at('biopsy-request-date')) biopsy.state = 'pending';
return [
step('Toma de muestra', by(cytology?.effectiveDateTime), 'recorded'),
step('Resultado de citología', at('report-date'), 'recorded'),
step('Colposcopía', at('colposcopy-date'), 'inferred'),
biopsy,
step('Diagnóstico', at('diagnosis-date'), 'inferred'),
];
}
/** Whole days between two days; none when either is missing or they are out of order. */
export function between(from?: string, to?: string): number | undefined {
if (!from || !to || to < from) return undefined;
return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);
}
/** The stages as a line of dots; `detail` adds each one's state, day and days elapsed. */
@Component({
selector: 'app-stages',
template: `
<ol [class.detail]="detail()">
@for (s of shown(); track s.label) {
<li [title]="s.label + ': ' + s.text">
<span class="dot" [class]="s.state"></span>
@if (detail()) {
<strong>{{ s.label }}</strong>
<span>{{ s.text }}</span>
@if (s.day) {
<span>{{ s.day }}</span>
}
@if (s.previous !== undefined) {
<span>{{ s.previous }} días desde la etapa anterior</span>
}
@if (s.sample !== undefined) {
<span>{{ s.sample }} días desde la toma</span>
}
}
</li>
}
</ol>
`,
styles: `
ol {
display: flex;
gap: 6px;
list-style: none;
margin: 0;
padding: 0;
}
ol.detail {
flex-wrap: wrap;
gap: 16px;
}
.detail li {
display: flex;
flex: 1 1 120px;
flex-direction: column;
font-size: 0.85rem;
}
.dot {
border: 2px solid #9aa3ab;
border-radius: 50%;
display: inline-block;
height: 12px;
width: 12px;
}
.recorded {
background: #6a8000;
border-color: #6a8000;
}
.inferred {
background: #a8c243;
border-color: #6a8000;
}
.pending {
border-color: #c24269;
}
`,
})
export class Stages {
readonly stages = input.required<Stage[]>();
readonly detail = input(false);
protected readonly shown = computed(() => {
const all = this.stages();
return all.map((s, i) => ({
...s,
text: STATES[s.state],
previous: i ? between(all[i - 1].day, s.day) : undefined,
sample: i > 1 ? between(all[0].day, s.day) : undefined,
}));
});
}