344 lines
15 KiB
Python
344 lines
15 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Phase 6c gegen PostgreSQL: Folge-Mails mit Dokumenten, gestrichene Einträge,
|
|
Erinnerungen, tägliche Zusammenfassung (CI)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import uuid
|
|
from datetime import UTC, datetime, timedelta
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
|
|
from fastapi.testclient import TestClient
|
|
from helpers import new_client, token_for
|
|
from sqlalchemy import select, update
|
|
from sqlalchemy.orm import Session
|
|
from test_forms import creator, fill, form_row, participant
|
|
from test_mail import content, messages
|
|
from test_phase5 import bookings, options_of, slot_form
|
|
|
|
from surveybox import db
|
|
from surveybox.forms import digest, followups, reminders
|
|
from surveybox.models import (
|
|
Followup,
|
|
FollowupDocument,
|
|
Form,
|
|
FormAccess,
|
|
FormAccessEntry,
|
|
UserAccount,
|
|
)
|
|
from surveybox.settings import get_settings
|
|
|
|
pytestmark = pytest.mark.db
|
|
|
|
PDF = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n"
|
|
|
|
|
|
def path_of(url: str) -> str:
|
|
return url.replace(get_settings().public_origin, "")
|
|
|
|
|
|
def create_followup(client: TestClient, pid: str, **fields: Any) -> str:
|
|
data = {"subject": "Unterlagen zu {form}", "body": "Hallo {name},\nanbei das Programm.",
|
|
"trigger": "manual", "link_days": "90", "catch_up": "no", **fields}
|
|
csrf = token_for(client, f"/forms/{pid}/followups/new")
|
|
resp = client.post(f"/forms/{pid}/followups/new", data={"csrf_token": csrf, **data})
|
|
assert resp.status_code == 303, resp.text
|
|
match = re.search(r"/followups/([0-9a-f-]{36})", resp.headers["location"])
|
|
assert match
|
|
return match.group(1)
|
|
|
|
|
|
def upload_pdf(client: TestClient, pid: str, fid: str) -> None:
|
|
url = f"/forms/{pid}/followups/{fid}"
|
|
csrf = token_for(client, url)
|
|
resp = client.post(f"{url}/documents", data={"csrf_token": csrf, "title": "Programm"},
|
|
files={"document": ("programm.pdf", PDF, "application/pdf")})
|
|
assert resp.status_code == 303, resp.text
|
|
|
|
|
|
def send_now(client: TestClient, pid: str, fid: str) -> Any:
|
|
url = f"/forms/{pid}/followups/{fid}"
|
|
csrf = token_for(client, url)
|
|
return client.post(f"{url}/send", data={"csrf_token": csrf, "confirm": "on"})
|
|
|
|
|
|
def downloads() -> list[int]:
|
|
with Session(db.get_engine()) as s:
|
|
return [d.downloads for d in s.scalars(select(FollowupDocument))]
|
|
|
|
|
|
def test_followup_on_submit_with_personal_document_link(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, _) = slot_form(carla)
|
|
fid = create_followup(carla, pid, trigger="submit")
|
|
upload_pdf(carla, pid, fid)
|
|
paul = participant(app)
|
|
assert fill(paul, token, {f"q{qid}": early}).status_code == 303
|
|
(mail,) = messages("followup")
|
|
assert mail.recipient == "paul@example.de"
|
|
data = content(mail)
|
|
assert data["subject"] == "Unterlagen zu Sommerfest"
|
|
assert data["text"].startswith("Hallo Anna,") # Testkonten heißen "Anna"
|
|
(link,) = [w for w in data["text"].split() if "/d/" in w]
|
|
# Persönlicher Link funktioniert ohne Anmeldung, zählt nur anonym
|
|
resp = new_client(app).get(path_of(link))
|
|
assert resp.status_code == 200 and resp.content == PDF
|
|
assert "attachment" in resp.headers["content-disposition"]
|
|
assert downloads() == [1]
|
|
# Die Bestätigungsseite zeigt das Dokument; nur der Empfänger kommt dran
|
|
page = paul.get(f"/f/{token}").text
|
|
assert "Programm" in page
|
|
doc_url = re.search(rf"/f/{token}/documents/[0-9a-f-]{{36}}", page).group(0) # type: ignore[union-attr]
|
|
assert paul.get(doc_url).status_code == 200
|
|
other = participant(app, "olga@example.de")
|
|
assert other.get(doc_url).status_code == 404
|
|
# Geänderte Antwort: keine zweite Mail
|
|
fill(paul, token, {f"q{qid}": early}, path="/edit")
|
|
assert len(messages("followup")) == 1
|
|
|
|
|
|
def test_manual_send_reaches_everyone_once(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, late) = slot_form(carla, capacity="")
|
|
fid = create_followup(carla, pid)
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
fill(participant(app, "olga@example.de"), token, {f"q{qid}": late})
|
|
page = carla.get(f"/forms/{pid}/followups/{fid}").text
|
|
assert "2 people who have not received it yet" in page
|
|
assert "Unterlagen zu Sommerfest" in page # Vorschau
|
|
resp = send_now(carla, pid, fid)
|
|
assert resp.status_code == 303 and "sent=2" in resp.headers["location"]
|
|
assert send_now(carla, pid, fid).headers["location"].count("sent=0") == 1
|
|
assert sorted(m.recipient for m in messages("followup")) == [
|
|
"olga@example.de", "paul@example.de"]
|
|
|
|
|
|
def test_only_confirmed_places(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, _) = slot_form(carla, waitlist=True)
|
|
fid = create_followup(carla, pid, only_confirmed="on")
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
fill(participant(app, "olga@example.de"), token, {f"q{qid}": early})
|
|
assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"]
|
|
send_now(carla, pid, fid)
|
|
assert [m.recipient for m in messages("followup")] == ["paul@example.de"]
|
|
|
|
|
|
def test_followup_when_form_closes(app: Any) -> None:
|
|
from test_forms import set_status
|
|
|
|
carla = creator(app)
|
|
pid, token, qid, (early, _) = slot_form(carla)
|
|
create_followup(carla, pid, trigger="close")
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
settings = get_settings()
|
|
with Session(db.get_engine()) as s:
|
|
assert followups.run_due(s, settings, datetime.now(UTC)) == 0
|
|
s.commit()
|
|
assert set_status(carla, pid, "closed").status_code == 303
|
|
with Session(db.get_engine()) as s:
|
|
assert followups.run_due(s, settings, datetime.now(UTC)) == 1
|
|
s.commit()
|
|
(item,) = s.scalars(select(Followup)).all()
|
|
assert item.sent_at is not None
|
|
assert followups.run_due(s, settings, datetime.now(UTC)) == 0
|
|
|
|
|
|
def test_removed_entry_notifies_and_frees_bookings(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, late) = slot_form(carla, capacity="")
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
labels = {o["id"]: o["label"] for o in options_of(qid)}
|
|
assert labels[early] == "Früh"
|
|
# "Früh" streichen
|
|
csrf = token_for(carla, f"/forms/{pid}/questions/{qid}")
|
|
resp = carla.post(f"/forms/{pid}/questions/{qid}", data={
|
|
"csrf_token": csrf, "label": "Schicht", "slot_mode": "list",
|
|
"option_id": [late], "option_label": ["Spät"], "option_capacity": [""]})
|
|
assert resp.status_code == 303
|
|
assert bookings(qid) == []
|
|
(mail,) = messages("changed")
|
|
assert mail.recipient == "paul@example.de" and "Früh" in content(mail)["text"]
|
|
|
|
|
|
def test_reminder_for_invited_people(app: Any) -> None:
|
|
carla = creator(app)
|
|
_, token, qid, (early, _) = slot_form(carla)
|
|
participant(app) # paul
|
|
participant(app, "olga@example.de")
|
|
with Session(db.get_engine()) as s:
|
|
form = s.scalar(select(Form).where(Form.share_token == token))
|
|
assert form is not None
|
|
users = {u.email: u.id for u in s.scalars(select(UserAccount))}
|
|
for email in ("paul@example.de", "olga@example.de"):
|
|
s.add(FormAccessEntry(form_id=form.id, user_id=users[email]))
|
|
s.execute(update(Form).where(Form.id == form.id).values(
|
|
access=FormAccess.RESTRICTED, closes_at=datetime.now(UTC) + timedelta(days=2),
|
|
reminder_days=3))
|
|
s.commit()
|
|
olga = new_client(app)
|
|
from helpers import login
|
|
|
|
login(olga, "olga@example.de")
|
|
assert fill(olga, token, {f"q{qid}": early}).status_code == 303
|
|
settings = get_settings()
|
|
with Session(db.get_engine()) as s:
|
|
assert reminders.run_due(s, settings, datetime.now(UTC)) == 1
|
|
s.commit()
|
|
assert reminders.run_due(s, settings, datetime.now(UTC)) == 0 # nur einmal
|
|
s.commit()
|
|
assert [m.recipient for m in messages("reminder")] == ["paul@example.de"]
|
|
|
|
|
|
def test_daily_digest_for_managers(app: Any) -> None:
|
|
carla = creator(app)
|
|
_, token, qid, (early, _) = slot_form(carla)
|
|
since = datetime.now(UTC) - timedelta(minutes=1)
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
with Session(db.get_engine()) as s:
|
|
assert digest.run(s, get_settings(), since, "2026-11-25") == 1
|
|
s.commit()
|
|
assert digest.run(s, get_settings(), since, "2026-11-25") == 0 # einmal je Tag
|
|
(mail,) = messages("digest")
|
|
assert mail.recipient == "carla@example.de"
|
|
assert "1 new answer" in content(mail)["text"]
|
|
|
|
|
|
def test_copy_keeps_followups_and_documents(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, _, _, _ = slot_form(carla)
|
|
fid = create_followup(carla, pid, trigger="submit")
|
|
upload_pdf(carla, pid, fid)
|
|
csrf = token_for(carla, f"/forms/{pid}")
|
|
resp = carla.post(f"/forms/{pid}/copy", data={"csrf_token": csrf})
|
|
assert resp.status_code == 303
|
|
with Session(db.get_engine()) as s:
|
|
assert len(s.scalars(select(Followup)).all()) == 2
|
|
assert len(s.scalars(select(FollowupDocument)).all()) == 2
|
|
assert form_row(pid) is not None
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Empfängerübersicht und Hinweise an Gäste
|
|
# --------------------------------------------------------------------------
|
|
|
|
|
|
def recipients_page(client: TestClient, pid: str, fid: str) -> str:
|
|
resp = client.get(f"/forms/{pid}/followups/{fid}/recipients")
|
|
assert resp.status_code == 200
|
|
return str(resp.text)
|
|
|
|
|
|
def send_to(client: TestClient, pid: str, fid: str, key: str) -> Any:
|
|
url = f"/forms/{pid}/followups/{fid}/recipients"
|
|
csrf = token_for(client, url)
|
|
return client.post(f"{url}/send", data={"csrf_token": csrf, "recipient": key})
|
|
|
|
|
|
def test_guest_without_address_is_told_once(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional")
|
|
guest = new_client(app)
|
|
# Ohne Folge-Mail: kein Hinweis
|
|
assert fill(guest, token, {f"q{qid}": early}).status_code == 303
|
|
create_followup(carla, pid)
|
|
guest = new_client(app)
|
|
form_page = guest.get(f"/f/{token}").text
|
|
assert "You only receive it if you enter your email address" in form_page
|
|
first = fill(guest, token, {f"q{qid}": early})
|
|
assert first.status_code == 200
|
|
assert "You have not entered an email address" in first.text
|
|
assert 'name="followup_ack" value="1"' in first.text
|
|
second = fill(guest, token, {f"q{qid}": early, "followup_ack": "1"})
|
|
assert second.status_code == 303 and second.headers["location"].endswith("?mail=none")
|
|
assert "without an email address" in guest.get(second.headers["location"]).text
|
|
# Mit Adresse: Hinweis in der Eingangsbestätigung und auf der Dankeseite
|
|
other = new_client(app)
|
|
resp = fill(other, token, {f"q{qid}": early, "guest_email": "gast@example.de"})
|
|
assert resp.headers["location"].endswith("?mail=confirm")
|
|
(mail,) = messages("guest_receipt")
|
|
assert "You only receive it if you confirm your email address" in content(mail)["text"]
|
|
|
|
|
|
def test_recipient_overview_and_sending_again(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional")
|
|
fid = create_followup(carla, pid)
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
fill(new_client(app), token, {f"q{qid}": early, "guest_email": "gast@example.de"})
|
|
fill(new_client(app), token, {f"q{qid}": early, "followup_ack": "1"})
|
|
page = recipients_page(carla, pid, fid)
|
|
assert "Not sent yet" in page and "Address not confirmed" in page
|
|
assert "No email address" in page
|
|
assert "gast@example.de" not in page # Zusage an Gäste: Adresse bleibt verborgen
|
|
keys = re.findall(r'name="recipient" value="([^"]+)"', page)
|
|
assert len(keys) == 1 and keys[0].startswith("u:") # nur Paul kann eine Mail bekommen
|
|
resp = send_to(carla, pid, fid, keys[0])
|
|
assert resp.status_code == 303 and resp.headers["location"].endswith("result=sent")
|
|
page = recipients_page(carla, pid, fid)
|
|
assert "Received" in page and "Send again" in page and "waiting to be sent" in page
|
|
# Erneut senden: zweite Mail trotz Sperre gegen doppelte Einträge
|
|
assert send_to(carla, pid, fid, keys[0]).headers["location"].endswith("result=sent")
|
|
assert [m.recipient for m in messages("followup")] == ["paul@example.de"] * 2
|
|
# Kein Teilnehmer dieses Formulars, kein Versand
|
|
bad = send_to(carla, pid, fid, "u:00000000-0000-0000-0000-000000000000")
|
|
assert bad.headers["location"].endswith("result=failed")
|
|
# Der Gesamtversand bleibt bei "noch nicht erhalten": Paul ist erledigt
|
|
assert "sent=0" in send_now(carla, pid, fid).headers["location"]
|
|
|
|
|
|
def test_planned_ignores_finished_one_time_mails(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, _, _, _ = slot_form(carla)
|
|
with Session(db.get_engine()) as s:
|
|
form = s.get(Form, form_row(pid).id)
|
|
assert form is not None and not followups.planned(s, form)
|
|
fid = create_followup(carla, pid, trigger="close")
|
|
with Session(db.get_engine()) as s:
|
|
form = s.get(Form, form_row(pid).id)
|
|
assert form is not None and followups.planned(s, form)
|
|
s.execute(update(Followup).where(Followup.public_id == uuid.UUID(fid))
|
|
.values(sent_at=datetime.now(UTC)))
|
|
s.expire_all()
|
|
assert not followups.planned(s, form)
|
|
|
|
|
|
def test_catch_up_for_people_who_join_later(app: Any) -> None:
|
|
carla = creator(app)
|
|
pid, token, qid, (early, _) = slot_form(carla, capacity="", guest_email="optional")
|
|
# Die Frage nach dem Nachholen muss beantwortet werden
|
|
csrf = token_for(carla, f"/forms/{pid}/followups/new")
|
|
resp = carla.post(f"/forms/{pid}/followups/new", data={
|
|
"csrf_token": csrf, "subject": "S", "body": "B", "trigger": "manual", "link_days": "90"})
|
|
assert resp.status_code == 400 and "join later" in resp.text
|
|
auto = create_followup(carla, pid, subject="Automatisch", catch_up="yes")
|
|
by_hand = create_followup(carla, pid, subject="Von Hand", catch_up="no")
|
|
fill(participant(app), token, {f"q{qid}": early})
|
|
# Vor dem ersten Versand wird nichts nachgeholt
|
|
assert messages("followup") == []
|
|
send_now(carla, pid, auto)
|
|
send_now(carla, pid, by_hand)
|
|
assert len(messages("followup")) == 2
|
|
# Spätere Teilnahme: nur die Mail mit Nachholen kommt automatisch
|
|
fill(participant(app, "olga@example.de"), token, {f"q{qid}": early})
|
|
later = [content(m)["subject"] for m in messages("followup")
|
|
if m.recipient == "olga@example.de"]
|
|
assert later == ["Automatisch"]
|
|
# Gast bestätigt seine Adresse erst später
|
|
guest = new_client(app)
|
|
fill(guest, token, {f"q{qid}": early, "guest_email": "gast@example.de"})
|
|
(receipt,) = messages("guest_receipt")
|
|
(confirm,) = [w for w in content(receipt)["text"].split() if "/g/confirm/" in w]
|
|
other = new_client(app)
|
|
page = other.get(path_of(confirm))
|
|
csrf = re.search(r'name="csrf_token" value="([0-9a-f]+)"', page.text).group(1) # type: ignore[union-attr]
|
|
assert other.post(path_of(confirm), data={"csrf_token": csrf}).status_code == 200
|
|
guest_mails = [content(m)["subject"] for m in messages("followup")
|
|
if m.recipient == "gast@example.de"]
|
|
assert guest_mails == ["Automatisch"]
|