diff --git a/database/schema.sql b/database/schema.sql index c512305..066e4f1 100644 --- a/database/schema.sql +++ b/database/schema.sql @@ -261,7 +261,13 @@ CREATE TABLE medication_administrations ( corrects_event_id INTEGER REFERENCES medication_administrations(id), corrected_target_status TEXT, correction_reason TEXT, - business_revision TEXT + business_revision TEXT, + planned_quantity_value TEXT, + planned_dosage_form TEXT, + planned_strength TEXT, + actual_quantity_value TEXT, + actual_dosage_form TEXT, + actual_strength TEXT ); CREATE TABLE medikamente ( @@ -276,6 +282,14 @@ CREATE TABLE medikamente ( prescription_status_source TEXT, prescription_status_provenance TEXT, business_revision TEXT, + administration_preset_quantity_value TEXT, + administration_preset_dosage_form TEXT, + administration_preset_strength TEXT, + administration_preset_route_original TEXT, + administration_preset_route TEXT, + administration_preset_source TEXT, + administration_preset_provenance TEXT, + administration_preset_revision TEXT, FOREIGN KEY (dokument_id) REFERENCES dokumente(id) ); diff --git a/scripts/health/dashboard_v5/medication_contract.py b/scripts/health/dashboard_v5/medication_contract.py index 1d45091..0f044dd 100644 --- a/scripts/health/dashboard_v5/medication_contract.py +++ b/scripts/health/dashboard_v5/medication_contract.py @@ -9,7 +9,9 @@ import sqlite3 from typing import Any, Mapping PUBLIC_CONTRACT_VERSION = "health.medication_history.v1" -ACTION_CONTRACT_VERSION = "health.medication_action.v1" +ACTION_CONTRACT_VERSION_V1 = "health.medication_action.v1" +ACTION_CONTRACT_VERSION = "health.medication_action.v2" +ACTION_CONTRACT_VERSIONS = frozenset({ACTION_CONTRACT_VERSION_V1, ACTION_CONTRACT_VERSION}) ROUTES = frozenset( { "oral", @@ -57,6 +59,12 @@ EVENT_FIELDS = ( "corrected_target_status", "correction_reason", "business_revision", + "planned_quantity_value", + "planned_dosage_form", + "planned_strength", + "actual_quantity_value", + "actual_dosage_form", + "actual_strength", ) PRESCRIPTION_FIELDS = ( "id", @@ -68,9 +76,24 @@ PRESCRIPTION_FIELDS = ( "prescription_status_source", "prescription_status_provenance", "business_revision", + "administration_preset_quantity_value", + "administration_preset_dosage_form", + "administration_preset_strength", + "administration_preset_route_original", + "administration_preset_route", + "administration_preset_source", + "administration_preset_provenance", + "administration_preset_revision", ) +class MedicationFieldError(ValueError): + def __init__(self, field: str, code: str = "invalid") -> None: + super().__init__(f"invalid medication field: {field}") + self.field = field + self.code = code + + def _canonical(value: Any) -> str: return json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")) @@ -116,6 +139,65 @@ def event_ref(row: sqlite3.Row | Mapping[str, Any], key: bytes) -> str: )[:24] +def prescription_preset( + row: sqlite3.Row | Mapping[str, Any], key: bytes +) -> dict[str, str] | None: + fields = ( + "administration_preset_quantity_value", + "administration_preset_dosage_form", + "administration_preset_strength", + "administration_preset_source", + "administration_preset_provenance", + "administration_preset_revision", + ) + if any(not _value(row, field) for field in fields): + return None + route = str(_value(row, "administration_preset_route") or "") + route_original = str(_value(row, "administration_preset_route_original") or "") + if route and (route not in ROUTES or not route_original): + return None + revision = str(_value(row, "administration_preset_revision")) + if not REVISION_RE.fullmatch(revision): + return None + return { + "quantity_value": str(_value(row, "administration_preset_quantity_value")), + "dosage_form": str(_value(row, "administration_preset_dosage_form")), + "strength": str(_value(row, "administration_preset_strength")), + "route_original": route_original, + "route_normalized": route, + "preset_revision": _opaque_digest( + key, + "health-medication-administration-preset-v1", + [revision, _value(row, "id"), _value(row, "medikament_name")], + ), + } + + +def planned_event_preset( + row: sqlite3.Row | Mapping[str, Any], key: bytes +) -> dict[str, str] | None: + values = tuple( + str(_value(row, field) or "") + for field in ("planned_quantity_value", "planned_dosage_form", "planned_strength") + ) + if not all(values): + return None + route = str(_value(row, "route_normalized") or "") + if route and route not in ROUTES: + return None + return { + "quantity_value": values[0], + "dosage_form": values[1], + "strength": values[2], + "route_normalized": route, + "preset_revision": _opaque_digest( + key, + "health-medication-planned-administration-preset-v1", + [event_revision(row), event_ref(row, key)], + ), + } + + def _available_fields(connection: sqlite3.Connection, table: str, fields: tuple[str, ...]) -> tuple[str, ...]: actual = {str(row[1]) for row in connection.execute(f'PRAGMA table_info("{table}")')} return tuple(field for field in fields if field in actual) @@ -293,15 +375,67 @@ def resolve_action_preview( and prescription["prescription_status_provenance"] and prescription["business_revision"] ) - if data["status"] != "corrected" and not trusted_active: + is_v2 = data.get("contract") == ACTION_CONTRACT_VERSION + if is_v2: + if data["mode"] == "planned" and not trusted_active: + raise RuntimeError("planned administration requires an explicitly active prescription") + elif data["status"] != "corrected" and not trusted_active: raise RuntimeError("medication prescription is not explicitly active") planned = resolve_event(connection, data["planned_event_ref"]) if data["planned_event_ref"] else None - target = resolve_event(connection, data["correction_target_ref"]) if data["correction_target_ref"] else None + target_ref = data.get("correction_target_ref", "") + target = resolve_event(connection, target_ref) if target_ref else None + if is_v2: + if data["mode"] == "historical" and planned is not None: + raise RuntimeError("historical administration cannot consume a plan") + if data["mode"] == "planned" and planned is None: + raise RuntimeError("planned administration requires a real plan") if planned is not None and str(planned["event_type"] or "").strip().casefold() != "planned": raise RuntimeError("planned event reference changed") consumed = plan_is_consumed(connection, int(planned["id"])) if planned is not None else False if consumed: raise RuntimeError("planned medication event is already consumed") + if is_v2: + key = public_identity_key(connection) + preset = prescription_preset(prescription, key) + baseline: tuple[str, str, str, str] | None = None + expected_revision = "" + if data["mode"] == "planned" and planned is not None: + baseline_values = tuple( + str(_value(planned, field) or "") + for field in ( + "planned_quantity_value", "planned_dosage_form", + "planned_strength", "route_normalized", + ) + ) + if not all(baseline_values[:3]): + raise RuntimeError("planned medication event lacks a structured administration preset") + baseline = ( + baseline_values[0], baseline_values[1], + baseline_values[2], baseline_values[3], + ) + expected_revision = _opaque_digest( + key, + "health-medication-planned-administration-preset-v1", + [event_revision(planned), event_ref(planned, key)], + ) + elif preset is not None: + baseline = ( + preset["quantity_value"], preset["dosage_form"], + preset["strength"], preset["route_normalized"], + ) + expected_revision = preset["preset_revision"] + if baseline is None: + if data["preset_revision"]: + raise RuntimeError("administration preset is no longer available") + else: + if not hmac.compare_digest(expected_revision, data["preset_revision"]): + raise RuntimeError("administration preset changed") + actual = ( + data["quantity_value"], data["dosage_form"], + data["strength"], data["route_normalized"], + ) + if actual != baseline and not data["deviation_confirmed"]: + raise RuntimeError("administration differs from verified preset") if target is not None and connection.execute( "SELECT 1 FROM medication_administrations WHERE corrects_event_id=? LIMIT 1", (int(target["id"]),), @@ -334,13 +468,22 @@ def _text(value: Any, maximum: int, *, required: bool = False) -> str: if ( (required and not cleaned) or len(cleaned) > maximum - or re.search(r"[\x00-\x1f\x7f]|https?://|/|\\|\.hermes", cleaned, re.I) + or re.search(r"[\x00-\x1f\x7f]|https?://|\\|\.hermes", cleaned, re.I) + or cleaned.startswith("/") + or re.search(r"(?:^|/)\.\.(?:/|$)", cleaned) ): raise ValueError("invalid medication text") return cleaned -def validate_action_data(data: Any) -> dict[str, Any]: +def _field_text(field: str, value: Any, maximum: int, *, required: bool = False) -> str: + try: + return _text(value, maximum, required=required) + except ValueError as error: + raise MedicationFieldError(field) from error + + +def _validate_action_data_v1(data: Any) -> dict[str, Any]: required = { "contract", "status", @@ -366,7 +509,7 @@ def validate_action_data(data: Any) -> dict[str, Any]: "deviation_confirmed", "duplicate_confirmed", } - if not isinstance(data, dict) or set(data) != required or data.get("contract") != ACTION_CONTRACT_VERSION: + if not isinstance(data, dict) or set(data) != required or data.get("contract") != ACTION_CONTRACT_VERSION_V1: raise ValueError("invalid medication action shape") status = data["status"] if status not in STATUSES: @@ -425,7 +568,7 @@ def validate_action_data(data: Any) -> dict[str, Any]: elif actual_value or actual_unit or planned_value or planned_unit: raise ValueError("missed or unknown correction cannot assert dose values") return { - "contract": ACTION_CONTRACT_VERSION, + "contract": ACTION_CONTRACT_VERSION_V1, "status": status, "medication_ref": medication, "planned_event_ref": planned, @@ -449,3 +592,74 @@ def validate_action_data(data: Any) -> dict[str, Any]: "deviation_confirmed": data["deviation_confirmed"], "duplicate_confirmed": data["duplicate_confirmed"], } + + +def _validate_action_data_v2(data: Any) -> dict[str, Any]: + required = { + "contract", "mode", "status", "medication_ref", "planned_event_ref", + "name", "quantity_value", "dosage_form", "strength", "route_original", + "route_normalized", "injection_region", "injection_side", "injection_detail", + "note", "preset_revision", "preview_revision", "deviation_confirmed", + "duplicate_confirmed", + } + if not isinstance(data, dict) or set(data) != required or data.get("contract") != ACTION_CONTRACT_VERSION: + raise ValueError("invalid medication action shape") + if data["mode"] not in {"historical", "planned"}: + raise ValueError("invalid medication capture mode") + if data["status"] != "administered": + raise ValueError("historical hotfix accepts documented administrations only") + medication = data["medication_ref"] + planned = data["planned_event_ref"] + if not isinstance(medication, str) or not OPAQUE_RE.fullmatch(medication) or not medication.startswith("medrx_"): + raise ValueError("invalid medication reference") + if planned and (not isinstance(planned, str) or not OPAQUE_RE.fullmatch(planned) or not planned.startswith("medevt_")): + raise ValueError("invalid medication event reference") + if data["mode"] == "historical" and planned: + raise ValueError("historical administration cannot reference a plan") + if data["mode"] == "planned" and not planned: + raise ValueError("planned administration requires a real plan") + for field in ("preview_revision", "preset_revision"): + value = data[field] + if value and (not isinstance(value, str) or not REVISION_RE.fullmatch(value)): + raise ValueError(f"invalid {field.replace('_', ' ')}") + route = data["route_normalized"] + side = data["injection_side"] + if route not in ROUTES or side not in (SIDES | {""}): + raise ValueError("invalid medication route or side") + quantity = _field_text("quantity_value", data["quantity_value"], 40, required=True) + dosage_form = _field_text("dosage_form", data["dosage_form"], 40, required=True) + strength = _field_text("strength", data["strength"], 80, required=True) + injection_region = _field_text("injection_region", data["injection_region"], 80) + injection_detail = _field_text("injection_detail", data["injection_detail"], 120) + if (injection_region or side or injection_detail) and route not in INJECTION_ROUTES: + raise ValueError("injection details require injection route") + for flag in ("deviation_confirmed", "duplicate_confirmed"): + if type(data[flag]) is not bool: + raise ValueError("invalid medication confirmation") + return { + "contract": ACTION_CONTRACT_VERSION, + "mode": data["mode"], + "status": "administered", + "medication_ref": medication, + "planned_event_ref": planned, + "name": _field_text("medication", data["name"], 120, required=True), + "quantity_value": quantity, + "dosage_form": dosage_form, + "strength": strength, + "route_original": _field_text("route_original", data["route_original"], 60), + "route_normalized": route, + "injection_region": injection_region, + "injection_side": side, + "injection_detail": injection_detail, + "note": _field_text("note", data["note"], 300), + "preset_revision": data["preset_revision"], + "preview_revision": data["preview_revision"], + "deviation_confirmed": data["deviation_confirmed"], + "duplicate_confirmed": data["duplicate_confirmed"], + } + + +def validate_action_data(data: Any) -> dict[str, Any]: + if isinstance(data, dict) and data.get("contract") == ACTION_CONTRACT_VERSION_V1: + return _validate_action_data_v1(data) + return _validate_action_data_v2(data) diff --git a/scripts/health/dashboard_v5/medication_schema.py b/scripts/health/dashboard_v5/medication_schema.py index 7c04ce0..2e8dd38 100644 --- a/scripts/health/dashboard_v5/medication_schema.py +++ b/scripts/health/dashboard_v5/medication_schema.py @@ -10,14 +10,22 @@ import re import sqlite3 import secrets -MIGRATION_NAME = "sprint7c_f_additive_medication_history" -SCHEMA_VERSION = 7 +MIGRATION_NAME = "sprint7c_f1_medication_capture_hotfix" +SCHEMA_VERSION = 8 PRESCRIPTION_COLUMNS: tuple[tuple[str, str], ...] = ( ("prescription_status", "TEXT"), ("prescription_status_source", "TEXT"), ("prescription_status_provenance", "TEXT"), ("business_revision", "TEXT"), + ("administration_preset_quantity_value", "TEXT"), + ("administration_preset_dosage_form", "TEXT"), + ("administration_preset_strength", "TEXT"), + ("administration_preset_route_original", "TEXT"), + ("administration_preset_route", "TEXT"), + ("administration_preset_source", "TEXT"), + ("administration_preset_provenance", "TEXT"), + ("administration_preset_revision", "TEXT"), ) EVENT_COLUMNS: tuple[tuple[str, str], ...] = ( @@ -37,6 +45,12 @@ EVENT_COLUMNS: tuple[tuple[str, str], ...] = ( ("corrected_target_status", "TEXT"), ("correction_reason", "TEXT"), ("business_revision", "TEXT"), + ("planned_quantity_value", "TEXT"), + ("planned_dosage_form", "TEXT"), + ("planned_strength", "TEXT"), + ("actual_quantity_value", "TEXT"), + ("actual_dosage_form", "TEXT"), + ("actual_strength", "TEXT"), ) ROUTES = ( @@ -53,6 +67,16 @@ EVENT_STATUSES = ("planned", "administered", "missed", "corrected") CORRECTED_TARGET_STATUSES = ("planned", "administered", "missed") PRESCRIPTION_STATUSES = ("active", "ended", "paused", "unknown") INJECTION_SIDES = ("left", "right", "unspecified") +HYRIMOZ_PRESET_NAME = "Hyrimoz / Adalimumab" +HYRIMOZ_PRESET = ( + "1", + "Spritze", + "40 mg/0,4 ml", + "subkutan", + "subcutaneous", + "user_verified", + "sprint7c_f1_explicit_acceptance_contract", +) MANAGED_INDEX_NAMES = { "ux_medication_correction_origin", "ix_medication_event_medication_time", @@ -67,7 +91,7 @@ MANAGED_INDEX_SHA256 = { MANAGED_TRIGGER_SHA256 = { "trg_medication_event_immutable_delete": "ca6ec62519fbde1218cad8e425acf6a07b40205480c9a0abf16d4db92d7c1caa", "trg_medication_event_immutable_update": "3604f96e3eac08cf1675fa75b105c7fcf126e8530b6b57ee81c11e2ec89269fb", - "trg_medication_event_validate_insert": "822efdfca9ca473cf6a70fae585d1e199717de64b207bc62c2ee97cbe6f24b27", + "trg_medication_event_validate_insert": "e9d05b5824d3e3fdb3445ce19d19bbcc7cbc2afeab762ecb70bc30de31e2460a", "trg_medication_plan_correction_consumption_insert": "7e8fbf85f3e419af13df8a94f4c56f940071527d9602aa4a23bf298ba185d4e0", "trg_medication_plan_effective_consumption_insert": "a1284f1ca648da51ecfd6ecca31f75b5b882c598a156bf6fd11d52e29f3fb0f7", "trg_medication_prescription_validate_insert": "42c4d290ea34f3bd4542527d39d817cf6d5c0663577d7ede8d5667a6bdd18ef9", @@ -106,6 +130,53 @@ def _add_columns( return changes +def _install_verified_presets(connection: sqlite3.Connection) -> list[str]: + """Install only the exact preset explicitly verified for this hotfix.""" + rows = connection.execute( + """SELECT id,anwendungsform, + administration_preset_quantity_value, + administration_preset_dosage_form, + administration_preset_strength, + administration_preset_route_original, + administration_preset_route, + administration_preset_source, + administration_preset_provenance, + administration_preset_revision + FROM medikamente WHERE medikament_name=? ORDER BY id""", + (HYRIMOZ_PRESET_NAME,), + ).fetchall() + if not rows: + return [] + if len(rows) != 1: + raise RuntimeError("verified Hyrimoz preset identity is ambiguous") + row = rows[0] + if str(row[1] or "").strip().casefold() != "subkutan": + raise RuntimeError("verified Hyrimoz route source changed") + revision = hashlib.sha256( + (HYRIMOZ_PRESET_NAME + "\0" + "\0".join(HYRIMOZ_PRESET)).encode("utf-8") + ).hexdigest() + expected = (*HYRIMOZ_PRESET, revision) + current = tuple(row[index] for index in range(2, 10)) + if all(value is None for value in current): + connection.execute( + """UPDATE medikamente SET + administration_preset_quantity_value=?, + administration_preset_dosage_form=?, + administration_preset_strength=?, + administration_preset_route_original=?, + administration_preset_route=?, + administration_preset_source=?, + administration_preset_provenance=?, + administration_preset_revision=? + WHERE id=?""", + (*expected, int(row[0])), + ) + return ["medikamente.verified_hyrimoz_administration_preset"] + if current != expected: + raise RuntimeError("verified Hyrimoz preset conflicts with existing data") + return [] + + def _has_legacy_event_uniqueness(connection: sqlite3.Connection) -> bool: for row in connection.execute("PRAGMA index_list('medication_administrations')"): if not int(row[2]): @@ -223,6 +294,7 @@ def _apply_schema_uncommitted(connection: sqlite3.Connection) -> list[str]: changes.append("medication_administrations.relax_legacy_tuple_uniqueness") changes.extend(_add_columns(connection, "medikamente", PRESCRIPTION_COLUMNS)) changes.extend(_add_columns(connection, "medication_administrations", EVENT_COLUMNS)) + changes.extend(_install_verified_presets(connection)) _execute_sql_script( connection, f""" @@ -310,6 +382,23 @@ def _apply_schema_uncommitted(connection: sqlite3.Connection) -> list[str]: AND lower(trim(COALESCE(p.event_type,'')))='planned' AND (p.medication_id=NEW.medication_id OR (p.medication_id IS NULL AND p.medication_name=NEW.medication_name)) ) THEN RAISE(ABORT,'invalid planned event relation') END; + SELECT CASE WHEN + ((NEW.actual_quantity_value IS NOT NULL)+(NEW.actual_dosage_form IS NOT NULL)+(NEW.actual_strength IS NOT NULL)) NOT IN (0,3) + OR ((NEW.planned_quantity_value IS NOT NULL)+(NEW.planned_dosage_form IS NOT NULL)+(NEW.planned_strength IS NOT NULL)) NOT IN (0,3) + THEN RAISE(ABORT,'incomplete structured medication fields') END; + SELECT CASE WHEN NEW.source='dashboard_medication_action_version_two' AND ( + trim(COALESCE(NEW.actual_quantity_value,''))='' OR + trim(COALESCE(NEW.actual_dosage_form,''))='' OR + trim(COALESCE(NEW.actual_strength,''))='' OR + (NEW.planned_event_id IS NOT NULL AND ( + trim(COALESCE(NEW.planned_quantity_value,''))='' OR + trim(COALESCE(NEW.planned_dosage_form,''))='' OR + trim(COALESCE(NEW.planned_strength,''))='' + )) OR + (NEW.planned_event_id IS NULL AND ( + NEW.planned_quantity_value IS NOT NULL OR NEW.planned_dosage_form IS NOT NULL OR NEW.planned_strength IS NOT NULL + )) + ) THEN RAISE(ABORT,'invalid version two structured medication fields') END; SELECT CASE WHEN lower(trim(COALESCE(NEW.event_type,'')))='corrected' AND ( NEW.corrects_event_id IS NULL OR NEW.corrected_target_status NOT IN ('planned','administered','missed') OR diff --git a/scripts/health/health_dashboard_action_worker.py b/scripts/health/health_dashboard_action_worker.py index 5efcc3a..f8662fe 100644 --- a/scripts/health/health_dashboard_action_worker.py +++ b/scripts/health/health_dashboard_action_worker.py @@ -35,7 +35,7 @@ try: from dashboard_v5.capture_contract import validate_capture_payload from dashboard_v5.medication_schema import assert_schema as assert_medication_schema from dashboard_v5.medication_contract import ( - ACTION_CONTRACT_VERSION as MEDICATION_ACTION_CONTRACT, + ACTION_CONTRACT_VERSIONS as MEDICATION_ACTION_CONTRACTS, resolve_action_preview, ) from dashboard_v5.capture_media import cleanup_expired, promote_attachment @@ -92,7 +92,7 @@ except ModuleNotFoundError: # direct importlib fixture execution from dashboard_v5.capture_contract import validate_capture_payload from dashboard_v5.medication_schema import assert_schema as assert_medication_schema from dashboard_v5.medication_contract import ( - ACTION_CONTRACT_VERSION as MEDICATION_ACTION_CONTRACT, + ACTION_CONTRACT_VERSIONS as MEDICATION_ACTION_CONTRACTS, resolve_action_preview, ) from dashboard_v5.capture_media import cleanup_expired, promote_attachment @@ -1043,7 +1043,7 @@ def apply_capture_action(payload: dict[str, Any]) -> str: str(row[0]) for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'") } - if payload["capture_type"] == "medication" and data.get("contract") == MEDICATION_ACTION_CONTRACT: + if payload["capture_type"] == "medication" and data.get("contract") in MEDICATION_ACTION_CONTRACTS: assert_medication_schema(connection) expected_revision, prescription, planned, correction_target = resolve_action_preview( connection, payload @@ -1051,28 +1051,47 @@ def apply_capture_action(payload: dict[str, Any]) -> str: if not hmac.compare_digest(expected_revision, data["preview_revision"]): raise RuntimeError("stale medication preview revision") medication_id = int(prescription["id"]) - duplicate = connection.execute( - """SELECT 1 FROM medication_administrations - WHERE business_revision IS NOT NULL AND medication_id=? - AND COALESCE(planned_event_id,-1)=COALESCE(?,-1) - AND COALESCE(occurred_at,'')=? - AND lower(trim(COALESCE(event_type,'')))=? - AND COALESCE(actual_dose_value,'')=? - AND COALESCE(actual_dose_unit,'')=? LIMIT 1""", - ( - medication_id, - int(planned["id"]) if planned is not None else None, - payload["occurred_at"], - data["status"], - data["actual_dose_value"], - data["actual_dose_unit"], - ), - ).fetchone() + if data["contract"] == "health.medication_action.v2": + duplicate = connection.execute( + """SELECT 1 FROM medication_administrations + WHERE business_revision IS NOT NULL AND medication_id=? + AND COALESCE(planned_event_id,-1)=COALESCE(?,-1) + AND COALESCE(occurred_at,'')=? + AND lower(trim(COALESCE(event_type,'')))=? + AND COALESCE(actual_quantity_value,'')=? + AND COALESCE(actual_dosage_form,'')=? + AND COALESCE(actual_strength,'')=? LIMIT 1""", + ( + medication_id, + int(planned["id"]) if planned is not None else None, + payload["occurred_at"], data["status"], + data["quantity_value"], data["dosage_form"], data["strength"], + ), + ).fetchone() + else: + duplicate = connection.execute( + """SELECT 1 FROM medication_administrations + WHERE business_revision IS NOT NULL AND medication_id=? + AND COALESCE(planned_event_id,-1)=COALESCE(?,-1) + AND COALESCE(occurred_at,'')=? + AND lower(trim(COALESCE(event_type,'')))=? + AND COALESCE(actual_dose_value,'')=? + AND COALESCE(actual_dose_unit,'')=? LIMIT 1""", + ( + medication_id, + int(planned["id"]) if planned is not None else None, + payload["occurred_at"], data["status"], + data["actual_dose_value"], data["actual_dose_unit"], + ), + ).fetchone() if duplicate and not data["duplicate_confirmed"]: raise RuntimeError("possible duplicate medication event") medication_context = { "medication_id": medication_id, "planned_event_id": int(planned["id"]) if planned is not None else None, + "planned_quantity_value": str(planned["planned_quantity_value"] or "") if planned is not None else "", + "planned_dosage_form": str(planned["planned_dosage_form"] or "") if planned is not None else "", + "planned_strength": str(planned["planned_strength"] or "") if planned is not None else "", "corrects_event_id": int(correction_target["id"]) if correction_target is not None else None, } elif payload["capture_type"] == "medication" and "medication_administrations" in known_tables: @@ -1093,7 +1112,11 @@ def apply_capture_action(payload: dict[str, Any]) -> str: } if data["name"] not in known_supplements: raise RuntimeError("supplement is not in the known exact plan") - if payload["capture_type"] in {"medication", "supplement"} and data["status"] == "administered": + if ( + payload["capture_type"] in {"medication", "supplement"} + and data["status"] == "administered" + and data.get("contract") != "health.medication_action.v2" + ): if not (data["plan_value_confirmed"] or data["deviation_confirmed"]): raise RuntimeError("planned administration requires conscious confirmation") if payload["capture_type"] == "measurement": @@ -1223,44 +1246,57 @@ def apply_capture_action(payload: dict[str, Any]) -> str: ) elif payload["capture_type"] == "medication" and "medication_administrations" in available_tables: if medication_context is not None: - actual_dose = " ".join( - part for part in (data["actual_dose_value"], data["actual_dose_unit"]) if part - ) - legacy_route = data["route_original"] or data["route_normalized"] - connection.execute( - """INSERT INTO medication_administrations( - datum,medication_name,dose,route,event_type,scheduled_next_date,notes,source,occurred_at, - medication_id,planned_event_id,planned_dose_value,planned_dose_unit,actual_dose_value, - actual_dose_unit,route_original,route_normalized,injection_region,injection_side, - injection_detail,lot_number,corrects_event_id,corrected_target_status,correction_reason, - business_revision) VALUES(?,?,?,?,?,NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", - ( - day, - data["name"], - actual_dose or None, - legacy_route or None, - data["status"], - data["note"] or None, - "dashboard_v5_medication_action", - payload["occurred_at"], - medication_context["medication_id"], - medication_context["planned_event_id"], - data["planned_dose_value"] or None, - data["planned_dose_unit"] or None, - data["actual_dose_value"] or None, - data["actual_dose_unit"] or None, - data["route_original"] or None, - data["route_normalized"] or None, - data["injection_region"] or None, - data["injection_side"] or None, - data["injection_detail"] or None, - data["lot_number"] or None, - medication_context["corrects_event_id"], - data["corrected_target_status"] or None, - data["correction_reason"] or None, - action_hash, - ), - ) + if data["contract"] == "health.medication_action.v2": + legacy_dose = f"{data['quantity_value']} {data['dosage_form']} ยท {data['strength']}" + legacy_route = data["route_original"] or data["route_normalized"] + connection.execute( + """INSERT INTO medication_administrations( + datum,medication_name,dose,route,event_type,scheduled_next_date,notes,source,occurred_at, + medication_id,planned_event_id,planned_quantity_value,planned_dosage_form, + planned_strength,route_original,route_normalized,injection_region, + injection_side,injection_detail,business_revision,actual_quantity_value, + actual_dosage_form,actual_strength) + VALUES(?,?,?,?,?,NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + ( + day, data["name"], legacy_dose, legacy_route or None, + data["status"], data["note"] or None, + "dashboard_medication_action_version_two", payload["occurred_at"], + medication_context["medication_id"], medication_context["planned_event_id"], + medication_context["planned_quantity_value"] or None, + medication_context["planned_dosage_form"] or None, + medication_context["planned_strength"] or None, + data["route_original"] or None, data["route_normalized"] or None, + data["injection_region"] or None, data["injection_side"] or None, + data["injection_detail"] or None, action_hash, + data["quantity_value"], data["dosage_form"], data["strength"], + ), + ) + else: + actual_dose = " ".join( + part for part in (data["actual_dose_value"], data["actual_dose_unit"]) if part + ) + legacy_route = data["route_original"] or data["route_normalized"] + connection.execute( + """INSERT INTO medication_administrations( + datum,medication_name,dose,route,event_type,scheduled_next_date,notes,source,occurred_at, + medication_id,planned_event_id,planned_dose_value,planned_dose_unit,actual_dose_value, + actual_dose_unit,route_original,route_normalized,injection_region,injection_side, + injection_detail,lot_number,corrects_event_id,corrected_target_status,correction_reason, + business_revision) VALUES(?,?,?,?,?,NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + ( + day, data["name"], actual_dose or None, legacy_route or None, + data["status"], data["note"] or None, + "dashboard_v5_medication_action", payload["occurred_at"], + medication_context["medication_id"], medication_context["planned_event_id"], + data["planned_dose_value"] or None, data["planned_dose_unit"] or None, + data["actual_dose_value"] or None, data["actual_dose_unit"] or None, + data["route_original"] or None, data["route_normalized"] or None, + data["injection_region"] or None, data["injection_side"] or None, + data["injection_detail"] or None, data["lot_number"] or None, + medication_context["corrects_event_id"], data["corrected_target_status"] or None, + data["correction_reason"] or None, action_hash, + ), + ) else: dose = " ".join( str(part) __HERMES_CWD_8d46a20096ed__/home/agent/.hermes/repos/HealthManager__HERMES_CWD_8d46a20096ed__