"""Read the breast screening cohort from the existing silver tables. The current silver tables keep only the last version of each fact. Filtering by load date prevents future facts from appearing at an earlier cutoff, but cannot restore a previous value after an update. """ from datetime import date, datetime, time, timedelta, timezone from sqlalchemy import select from indicadores_kit.cama.consultas.plata import biopsias, mastografias from indicadores_kit.cama.familias.histopatologia_birads.consulta import BIRADS from indicadores_kit.cama.tablas import TABLAS COHORT = "cama_birads_v1" SCENARIO = "diagnostico" THRESHOLD = 5 def _date(value): return date.fromisoformat(value) if isinstance(value, str) else value def _known(value, cutoff): if value is None: return False if isinstance(value, str): value = datetime.fromisoformat(value) if value.tzinfo is None: value = value.replace(tzinfo=timezone.utc) return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc) def _age_group(birth, cutoff): if birth is None or birth > cutoff: return "SIN_DATO" age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day)) if age < 40: return "MENOR_40" if age >= 70: return "70+" return f"{age // 10 * 10}-{age // 10 * 10 + 9}" class CamaCohort: """Materialize one row per eligible patient, using a caller-owned session.""" def __init__(self, session): self.session = session def rows(self, cutoff: date): t = TABLAS loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()} procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()} observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()} people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()} def procedure_known(identifier): p = procedures.get(identifier) return bool(p and _known(loads.get(p.carga_id), cutoff)) def observation_known(identifier, result, patient): o = observations.get((identifier, result)) return bool(o and o.pac_id == patient and _known(loads.get(o.carga_id), cutoff)) def load_time(record): value = loads.get(record.carga_id) if record else None return value.isoformat() if value else None candidates = {} for row in self.session.execute(select(mastografias(t))).mappings(): taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte']) if not (taken and reported and taken <= reported <= cutoff and row['birads'] and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id']) and procedures[row['reporte_id']].pac_id == row['pac_id'] and observation_known(row['reporte_id'], 'mastografia.birads', row['pac_id'])): continue key = (taken, str(row['fuente_id']), reported, row['reporte_id']) prior = candidates.get(row['pac_id']) if prior is None or key > prior[0]: candidates[row['pac_id']] = (key, row) reports = {} orders = {} for p in procedures.values(): when = _date(p.fecha) if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when or when > cutoff or not procedure_known(p.procedimiento_id)): continue key = (p.pac_id, p.padre_id) rank = (when, str(p.fuente_id), p.procedimiento_id) if key not in orders or rank > orders[key][0]: orders[key] = (rank, p) for row in self.session.execute(select(biopsias(t))).mappings(): reported, ordered, taken = (_date(row['fecha_reporte']), _date(row['fecha_solicitud']), _date(row['fecha_toma'])) procedure = procedures.get(row['procedimiento_id']) order = procedures.get(procedure.padre_id) if procedure else None if not (taken and reported and ordered and taken <= ordered <= reported <= cutoff and row['toma_id'] and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id']) and order and order.pac_id == row['pac_id'] and procedure_known(order.procedimiento_id)): continue key = (row['pac_id'], row['toma_id']) rank = (reported, str(row['fuente_id']), row['procedimiento_id']) if key not in reports or rank > reports[key][0]: reports[key] = (rank, row) rows = [] for patient, (_, m) in candidates.items(): code = BIRADS.get(m['birads']) if not code or patient not in people: continue b = reports.get((patient, m['procedimiento_id'])) b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None if not order: found_order = orders.get((patient, m['procedimiento_id'])) order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None rows.append({ 'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(), 'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(), 'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff), 'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None, 'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None, 'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]), 'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]), 'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))), 'biopsia_solicitud_carga_inicio': load_time(order), 'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None, 'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado'))) if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None, }) return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))