import { DecimalPipe } from '@angular/common'; import { Component, computed, input } from '@angular/core'; import type { Parameters, ParametersParameter } from 'fhir/r4'; /** The states a resolution ends in, as the screens say them. */ export const STATUS_TEXT: Record = { resolved: 'Referencia disponible', not_published: 'Probabilidad no publicada en las tablas', missing_data: 'Falta un dato clínico', history_not_demonstrable: 'Antecedente no demostrable', not_applicable: 'Escenario no aplicable', contradictory: 'Resultados contradictorios', ambiguous: 'Escenario ambiguo', scenario_not_implemented: 'Escenario aún no resuelto', unverifiable_correspondence: 'Correspondencia no verificable', no_published_row: 'Sin fila publicada para esta combinación', }; /** Why a resolution or a comparison has no value. */ export const REASON_TEXT: Record = { no_cytology_reported_by_cutoff: 'No hay citología con resultado a la fecha de corte.', sample_not_reported_by_cutoff: 'La citología pedida no tenía resultado a la fecha de corte.', no_birth_date: 'Falta la fecha de nacimiento.', age_outside_25_65: 'La edad está fuera del rango de las tablas (25 a 65 años).', cytology_not_in_tables: 'El resultado citológico no está en las tablas.', missing_hpv: 'La citología no tiene resultado de VPH.', contradictory_hpv: 'El VPH es negativo pero se reporta un genotipo positivo.', hpv_positive_row: 'Las tablas muestran «VPH positivo» junto a VPH 16 y VPH 18; no se verificó si esa fila es el total o los otros tipos, y no se asume.', no_earlier_test_registered: 'La plataforma no tiene una prueba anterior con VPH; no demuestra que no haya antecedente.', earlier_test_older_than_5_years: 'La prueba anterior es de hace más de 5 años.', colposcopy_or_treatment_before: 'Hay una colposcopía, biopsia o tratamiento previo: es un escenario posterior a colposcopía o tratamiento, aún no resuelto.', history_is_a_surveillance_scenario: 'El antecedente anormal corresponde a la tabla de vigilancia, aún no resuelta.', registered_cin2_plus_before: 'Hay un CIN2+ registrado antes: las tablas lo excluyen.', hysterectomy_declared: 'El formulario declara una histerectomía: las tablas la excluyen.', procedure_after_without_named_referral: 'Hay una colposcopía o biopsia posterior, pero ningún registro la nombra como derivada de esta citología (una asociación por fechas no basta).', several_biopsies_name_the_cytology: 'Varias biopsias nombran esta citología.', not_a_referral_result_in_the_tables: 'La citología no es un resultado de derivación de las tablas.', hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.', cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.', biopsy_without_histology: 'La biopsia no tiene histología.', risk_blank_in_the_tables: 'Las tablas dejan esta probabilidad en blanco.', no_row_for_the_combination: 'Las tablas no publican esa combinación.', several_rows: 'Más de una fila podría corresponder.', no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.', outcome_differs: 'El desenlace del modelo no es el de la tabla (CIN3+).', unknown_model: 'El desenlace del modelo no está registrado para comparar.', horizon_not_published_by_model: 'El modelo no publica una predicción a este horizonte.', index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.', population_not_verified: 'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.', no_reference: 'Las tablas no dan una probabilidad a este horizonte.', }; const KEY_TEXT: Record = { history: 'Antecedente más reciente', hpv: 'VPH actual', cytology: 'Citología actual', referral: 'Resultado de tamizaje que originó la colposcopía', biopsy: 'Resultado de biopsia', }; const USED_TEXT: Record = { 'sample-date': 'toma', 'report-date': 'reporte', 'request-date': 'solicitud', result: 'resultado', hpv: 'VPH', 'hpv-16': 'VPH 16', 'hpv-18': 'VPH 18', histology: 'histología', }; const usedValue = (v: unknown) => (v === true ? 'positivo' : v === false ? 'negativo' : String(v)); export interface ComparisonView { model?: string; title?: string; outcome?: string; /** probabilities, 0 to 1 */ institutional?: number; low?: number; high?: number; status: string; /** percentage points, institutional minus reference */ differencePp?: number; reasons: string[]; } export interface HorizonView { years: number; label: string; published: boolean; /** probability, 0 to 1; none when the tables leave it blank */ reference?: number; comparisons: ComparisonView[]; } export interface ReferenceView { status: string; reasons: string[]; cutoff?: string; scenario?: { label: string; keys: { name: string; value: string }[] }; index?: { sampleDate?: string; reportDate?: string; result?: string; age?: number }; evaluationDate?: string; source?: { id?: string; file?: string; sha256?: string; outcome?: string; status?: string }; row?: { sheet?: string; number?: number; officialCheck?: string; matchedVia?: string }; used: { label: string; details: string }[]; assumptions: string[]; horizons: HorizonView[]; } type Part = ParametersParameter; const value = (p?: Part) => p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueInteger ?? p?.valueDecimal ?? p?.valueBoolean ?? undefined; const named = (parts: Part[] | undefined, name: string) => (parts ?? []).filter((p) => p.name === name); const one = (parts: Part[] | undefined, name: string) => value(named(parts, name)[0]); /** The horizon's name; the colposcopy table's one year is a year, never "immediate". */ export function horizonLabel(years: number): string { return years === 0 ? 'Inmediato (al índice)' : years === 1 ? '1 año' : `${years} años`; } /** The result of `$reference-risk` as the section shows it. A value absent from the answer stays * absent: no zero is made of a blank, and no difference is made of a comparison that is not one. */ export function referenceView(answer: Parameters): ReferenceView { const top = answer.parameter ?? []; const scenario = named(top, 'scenario')[0]; const index = named(top, 'index')[0]?.part; const row = named(top, 'row')[0]?.part; const source = named(top, 'source')[0]?.part; const view: ReferenceView = { status: String(one(top, 'status') ?? 'missing_data'), reasons: named(top, 'reason').map((r) => String(value(r))), cutoff: one(top, 'cutoff') as string | undefined, evaluationDate: one(top, 'evaluation-date') as string | undefined, used: named(top, 'used').map((u) => ({ label: String(one(u.part, 'label') ?? ''), details: (u.part ?? []) .filter((p) => p.name !== 'label') .map((p) => `${USED_TEXT[p.name ?? ''] ?? p.name}: ${usedValue(value(p))}`) .join(' · '), })), assumptions: named(top, 'assumption').map((a) => String(value(a))), horizons: named(top, 'horizon').map((h) => { const years = Number(one(h.part, 'years')); return { years, label: horizonLabel(years), published: one(h.part, 'published') === true, reference: one(h.part, 'reference') as number | undefined, comparisons: named(h.part, 'comparison').map((c) => ({ model: one(c.part, 'model') as string | undefined, title: one(c.part, 'title') as string | undefined, outcome: one(c.part, 'outcome') as string | undefined, institutional: one(c.part, 'institutional') as number | undefined, low: one(c.part, 'institutional-low') as number | undefined, high: one(c.part, 'institutional-high') as number | undefined, status: String(one(c.part, 'status')), differencePp: one(c.part, 'difference-pp') as number | undefined, reasons: named(c.part, 'reason').map((r) => String(value(r))), })), }; }), }; if (scenario?.part) view.scenario = { label: String(one(scenario.part, 'label') ?? ''), keys: named(scenario.part, 'key').map((k) => ({ name: KEY_TEXT[String(one(k.part, 'name'))] ?? String(one(k.part, 'name')), value: String(one(k.part, 'value')), })), }; if (index) view.index = { sampleDate: one(index, 'sample-date') as string | undefined, reportDate: one(index, 'report-date') as string | undefined, result: one(index, 'result') as string | undefined, age: one(index, 'age') as number | undefined, }; if (row) view.row = { sheet: one(row, 'sheet') as string | undefined, number: one(row, 'number') as number | undefined, officialCheck: one(row, 'official-check') as string | undefined, matchedVia: one(row, 'matched-via') as string | undefined, }; if (source) view.source = { id: one(source, 'id') as string | undefined, file: one(source, 'file') as string | undefined, sha256: one(source, 'sha256') as string | undefined, outcome: one(source, 'outcome') as string | undefined, status: one(source, 'status') as string | undefined, }; return view; } /** Outcome names as the screens say them; presentation only: the API's identifiers stay as they are * (an outcome this map does not know is shown as the API gave it). */ export const OUTCOME_TEXT: Record = { 'CIN3+': 'CIN3 o más grave (CIN3+)', 'CIN2+': 'CIN2 o más grave (CIN2+)', cancer: 'Cáncer', 'CIN2+ within one year': 'CIN2+ en un año', 'not stated as a histology outcome': 'No expresado como desenlace histológico', }; export const outcomeText = (outcome?: string) => (outcome ? (OUTCOME_TEXT[outcome] ?? outcome) : ''); export interface ModelRow extends Omit { years: number; label: string; /** the reasons of this horizon that its model's other horizons do not share */ reasons: string[]; } export interface ModelBlock { model?: string; title?: string; outcome?: string; /** reasons shared by every non-comparable horizon of this model, said once */ reasons: string[]; rows: ModelRow[]; } export interface Grouped { /** the reference by horizon: one table, whatever the models */ reference: { years: number; label: string; published: boolean; reference?: number }[]; /** reasons shared by every non-comparable comparison of every model, said once */ common: string[]; models: ModelBlock[]; /** no institutional model evaluated her: said once, with its reasons */ withoutModel: string[]; } const shared = (lists: string[][]) => lists.length > 1 ? lists[0].filter((r) => lists.every((l) => l.includes(r))) : []; /** Groups only what is equivalent: the reference once per horizon; a reason that every non-comparable * comparison of a model (or of all models) gives, once; everything else stays where it is. Nothing is * dropped, and a difference is never made: it is only the API's, on a comparable row. */ export function groupReference(v: ReferenceView): Grouped { const reference = v.horizons.map((h) => ({ years: h.years, label: h.label, published: h.published, reference: h.reference, })); const byModel = new Map(); const withoutModel: string[] = []; for (const h of v.horizons) for (const c of h.comparisons) { if (!c.model) { for (const r of c.reasons) if (!withoutModel.includes(r)) withoutModel.push(r); continue; } const block = byModel.get(c.model) ?? { model: c.model, title: c.title, outcome: c.outcome, reasons: [], rows: [], }; byModel.set(c.model, block); block.rows.push({ ...c, years: h.years, label: h.label }); } const models = [...byModel.values()]; const notComparable = (b: ModelBlock) => b.rows.filter((r) => r.status !== 'comparable'); const common = shared(models.flatMap(notComparable).map((r) => r.reasons)); const everyModel = models.length > 1 ? common : []; for (const b of models) { const own = shared(notComparable(b).map((r) => r.reasons.filter((x) => !everyModel.includes(x)))); b.reasons = own; for (const r of b.rows) if (r.status !== 'comparable') r.reasons = r.reasons.filter((x) => !everyModel.includes(x) && !own.includes(x)); } return { reference, common: everyModel, models, withoutModel }; } const OFFICIAL: Record = { match: 'coincide con la tabla del NCI', 'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo', differs: 'no coincide con la tabla del NCI', not_found_in_official: 'sin fila equivalente en la tabla del NCI consultada', blank_in_both: 'en blanco en ambas', no_official_file: 'sin tabla del NCI para cotejar', }; /** Comparison with the NCI's reference risks (experimental): the reference by horizon beside the * institutional models', the difference only where the two are the same estimate. */ @Component({ selector: 'app-reference-risk', imports: [DecimalPipe], template: ` @let v = view();

Comparación de probabilidades de referencia

Estado
{{ statusText(v.status) }}
@if (v.scenario; as s) {
Escenario clínico
{{ s.label }}
} @if (v.source?.outcome; as out) {
Desenlace de la referencia
{{ outcomeText(out) }}
} @if (v.evaluationDate ?? v.index?.sampleDate; as day) {
Fecha de evaluación
{{ day }}
} @if (v.cutoff) {
Fecha de corte
{{ v.cutoff }}
} @if (v.source; as src) {
Fuente y versión
Tablas NCI (libro {{ src.file }}, {{ src.id }}); no validadas
}
@if (v.reasons.length) {
    @for (r of v.reasons; track r) {
  • {{ reasonText(r) }}
  • }
} @if (v.horizons.length) { @let g = grouped(); @for (h of g.reference; track h.years) { }
Horizonte Referencia NCI
{{ h.label }} @if (h.reference !== undefined) { {{ h.reference * 100 | number: '1.2-2' }} % } @else { No publicado }

Modelos institucionales

@if (g.withoutModel.length || !g.models.length) {

No disponible

    @for (r of g.withoutModel; track r) {
  • {{ reasonText(r) }}
  • }
} @if (g.common.length) {

Motivos que comparten todas las comparaciones no válidas:

    @for (r of g.common; track r) {
  • {{ reasonText(r) }}
  • }
} @for (m of g.models; track m.model) {
{{ m.title }} {{ outcomeText(m.outcome) }}
@if (m.reasons.length) {

No comparable en estos horizontes:

    @for (r of m.reasons; track r) {
  • {{ reasonText(r) }}
  • }
} @for (c of m.rows; track c.years) { }
Horizonte Modelo institucional Diferencia (puntos porcentuales)
{{ c.label }} @if (c.institutional !== undefined) { {{ c.institutional * 100 | number: '1.2-2' }} % @if (c.low !== undefined && c.high !== undefined) { (IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{ c.high * 100 | number: '1.2-2' }} %) } } @else { No disponible } @if (c.status === 'comparable' && c.differencePp !== undefined) { {{ c.differencePp > 0 ? '+' : '' }}{{ c.differencePp | number: '1.2-2' }} } @else { No comparable @if (c.reasons.length) {
    @for (r of c.reasons; track r) {
  • {{ reasonText(r) }}
  • }
} }
}

La diferencia es la probabilidad institucional menos la probabilidad NCI y solo se calcula si ambos estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).

} @if (v.used.length || v.assumptions.length || v.scenario || v.row) {
Antecedentes utilizados @if (v.scenario; as s) {
    @for (k of s.keys; track k.name) {
  • {{ k.name }}: {{ k.value }}
  • }
} @if (v.index; as i) {

Citología evaluada: toma {{ i.sampleDate }}, reporte {{ i.reportDate }}, resultado {{ i.result }} @if (i.age !== undefined) { , edad {{ i.age }} años } .

}
    @for (u of v.used; track $index) {
  • {{ u.label }}: {{ u.details }}
  • }
@if (v.row; as r) {

Fila de origen: «{{ r.sheet }}», fila {{ r.number }} @if (r.matchedVia === 'table_group') { (categoría agrupada definida por la propia tabla) } — {{ official(r.officialCheck) }}.

} @for (a of v.assumptions; track a) {

Sin verificar: {{ a }}

}
}
`, styles: ` .reference { border: 1px dashed #9aa3ab; border-radius: 6px; margin: 16px 0; padding: 12px 16px; } h3 { margin: 0 0 8px; } .meta { display: flex; flex-wrap: wrap; gap: 8px 24px; margin: 0 0 8px; } .meta dt { color: var(--color-text-secondary); font-size: 12px; } .meta dd { font-weight: 500; margin: 0; } table { border-collapse: collapse; width: 100%; table-layout: fixed; } th, td { padding: 6px 8px; text-align: left; vertical-align: top; } .model { border-top: 1px solid #dce3e7; margin-top: 8px; padding-top: 4px; } h4, h5 { margin: 12px 0 4px; } h5 .muted { font-weight: 400; margin-left: 8px; } .why { margin: 4px 0; padding-left: 18px; } .note { font-size: 12px; } .used { margin-top: 8px; } .used summary { cursor: pointer; } @media (max-width: 700px) { .reference { padding: 8px 10px; } table, thead, tbody, tr, th, td { display: block; } thead { display: none; } tr { border-bottom: 1px solid #dce3e7; padding: 6px 0; } td { padding: 2px 0; } td::before { color: var(--color-text-secondary); content: attr(data-label); display: block; font-size: 12px; } } `, }) export class ReferenceRisk { readonly view = input.required(); protected readonly grouped = computed(() => groupReference(this.view())); protected outcomeText(outcome?: string) { return outcomeText(outcome); } protected statusText(status: string) { return STATUS_TEXT[status] ?? status; } protected reasonText(reason: string) { return REASON_TEXT[reason] ?? reason; } protected official(check?: string) { return OFFICIAL[check ?? ''] ?? 'sin cotejo'; } }