Files
surveybox/surveybox/forms/summary.py
T
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

161 lines
6.3 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Auswertung je Frage: Anzahlen, Summen, Durchschnitte, Freitexte.
Das Modul rechnet nur; die (gefilterten) Antworten kommen als Liste herein.
"""
from __future__ import annotations
from collections import Counter
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Any
from zoneinfo import ZoneInfo
from surveybox.forms import types
from surveybox.i18n import gettext
@dataclass
class Bar:
label: str
count: int
@dataclass
class QuestionSummary:
question: Any
answered: int
bars: list[Bar] = field(default_factory=list)
total: Decimal | None = None
average: Decimal | None = None
note: str = ""
poll_rows: list[dict[str, Any]] = field(default_factory=list)
slot_rows: list[dict[str, Any]] = field(default_factory=list)
texts: list[str] = field(default_factory=list) # Freitexte (die ersten MAX_TEXTS)
more_texts: int = 0
MAX_TEXTS = 50
TEXT_TYPES = ("short_text", "long_text", "email", "phone", "participant_name", "date", "time",
"datetime")
def _round(value: Decimal) -> Decimal:
return value.quantize(Decimal("0.01")).normalize()
def summarize(
questions: Sequence[Any],
answers: Iterable[tuple[int, dict[str, Any]]],
places: Mapping[int, Mapping[str, Any]] | None = None,
tz: ZoneInfo | None = None,
) -> list[QuestionSummary]:
"""answers: (Fragen-ID, gespeicherte Werte) je Antwort.
places: je Teilnahme-Frage die Belegung (forms.booking.Availability).
"""
by_question: dict[int, list[dict[str, Any]]] = {}
for qid, stored in answers:
by_question.setdefault(qid, []).append(stored)
result: list[QuestionSummary] = []
for q in questions:
qtype = types.TYPES.get(q.type)
if qtype is None or not qtype.is_input:
continue
rows = by_question.get(q.id, [])
item = QuestionSummary(q, len(rows))
cfg = q.config
if q.type == "yes_no":
answers_yn = Counter(r.get("value_bool") for r in rows)
item.bars = [
Bar(cfg.get("label_yes") or gettext("Yes"), answers_yn[True]),
Bar(cfg.get("label_no") or gettext("No"), answers_yn[False]),
]
elif q.type in ("single_choice", "multiple_choice"):
counts: Counter[str] = Counter()
other = 0
for r in rows:
if q.type == "single_choice":
chosen = [r.get("value_text")]
if r.get("value_text") == types.OTHER:
chosen = []
other += 1
else:
data = r.get("value_json") or {}
chosen = list(data.get("selected") or [])
other += 1 if data.get("other") else 0
counts.update(c for c in chosen if c)
item.bars = [Bar(o["label"], counts[o["id"]]) for o in types.options_of(q)]
if cfg.get("allow_other"):
item.bars.append(Bar(gettext("Other"), other))
elif q.type in ("number", "rating"):
values = [Decimal(r["value_number"]) for r in rows if r.get("value_number") is not None]
if values:
item.total = sum(values, Decimal(0))
item.average = _round(item.total / len(values))
if q.type == "rating":
per_value = Counter(int(v) for v in values)
scale = int(cfg.get("scale_max") or 5)
item.bars = [Bar(str(i), per_value[i]) for i in range(1, scale + 1)]
item.total = None
elif q.type == "poll":
tally: dict[str, Counter[str]] = {}
for r in rows:
for oid, vote in ((r.get("value_json") or {}).get("votes") or {}).items():
tally.setdefault(oid, Counter())[vote] += 1
confirmed = set(cfg.get("confirmed") or [])
for option in types.options_of(q):
counts_o = tally.get(option["id"], Counter())
item.poll_rows.append(
{
"id": option["id"],
"text": types.option_text(option),
"yes": counts_o["yes"],
"maybe": counts_o["maybe"],
"no": counts_o["no"],
"proposed": bool(option.get("proposed")),
"confirmed": option["id"] in confirmed,
}
)
if item.poll_rows:
best = max((r["yes"], r["maybe"]) for r in item.poll_rows)
if best > (0, 0):
for row in item.poll_rows:
row["best"] = (row["yes"], row["maybe"]) == best
elif q.type == "slots":
occupancy = (places or {}).get(q.id, {})
for option in types.options_of(q):
state = occupancy.get(option["id"])
item.slot_rows.append(
{
"id": option["id"],
"text": gettext("signed up") if q.config.get("single") else option["label"],
"capacity": option.get("capacity"),
"confirmed": state.confirmed if state else 0,
"waiting": state.waiting if state else 0,
}
)
elif q.type in TEXT_TYPES:
shown = [types.display_answer(q, r, tz or ZoneInfo("UTC")) for r in rows]
shown = [text for text in shown if text]
item.texts = shown[:MAX_TEXTS]
item.more_texts = max(len(shown) - MAX_TEXTS, 0)
elif q.type == "ranking":
ranks: dict[str, list[int]] = {}
for r in rows:
for place, oid in enumerate((r.get("value_json") or {}).get("order") or [], 1):
ranks.setdefault(oid, []).append(place)
def average_place(
option: dict[str, str], ranks: dict[str, list[int]] = ranks
) -> float:
found = ranks.get(option["id"]) or [99]
return sum(found) / len(found)
ranked = sorted(types.options_of(q), key=average_place)
item.note = ", ".join(f"{i}. {o['label']}" for i, o in enumerate(ranked, 1))
result.append(item)
return result