Files
surveybox/surveybox/models/forms.py
T
marco.morath 94466378c7
CI / audit (push) Skipped
CI / checks (push) Successful in 4m13s
CI / image (push) Successful in 1m16s
fix:Umfrageergebnisse und Archivierung
2026-11-26 15:19:43 +01:00

515 lines
23 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Formulare, Fragen, Antworten.
Antworten werden typisiert gespeichert: je Fragetyp genau eine Wertspalte.
So rechnet die Datenbank später Summen, Durchschnitte und Datumsvergleiche
direkt aus, statt Texte umzuwandeln.
"""
from __future__ import annotations
import uuid
from datetime import date, datetime, time
from decimal import Decimal
from enum import StrEnum
from typing import Any
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
Date,
DateTime,
ForeignKey,
Integer,
Numeric,
PrimaryKeyConstraint,
Text,
Time,
UniqueConstraint,
func,
text,
)
from sqlalchemy.dialects.postgresql import BYTEA, JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from surveybox.models.base import Base
class FormStatus(StrEnum):
DRAFT = "draft"
OPEN = "open"
CLOSED = "closed"
class FormAccess(StrEnum):
USERS = "users" # alle angemeldeten Benutzer
RESTRICTED = "restricted" # bestimmte Benutzer und Gruppen
LINK = "link" # jeder mit dem Link, auch ohne Konto
LINK_PASSWORD = "link_password" # noqa: S105 - Zugriffsart: Link und Passwort
class Form(Base):
__tablename__ = "form"
__table_args__ = (
CheckConstraint("status IN ('draft', 'open', 'closed')", name="status_valid"),
CheckConstraint(
"access IN ('users', 'restricted', 'link', 'link_password')", name="access_valid"
),
CheckConstraint("allow_edit IN ('no', 'until_close')", name="allow_edit_valid"),
CheckConstraint(
"guest_email IN ('none', 'optional', 'required', 'question')",
name="guest_email_valid",
),
CheckConstraint(
"results_visibility IN ('never', 'after_submit', 'after_close')",
name="results_visibility_valid",
),
CheckConstraint("deletion_mode IN ('delete', 'anonymize')", name="deletion_mode_valid"),
CheckConstraint("calendar_mode IN ('off', 'file', 'feed')", name="calendar_mode_valid"),
CheckConstraint(
"comments_mode IN ('off', 'moderated', 'public')", name="comments_mode_valid"
),
CheckConstraint("slot_names IN ('off', 'full', 'short')", name="slot_names_valid"),
CheckConstraint("poll_names IN ('off', 'full', 'short')", name="poll_names_valid"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
public_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), unique=True, nullable=False, server_default=func.gen_random_uuid()
)
# Teil der Teilnahme-Adresse /f/<share_token>; nicht erratbar
share_token: Mapped[str] = mapped_column(Text, unique=True, nullable=False)
owner_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="SET NULL"), index=True
)
# Gruppe, zu der die Umfrage gehört; ihre Gruppenadministratoren verwalten sie mit
group_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_group.id", ondelete="SET NULL"), index=True
)
title: Mapped[str] = mapped_column(Text, nullable=False)
description: Mapped[str | None] = mapped_column(Text)
status: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'draft'"))
opens_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
closes_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Von Hand geschlossen (Beginn der Löschfrist, wenn kein Enddatum gilt)
closed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Archiviert: für Teilnehmende nicht mehr erreichbar, in der Formularliste im Archiv
archived_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Hinweis an den Eigentümer, dass die Löschfrist bald abläuft
retention_notified_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
access: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'users'"))
link_password_hash: Mapped[str | None] = mapped_column(Text)
allow_multiple: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
allow_edit: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'until_close'")
)
anonymous: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
guest_email: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'none'"))
results_visibility: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'never'")
)
retention_days: Mapped[int | None] = mapped_column(Integer)
deletion_mode: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'anonymize'")
)
privacy_notice: Mapped[str | None] = mapped_column(Text)
require_consent: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
consent_text: Mapped[str | None] = mapped_column(Text)
# Namen der Eingetragenen bei Teilnahme-Feldern zeigen: aus, voll, Vorname + Initial
slot_names: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'off'"))
# Namen bei Abstimmungen in den Ergebnissen für Teilnehmende: aus (nur Anzahlen), voll,
# Vorname + Initial
poll_names: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'off'"))
# Höchstzahl gebuchter Plätze je Person über alle Teilnahme-Felder (leer: keine)
slots_max_per_person: Mapped[int | None] = mapped_column(Integer)
# Einladungen (siehe forms.invitations): Versand (leer: sobald das Formular offen ist),
# erste und letzte Erinnerung an Eingeladene ohne Teilnahme (leer: keine)
invite_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
remind_first_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
remind_last_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Personen und Gruppen der Zugriffsliste per Mail einladen
invite_accounts: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
# Bestätigte Termine: aus, als Datei oder zusätzlich als Abo-Link
calendar_mode: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'off'")
)
calendar_token: Mapped[str | None] = mapped_column(Text, unique=True)
# Kommentare: aus, moderiert, direkt öffentlich
comments_mode: Mapped[str] = mapped_column(
Text, nullable=False, server_default=text("'moderated'")
)
comments_anonymous: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
# Antwort-an-Adresse für Mails zu diesem Formular (sonst der Standard)
reply_to: Mapped[str | None] = mapped_column(Text)
comments_notify: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("true")
)
# Vorlage: erscheint nicht als Formular, sondern unter "Neu aus Vorlage"
is_template: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
# Vorlage für alle Ersteller sichtbar (sonst nur für den Eigentümer)
template_shared: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
)
questions: Mapped[list[Question]] = relationship(
back_populates="form",
order_by=lambda: (Question.position, Question.id),
cascade="all, delete-orphan",
passive_deletes=True,
)
class FormAccessEntry(Base):
"""Bei Zugriff "restricted": wer darf ausfüllen (Benutzer oder Gruppe)."""
__tablename__ = "form_access"
__table_args__ = (
CheckConstraint("(user_id IS NULL) <> (group_id IS NULL)", name="exactly_one_target"),
UniqueConstraint("form_id", "user_id", name="uq_form_access_user"),
UniqueConstraint("form_id", "group_id", name="uq_form_access_group"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="CASCADE"), index=True
)
group_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_group.id", ondelete="CASCADE"), index=True
)
class Question(Base):
__tablename__ = "question"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
type: Mapped[str] = mapped_column(Text, nullable=False)
label: Mapped[str] = mapped_column(Text, nullable=False)
help_text: Mapped[str | None] = mapped_column(Text)
required: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
# Personenbezogen: steuert Export-Filter, Anonymisierung, Löschfristen
personal: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
config: Mapped[dict[str, Any]] = mapped_column(
JSONB, nullable=False, server_default=text("'{}'::jsonb")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
form: Mapped[Form] = relationship(back_populates="questions")
class Response(Base):
"""Eine Teilnahme. Bei anonymen Formularen ohne Bezug zur Person."""
__tablename__ = "response"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
public_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), unique=True, nullable=False, server_default=func.gen_random_uuid()
)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
user_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="SET NULL"), index=True
)
submitted_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
consent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Gäste: Adresse (falls angegeben) und Hash des persönlichen Links
guest_contact_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("guest_contact.id", ondelete="SET NULL"), index=True
)
access_hash: Mapped[bytes | None] = mapped_column(BYTEA, unique=True)
# Nach Ablauf der Löschfrist oder Löschung der Person: ohne Bezug zur Person
anonymized_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Wer zuletzt geändert hat: participant oder manager (Verlauf: nur Änderungen
# von Verwaltern lassen sich zurücknehmen)
edited_by: Mapped[str | None] = mapped_column(Text)
answers: Mapped[list[Answer]] = relationship(
back_populates="response", cascade="all, delete-orphan", passive_deletes=True
)
class Answer(Base):
__tablename__ = "answer"
__table_args__ = (UniqueConstraint("response_id", "question_id", name="uq_answer_question"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
response_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("response.id", ondelete="CASCADE"), nullable=False
)
question_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("question.id", ondelete="CASCADE"), nullable=False, index=True
)
value_text: Mapped[str | None] = mapped_column(Text)
value_number: Mapped[Decimal | None] = mapped_column(Numeric(20, 6))
value_bool: Mapped[bool | None] = mapped_column(Boolean)
value_date: Mapped[date | None] = mapped_column(Date)
value_time: Mapped[time | None] = mapped_column(Time)
value_datetime: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
value_json: Mapped[Any | None] = mapped_column(JSONB)
response: Mapped[Response] = relationship(back_populates="answers")
class FormParticipation(Base):
"""Merker "hat schon teilgenommen" für anonyme Formulare.
Gespeichert wird nur ein Schlüssel-Hash aus Formular und Konto. Damit lässt
sich eine zweite Teilnahme verhindern, ohne dass eine Antwort einer Person
zugeordnet werden kann.
"""
__tablename__ = "form_participation"
__table_args__ = (PrimaryKeyConstraint("form_id", "marker"),)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False
)
marker: Mapped[bytes] = mapped_column(BYTEA, nullable=False)
class MemberRole(StrEnum):
EDITOR = "editor" # bearbeitet Fragen und Einstellungen, sieht Antworten
EVALUATOR = "evaluator" # sieht nur die Antworten
class FormMember(Base):
"""Mitbearbeitende und Auswertende eines Formulars (Benutzer oder Gruppe)."""
__tablename__ = "form_member"
__table_args__ = (
CheckConstraint("(user_id IS NULL) <> (group_id IS NULL)", name="exactly_one_target"),
CheckConstraint("role IN ('editor', 'evaluator')", name="role_valid"),
UniqueConstraint("form_id", "user_id", name="uq_form_member_user"),
UniqueConstraint("form_id", "group_id", name="uq_form_member_group"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
user_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="CASCADE"), index=True
)
group_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_group.id", ondelete="CASCADE"), index=True
)
role: Mapped[str] = mapped_column(Text, nullable=False)
class MediaKind(StrEnum):
IMAGE = "image" # Bild zu einer Frage oder einer Antwortmöglichkeit
VIDEO = "video" # hochgeladenes Video
CAPTIONS = "captions" # Untertitel (WebVTT) zu einem Video
DOCUMENT = "document" # Dokument zum Herunterladen (Folge-Mail, Phase 6)
UPLOAD = "upload" # Datei, die eine teilnehmende Person hochgeladen hat
class MediaFile(Base):
"""Eine gespeicherte Datei. Der Inhalt liegt im Volume unter `storage_key`.
Dateien werden nie verändert. Kopierte Formulare teilen sich deshalb den
Inhalt; gelöscht wird eine Datei erst, wenn kein Eintrag mehr auf sie
verweist und sie älter als einen Tag ist (Aufräumen im Worker). So fehlt
in keiner Sicherung eine Datei, die zur gesicherten Datenbank gehört.
"""
__tablename__ = "media_file"
__table_args__ = (
CheckConstraint(
"kind IN ('image', 'video', 'captions', 'document', 'upload')", name="kind_valid"
),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
public_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), unique=True, nullable=False, server_default=func.gen_random_uuid()
)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
question_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("question.id", ondelete="CASCADE"), index=True
)
response_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("response.id", ondelete="CASCADE"), index=True
)
kind: Mapped[str] = mapped_column(Text, nullable=False)
storage_key: Mapped[str] = mapped_column(Text, nullable=False, index=True)
thumb_key: Mapped[str | None] = mapped_column(Text, index=True)
content_type: Mapped[str] = mapped_column(Text, nullable=False)
size: Mapped[int] = mapped_column(BigInteger, nullable=False)
original_name: Mapped[str | None] = mapped_column(Text)
width: Mapped[int | None] = mapped_column(Integer)
height: Mapped[int | None] = mapped_column(Integer)
# Hochgeladen beim Ausfüllen, aber noch nicht abgeschickt: verfällt danach
pending_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
class BookingStatus(StrEnum):
CONFIRMED = "confirmed"
WAITING = "waiting"
class Booking(Base):
"""Ein gebuchter Platz (oder Wartelistenplatz) im Teilnahme-Feld."""
__tablename__ = "booking"
__table_args__ = (
CheckConstraint("status IN ('confirmed', 'waiting')", name="status_valid"),
UniqueConstraint("response_id", "question_id", "option_id", name="uq_booking_option"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
question_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("question.id", ondelete="CASCADE"), nullable=False, index=True
)
option_id: Mapped[str] = mapped_column(Text, nullable=False)
response_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("response.id", ondelete="CASCADE"), nullable=False, index=True
)
status: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
# Von der Warteliste nachgerückt (Benachrichtigung: mail.notify.promoted)
promoted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class CommentStatus(StrEnum):
PENDING = "pending"
PUBLISHED = "published"
class Comment(Base):
"""Kommentar zu einem Formular. Reiner Text."""
__tablename__ = "comment"
__table_args__ = (
CheckConstraint("status IN ('pending', 'published')", name="status_valid"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
public_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), unique=True, nullable=False, server_default=func.gen_random_uuid()
)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
user_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="SET NULL"), index=True
)
# Gäste: selbst gewählter Name und ein Schlüssel-Hash, um eigene Kommentare
# wiederzuerkennen (der Schlüssel liegt nur im Cookie des Gastes)
guest_name: Mapped[str | None] = mapped_column(Text)
author_token: Mapped[bytes | None] = mapped_column(BYTEA)
# Konto des Autors wurde gelöscht: Anzeige als "Gelöschter Benutzer"
author_deleted: Mapped[bool] = mapped_column(
Boolean, nullable=False, server_default=text("false")
)
body: Mapped[str] = mapped_column(Text, nullable=False)
status: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class ResponseNote(Base):
"""Vermerk zu einer Antwort, die ein Verwalter geändert hat. Nur für Verwalter sichtbar
(und in der Auskunft der betroffenen Person)."""
__tablename__ = "response_note"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
response_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("response.id", ondelete="CASCADE"), nullable=False, index=True
)
author_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="SET NULL"), index=True
)
body: Mapped[str] = mapped_column(Text, nullable=False)
# Beschriftungen der geänderten Fragen (zum Zeitpunkt der Änderung)
changed: Mapped[list[str]] = mapped_column(JSONB, nullable=False, server_default=text("'[]'"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
class FormInvitation(Base):
"""Einladung zu einem Formular: ein Konto (aus der Zugriffsliste) oder eine
E-Mail-Adresse (Gast mit persönlichem Einladungslink). Hält fest, wann
eingeladen und erinnert wurde und ob die Person teilgenommen hat."""
__tablename__ = "form_invitation"
__table_args__ = (
CheckConstraint("(user_id IS NULL) <> (email IS NULL)", name="exactly_one_target"),
UniqueConstraint("form_id", "user_id", name="uq_form_invitation_user"),
UniqueConstraint("form_id", "email", name="uq_form_invitation_email"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
public_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), unique=True, nullable=False, server_default=func.gen_random_uuid()
)
form_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("form.id", ondelete="CASCADE"), nullable=False, index=True
)
user_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="CASCADE"), index=True
)
email: Mapped[str | None] = mapped_column(Text)
created_by: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("user_account.id", ondelete="SET NULL")
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
reminded_first_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
reminded_last_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# Gäste: Teilnahme über den Einladungslink (bei anonymen Formularen ohne Antwort)
participated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
response_id: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("response.id", ondelete="SET NULL"), index=True
)
# Gast will keine Mails mehr zu dieser Einladung
unsubscribed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))