321 lines
12 KiB
Python
321 lines
12 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Plätze im Teilnahme-Feld vergeben, mit Warteliste.
|
|
|
|
Vergabe beim Absenden in derselben Transaktion wie die Antwort. Vorher wird
|
|
die Zeile der Frage gesperrt (SELECT … FOR UPDATE). Zwei gleichzeitige
|
|
Buchungen derselben Frage laufen damit nacheinander; der letzte Platz kann
|
|
nicht doppelt vergeben werden.
|
|
|
|
Wird ein Platz frei (Antwort geändert, Option abgewählt, Kapazität erhöht),
|
|
rückt die am längsten wartende Person nach; `promoted_at` merkt sich, wer
|
|
nachgerückt ist. Was dabei passiert, sammelt `Events`; die Benachrichtigungen
|
|
verschickt der Aufrufer (mail.notify.booking_events).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Mapping
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from surveybox.forms import types
|
|
from surveybox.models import Booking, BookingStatus, Form, Question, Response
|
|
|
|
|
|
class SlotFull(Exception):
|
|
def __init__(self, question_id: int, option_id: str) -> None:
|
|
super().__init__(f"{question_id}:{option_id}")
|
|
self.question_id = question_id
|
|
self.option_id = option_id
|
|
|
|
|
|
@dataclass
|
|
class Availability:
|
|
capacity: int | None
|
|
confirmed: int
|
|
waiting: int
|
|
|
|
@property
|
|
def free(self) -> int | None:
|
|
return None if self.capacity is None else max(self.capacity - self.confirmed, 0)
|
|
|
|
@property
|
|
def full(self) -> bool:
|
|
return self.capacity is not None and self.confirmed >= self.capacity
|
|
|
|
|
|
def _capacity(question: Question, option_id: str) -> int | None:
|
|
for option in types.options_of(question):
|
|
if option["id"] == option_id:
|
|
raw: Any = option.get("capacity")
|
|
return int(raw) if raw else None
|
|
return 0 # gelöschte Option: nichts mehr frei
|
|
|
|
|
|
def _lock(db: Session, question: Question) -> None:
|
|
# FOR NO KEY UPDATE: sperrt gleichzeitige Buchungen gegeneinander, aber nicht gegen
|
|
# Fremdschlüssel-Prüfungen (Antworten auf diese Frage); FOR UPDATE führte zu Deadlocks
|
|
db.execute(select(Question.id).where(Question.id == question.id)
|
|
.with_for_update(key_share=True))
|
|
|
|
|
|
def _counts(db: Session, question: Question) -> dict[tuple[str, str], int]:
|
|
rows = db.execute(
|
|
select(Booking.option_id, Booking.status, func.count())
|
|
.where(Booking.question_id == question.id)
|
|
.group_by(Booking.option_id, Booking.status)
|
|
).all()
|
|
return {(option, status): int(n) for option, status, n in rows}
|
|
|
|
|
|
def availability(db: Session, question: Question) -> dict[str, Availability]:
|
|
counts = _counts(db, question)
|
|
return {
|
|
o["id"]: Availability(
|
|
_capacity(question, o["id"]),
|
|
counts.get((o["id"], BookingStatus.CONFIRMED), 0),
|
|
counts.get((o["id"], BookingStatus.WAITING), 0),
|
|
)
|
|
for o in types.options_of(question)
|
|
}
|
|
|
|
|
|
def form_availability(db: Session, form: Form) -> dict[int, dict[str, Availability]]:
|
|
return {q.id: availability(db, q) for q in form.questions if q.type == "slots"}
|
|
|
|
|
|
def availability_for(
|
|
db: Session, form: Form, response_ids: list[int]
|
|
) -> dict[int, dict[str, Availability]]:
|
|
"""Belegung nur durch bestimmte Antworten (gefilterte Auswertung)."""
|
|
rows = db.execute(
|
|
select(Booking.question_id, Booking.option_id, Booking.status, func.count())
|
|
.where(Booking.form_id == form.id, Booking.response_id.in_(response_ids))
|
|
.group_by(Booking.question_id, Booking.option_id, Booking.status)
|
|
).all() if response_ids else []
|
|
counts = {(qid, oid, status): int(n) for qid, oid, status, n in rows}
|
|
return {
|
|
q.id: {
|
|
o["id"]: Availability(
|
|
_capacity(q, o["id"]),
|
|
counts.get((q.id, o["id"], BookingStatus.CONFIRMED), 0),
|
|
counts.get((q.id, o["id"], BookingStatus.WAITING), 0),
|
|
)
|
|
for o in types.options_of(q)
|
|
}
|
|
for q in form.questions if q.type == "slots"
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class SlotNames:
|
|
confirmed: list[str] = field(default_factory=list)
|
|
waiting: list[str] = field(default_factory=list)
|
|
|
|
|
|
def _display_name(full: str, mode: str) -> str:
|
|
if mode != "short":
|
|
return full
|
|
first, _, last = full.rpartition(" ") if " " in full else (full, "", "")
|
|
return types.short_name(first, last) if last else full
|
|
|
|
|
|
def names_for_form(db: Session, form: Form) -> dict[int, dict[str, SlotNames]]:
|
|
"""Wer sich schon eingetragen hat, je Teilnahme-Feld und Option (in Reihenfolge).
|
|
|
|
Nur, wenn das Formular es so eingestellt hat und nicht anonym ist. Der Name kommt
|
|
aus dem Feld "Teilnehmer-Name", sonst aus dem Konto; Gäste ohne Namen erscheinen
|
|
als "Gast". E-Mail-Adressen werden nie angezeigt.
|
|
"""
|
|
mode = form.slot_names
|
|
if mode not in ("full", "short") or form.anonymous:
|
|
return {}
|
|
from surveybox.i18n import gettext
|
|
from surveybox.models import Answer, UserAccount
|
|
|
|
name_q = next((q for q in form.questions if q.type == "participant_name"), None)
|
|
rows = db.execute(
|
|
select(Booking.question_id, Booking.option_id, Booking.status, Booking.response_id,
|
|
Response.user_id)
|
|
.join(Response, Response.id == Booking.response_id)
|
|
.where(Booking.form_id == form.id)
|
|
.order_by(Booking.created_at, Booking.id)
|
|
).all()
|
|
if not rows:
|
|
return {}
|
|
response_ids = {r.response_id for r in rows}
|
|
given: dict[int, str] = {}
|
|
if name_q is not None:
|
|
for answer in db.scalars(select(Answer).where(
|
|
Answer.question_id == name_q.id, Answer.response_id.in_(response_ids))):
|
|
parts = types.name_parts({"value_json": answer.value_json})
|
|
if parts["first"] or parts["last"]:
|
|
given[answer.response_id] = (
|
|
types.short_name(parts["first"], parts["last"]) if mode == "short"
|
|
else f"{parts['first']} {parts['last']}".strip()
|
|
)
|
|
user_ids = {r.user_id for r in rows if r.user_id is not None and r.response_id not in given}
|
|
accounts = dict(db.execute(
|
|
select(UserAccount.id, UserAccount.display_name).where(UserAccount.id.in_(user_ids))
|
|
).tuples().all()) if user_ids else {}
|
|
guest = gettext("Guest")
|
|
result: dict[int, dict[str, SlotNames]] = {}
|
|
for row in rows:
|
|
name = given.get(row.response_id)
|
|
if name is None:
|
|
account = accounts.get(row.user_id) if row.user_id is not None else None
|
|
name = _display_name(account, mode) if account else guest
|
|
names = result.setdefault(row.question_id, {}).setdefault(row.option_id, SlotNames())
|
|
(names.waiting if row.status == BookingStatus.WAITING else names.confirmed).append(name)
|
|
return result
|
|
|
|
|
|
@dataclass
|
|
class Events:
|
|
"""Was beim Buchen passiert ist; daraus entstehen Benachrichtigungen (mail.notify)."""
|
|
|
|
promoted: list[tuple[Question, Booking]] = field(default_factory=list)
|
|
filled: list[tuple[Question, str]] = field(default_factory=list)
|
|
|
|
|
|
def promote(db: Session, question: Question, option_id: str) -> list[Booking]:
|
|
"""Lässt Wartende nachrücken, solange Plätze frei sind. Gibt die Nachgerückten zurück."""
|
|
capacity = _capacity(question, option_id)
|
|
confirmed = db.scalar(
|
|
select(func.count()).select_from(Booking).where(
|
|
Booking.question_id == question.id,
|
|
Booking.option_id == option_id,
|
|
Booking.status == BookingStatus.CONFIRMED,
|
|
)
|
|
) or 0
|
|
free = None if capacity is None else capacity - confirmed
|
|
waiting = db.scalars(
|
|
select(Booking)
|
|
.where(
|
|
Booking.question_id == question.id,
|
|
Booking.option_id == option_id,
|
|
Booking.status == BookingStatus.WAITING,
|
|
)
|
|
.order_by(Booking.created_at, Booking.id)
|
|
).all()
|
|
moved: list[Booking] = []
|
|
for booking in waiting:
|
|
if free is not None and free <= 0:
|
|
break
|
|
booking.status = BookingStatus.CONFIRMED
|
|
booking.promoted_at = datetime.now(UTC)
|
|
moved.append(booking)
|
|
if free is not None:
|
|
free -= 1
|
|
return moved
|
|
|
|
|
|
def promote_all(db: Session, question: Question, events: Events | None = None) -> int:
|
|
"""Nach einer Änderung der Kapazitäten im Designer."""
|
|
if question.type != "slots":
|
|
return 0
|
|
_lock(db, question)
|
|
count = 0
|
|
for option in types.options_of(question):
|
|
moved = promote(db, question, option["id"])
|
|
count += len(moved)
|
|
if events is not None:
|
|
events.promoted.extend((question, b) for b in moved)
|
|
return count
|
|
|
|
|
|
def book(
|
|
db: Session,
|
|
form: Form,
|
|
response: Response,
|
|
selections: Mapping[int, list[str]],
|
|
events: Events | None = None,
|
|
) -> dict[int, dict[str, str]]:
|
|
"""Bringt die Buchungen einer Antwort auf den gewünschten Stand.
|
|
|
|
selections: je Teilnahme-Frage die gewählten Optionen (auch leer, um alles
|
|
freizugeben). Ergebnis: je Frage Option -> Status. Ist ein Platz voll und
|
|
gibt es keine Warteliste, wird SlotFull ausgelöst; der Aufrufer rollt die
|
|
Transaktion zurück.
|
|
"""
|
|
db.flush() # die Antwort braucht ihre ID
|
|
result: dict[int, dict[str, str]] = {}
|
|
for question in form.questions:
|
|
if question.type != "slots":
|
|
continue
|
|
wanted = list(dict.fromkeys(selections.get(question.id) or []))
|
|
existing = {
|
|
b.option_id: b
|
|
for b in db.scalars(
|
|
select(Booking).where(
|
|
Booking.response_id == response.id, Booking.question_id == question.id
|
|
)
|
|
)
|
|
}
|
|
if not wanted and not existing:
|
|
continue
|
|
_lock(db, question)
|
|
released = [oid for oid in existing if oid not in wanted]
|
|
for option_id in released:
|
|
db.delete(existing.pop(option_id))
|
|
db.flush()
|
|
statuses: dict[str, str] = {}
|
|
for option_id in wanted:
|
|
if option_id in existing:
|
|
statuses[option_id] = existing[option_id].status
|
|
continue
|
|
capacity = _capacity(question, option_id)
|
|
confirmed = db.scalar(
|
|
select(func.count()).select_from(Booking).where(
|
|
Booking.question_id == question.id,
|
|
Booking.option_id == option_id,
|
|
Booking.status == BookingStatus.CONFIRMED,
|
|
)
|
|
) or 0
|
|
if capacity is None or confirmed < capacity:
|
|
status = BookingStatus.CONFIRMED
|
|
if events is not None and capacity is not None and confirmed + 1 >= capacity:
|
|
events.filled.append((question, option_id))
|
|
elif question.config.get("waitlist"):
|
|
status = BookingStatus.WAITING
|
|
else:
|
|
raise SlotFull(question.id, option_id)
|
|
db.add(
|
|
Booking(
|
|
form_id=form.id,
|
|
question_id=question.id,
|
|
option_id=option_id,
|
|
response_id=response.id,
|
|
status=status,
|
|
)
|
|
)
|
|
statuses[option_id] = status
|
|
db.flush()
|
|
for option_id in released:
|
|
moved = promote(db, question, option_id)
|
|
if events is not None:
|
|
events.promoted.extend((question, b) for b in moved)
|
|
result[question.id] = statuses
|
|
return result
|
|
|
|
|
|
def statuses_for(db: Session, response: Response) -> dict[tuple[int, str], str]:
|
|
return {
|
|
(b.question_id, b.option_id): b.status
|
|
for b in db.scalars(select(Booking).where(Booking.response_id == response.id))
|
|
}
|
|
|
|
|
|
def slots_chosen(form: Form, stored: Mapping[int, Mapping[str, Any]]) -> dict[int, list[str]]:
|
|
"""Gewählte Optionen je Teilnahme-Frage aus den geprüften Antworten."""
|
|
result: dict[int, list[str]] = {}
|
|
for question in form.questions:
|
|
if question.type == "slots":
|
|
data = (stored.get(question.id) or {}).get("value_json") or {}
|
|
result[question.id] = list(data.get("selected") or [])
|
|
return result
|