"""Canonical Pydantic v2 data models for iMednet Data Dictionary."""
# ruff: noqa: N815
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, model_validator
from .normalize import to_camel_case
[docs]class DictCompatMixin:
"""Provides dictionary-like interface for legacy callers."""
def __getitem__(self, key: str) -> Any:
"""Allow dict-like indexing with header names or attribute names."""
# 1. Exact attribute
if hasattr(self, key):
val = getattr(self, key)
if not callable(val):
return val
# 2. camelCased attribute
camel = to_camel_case(key)
if hasattr(self, camel):
val = getattr(self, camel)
if not callable(val):
return val
# 3. extraAttributes
extra: dict[str, Any] = getattr(self, "extraAttributes", {})
if key in extra:
return extra[key]
if camel in extra:
return extra[camel]
# 4. Case-insensitive lookup in extraAttributes
for k, v in extra.items():
if k.lower() == key.lower():
return v
raise KeyError(key)
[docs] def get(self, key: str, default: Any = None) -> Any:
"""Return value for key or default if absent."""
try:
val = self[key]
return default if val is None else val
except KeyError:
return default
def __contains__(self, key: str) -> bool:
"""Check if key exists in attributes or extraAttributes."""
try:
self[key]
return True
except KeyError:
return False
[docs] def keys(self) -> list[str]:
"""Return list of accessible keys."""
res: list[str] = []
if isinstance(self, BaseModel):
res.extend(type(self).model_fields.keys())
extra = getattr(self, "extraAttributes", {})
res.extend(extra.keys())
# Include dynamic backward-compatibility properties if present on object
for prop in ("questions", "choices", "business_logic"):
if hasattr(self, prop) and prop not in res:
res.append(prop)
return res
[docs] def items(self) -> list[tuple[str, Any]]:
"""Return list of (key, value) pairs."""
res: list[tuple[str, Any]] = []
for k in self.keys():
res.append((k, self.get(k)))
return res
[docs]class Choice(DictCompatMixin, BaseModel):
"""A choice option for single-select or multi-select variables."""
model_config = ConfigDict(populate_by_name=True, extra="forbid")
choiceText: str = Field(description="Display text of the choice")
choiceValue: str = Field(description="Coded value of the choice")
position: int | None = Field(default=None, description="Display order sequence")
extraAttributes: dict[str, Any] = Field(
default_factory=dict, description="Unknown columns for this choice"
)
[docs]class Variable(DictCompatMixin, BaseModel):
"""A clinical data variable (data point) on a form."""
model_config = ConfigDict(populate_by_name=True, extra="forbid")
variableName: str = Field(description="Unique identifier for variable within form")
label: str | None = Field(
default=None, description="Display prompt/label on the Form for a Subject"
)
variableType: str | None = Field(
default=None, description="Field type (Text, Radio, Date/Time Precision, etc.)"
)
sequence: int | None = Field(default=None, description="Display order within form")
required: str | None = Field(
default=None, description="Required policy (e.g. 'Yes', 'No', 'Auto Query')"
)
format: str | None = Field(default=None, description="Format mask or pattern")
precision: str | None = Field(default=None, description="Date/Time or number precision")
choices: list[Choice] = Field(
default_factory=list, description="Allowed choices for categorical variables"
)
extraAttributes: dict[str, Any] = Field(
default_factory=dict, description="Unknown columns for this variable"
)
@property
def variable_name(self) -> str:
"""Snake-case alias for variableName matching core Variable models."""
return self.variableName
@property
def variable_type(self) -> str | None:
"""Snake-case alias for variableType matching core Variable models."""
return self.variableType
[docs]class BusinessLogicRule(DictCompatMixin, BaseModel):
"""An edit check, workflow trigger, or business logic rule."""
model_config = ConfigDict(populate_by_name=True, extra="forbid")
id: str | int | None = Field(default=None, description="Unique rule identifier")
name: str | None = Field(default=None, description="Descriptive name of the rule")
type: str | None = Field(
default=None, description="Rule category: Form, Workflow, Query, Approval, Required"
)
status: str | None = Field(default=None, description="Rule status (Active, Inactive)")
form: str | None = Field(
default=None, description="Form key if rule is form-scoped or attached"
)
sequence: int | None = Field(default=None, description="Execution sequence")
logic: dict[str, Any] | None = Field(
default=None, description="Structured parsed AST of the business logic"
)
logicRawXml: str | None = Field(
default=None, description="Verbatim XML string (optional, omitted with --no-raw-xml)"
)
extraAttributes: dict[str, Any] = Field(
default_factory=dict, description="Additional rule properties or unknown columns"
)
def _first_not_none(mapping: dict[str, Any], *keys: str, default: Any = None) -> Any:
"""Return the first value in ``mapping`` for ``keys`` that is not None or empty string."""
for key in keys:
if key in mapping:
val = mapping[key]
if val is not None and val != "":
return val
return default
[docs]class DataDictionary(DictCompatMixin, BaseModel):
"""Canonical root data dictionary container."""
model_config = ConfigDict(populate_by_name=True, extra="forbid")
metadata: Metadata = Field(default_factory=Metadata)
forms: list[Form] = Field(default_factory=list)
unassignedBusinessLogic: list[BusinessLogicRule] = Field(
default_factory=list,
description="Business logic not tied to a single form (Workflow, Query, Approval, Required)",
)
@model_validator(mode="before")
@classmethod
def _handle_legacy_or_flexible_init(cls, data: Any) -> Any:
"""Support legacy initialization via business_logic, choices, forms, questions."""
if not isinstance(data, dict):
return data
# If legacy keywords are provided
has_legacy = any(k in data for k in ("business_logic", "questions", "choices")) or (
"forms" in data
and data["forms"]
and isinstance(data["forms"][0], dict)
and "formKey" not in data["forms"][0]
and ("Form Key" in data["forms"][0] or "Form" in data["forms"][0])
)
if not has_legacy:
return data
raw_forms = data.get("forms", [])
raw_questions = data.get("questions", [])
raw_choices = data.get("choices", [])
raw_logic = data.get("business_logic", [])
# Process forms
forms_map: dict[str, Form] = {}
for item in raw_forms:
if isinstance(item, Form):
forms_map[item.formKey] = item
elif isinstance(item, dict):
fk = str(_first_not_none(item, "formKey", "Form Key", "Form", default=""))
fn = _first_not_none(item, "formName", "Form Name")
fid = _first_not_none(item, "formId", "Form ID")
ft = _first_not_none(item, "formType", "Form Type")
extra = {
to_camel_case(k): v
for k, v in item.items()
if k
not in {
"formKey",
"Form Key",
"Form",
"formName",
"Form Name",
"formId",
"Form ID",
"formType",
"Form Type",
"variables",
"businessLogic",
}
}
forms_map[fk] = Form(
formKey=fk, formName=fn, formId=fid, formType=ft, extraAttributes=extra
)
# Process variables (questions)
var_map: dict[tuple[str, str], Variable] = {}
for item in raw_questions:
if isinstance(item, Variable):
continue
if isinstance(item, dict):
fk = str(_first_not_none(item, "Form", "Form Key", "formKey", default=""))
vname = str(_first_not_none(item, "Variable Name", "variableName", default=""))
if not fk and not vname:
continue
vtype = _first_not_none(item, "Variable Type", "variableType")
lbl = _first_not_none(item, "Label", "label")
req = _first_not_none(item, "Required Field", "Required", "required")
seq_val = _first_not_none(item, "Sequence", "sequence")
seq = (
int(seq_val)
if seq_val is not None
and not isinstance(seq_val, bool)
and str(seq_val).strip().isdigit()
else None
)
fmt_raw = _first_not_none(item, "Format", "format")
fmt = str(fmt_raw) if fmt_raw is not None else None
prec_raw = _first_not_none(item, "Precision", "precision")
prec = str(prec_raw) if prec_raw is not None else None
extra = {
to_camel_case(k): v
for k, v in item.items()
if k
not in {
"Form",
"Form Key",
"formKey",
"Variable Name",
"variableName",
"Variable Type",
"variableType",
"Label",
"label",
"Required Field",
"Required",
"required",
"Sequence",
"sequence",
"Format",
"format",
"Precision",
"precision",
"choices",
}
}
var = Variable(
variableName=vname,
label=lbl,
variableType=vtype,
sequence=seq,
required=req,
format=fmt,
precision=prec,
extraAttributes=extra,
)
if fk not in forms_map:
forms_map[fk] = Form(formKey=fk)
forms_map[fk].variables.append(var)
var_map[(fk, vname)] = var
# Process choices
for item in raw_choices:
if isinstance(item, Choice):
continue
if isinstance(item, dict):
fk = str(_first_not_none(item, "Form", "Form Key", "formKey", default=""))
vname = str(_first_not_none(item, "Variable Name", "variableName", default=""))
ctext = str(_first_not_none(item, "Choice Text", "choiceText", default=""))
cval = str(_first_not_none(item, "Choice Value", "choiceValue", default=""))
pos_val = _first_not_none(item, "Position", "position")
pos = (
int(pos_val)
if pos_val is not None
and not isinstance(pos_val, bool)
and str(pos_val).strip().isdigit()
else None
)
extra = {
to_camel_case(k): v
for k, v in item.items()
if k
not in {
"Form",
"Form Key",
"formKey",
"Variable Name",
"variableName",
"Choice Text",
"choiceText",
"Choice Value",
"choiceValue",
"Position",
"position",
}
}
choice = Choice(
choiceText=ctext, choiceValue=cval, position=pos, extraAttributes=extra
)
if (fk, vname) in var_map:
var_map[(fk, vname)].choices.append(choice)
else:
placeholder_var = Variable(
variableName=vname,
variableType=_first_not_none(item, "Variable Type", "variableType"),
choices=[choice],
)
if fk not in forms_map:
forms_map[fk] = Form(formKey=fk)
forms_map[fk].variables.append(placeholder_var)
var_map[(fk, vname)] = placeholder_var
# Process business logic
unassigned: list[BusinessLogicRule] = []
for item in raw_logic:
if isinstance(item, BusinessLogicRule):
if (item.type or "").strip().lower() == "form" and item.form in forms_map:
forms_map[item.form].businessLogic.append(item)
else:
unassigned.append(item)
elif isinstance(item, dict):
rtype = _first_not_none(item, "Type", "type")
rname = _first_not_none(item, "Name", "name")
rstat = _first_not_none(item, "Status", "status")
rid = _first_not_none(item, "ID", "id")
rform_raw = _first_not_none(item, "Form", "form")
rform = str(rform_raw) if rform_raw is not None else None
rseq_val = _first_not_none(item, "Sequence", "sequence")
rseq = (
int(rseq_val)
if rseq_val is not None
and not isinstance(rseq_val, bool)
and str(rseq_val).strip().isdigit()
else None
)
raw_logic_val = _first_not_none(
item,
"Logic",
"logic",
"LogicRawXml",
"logicRawXml",
"ruleXml",
"xml",
)
logic_ast: dict[str, Any] | None = None
xml_content: str | None = None
if isinstance(raw_logic_val, dict):
logic_ast = raw_logic_val
raw_xml = _first_not_none(item, "LogicRawXml", "logicRawXml")
if isinstance(raw_xml, str):
xml_content = raw_xml
elif isinstance(raw_logic_val, str) and raw_logic_val.strip():
xml_content = raw_logic_val
try:
from .logic import parse_logic_xml
logic_ast = parse_logic_xml(raw_logic_val)
except ValueError as exc:
malformed_err = str(exc)
except Exception:
malformed_err = None
else:
malformed_err = None
else:
malformed_err = None
extra = {
to_camel_case(k): v
for k, v in item.items()
if k
not in {
"Type",
"type",
"Name",
"name",
"Status",
"status",
"ID",
"id",
"Form",
"form",
"Sequence",
"sequence",
"Logic",
"logic",
"LogicRawXml",
"logicRawXml",
"ruleXml",
"rulexml",
"xml",
"XML",
"businessLogic",
}
}
if isinstance(raw_logic_val, str) and raw_logic_val.strip() and malformed_err:
extra.setdefault("malformedLogicXml", malformed_err)
rule = BusinessLogicRule(
id=rid,
name=rname,
type=rtype,
status=rstat,
form=rform,
sequence=rseq,
logic=logic_ast,
logicRawXml=xml_content,
extraAttributes=extra,
)
if (rtype or "").strip().lower() == "form" and rform in forms_map:
forms_map[rform].businessLogic.append(rule)
else:
unassigned.append(rule)
raw_meta = data.get("metadata")
if isinstance(raw_meta, Metadata):
meta_obj = raw_meta
elif isinstance(raw_meta, dict):
meta_known = {k: v for k, v in raw_meta.items() if k in Metadata.model_fields}
meta_extra = dict(meta_known.get("extraAttributes") or {})
for k, v in raw_meta.items():
if k not in Metadata.model_fields:
meta_extra[to_camel_case(k)] = v
if meta_extra:
meta_known["extraAttributes"] = meta_extra
meta_obj = Metadata(**meta_known)
else:
meta_obj = Metadata()
top_extra = {
to_camel_case(k): v
for k, v in data.items()
if k
not in {
"metadata",
"forms",
"questions",
"choices",
"business_logic",
"unassignedBusinessLogic",
}
}
if top_extra:
meta_obj.extraAttributes.update(top_extra)
existing_unassigned = data.get("unassignedBusinessLogic")
if isinstance(existing_unassigned, list):
unassigned = [*existing_unassigned, *unassigned]
res_data: dict[str, Any] = {
"metadata": meta_obj,
"forms": list(forms_map.values()),
"unassignedBusinessLogic": unassigned,
}
return res_data
@property
def questions(self) -> list[Variable]:
"""Backward-compatible access to all variables as questions."""
return [v for f in self.forms for v in f.variables]
@property
def choices(self) -> list[Choice]:
"""Backward-compatible access to all choices."""
return [c for f in self.forms for v in f.variables for c in v.choices]
@property
def business_logic(self) -> list[Any]:
"""Backward-compatible access to all business logic rules."""
res: list[Any] = []
for f in self.forms:
res.extend(f.businessLogic)
res.extend(self.unassignedBusinessLogic)
return res
def _unassigned_rule_matches_form(
self,
rule: BusinessLogicRule,
form: Form | None,
form_key: str,
) -> bool:
"""Return True if an unassigned rule with form=None applies to ``form_key``."""
if form is None:
return False
from .logic import LogicTreeEvaluator
meta = LogicTreeEvaluator().extract_rule_metadata(rule)
if meta is None or meta.is_cross_scope:
return False
referenced_vars = {
v for cond in meta.conditions for v in (cond.variable, cond.compare_variable) if v
}
if not referenced_vars:
target_vars = rule.extraAttributes.get("targetVariables")
if isinstance(target_vars, list):
referenced_vars = {str(v).strip() for v in target_vars if str(v).strip()}
if not referenced_vars:
return False
form_vars = {var.variableName for var in form.variables if var.variableName}
if meta.form is not None:
if meta.form != form_key:
return False
if not form_vars:
return True
return referenced_vars.issubset(form_vars) or all(
v in form_vars or f"{form_key}.{v}" in form_vars for v in referenced_vars
)
return bool(form_vars) and referenced_vars.issubset(form_vars)
def __eq__(self, other: Any) -> bool:
"""Compare data dictionaries ignoring generatedAt timestamp."""
if not isinstance(other, DataDictionary):
return False
return (
self.metadata == other.metadata
and self.forms == other.forms
and self.unassignedBusinessLogic == other.unassignedBusinessLogic
)
def __hash__(self) -> int:
"""Hash method based on object identity."""
return id(self)