# SPDX-License-Identifier: AGPL-3.0-or-later """Phase 5 gegen PostgreSQL: Plätze, Warteliste, Abstimmung, Kalender, Kommentare (CI).""" from __future__ import annotations import uuid from concurrent.futures import ThreadPoolExecutor 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 from sqlalchemy.orm import Session from test_forms import ( add_question, create_form, creator, fill, form_row, participant, question_ids, save_settings, set_status, ) from surveybox import db from surveybox.models import Booking, Comment, Form, Question pytestmark = pytest.mark.db def options_of(qid: int) -> list[dict[str, Any]]: with Session(db.get_engine()) as s: q = s.get(Question, qid) assert q is not None return list(q.config["options"]) def bookings(qid: int) -> list[tuple[str, str, bool]]: with Session(db.get_engine()) as s: return [ (b.option_id, b.status, b.promoted_at is not None) for b in s.scalars(select(Booking).where(Booking.question_id == qid) .order_by(Booking.id)) ] def slot_form(owner: TestClient, capacity: str = "1", *, waitlist: bool = False, multiple: bool = False, **settings: Any) -> tuple[str, str, int, list[str]]: pid = create_form(owner) fields: dict[str, Any] = { "label": "Schicht", "slot_mode": "list", "option_id": ["", ""], "option_label": ["Früh", "Spät"], "option_capacity": [capacity, ""], } if waitlist: fields["waitlist"] = "on" if multiple: fields["multiple"] = "on" add_question(owner, pid, "slots", **fields) assert save_settings(owner, pid, access="link", **settings).status_code == 303 assert set_status(owner, pid, "open").status_code == 303 (qid,) = question_ids(pid) return pid, form_row(pid).share_token, qid, [o["id"] for o in options_of(qid)] def test_last_place_not_twice(app: Any) -> None: owner = creator(app) _, token, qid, (early, late) = slot_form(owner) first, second = new_client(app), new_client(app) assert fill(first, token, {f"q{qid}": early}).status_code == 303 resp = fill(second, token, {f"q{qid}": early}) assert resp.status_code == 409 assert "just been taken" in resp.text assert f'value="{early}"' in resp.text # Formular bleibt ausgefüllt assert fill(second, token, {f"q{qid}": late}).status_code == 303 assert sorted(bookings(qid)) == sorted([(early, "confirmed", False), (late, "confirmed", False)]) places = first.get(f"/f/{token}/places").json() assert places[str(qid)][early] == {"free": 0, "full": True} assert places[str(qid)][late]["free"] is None def test_concurrent_bookings(app: Any) -> None: owner = creator(app) _, token, qid, (early, _) = slot_form(owner) clients = [new_client(app) for _ in range(4)] tokens = [token_for(c, f"/f/{token}") for c in clients] def submit(index: int) -> int: resp = clients[index].post(f"/f/{token}", data={"csrf_token": tokens[index], f"q{qid}": early}) return resp.status_code with ThreadPoolExecutor(max_workers=4) as pool: codes = list(pool.map(submit, range(4))) assert codes.count(303) == 1 and codes.count(409) == 3 assert [b for b in bookings(qid) if b[1] == "confirmed"] == [(early, "confirmed", False)] def test_waitlist_and_promotion(app: Any) -> None: owner = creator(app) pid, token, qid, (early, late) = slot_form(owner, waitlist=True) anna = participant(app, "anna2@example.de") bert = participant(app, "bert@example.de") assert fill(anna, token, {f"q{qid}": early}).status_code == 303 assert fill(bert, token, {f"q{qid}": early}).status_code == 303 assert [b[1] for b in bookings(qid)] == ["confirmed", "waiting"] assert "waiting list" in bert.get(f"/f/{token}/edit").text # Anna wechselt: Bert rückt nach resp = fill(anna, token, {f"q{qid}": late}, path="/edit") assert resp.status_code == 303 states = {(b[0], b[1], b[2]) for b in bookings(qid)} assert (early, "confirmed", True) in states and (late, "confirmed", False) in states # Mehr Plätze im Designer: weitere Wartende rücken nach carl = participant(app, "carl2@example.de") assert fill(carl, token, {f"q{qid}": early}).status_code == 303 csrf = token_for(owner, f"/forms/{pid}/questions/{qid}") owner.post(f"/forms/{pid}/questions/{qid}", data={ "csrf_token": csrf, "label": "Schicht", "waitlist": "on", "slot_mode": "list", "option_id": [early, late], "option_label": ["Früh", "Spät"], "option_capacity": ["2", ""]}) assert all(b[1] == "confirmed" for b in bookings(qid)) def test_places_per_person(app: Any) -> None: owner = creator(app) _, token, qid, (early, late) = slot_form(owner, capacity="", multiple=True, slots_max_per_person="1") guest = new_client(app) resp = fill(guest, token, {f"q{qid}": [early, late]}) assert resp.status_code == 400 assert "more places than allowed" in resp.text # --------------------------------------------------------------------------- # Abstimmung und Kalender # --------------------------------------------------------------------------- def poll_form(owner: TestClient) -> tuple[str, str, int]: pid = create_form(owner) add_question(owner, pid, "poll", label="Wann?", required="on", mode="dates", answers="ynm", allow_proposals="on", date_option_id=["", ""], option_date=["2026-07-01", "2026-07-08"], option_time=["18:30", ""], option_duration=["90", ""], date_option_label=["", ""]) assert save_settings(owner, pid, access="link", calendar_mode="feed", results_visibility="after_submit").status_code == 303 assert set_status(owner, pid, "open").status_code == 303 (qid,) = question_ids(pid) return pid, form_row(pid).share_token, qid def test_poll_votes_proposal_results_and_calendar(app: Any) -> None: owner = creator(app) pid, token, qid = poll_form(owner) first, second = (o["id"] for o in options_of(qid)) guest = new_client(app) resp = fill(guest, token, {f"q{qid}_{first}": "yes"}) assert resp.status_code == 400 and "Please answer every option." in resp.text resp = fill(guest, token, {f"q{qid}_{first}": "yes", f"q{qid}_{second}": "maybe", f"q{qid}_propose_date": "2026-07-15", f"q{qid}_propose_time": "19:00"}) assert resp.status_code == 303 options = options_of(qid) assert len(options) == 3 and options[-1]["proposed"] and options[-1]["date"] == "2026-07-15" thanks = guest.get(f"/f/{token}/thanks").text assert 'class="poll-result"' in thanks other = new_client(app) votes = {f"q{qid}_{o['id']}": "no" for o in options} votes[f"q{qid}_{first}"] = "yes" assert fill(other, token, votes).status_code == 303 results = owner.get(f"/forms/{pid}/responses").text assert '