"""Ruta individual acreditada por los vínculos de la plata de CaCu.""" from collections import defaultdict from datetime import date from hmac import compare_digest, digest from secrets import token_bytes from sqlalchemy import and_, literal, or_, select, union_all from webapi.follow_up.pivot import hijos_de, pivote from webapi.orchestration.tables.cacu import TABLAS ETAPAS = ("citologia", "colposcopia", "biopsia", "diagnostico") _CLAVE = token_bytes(32) def _ref(tipo, *partes): mensaje = ":".join(map(str, (tipo, *partes))).encode() return digest(_CLAVE, mensaje, "sha256").hex() def _eventos(sesion, tomas, corte, tablas): """Una consulta por página. Solo sigue padres del mismo paciente.""" toma = pivote(tablas, "citologia", "toma", nombre="ruta_toma") cito = pivote(tablas, "citologia", "reporte", nombre="ruta_citologia") orden = pivote(tablas, "biopsia", "orden", nombre="ruta_orden_biopsia") biopsia = pivote(tablas, "biopsia", "reporte", nombre="ruta_reporte_biopsia") observacion = tablas.Observacion.__table__ def hijo(padre, evento): return and_(hijos_de(padre, evento), padre.c.pac_id == evento.c.pac_id) desde_toma = toma.c.procedimiento_id.in_(tomas) hasta_corte = corte.isoformat() con_resultado = select(observacion.c.procedimiento_id).where( observacion.c.procedimiento_id == cito.c.procedimiento_id, observacion.c.pac_id == cito.c.pac_id, observacion.c.resultado_id == "citologia.bethesda", or_(observacion.c.valor_id.is_not(None), observacion.c.valor_fuente.is_not(None)), ).exists() reportes_cito = ( select(toma.c.procedimiento_id, literal("citologia"), cito.c.procedimiento_id, cito.c.fecha) .select_from(toma.join(cito, hijo(toma, cito))) .where(desde_toma, cito.c.fecha >= toma.c.fecha, cito.c.fecha <= hasta_corte, con_resultado) ) ordenes = toma.join(orden, hijo(toma, orden)) ordenes_biopsia = ( select(toma.c.procedimiento_id, literal("orden"), orden.c.procedimiento_id, orden.c.fecha) .select_from(ordenes) .where(desde_toma, orden.c.fecha >= toma.c.fecha, orden.c.fecha <= hasta_corte) ) reportes_biopsia = ( select(toma.c.procedimiento_id, literal("biopsia"), biopsia.c.procedimiento_id, biopsia.c.fecha) .select_from(ordenes.join(biopsia, hijo(orden, biopsia))) .where(desde_toma, biopsia.c.fecha >= toma.c.fecha, biopsia.c.fecha <= hasta_corte, or_(orden.c.fecha.is_(None), and_(orden.c.fecha >= toma.c.fecha, biopsia.c.fecha >= orden.c.fecha))) ) por_toma = defaultdict(lambda: defaultdict(list)) for toma_id, tipo, evento_id, fecha in sesion.execute(union_all(reportes_cito, ordenes_biopsia, reportes_biopsia)): fecha = date.fromisoformat(str(fecha)[:10]) por_toma[toma_id][tipo].append((fecha, evento_id)) return por_toma def rutas_de(sesion, tomas, corte, tablas=TABLAS, *, detalle=False): """Proyecta tomas seleccionadas {id: (pac_id, fecha)} sin leer otras filas.""" if not tomas: return {} eventos = _eventos(sesion, tomas, corte, tablas) return { toma_id: _ruta(toma_id, pac_id, toma, corte, eventos[toma_id], detalle) for toma_id, (pac_id, toma) in tomas.items() } def _ruta(toma_id, pac_id, toma, corte, eventos, detalle): ruta_id = _ref("ruta", pac_id, toma_id, corte) ultimo = anterior = toma etapas = [] for codigo in ETAPAS: registros = sorted(eventos[codigo]) fecha, evento_id = registros[0] if registros else (None, None) pendiente = codigo == "biopsia" and bool(eventos["orden"]) estado = "registrada" if fecha else "pendiente" if pendiente else "desconocida" etapa = {"codigo": codigo, "estado": estado, "fecha": fecha.isoformat() if fecha else None} if detalle: etapa.update( dias_desde_toma=(fecha - toma).days if fecha else None, dias_desde_anterior=(fecha - anterior).days if fecha and anterior and fecha >= anterior else None, evento_ref=_ref("evento", ruta_id, evento_id) if evento_id is not None else None, eventos=[{"ref": _ref("evento", ruta_id, eid), "fecha": f.isoformat()} for f, eid in registros], ) if codigo == "biopsia": etapa["ordenes"] = [ {"ref": _ref("evento", ruta_id, eid), "fecha": f.isoformat()} for f, eid in sorted(eventos["orden"]) ] etapas.append(etapa) anterior = fecha if fecha is not None: ultimo = max(ultimo, fecha) ruta = {"id": ruta_id, "corte": corte.isoformat(), "toma": toma.isoformat(), "etapas": etapas, "dias_desde_ultimo_evento": (corte - ultimo).days} if detalle: ruta["toma_ref"] = _ref("evento", ruta_id, toma_id) else: ruta["detalle_url"] = f"/cacu/seguimiento/rutas/{pac_id}/{ruta_id}?corte={corte.isoformat()}" return ruta def detalle_de(sesion, pac_id, ruta_id, corte, tablas=TABLAS): toma = tablas.Procedimiento.__table__ candidatas = select(toma.c.procedimiento_id, toma.c.fecha).where( toma.c.pac_id == pac_id, toma.c.estudio_id == "citologia", toma.c.clase == "toma", toma.c.fecha <= corte, ) for toma_id, fecha in sesion.execute(candidatas): if compare_digest(_ref("ruta", pac_id, toma_id, corte), ruta_id): return rutas_de(sesion, {toma_id: (pac_id, fecha)}, corte, tablas, detalle=True)[toma_id] return None