import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4'; import { code, ext } from '../fhir'; export type PeriodType = 'semester' | 'month'; export function periods(type: PeriodType, years = 6, today = new Date()): string[] { const found: string[] = []; const year = today.getFullYear(); if (type === 'semester') { for (let y = year; y > year - years; y--) { if (y < year || today.getMonth() >= 6) found.push(`${y}-S2`); found.push(`${y}-S1`); } } else { for (let i = 0; i < years * 12; i++) { const d = new Date(year, today.getMonth() - i, 1); found.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`); } } return found; } export function periodLabel(period: string): string { const [year, part] = period.split('-'); if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`; const month = new Date(Number(year), Number(part) - 1, 1).toLocaleString('es-MX', { month: 'short', }); return `${month} ${year}`; } export function periodTypes(measure: Measure): PeriodType[] { return (measure.extension ?? []) .filter((e) => e.url.endsWith('/period-type')) .map((e) => e.valueCode as PeriodType); } export interface Reading { populations: Record; score?: number; low?: number; high?: number; unit?: string; strata: Record>>; rates?: Record>; } function counts(group: { population?: { code?: { coding?: { code?: string }[] }; count?: number }[]; }) { return Object.fromEntries( (group.population ?? []).map((p) => [p.code?.coding?.[0]?.code ?? '', p.count ?? 0]), ); } export function reading(report: MeasureReport | undefined): Reading | undefined { const group: MeasureReportGroup | undefined = report?.group?.[0]; if (!group) return undefined; const score = group.measureScore; const strata: Reading['strata'] = {}; const rates: Record> = {}; for (const s of group.stratifier ?? []) { const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); const scored = (s.stratum ?? []).filter((x) => x.measureScore?.value !== undefined); if (scored.length) { rates[name] = Object.fromEntries( scored.map((x) => [x.value?.text ?? '', x.measureScore!.value!]), ); } strata[name] = Object.fromEntries( (s.stratum ?? []).map((x) => [ x.component?.length ? x.component.map((c) => c.value?.text ?? '').join('|') : (x.value?.text ?? ''), counts(x), ]), ); } return { populations: counts(group), score: score?.value, low: (ext(score, 'ic-bajo') ?? ext(score, 'q1'))?.valueDecimal, high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, unit: score?.unit, strata, ...(Object.keys(rates).length ? { rates } : {}), }; } export const LABELS: Record = { NILM: 'Normal (NILM)', LSIL: 'LIEBG', HSIL: 'LIEAG', normal: 'Normal', carcinoma: 'Carcinoma', no_data: 'Sin dato', no_biopsy: 'Sin biopsia', pre_colposcopy: 'Pre colposcopia', post_colposcopy: 'Post colposcopia', post_treatment: 'Post tratamiento', case: 'Caso (cáncer)', low: 'Bajo', intermediate: 'Intermedio', high: 'Alto', satisfactory: 'satisfactoria', unsatisfactory: 'insatisfactoria', benign: 'Benigno', in_situ: 'Carcinoma in situ', invasive: 'Carcinoma invasor', cancer: 'Diagnóstico confirmado', pending_biopsy: 'Pendiente de biopsia', biopsy_no_result: 'Biopsia sin resultado', benign_biopsy: 'Biopsia benigna', confirmed: 'Diagnóstico confirmado', in_process: 'En proceso', not_confirmed: 'Sin TEA', mchat_only: 'Solo M-CHAT', psychology: 'Psicología (ADOS-2)', neuropediatrics: 'Neuropediatría', eeg: 'EEG', female: 'Femenino', male: 'Masculino', abnormal: 'Anormal', not_scored: 'Sin puntuar', no_valid_eeg: 'Sin EEG válido', posterior_rhythm: 'Ritmo posterior', spindles: 'Husos de sueño', paroxysmal_spikes: 'Puntas paroxísticas', anteroposterior_gradient: 'Gradiente anteroposterior', good: 'Bueno', bad: 'Malo', not_analyzed: 'Sin analizar', ...Object.fromEntries( ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ), }; export const PRIORITY: Record = { high: 'Alta', medium: 'Media', low: 'Baja' }; export const STRATA: Record = { category: 'Categoría', age_group: 'Grupo de edad', sex: 'Sexo', age_sex: 'Grupo de edad y sexo', follow_up_status: 'Estatus de seguimiento', result: 'Citología de alto grado', birads: 'BI-RADS de la mastografía', }; export const name = (value: string) => LABELS[value] ?? value;