import { HttpErrorResponse } from '@angular/common/http'; import type { Parameters, ParametersParameter } from 'fhir/r4'; /** The exclusion criteria `$eligibility` names, as the screens say them. */ const CRITERIA: Record = { hysterectomy: 'Histerectomía previa al índice', under_18: 'Edad menor de 18 años al índice', prior_outcome: 'Resultado CIN2+ previo al índice', no_index_result: 'Sin resultado de citología o VPH en la visita índice', unreported_biopsy: 'Biopsia solicitada sin resultado', outcome_by_index: 'Resultado CIN2+ hasta la visita índice', cancer_history: 'Antecedente de cáncer cervicouterino', prior_treatment: 'Tratamiento previo a la visita índice', no_referral: 'Sin citología de referencia previa a la colposcopia', referral_not_graded: 'Citología de referencia de bajo grado sin VPH positivo', no_cotest: 'Sin cotest de citología y VPH en la visita índice', no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido', outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice', no_birth_date: 'Fecha de nacimiento desconocida', died_by_index: 'Defunción en o antes de la visita índice', not_evaluated: 'Escenario que la plataforma no evalúa por ahora', }; /** One indexed visit of a scenario: the backend's decision and its reasons, as they are. */ export interface Visit { scenario: string; indexDate: string; eligible: boolean; reasons: string[]; } /** What `$eligibility` answered; "eligible" is never inferred, only read. */ export type EligibilityState = | { kind: 'loading' | 'error' | 'unavailable' | 'none' } | { kind: 'gold'; text?: string } | { kind: 'evaluated'; visits: Visit[] }; type Part = ParametersParameter; const parts = (of: Part[] | undefined, name: string) => (of ?? []).filter((p) => p.name === name); const first = (of: Part[] | undefined, name: string) => parts(of, name)[0]; /** The answer's visits, latest first. An answer outside the contract is "unavailable". */ export function eligibilityView(answer: Parameters | null | undefined): EligibilityState { const top = answer?.resourceType === 'Parameters' ? answer.parameter : undefined; if (!Array.isArray(top)) return { kind: 'unavailable' }; const status = first(top, 'status')?.valueCode; const candidates = parts(top, 'candidate'); if (status === 'no_candidate' && !candidates.length) return { kind: 'none' }; if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' }; const visits: Visit[] = []; for (const { part } of candidates) { const scenario = first(part, 'scenario')?.valueCoding?.code; const indexDate = first(part, 'index-date')?.valueDate; const eligible = first(part, 'eligible')?.valueBoolean; if (!scenario || !indexDate || eligible === undefined) return { kind: 'unavailable' }; const reasons = parts(part, 'criterion') .map((r) => r.valueCoding) .filter((k) => !!k?.code) .map((k) => CRITERIA[k!.code!] ?? k!.display ?? k!.code!); visits.push({ scenario, indexDate, eligible, reasons }); } return { kind: 'evaluated', visits: visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate)), }; } /** A failed answer: the gold to rebuild (409), no such operation for her (404, 422), or the call * itself (anything else). */ export function eligibilityFailure(error: unknown): EligibilityState { if (!(error instanceof HttpErrorResponse)) return { kind: 'error' }; if (error.status === 409) return { kind: 'gold', text: error.error?.issue?.[0]?.diagnostics }; return error.status === 404 || error.status === 422 ? { kind: 'unavailable' } : { kind: 'error' }; } /** The scenarios that speak for a follow-up status, the first with a visit by the day wins. */ const SPEAKS_FOR: Record = { pre_colposcopy: ['pre_colposcopy', 'surveillance'], post_colposcopy: ['post_colposcopy'], }; /** Why she has no risk estimate in her scenario by `day`; nothing when she is eligible or no visit * of it is known. A treated patient has none, whatever was indexed. */ export function ineligibility(state: EligibilityState, status: string, day: string) { if (status === 'post_treatment') return 'No disponible por: paciente ya tratada.'; if (state.kind !== 'evaluated') return undefined; for (const scenario of SPEAKS_FOR[status] ?? []) { const latest = state.visits.find((v) => v.scenario === scenario && v.indexDate <= day); if (latest) return latest.eligible ? undefined : `No disponible por: ${latest.reasons.join('; ')}.`; } return undefined; } /** Which cytology her estimates speak of, against her latest by the cut-off: after the first * post-colposcopy visit nothing is evaluated; otherwise a later cytology is only said. */ export function currency(estimates: { model: string; index: string }[], cytologies: string[]) { const sample = estimates .map((e) => e.index.slice(0, 10)) .sort() .at(-1); if (!sample) return {}; const latest = cytologies .map((d) => d.slice(0, 10)) .sort() .at(-1); const said = `Estimación de la citología del ${sample}.`; if (!latest || latest <= sample) return { sample, note: said }; if (estimates.some((e) => e.model.includes('post_colposcopy'))) return { sample, excluded: `No disponible por: hay una citología posterior a la primera visita poscolposcopía (${latest}) y solo se evalúa esa primera visita.`, }; return { sample, note: `${said} Hay una citología posterior, del ${latest}, que no se evalúa.` }; }