# SPDX-License-Identifier: AGPL-3.0-or-later """Phase 7a gegen PostgreSQL: Löschfristen, Hinweis an den Eigentümer (CI).""" from __future__ import annotations import re from datetime import UTC, datetime, timedelta from typing import Any import pytest pytest.importorskip("fastapi") from helpers import new_client from sqlalchemy import func, select, update from sqlalchemy.orm import Session from test_forms import ( creator, fill, form_row, option_ids, participant, question_ids, set_status, simple_form, ) from test_mail import content, messages from surveybox import db from surveybox.forms import retention from surveybox.models import Answer, AuditEvent, Comment, Form, Question, Response from surveybox.settings import get_settings pytestmark = pytest.mark.db def prepare(app: Any, mode: str = "anonymize") -> tuple[str, str, list[int], Any]: """Formular mit personenbezogener Namensfrage, zwei Antworten, geschlossen.""" carla = creator(app) pid, token, (name_q, food_q) = simple_form( carla, access="link", guest_email="optional", deletion_mode=mode) with Session(db.get_engine()) as s: s.execute(update(Question).where(Question.id == name_q).values(personal=True)) s.commit() options = option_ids(pid, food_q) assert fill(participant(app), token, {f"q{name_q}": "Paul", f"q{food_q}": options[0]} ).status_code == 303 guest = new_client(app) resp = fill(guest, token, {f"q{name_q}": "Gast", f"q{food_q}": options[1], "guest_email": "gast@example.de"}) assert resp.status_code == 303 assert set_status(carla, pid, "closed").status_code == 303 assert form_row(pid).closed_at is not None return pid, token, [name_q, food_q], carla def run(now: datetime) -> tuple[int, int]: with Session(db.get_engine()) as s: result = retention.run_due(s, get_settings(), now) s.commit() return result def shift_end(pid: str, days_ago: int, retention_days: int) -> None: with Session(db.get_engine()) as s: s.execute(update(Form).where(Form.id == form_row(pid).id).values( closed_at=datetime.now(UTC) - timedelta(days=days_ago), retention_days=retention_days)) s.commit() def responses(pid: str) -> list[Response]: with Session(db.get_engine()) as s: rows = list(s.scalars(select(Response).where(Response.form_id == form_row(pid).id))) for row in rows: s.expunge(row) return rows def test_anonymize_after_notice_and_grace(app: Any) -> None: pid, _, (name_q, food_q), carla = prepare(app) (receipt,) = messages("guest_receipt") personal_link = re.search(r"https?://\S+/r/\S+", content(receipt)["text"]).group(0) # type: ignore[union-attr] # Frist abgelaufen, aber noch kein Hinweis: erst Hinweis, keine Löschung shift_end(pid, days_ago=40, retention_days=30) now = datetime.now(UTC) assert run(now) == (1, 0) (notice,) = messages("retention_notice") assert notice.recipient == "carla@example.de" assert "will be anonymized" in content(notice)["text"] assert all(r.anonymized_at is None for r in responses(pid)) assert run(now + timedelta(days=6)) == (0, 0) # Karenz nach dem Hinweis # Nach sieben Tagen: anonymisiert assert run(now + timedelta(days=8)) == (0, 2) rows = responses(pid) assert len(rows) == 2 assert all(r.user_id is None and r.guest_contact_id is None and r.access_hash is None and r.anonymized_at is not None for r in rows) with Session(db.get_engine()) as s: kept = set(s.scalars(select(Answer.question_id).where( Answer.response_id.in_([r.id for r in rows])))) assert kept == {food_q} # Name (personenbezogen) gelöscht, Auswahl bleibt actions = list(s.scalars(select(AuditEvent.action))) assert "form.retention_applied" in actions # Persönlicher Link des Gasts ist ungültig, Ergebnis bleibt sichtbar path = personal_link.replace(get_settings().public_origin, "") assert new_client(app).get(path).status_code in (404, 410) assert "Pizza" in carla.get(f"/forms/{pid}/responses").text assert run(now + timedelta(days=9)) == (0, 0) # nichts mehr zu tun assert question_ids(pid) == [name_q, food_q] def test_delete_mode_removes_answers_and_comments(app: Any) -> None: pid, _, _, _ = prepare(app, mode="delete") with Session(db.get_engine()) as s: s.add(Comment(form_id=form_row(pid).id, guest_name="Gast", body="Hallo", status="published")) s.commit() shift_end(pid, days_ago=400, retention_days=30) now = datetime.now(UTC) run(now) assert "will be deleted completely" in content(messages("retention_notice")[0])["text"] assert run(now + timedelta(days=8)) == (0, 2) assert responses(pid) == [] with Session(db.get_engine()) as s: assert s.scalar(select(func.count()).select_from(Comment)) == 0 def test_open_form_and_reopened_form_are_left_alone(app: Any) -> None: pid, _, _, carla = prepare(app) shift_end(pid, days_ago=400, retention_days=1) assert set_status(carla, pid, "open").status_code == 303 assert form_row(pid).closed_at is None assert run(datetime.now(UTC) + timedelta(days=30)) == (0, 0) assert messages("retention_notice") == [] def test_settings_show_planned_date(app: Any) -> None: pid, _, _, carla = prepare(app) page = carla.get(f"/forms/{pid}/settings").text assert "The answers will be anonymized on" in page assert "default of this installation (730 days)" in page assert "The retention period ends" in carla.get(f"/forms/{pid}/responses").text