Files
surveybox/surveybox/forms/conditions.py
T
marco.morath 22a17bff6f
CI / audit (push) Skipped
CI / checks (push) Failing after 55s
CI / image (push) Skipped
fix:mypy
2026-11-25 22:01:32 +01:00

481 lines
17 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Bedingungen: Fragen, Abschnitte und Seiten abhängig von Antworten zeigen.
Eine Bedingung steht in `question.config["condition"]`:
{"action": "show" | "hide", "match": "all" | "any",
"rules": [{"q": <frühere Frage>, "op": "eq", "value": "…"}]}
Bei einer Überschrift gilt sie für den ganzen Abschnitt bis zur nächsten
Überschrift oder Seite, bei einem Seitenumbruch für die ganze Seite, bei einer
Fragengruppe für alle Fragen der Gruppe (siehe forms.groups).
Der Browser (static/js/fill.js) wertet dieselben Regeln aus, damit die Seite
sofort reagiert. Verbindlich ist die Auswertung hier beim Absenden: Was
ausgeblendet ist, wird weder geprüft noch gespeichert. Eine Regel darf nur
auf frühere Fragen verweisen; damit sind Kreisbezüge ausgeschlossen.
Das Modul kennt weder Datenbank noch Web.
"""
from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequence
from datetime import date, datetime, time
from decimal import Decimal, InvalidOperation
from typing import Any, Protocol
from surveybox.forms import groups, types
from surveybox.i18n import N_
MAX_RULES = 20
MAX_VALUE = 200
OPS: dict[str, str] = {
"eq": N_("is"),
"ne": N_("is not"),
"contains": N_("contains"),
"not_contains": N_("does not contain"),
"gt": N_("is greater than"),
"lt": N_("is less than"),
"empty": N_("is not answered"),
"not_empty": N_("is answered"),
}
NO_VALUE = {"empty", "not_empty"}
# Art des Vergleichs je Fragetyp
KIND: dict[str, str] = {
"short_text": "text",
"long_text": "text",
"email": "text",
"phone": "text",
"number": "number",
"rating": "number",
"date": "date",
"time": "time",
"datetime": "datetime",
"yes_no": "choice",
"single_choice": "choice",
"multiple_choice": "multi",
"ranking": "presence",
"file_upload": "presence",
"slots": "multi",
"poll": "presence",
}
OPS_FOR: dict[str, list[str]] = {
"text": ["eq", "ne", "contains", "not_contains", "empty", "not_empty"],
"number": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
"date": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
"time": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
"datetime": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
"choice": ["eq", "ne", "empty", "not_empty"],
"multi": ["contains", "not_contains", "empty", "not_empty"],
"presence": ["empty", "not_empty"],
}
class QuestionLike(Protocol):
id: int
position: int
type: str
label: str
required: bool
config: dict[str, Any]
class ConditionError(ValueError):
def __init__(self, code: str) -> None:
super().__init__(code)
self.code = code
# --------------------------------------------------------------------------
# Werte normalisieren (gleich wie im Browser)
# --------------------------------------------------------------------------
def _text(value: str) -> str:
return " ".join(value.split()).lower()
def _number(value: str) -> Decimal | None:
raw = value.strip().replace(",", ".").replace(" ", "")
if not raw:
return None
try:
number = Decimal(raw)
except InvalidOperation:
return None
return number if number.is_finite() else None
def _temporal(kind: str, value: str) -> str:
"""Datum "JJJJ-MM-TT", Zeit "HH:MM", Datum+Zeit "JJJJ-MM-TTTHH:MM"."""
raw = value.strip()
return raw[: {"date": 10, "time": 5, "datetime": 16}[kind]]
def options_for_rules(question: QuestionLike) -> list[tuple[str, str]]:
"""Mögliche Vergleichswerte einer Auswahlfrage: (Wert, Beschriftung)."""
if question.type == "yes_no":
cfg = question.config
return [("yes", cfg.get("label_yes") or "Yes"), ("no", cfg.get("label_no") or "No")]
if question.type == "slots" and question.config.get("single"):
return [(types.SINGLE_SLOT, "signed up")]
result = [(o["id"], o["label"]) for o in types.options_of(question)]
if question.config.get("allow_other"):
result.append((types.OTHER, "Other"))
return result
def clean_value(question: QuestionLike, op: str, raw: str) -> str:
"""Vergleichswert aus dem Designer prüfen und vereinheitlichen."""
if op in NO_VALUE:
return ""
kind = KIND[question.type]
value = raw.strip()
if kind in ("choice", "multi"):
if value not in {v for v, _ in options_for_rules(question)}:
raise ConditionError("condition_value_invalid")
return value
if not value:
raise ConditionError("condition_value_invalid")
if kind == "text":
if len(value) > MAX_VALUE:
raise ConditionError("condition_value_invalid")
return " ".join(value.split())
if kind == "number":
number = _number(value)
if number is None:
raise ConditionError("condition_value_invalid")
return str(number.normalize())
try:
if kind == "date":
return date.fromisoformat(value).isoformat()
if kind == "time":
return time.fromisoformat(value).strftime("%H:%M")
return datetime.fromisoformat(value).strftime("%Y-%m-%dT%H:%M")
except ValueError as exc:
raise ConditionError("condition_value_invalid") from exc
# --------------------------------------------------------------------------
# Bedingung aus dem Designer
# --------------------------------------------------------------------------
def _first(fields: Mapping[str, list[str]], name: str) -> str:
values = fields.get(name) or []
return values[0] if values else ""
def earlier_inputs(
question: QuestionLike | None, questions: Sequence[QuestionLike]
) -> list[QuestionLike]:
"""Fragen, auf die sich eine Bedingung beziehen darf (Eingabefragen davor)."""
limit = question.position if question is not None and question.id else None
return [
q
for q in questions
if q.type in KIND and (limit is None or q.position < limit) and q is not question
]
def parse(
question: QuestionLike | None,
fields: Mapping[str, list[str]],
questions: Sequence[QuestionLike],
) -> dict[str, Any] | None:
"""Liest den Bedingungs-Editor. None: keine Bedingung."""
candidates = {q.id: q for q in earlier_inputs(question, questions)}
refs = fields.get("rule_q") or []
ops = fields.get("rule_op") or []
texts = fields.get("rule_text") or []
options = fields.get("rule_option") or []
rules: list[dict[str, Any]] = []
for index, raw_ref in enumerate(refs):
if not raw_ref.strip():
continue
try:
ref = candidates[int(raw_ref)]
except (ValueError, KeyError) as exc:
raise ConditionError("condition_ref_invalid") from exc
op = ops[index] if index < len(ops) else ""
if op not in OPS_FOR[KIND[ref.type]]:
raise ConditionError("condition_op_invalid")
kind = KIND[ref.type]
source = options if kind in ("choice", "multi") else texts
raw = source[index] if index < len(source) else ""
rules.append({"q": ref.id, "op": op, "value": clean_value(ref, op, raw)})
if not rules:
return None
if len(rules) > MAX_RULES:
raise ConditionError("condition_too_many")
return {
"action": "hide" if _first(fields, "cond_action") == "hide" else "show",
"match": "any" if _first(fields, "cond_match") == "any" else "all",
"rules": rules,
}
# --------------------------------------------------------------------------
# Auswertung
# --------------------------------------------------------------------------
def _answer(question: QuestionLike, fields: Mapping[str, list[str]], with_files: set[int]) -> Any:
"""Eingabe einer Frage in vergleichbarer Form; None/""/[] bedeutet leer."""
name = f"q{question.id}"
kind = KIND.get(question.type)
raw = _first(fields, name)
if kind == "text":
return _text(raw)
if kind == "number":
return _number(raw)
if kind in ("date", "time", "datetime"):
return _temporal(kind, raw)
if kind == "choice":
return raw.strip()
if kind == "multi":
return [v for v in fields.get(name) or [] if v]
if question.type == "ranking":
prefix = f"{name}_rank_"
return any(_first(fields, k) for k in fields if k.startswith(prefix))
if question.type == "file_upload":
return question.id in with_files
if question.type == "poll":
prefix = f"{name}_"
votes = [k for k in fields if k.startswith(prefix) and "_" not in k[len(prefix) :]]
return any(_first(fields, k) for k in votes)
return None
def _is_empty(value: Any) -> bool:
return value is None or value == "" or value == [] or value is False
def rule_matches(rule: Mapping[str, Any], kind: str, value: Any) -> bool:
op = rule.get("op")
target = str(rule.get("value", ""))
if op == "empty":
return _is_empty(value)
if op == "not_empty":
return not _is_empty(value)
if kind == "multi":
chosen = value or []
return (target in chosen) if op == "contains" else (target not in chosen)
if kind == "text":
wanted = _text(target)
if op == "eq":
return bool(value == wanted)
if op == "ne":
return bool(value != wanted)
if op == "contains":
return wanted in (value or "")
if op == "not_contains":
return wanted not in (value or "")
return False
if kind == "number":
wanted_n = _number(target)
if value is None or wanted_n is None:
return op == "ne"
return bool({"eq": value == wanted_n, "ne": value != wanted_n,
"gt": value > wanted_n, "lt": value < wanted_n}.get(str(op), False))
if kind in ("date", "time", "datetime", "choice"):
if _is_empty(value):
return op == "ne"
return bool({"eq": value == target, "ne": value != target,
"gt": value > target, "lt": value < target}.get(str(op), False))
return False
def _holds(
condition: Mapping[str, Any] | None,
by_id: Mapping[int, QuestionLike],
values: Mapping[int, Any],
) -> bool:
"""Ist das Element sichtbar? Ohne Bedingung immer."""
if not condition or not condition.get("rules"):
return True
results = []
for rule in condition["rules"]:
ref = by_id.get(int(rule.get("q", 0)))
if ref is None or ref.type not in KIND:
results.append(False) # verwaiste Regel trifft nie zu
continue
results.append(rule_matches(rule, KIND[ref.type], values.get(ref.id)))
matched = any(results) if condition.get("match") == "any" else all(results)
return matched if condition.get("action", "show") == "show" else not matched
def visibility(
questions: Sequence[QuestionLike],
fields: Mapping[str, list[str]],
with_files: Iterable[int] = (),
) -> dict[int, bool]:
"""Sichtbarkeit jeder Frage, in der Reihenfolge des Formulars ausgewertet.
Antworten auf ausgeblendete Fragen zählen in späteren Regeln als leer.
"""
files = set(with_files)
by_id = {q.id: q for q in questions}
in_group = groups.member_of(questions)
values: dict[int, Any] = {}
visible: dict[int, bool] = {}
page_ok = True
section_ok = True
for question in questions:
own = _holds(question.config.get("condition"), by_id, values)
if question.type == "page_break":
page_ok = own
section_ok = True
visible[question.id] = page_ok
elif question.type == "heading":
section_ok = own
visible[question.id] = page_ok and section_ok
else:
group_ok = visible.get(in_group[question.id], True) if question.id in in_group else True
visible[question.id] = page_ok and section_ok and group_ok and own
if question.type in KIND:
values[question.id] = (
_answer(question, fields, files) if visible[question.id] else None
)
return visible
def hidden_ids(
questions: Sequence[QuestionLike],
fields: Mapping[str, list[str]],
with_files: Iterable[int] = (),
) -> set[int]:
return {qid for qid, shown in visibility(questions, fields, with_files).items() if not shown}
# --------------------------------------------------------------------------
# Pflege im Designer
# --------------------------------------------------------------------------
def references(question: QuestionLike) -> list[int]:
condition = question.config.get("condition") or {}
return [int(r["q"]) for r in condition.get("rules") or [] if "q" in r]
def order_violations(questions: Sequence[QuestionLike]) -> list[int]:
"""Fragen, deren Regeln (in dieser Reihenfolge) nicht auf frühere verweisen."""
seen: set[int] = set()
broken: list[int] = []
for question in questions:
if any(ref not in seen for ref in references(question)):
broken.append(question.id)
seen.add(question.id)
return broken
def without_reference(config: dict[str, Any], removed_id: int) -> dict[str, Any] | None:
"""Neue Konfiguration ohne Regeln auf `removed_id`; None, wenn unverändert."""
condition = config.get("condition") or {}
rules = condition.get("rules") or []
kept = [r for r in rules if int(r.get("q", 0)) != removed_id]
if len(kept) == len(rules):
return None
result = dict(config)
if kept:
result["condition"] = {**condition, "rules": kept}
else:
result.pop("condition", None)
return result
def remap(config: dict[str, Any], mapping: Mapping[int, int]) -> dict[str, Any]:
"""Regeln auf neue Fragen-IDs umstellen (beim Kopieren)."""
condition = config.get("condition")
if not condition:
return config
rules = [
{**r, "q": mapping[int(r["q"])]} for r in condition.get("rules") or []
if int(r.get("q", 0)) in mapping
]
result = dict(config)
if rules:
result["condition"] = {**condition, "rules": rules}
else:
result.pop("condition", None)
return result
def layout(questions: Sequence[QuestionLike]) -> list[dict[str, Any]]:
"""Seiten > Abschnitte > Fragen, für die Ausfüll-Seite.
Gruppierte Fragen stehen nicht selbst in `items`, sondern zeigt ihre
Gruppe (siehe groups.resolve).
"""
grouped = set(groups.member_of(questions))
pages: list[dict[str, Any]] = [{"break": None, "sections": [{"heading": None, "items": []}]}]
for question in questions:
if question.id in grouped:
continue
if question.type == "page_break":
pages.append({"break": question, "sections": [{"heading": None, "items": []}]})
elif question.type == "heading":
pages[-1]["sections"].append({"heading": question, "items": []})
else:
pages[-1]["sections"][-1]["items"].append(question)
# Leere erste Seite (Formular beginnt mit einem Seitenumbruch) weglassen
first = pages[0]
if len(pages) > 1 and not any(s["items"] or s["heading"] for s in first["sections"]):
pages.pop(0)
return pages
def describe(question: QuestionLike, questions: Sequence[QuestionLike]) -> dict[str, Any] | None:
"""Lesbare Zusammenfassung für den Designer (Texte schon übersetzt)."""
from surveybox.i18n import gettext
condition = question.config.get("condition") or {}
rules = condition.get("rules") or []
if not rules:
return None
by_id = {q.id: q for q in questions}
lines: list[str] = []
broken = False
for item in rules:
ref = by_id.get(int(item.get("q", 0)))
if ref is None or ref.type not in KIND or ref.position >= question.position:
broken = True
lines.append(gettext(N_("Invalid rule (question missing or not earlier)")))
continue
value = str(item.get("value", ""))
labels = dict(options_for_rules(ref)) if KIND[ref.type] in ("choice", "multi") else {}
shown = labels.get(value, value)
if ref.type == "yes_no" and value in ("yes", "no") and not ref.config.get(f"label_{value}"):
shown = gettext("Yes") if value == "yes" else gettext("No")
if ref.type == "slots" and value == types.SINGLE_SLOT and ref.config.get("single"):
shown = gettext("signed up")
if shown == types.OTHER or (value == types.OTHER and shown == "Other"):
shown = gettext("Other")
text = f"„{ref.label}“ {gettext(OPS.get(item.get('op', ''), ''))}"
if item.get("op") not in NO_VALUE:
text += f" „{shown}“"
lines.append(text)
action = condition.get("action", "show")
match = condition.get("match", "all")
if action == "show":
head = gettext("Shown if all apply:") if match == "all" else gettext(
"Shown if at least one applies:"
)
else:
head = gettext("Hidden if all apply:") if match == "all" else gettext(
"Hidden if at least one applies:"
)
return {"head": head, "lines": lines, "broken": broken}
def dependents(questions: Sequence[QuestionLike]) -> dict[int, int]:
"""Wie viele Bedingungen auf jede Frage verweisen."""
counts: dict[int, int] = {}
for question in questions:
for ref in set(references(question)):
counts[ref] = counts.get(ref, 0) + 1
return counts