Compare commits

...

22 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 1bbf5d4877 Pin WebApp with the CaMa selective rollback 2026-11-20 10:02:50 -06:00
angel 13e8c4fd87 Merge pull request 'Pin WebApp with final CaMa demo changes' (#15) from feature/cama-clasificacion-histologica-webapp-pin into dev 2026-11-20 00:53:52 -06:00
Angel Capetillo Zavala 70f10e57d1 Pin WebApp with final CaMa demo changes 2026-11-20 00:52:04 -06:00
angel ef0cdff393 Merge pull request 'Pin WebApp with the CaMa BI-RADS and histopathology updates' (#14) from feature/cama-histopathology-webapp-pin into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/14
2026-11-19 19:48:36 -06:00
Angel Capetillo Zavala 746ad93c4e Pin WebApp with the CaMa BI-RADS and histopathology updates 2026-11-19 19:45:33 -06:00
angel 1a8bad2815 Merge pull request 'Pin WebApp with the CaMa diagnosis-to-treatment card' (#13) from feature/cama-diagnosis-treatment-webapp-pin into dev 2026-11-19 17:52:06 -06:00
Angel Capetillo Zavala 8e43dccfe0 Pin WebApp with the CaMa diagnosis-to-treatment card 2026-11-19 17:50:26 -06:00
Angel Capetillo Zavala b8f58585ad Update WebApp pin for CaMa BI-RADS charts 2026-11-19 16:07:01 -06:00
Angel Capetillo Zavala 6bd3f40a6c Pin WebApp with visual login test fixes 2026-11-19 11:44:47 -06:00
Erick ivan 87cfae3969 chore(submodules): bump WebApi and WebApp with the front-only login
WebApi drops the session login and stays open for the data service; WebApp keeps the login and the per-account domains in the browser. .env.example no longer documents the session variables.
2026-11-19 10:32:44 -06:00
Erick ivan 47046eaea7 chore(submodules): bump WebApi and WebApp with the session login
WebApi brings /auth and the per-domain scope; WebApp brings the sign-in screen, the route guard and the domain filtering in the import workspace and governance. .env.example documents WEBAPI_USUARIOS and the session key.
2026-11-19 09:37:30 -06:00
angel b81c626013 Merge pull request 'chore(submodules): update WebApp with the CI spec fixes' (#12) from fix/ci-spec-contracts into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/12
2026-11-19 00:11:39 -06:00
Angel Capetillo Zavala aa840b9f31 chore(submodules): update WebApp with the CI spec fixes 2026-11-18 23:41:47 -06:00
Angel Capetillo Zavala d2f597cec8 chore(submodules): update WebApp dev color fixes 2026-11-18 15:30:00 -06:00
Angel Capetillo Zavala cc5738d036 chore(submodules): update WebApp for CaMa BI-RADS donut 2026-11-18 15:13:27 -06:00
Angel Capetillo Zavala 3cd094a8c5 chore: actualizar WebApp con ajustes de CaMa 2026-11-18 14:29:34 -06:00
Angel Capetillo Zavala 9ace5da517 chore: actualizar WebApp con ajustes de CaMa 2026-11-18 09:25:45 -06:00
Angel Capetillo Zavala 0017b0ca4c Update WebApp CaMa indicator labels 2026-11-17 12:44:43 -06:00
Angel Capetillo Zavala 9903e22c2a Add CaMa cohort and L3 measures with integrated API and dashboard
Publish deterministic cohort candidates and detection, result-to-diagnosis and BI-RADS histopathology measures. Pin locally prepared WebApi and WebApp commits based on current dev; retain models and shared persistence changes from upstream. Document compatibility, required views and stored-report behavior.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes 8885162147 wording fixes 2026-11-17 02:20:15 -06:00
Roberto Treviño Cervantes 20f244c014 wording fixes 2026-11-17 02:18:05 -06:00
roberto 9baeeb7ff0 Merge pull request 'Kit exit: retire indicadores_kit, converge TEA/CaMa work onto dev' (#11) from feature/kit-exit-integration into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/11
2026-11-16 21:09:40 -06:00
19 changed files with 625 additions and 15 deletions
@@ -14,6 +14,7 @@ from persistance.edges.gold.cohorts import (
CohortMember,
PatientMembership,
PatientRisk,
PendingBatch,
RiskOutsideCohort,
RiskHorizon,
change_state_in,
@@ -34,6 +35,7 @@ __all__ = [
"MeasureReportRepository",
"PatientMembership",
"PatientRisk",
"PendingBatch",
"PublicationRepository",
"ReferenceRepository",
"RiskOutsideCohort",
@@ -114,6 +114,22 @@ class CohortRepository(Repository):
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
for v in values})
def pending_batches(self) -> list["PendingBatch"]:
"""Batches with no evaluation confirmed or voided yet (ADR-MD-008): created by estimating, waiting for
someone's decision. Newest first."""
lote, e = self.cohortes.EvaluacionRiesgoLote, self.cohortes.EvaluacionRiesgo
with self._session_factory() as sesion:
lotes = sesion.exec(select(lote).order_by(lote.lote_id.desc())).all()
pending = []
for fila in lotes:
latest = _latest_versions(sesion, e, fila.lote_id)
decided = sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == fila.lote_id, e.estado != PRELIMINAR).limit(1)).first()
if decided is None:
pending.append(PendingBatch(fila.lote_id, fila.modelo_nombre, fila.modelo_version,
fila.evaluado_en, fila.n_evaluaciones))
return pending
def current_risk(self, pac_id: int) -> "PatientRisk | None":
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
@@ -159,6 +175,18 @@ class RiskHorizon:
estado: str
@dataclass(frozen=True)
class PendingBatch:
"""A risk batch waiting for someone to confirm or void it; no evaluation has reached `final` or
`entered-in-error` yet."""
lote_id: int
modelo_nombre: str
modelo_version: str
evaluado_en: datetime
n_evaluaciones: int
@dataclass(frozen=True)
class PatientRisk:
"""A patient's risks in the current batch, with the model that produced them."""
+19 -1
View File
@@ -15,7 +15,7 @@ from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, Cohor
from core.indicadores.cohortes import TablasCohorte
from sqlmodel import Session, create_engine
from persistance.edges.gold import CohortRepository, RiskHorizon
from persistance.edges.gold import CohortRepository, PendingBatch, RiskHorizon
URL = "cacu/cohorte_vigilancia"
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
@@ -90,3 +90,21 @@ def test_an_annulled_batch_is_no_longer_current(repository):
repository.change_state(first, "entered-in-error", "modelo equivocado")
assert repository.current_risk(10) is None
def test_pending_batches_are_the_ones_with_no_decision_yet(repository):
"""Pins down: a batch stays pending until it's confirmed or voided, newest first, and dropping off the list is
permanent either way. Fails if a confirmed or a voided batch is still listed, or the order is reversed."""
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
second = _batch(repository, "2", [(10, 1.0, 0.2, None, None)])
third = _batch(repository, "3", [(10, 1.0, 0.3, None, None)])
repository.change_state(second, "final", "revisado")
pending = repository.pending_batches()
assert [(b.lote_id, b.modelo_version, b.n_evaluaciones) for b in pending] == [(third, "3", 1), (first, "1", 1)]
assert all(isinstance(b, PendingBatch) and b.modelo_nombre == "cacu-cin2_logistic" for b in pending)
repository.change_state(third, "entered-in-error", "modelo equivocado")
assert [b.lote_id for b in repository.pending_batches()] == [first]
+6
View File
@@ -56,6 +56,12 @@ vars:
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
horizonte_toma_diagnostico_dias: 180
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
# Biopsy grades from least to most severe (models/cama/gold/eventos/cama_resultado_biopsia.sql): the keys of
# cama.catalogos.biopsia.
biopsia_gravedad: ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
# The grades that count as cancer in the detection rate (models/cama/gold/eventos/cama_deteccion_biopsia.sql): the
# values of the parameter cama.biopsia_cancer (a test keeps them equal).
grados_cancer: ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
# The analysis' stratifiers (models/cama/silver/cama_estratificadores.sql), from the catalog's provisional results
# read from reports; placeholders until the domain expert validates them. `estadios`: each clinical stage's
# group; `etapa_temprana`: the groups counted as early, the rest of the known ones advanced. The surrogate
@@ -0,0 +1,16 @@
-- One row per biopsy report, dated by the report, flagged for the detection rate: `con_resultado` when its grade is one
-- of `vars.cama.biopsia_gravedad` (benign, in situ or invasive; a report without a grade, or with one the catalog doesn't
-- know, has none) and `maligno` when it is one of `vars.cama.grados_cancer` (the keys of the parameter
-- `cama.biopsia_cancer`). The flags are of the model, not rows of the parameter table, so a database that already holds
-- the other CaMa views answers the measure with only this view added.
select
r.procedimiento_id,
r.fuente_id,
r.pac_id,
r.fecha_reporte,
r.grado,
r.reporte_conocido_en,
case when r.grado in {{ sql_list(var('cama')['biopsia_gravedad']) }} then 1 else 0 end as con_resultado,
case when r.grado in {{ sql_list(var('cama')['grados_cancer']) }} then 1 else 0 end as maligno
from {{ ref('cama_reportes_biopsia') }} r
@@ -0,0 +1,88 @@
version: 2
models:
- name: cama_deteccion_biopsia
description: "Reportes de biopsia de mama fechados por el reporte, con las marcas de resultado conocido y de resultado maligno."
config:
materialized: view
semantic_models:
- name: cama_deteccion_biopsia
description: "Breast biopsy reports with the flags of a known and of a malignant result: what the detection rate counts."
model: ref('cama_deteccion_biopsia')
defaults:
agg_time_dimension: fecha_reporte
entities:
- name: biopsia_deteccion
type: primary
expr: procedimiento_id
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_reporte
type: time
type_params:
time_granularity: day
- name: reporte_conocido_en
type: time
type_params:
time_granularity: day
- name: grado
type: categorical
- name: con_resultado
type: categorical
- name: maligno
type: categorical
measures:
- name: reportes_de_biopsia
description: "Distinct biopsy reports: each report counts, not each patient."
agg: count_distinct
expr: procedimiento_id
metrics:
- name: cama_tasa_deteccion_histopatologica_denominador
label: "Reportes de biopsia con resultado conocido"
type: simple
type_params:
measure: reportes_de_biopsia
filter: "{{ Dimension('biopsia_deteccion__con_resultado') }} = 1"
config:
meta:
poblaciones_fhir: [initial-population, denominator]
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
- name: cama_tasa_deteccion_histopatologica_numerador
label: "De ellos, con resultado maligno"
type: simple
type_params:
measure: reportes_de_biopsia
filter: "{{ Dimension('biopsia_deteccion__maligno') }} = 1"
config:
meta:
poblaciones_fhir: [numerator]
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
- name: cama_tasa_deteccion_histopatologica
# dbt wants labels unique in the project; the title on screen is `meta.titulo`.
label: "CaMa: tasa de detección histopatológica"
description: >-
De los reportes de biopsia de mama fechados en el periodo con un resultado conocido (benigno, carcinoma in situ o
carcinoma invasor), cuántos son malignos (carcinoma in situ o invasor). La unidad es el reporte de biopsia, no la
paciente; los reportes sin grado no entran. Es una proporción entre las biopsias con resultado: no es una tasa
sobre las mujeres tamizadas ni la proporción de mastografías de sospecha que tienen biopsia
(CAMA_CONFIRMACION_BIRADS45).
type: ratio
type_params:
numerator: cama_tasa_deteccion_histopatologica_numerador
denominator: cama_tasa_deteccion_histopatologica_denominador
config:
meta:
measure_url: cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA
titulo: "Tasa de detección histopatológica"
version: 0.1.0
scoring: proportion
basis: examen
grupo: principal
contrato: C1
tipos_periodo: [semestre, mes]
@@ -56,6 +56,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [reporte_conocido_en]
# One row per report: its grade.
@@ -65,3 +66,10 @@ metrics:
elige: ultimo_valido
valido: "{% raw %}{{ Dimension('biopsia__grado') }} is not null{% endraw %}"
orden: [fecha_reporte]
# The captions and colours of `cama.catalogos.biopsia` and `cama.catalogos.sin_dato`. A grade outside them
# (DESCONOCIDO) is published as it comes.
etiquetas:
BENIGNO: {etiqueta: "Benigno", color: "#9DBFE3"}
CARCINOMA_IN_SITU: {etiqueta: "Carcinoma in situ", color: "#D98E4A"}
CARCINOMA_INVASOR: {etiqueta: "Carcinoma invasor", color: "#7A2E0E"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
@@ -0,0 +1,44 @@
-- One row per mammogram's report and each biopsy report it led to (one row with nulls when it led to none): the grain of
-- the measures that cross a mammogram's BI-RADS with the result of its biopsy. A biopsy counts for the mammogram that
-- led to it (mammogram -> biopsy order -> biopsy report), of the same patient. When each became known: the start of the
-- loads that wrote them. `biopsia_gravedad` orders a patient's biopsies from least to most severe by
-- `vars.cama.biopsia_gravedad`: 0 for a grade the catalog doesn't know, -1 for a report without one, null when the
-- mammogram led to none. `birads_gravedad` orders BI-RADS as `cama_tomas_mastografia` does.
{% set r = var('cama') %}
select
m.procedimiento_id,
m.fuente_id,
m.pac_id,
m.fecha_toma,
toma.inicio as toma_conocida_en,
m.fecha_reporte,
m.birads,
case
{%- for b in r['birads_gravedad'] %}
when m.birads = '{{ b }}' then {{ loop.index }}
{%- endfor %}
else 0
end as birads_gravedad,
reporte.inicio as reporte_conocido_en,
b.fuente_id as biopsia_fuente_id,
b.fecha_reporte as biopsia_fecha_reporte,
b.grado as biopsia_grado,
case
when b.procedimiento_id is null then null
when b.grado is null then -1
{%- for grado in r['biopsia_gravedad'] %}
when b.grado = '{{ grado }}' then {{ loop.index }}
{%- endfor %}
else 0
end as biopsia_gravedad,
biopsia.inicio as biopsia_conocida_en
from {{ ref('cama_mastografias') }} m
join {{ source('silver', 'carga') }} toma
on toma.carga_id = m.toma_carga_id
left join {{ source('silver', 'carga') }} reporte
on reporte.carga_id = m.reporte_carga_id and m.reporte_id is not null
left join {{ ref('cama_biopsias') }} b
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
left join {{ source('silver', 'carga') }} biopsia
on biopsia.carga_id = b.reporte_carga_id
@@ -0,0 +1,120 @@
version: 2
models:
- name: cama_resultado_biopsia
description: "Mastografías con su reporte y el grado de cada biopsia que originaron, con cuándo se supo de cada uno."
config:
materialized: view
semantic_models:
- name: cama_resultado_biopsia
description: "Mammograms with their BI-RADS and the grade of the biopsies they led to: what the histopathological result by BI-RADS counts over."
model: ref('cama_resultado_biopsia')
defaults:
agg_time_dimension: fecha_toma
entities:
- name: mastografia_biopsia
type: primary
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '') || '-' || coalesce(biopsia_fuente_id, '')"
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_toma
type: time
type_params:
time_granularity: day
- name: toma_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_reporte
type: time
type_params:
time_granularity: day
- name: reporte_conocido_en
type: time
type_params:
time_granularity: day
- name: biopsia_fecha_reporte
type: time
type_params:
time_granularity: day
- name: biopsia_conocida_en
type: time
type_params:
time_granularity: day
- name: birads
type: categorical
- name: birads_gravedad
type: categorical
- name: biopsia_grado
type: categorical
- name: biopsia_gravedad
type: categorical
- name: biopsia_fuente_id
type: categorical
- name: fuente_id
type: categorical
measures:
- name: pacientes_con_mastografia_birads
description: "Distinct patients: each counts once per period, however many mammograms or biopsies."
agg: count_distinct
expr: pac_id
metrics:
- name: cama_histopatologia_birads
label: "CaMa: resultado histopatológico por categoría BI-RADS"
description: >-
De las pacientes con una mastografía del periodo con BI-RADS 4, 5 o 6 reportado, cada una en la más grave de sus
mastografías (la misma regla de CAMA_BIRADS456_PACIENTE), cuántas tienen cada resultado en la biopsia que esa
mastografía originó y que se reportó a la fecha de corte (la más grave; entre iguales, la más reciente), por
categoría BI-RADS. «Sin biopsia reportada»: la mastografía no tiene biopsia reportada al corte; «Sin dato»: la
biopsia no trae grado. A la fecha de corte, sin un plazo máximo: una paciente «sin biopsia» puede pasar a un
resultado mientras lleguen reportes.
type: simple
type_params:
measure: pacientes_con_mastografia_birads
config:
meta:
measure_url: cama/CAMA_HISTOPATOLOGIA_BIRADS
titulo: "Resultado histopatológico por categoría BI-RADS"
version: 0.1.0
scoring: composition
basis: paciente
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
birads_4_a_6: cama.birads_4_a_6
categoria:
valor: biopsia_grado
sin_dato: SIN_DATO
elige: mas_grave
valido: "{% raw %}{{ Dimension('mastografia_biopsia__birads') }} is not null{% endraw %}"
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad, fuente_id]
admite: "{% raw %}{{ Dimension('mastografia_biopsia__birads') }} in :birads_4_a_6{% endraw %}"
seguimiento:
existe: biopsia_fecha_reporte
fechada_en: [biopsia_fecha_reporte]
conocida_en: [biopsia_conocida_en]
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
sin_seguimiento: SIN_BIOPSIA
# The captions and colours of cama.catalogos.biopsia and cama.catalogos.sin_dato; a grade outside them is
# published as it comes.
etiquetas:
BENIGNO: {etiqueta: "Benigno", color: "#9DBFE3"}
CARCINOMA_IN_SITU: {etiqueta: "Carcinoma in situ", color: "#D98E4A"}
CARCINOMA_INVASOR: {etiqueta: "Carcinoma invasor", color: "#7A2E0E"}
SIN_BIOPSIA: {etiqueta: "Sin biopsia reportada", color: "#C9CDD2"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
estratos:
# The BI-RADS of the mammogram that gave the patient her place.
birads:
tipo: del_elegido
etiqueta: Categoría BI-RADS
valor: birads
@@ -0,0 +1,73 @@
-- One row per mammogram that has a report: the grain of the time from the mammogram's result to the diagnosis. No
-- period and no cut-off here: they're the question's. The diagnosis is the first diagnosing note of the patient dated
-- on or after the report (a `diagnostico` of the patient's timeline: a diagnosis ICD-10 of `cama.cie_diagnostico`
-- written by a specialty of `cama.especialidades_diagnostico`) and within the horizon of the report. It is a note of
-- the patient, not a link to this mammogram's episode: the notes carry no episode. It is not the date of a biopsy.
-- Days are differences of `dim_fecha.dia_num`. When the report and the note became known: the start of the loads that
-- wrote them. A breast cancer note (`antecedente`) before the mammogram leaves it out, as in the time from the
-- mammogram to the diagnosis.
{% set r = var('cama') %}
-- One observation per mammogram: its earliest dated report, ties by the report's platform identity.
-- Later corrections do not move the observation to another period or duplicate it.
with ordenadas as (
select procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id,
row_number() over (partition by procedimiento_id order by fecha_reporte, reporte_id, reporte_carga_id) as lugar
from {{ ref('cama_mastografias') }}
where reporte_id is not null and fecha_reporte is not null
),
reportada as (
select procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id
from ordenadas where lugar = 1
),
resuelve as (
select m.procedimiento_id, min(l.fecha) as fecha_diagnostico
from reportada m
join {{ ref('cama_linea_de_tiempo') }} l
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha >= m.fecha_reporte
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} dr on dr.fecha = m.fecha_reporte
where dl.dia_num - dr.dia_num < {{ r['horizonte_toma_diagnostico_dias'] }}
group by m.procedimiento_id
),
diagnostico as (
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
from resuelve r
join reportada m on m.procedimiento_id = r.procedimiento_id
join {{ ref('cama_linea_de_tiempo') }} l
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
group by r.procedimiento_id, r.fecha_diagnostico
),
primer_antecedente as (
select pac_id, min(fecha) as fecha
from {{ ref('cama_linea_de_tiempo') }}
where tipo = 'antecedente'
group by pac_id
)
select
m.procedimiento_id,
m.fuente_id,
m.pac_id,
m.fecha_toma,
m.fecha_reporte,
reporte.inicio as reporte_conocido_en,
dia_reporte.dia_num as reporte_dia,
dx.fecha_diagnostico,
dx.diagnostico_conocido_en,
dia_diagnostico.dia_num - dia_reporte.dia_num as dias_reporte_diagnostico,
case when antecedente.fecha < m.fecha_toma then 1 else 0 end as con_antecedente
from reportada m
join {{ source('silver', 'carga') }} reporte
on reporte.carga_id = m.reporte_carga_id
join {{ source('silver', 'dim_fecha') }} dia_reporte
on dia_reporte.fecha = m.fecha_reporte
left join diagnostico dx
on dx.procedimiento_id = m.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
on dia_diagnostico.fecha = dx.fecha_diagnostico
left join primer_antecedente antecedente
on antecedente.pac_id = m.pac_id
@@ -0,0 +1,87 @@
version: 2
models:
- name: cama_resultado_diagnostico
description: "Mastografías con reporte y la primera nota diagnóstica de la paciente a partir de ese reporte, con sus fechas y su conocimiento."
config:
materialized: view
semantic_models:
- name: cama_resultado_diagnostico
description: "Mammograms with a report and the first diagnosing note on or after it: what the time from result to diagnosis counts."
model: ref('cama_resultado_diagnostico')
defaults:
agg_time_dimension: fecha_reporte
entities:
- name: resultado_diagnostico
type: primary
expr: procedimiento_id
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_reporte
type: time
type_params:
time_granularity: day
- name: reporte_conocido_en
type: time
type_params:
time_granularity: day
- name: fecha_diagnostico
type: time
type_params:
time_granularity: day
- name: diagnostico_conocido_en
type: time
type_params:
time_granularity: day
- name: reporte_dia
type: categorical
- name: dias_reporte_diagnostico
type: categorical
- name: con_antecedente
type: categorical
- name: fuente_id
type: categorical
measures:
- name: mastografias_con_reporte
description: "Distinct mammograms by platform procedure identity, through their earliest report."
agg: count_distinct
expr: procedimiento_id
metrics:
- name: cama_dias_resultado_diagnostico
label: "CaMa: tiempo de resultado a diagnóstico"
description: >-
Días naturales del reporte de cada mastografía fechado en el periodo a la primera nota médica diagnóstica de la
paciente a partir de ese reporte: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito
por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. La nota es de la
paciente, no está ligada a la mastografía (las notas no traen episodio) y no es la fecha de la biopsia. Las
mastografías sin nota en el horizonte no se miden. Se excluyen las de pacientes con un diagnóstico de cáncer de
mama anterior a la toma.
type: simple
type_params:
measure: mastografias_con_reporte
filter: "{{ Dimension('resultado_diagnostico__con_antecedente') }} = 0"
config:
meta:
measure_url: cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO
titulo: "Tiempo de resultado a diagnóstico"
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [reporte_conocido_en]
observacion:
valor: dias_reporte_diagnostico
fechada_en: [fecha_diagnostico]
conocida_en: [diagnostico_conocido_en]
horizonte:
dias: "{{ var('cama')['horizonte_toma_diagnostico_dias'] }}"
dia_inicio: reporte_dia
@@ -88,6 +88,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
# Each patient's most severe BI-RADS among her mammograms of the period reported by the cut-off; one without a
@@ -100,6 +101,19 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad, fuente_id]
# The captions and colours of `cama.catalogos.birads` and `cama.catalogos.sin_dato`, in their order. A BI-RADS 4
# without subcategory is no declared category: a report that counts one publishes it as it comes.
etiquetas: &etiquetas_birads
B0: {etiqueta: "BI-RADS 0", color: "#8A9199"}
B1: {etiqueta: "BI-RADS 1", color: "#9DBFE3"}
B2: {etiqueta: "BI-RADS 2", color: "#2F6DB3"}
B3: {etiqueta: "BI-RADS 3", color: "#E8C28E"}
B4A: {etiqueta: "BI-RADS 4A", color: "#E0A060"}
B4B: {etiqueta: "BI-RADS 4B", color: "#CF7D3C"}
B4C: {etiqueta: "BI-RADS 4C", color: "#C26A2B"}
B5: {etiqueta: "BI-RADS 5", color: "#B55A1F"}
B6: {etiqueta: "BI-RADS 6", color: "#7A2E0E"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
- name: cama_birads_456_paciente
label: "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6"
description: >-
@@ -124,6 +138,13 @@ metrics:
orden: [birads_gravedad, fuente_id]
# After choosing the most severe: a patient with B6 and B4 counts in B6.
admite: "{% raw %}{{ Dimension('mastografia__birads') }} in :birads_4_a_6{% endraw %}"
# `cama.catalogos.birads_4_a_6`: what `admite` lets through, so no «Sin dato».
etiquetas: &etiquetas_birads_4_a_6
B4A: {etiqueta: "BI-RADS 4A", color: "#E0A060"}
B4B: {etiqueta: "BI-RADS 4B", color: "#CF7D3C"}
B4C: {etiqueta: "BI-RADS 4C", color: "#C26A2B"}
B5: {etiqueta: "BI-RADS 5", color: "#B55A1F"}
B6: {etiqueta: "BI-RADS 6", color: "#7A2E0E"}
- name: cama_birads_456_mastografia
label: "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6"
description: "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría."
@@ -140,6 +161,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
@@ -152,6 +174,7 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad]
etiquetas: *etiquetas_birads_4_a_6
- name: cama_eu38a
label: "Días de la toma de la mastografía a su resultado"
description: >-
@@ -171,6 +194,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
parametros:
@@ -204,6 +228,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
observacion:
@@ -0,0 +1,7 @@
version: 2
# Views the WebApi reads, not measures: the cycle creates them with the event models (`lee_la_webapi`).
models:
- name: cama_cohorte_birads
description: "Mastografías con BI-RADS reportado y los reportes de biopsia que originaron: los candidatos de la cohorte BI-RADS de la lista de seguimiento."
config: {materialized: view, meta: {lee_la_webapi: true}}
@@ -0,0 +1,27 @@
-- The candidates of the BI-RADS cohort for the follow-up list: one row per mammogram with a reported BI-RADS and
-- each biopsy report that mammogram led to (one row with nulls when it led to none). The cohort itself depends on the
-- cut-off asked for (each patient's latest mammogram reported by it, kept when its BI-RADS is 4 to 6), and a view takes
-- no parameter, so the WebApi picks the rows by date as it does for the other follow-up lists. Nothing here is
-- derived from a rule that isn't in silver: dates and codes are the source's.
select
m.pac_id,
m.procedimiento_id,
m.fuente_id,
m.fecha_toma,
m.reporte_id,
m.fecha_reporte,
m.birads,
p.fecha_nacimiento,
b.procedimiento_id as biopsia_id,
b.fuente_id as biopsia_fuente_id,
b.fecha_reporte as biopsia_fecha_reporte,
b.grado as biopsia_grado
from {{ ref('cama_mastografias') }} m
join {{ source('silver', 'persona') }} p
on p.pac_id = m.pac_id
left join {{ ref('cama_biopsias') }} b
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
where m.birads is not null
and m.fecha_toma is not null
and m.fecha_reporte is not null
+1 -1
Submodule WebApi updated: 9737b5a67f...7101913fff
+1 -1
Submodule WebApp updated: be77c50b45...d4d3ea3837
+15 -11
View File
@@ -276,24 +276,28 @@ guardan con su corte, así que una pregunta repetida no vuelve a calcular.
El riesgo individual (ficha de la paciente y lista de seguimiento) necesita
una versión del modelo `cacu-cin2_logistic` en producción. Después de la
primera carga, entrénela una vez:
primera carga, entrénela una vez, desde Gobernanza → Versiones de modelo →
**Entrenar cacu/cin2_logistic** (o, con acceso a la línea de comandos del
servidor, `docker compose run --rm entrenar`; ambos corren el mismo
entrenamiento). Exporta la cohorte armada, entrena con ella, registra la
versión en MLflow (dentro de `ISSSTELEON_DATOS`) y la pone en producción; si
ya existía una versión entrenada con esa cohorte, no hace nada. Si la versión
entrenada no tiene aún sus reportes de validación adjuntos, se queda
entrenada pero no en producción: adjúntelos desde el detalle de la versión y
promuévala desde ahí.
```sh
docker compose run --rm entrenar
```
Exporta la cohorte armada, entrena con ella, registra la versión en MLflow
(dentro de `ISSSTELEON_DATOS`) y la pone en producción; si ya existía una
versión entrenada con esa cohorte, no hace nada. Desde entonces cada corrida
del servicio `indicadores` escribe un lote de riesgos **preliminar**. Los
riesgos se muestran solo cuando alguien confirma el lote:
Desde entonces cada corrida del servicio `indicadores` escribe un lote de
riesgos **preliminar**. Los riesgos se muestran solo cuando alguien confirma
el lote, desde Gobernanza → **Lotes de riesgo** (confirmar o anular, con un
motivo), o con acceso a la línea de comandos:
```sh
docker compose exec webapi uv run --no-sync python -m webapi.orchestration confirm-risks cacu <lote_id> --reason "revisado por clínica"
```
El `lote_id` aparece en la corrida (`reportes/indicadores.jsonl`, paso
`estimate`). `--void` anula un lote en vez de confirmarlo.
`estimate`) y en la pestaña de Gobernanza. `--void` anula un lote en vez de
confirmarlo.
## 7. Datos, respaldos y reinstalación
+57
View File
@@ -0,0 +1,57 @@
# CaMa L1–L3 integration with dev
Prepared from ISSSTELEON dev `8885162147552cf57f4196c27a0152a07c08de48`,
WebApi dev `0571b5e6af6005737d918997f1f13daec5b4be16` and
WebApp dev `dc37c5493801f40f43cb0a67452b15ad2392b650`.
The existing model submodule and dev changes to governance, risk batches, cohort persistence and training are retained.
The local 18092 deployment and its images/data are not changed by these commits.
## Reconciled contracts
- The L1 follow-up and L2 descriptive blueprints are the only CaMa handlers registered by `create_app`.
The former `webapi/cama_analysis.py` is renamed to `cama_analysis_legacy.py` to avoid colliding with the new package.
Its explicit Python blueprint consumers remain compatible through package exports; legacy tests remain active.
An explicit `CAMA_COHORT_READER` override (including disabling it) retains dev's previous list/detail/aggregate
contract. The marked historical default selects the new production implementation. New descriptive sections require
the dbt views and are not provided by the old reader override.
- `/cama/pacientes/<pac_id>` is retained and uses the new follow-up selection, revision and suppression, returning `item`.
It returns 404 for a patient outside that selection. It does not bypass suppression by looking up a patient first.
- The existing optional `CAMA_COHORT_ACCESS` callback is retained for both new blueprints. There is no new auth mechanism.
- Clients must refresh the cohort context after upgrading; former revision hashes will produce 409.
The new age/filter options come from platform parameters; consumers should use the advertised options.
- CaMa defines its three new FHIR measures once, for both Resumen and Historico.
Clinical definitions and synthetic-data scope remain in `WebApi/docs/cama-*.md`.
## Deployment dependencies (not executed here)
The WebApi and WebApp commits must be available in their repositories before publishing the parent gitlink commit.
No push or remote deployment is part of this integration.
Compile dbt from the same parent revision used to build WebApi. On an existing database, arrange a separately approved
and backed-up view update before enabling the new pages: `cama_cohorte_birads` and the three L3 event views
(`cama_deteccion_biopsia`, `cama_resultado_biopsia`, `cama_resultado_diagnostico`). The normal event-model cycle
can create these views, but affects additional domain views and must not be invoked casually on a live deployment.
Follow-up/analysis return 503 when the cohort view is absent. These measures require no new Alembic migration.
FHIR reads can persist new reports and their units/strata. Existing CaCu reports are not deleted or recomputed:
the shared knowledge-date correction changes new composition calculations, while old stored results remain as stored.
Agree any historical recomputation separately. Aggregated FHIR small cells remain unsuppressed; real-data security
and disclosure policy remain separate prerequisites.
Local 18092-specific scripts, backups, logs, image IDs and absolute host paths are deliberately not product commits.
Validate with a compiled `DBT_MANIFEST`, the WebApi pytest suite (external MySQL tests require their own server),
`npm test -- --watch=false` and `npm run build` in WebApp. Record environment-specific logs outside the product tree.
## Integration validation (2026-11-17)
Based on remote dev: parent `8885162147552cf57f4196c27a0152a07c08de48`,
WebApi `0571b5e6af6005737d918997f1f13daec5b4be16`, WebApp `dc37c5493801f40f43cb0a67452b15ad2392b650`.
All three refs were checked again after the integration work and had not advanced.
- WebApi: 681 passed, with five dependency warnings; the two external-MySQL test files were excluded.
Covers legacy and new CaMa routes, optional access and reader overrides, individual selection, governance/risk batches,
CaCu and TEA. Tests used disposable container databases, without production volumes.
- WebApp: 1785 passed; the six known `saved-sql-connections.spec.ts` failures remain caused by unavailable
`localStorage` in Node 26. No other failures. Production build succeeded (known CommonJS warnings).
- No changes were deployed, no stored reports were recomputed, and no push was performed.
+1 -1
Submodule models updated: 55f036b53a...7b2eae2782