Abstimmungen: anlegen, Ergebnis mit Balken, beenden und löschen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-09-29 08:12:09 +02:00
parent ef8b381e5f
commit a6e3133e06
8 changed files with 332 additions and 2 deletions

85
app.py
View file

@ -954,6 +954,91 @@ async def alliance_page(request: Request):
return render(request, "alliance.html", user, data=data, error=error) return render(request, "alliance.html", user, data=data, error=error)
# ---------------------------------------------------------------------------
# Abstimmungen
# ---------------------------------------------------------------------------
POLL_DURATIONS = [("", "Bis ich sie beende"), ("3600", "1 Stunde"), ("21600", "6 Stunden"), ("43200", "12 Stunden"),
("86400", "1 Tag"), ("259200", "3 Tage"), ("604800", "1 Woche"), ("1209600", "2 Wochen")]
@app.get("/abstimmungen", response_class=HTMLResponse)
async def polls_page(request: Request):
user = current_user(request)
require_area(user, "polls")
try:
data = await siel._request("GET", "/api/polls")
guild = await siel.guild()
error = None
except siel.SielError as exc:
data, guild, error = {"polls": []}, None, str(exc)
draft = DRAFTS.pop((user["id"], "poll"), None)
return render(request, "polls.html", user, polls=data["polls"], guild=guild, error=error, draft=draft,
durations=POLL_DURATIONS, now=int(time.time()))
@app.post("/abstimmungen/neu")
async def poll_create(request: Request):
user = current_user(request)
require_area(user, "polls")
form = await form_with_csrf(request)
try:
payload = json.loads(str(form.get("payload", "")))
if not isinstance(payload, dict):
raise ValueError
except ValueError:
flash(request, "Die Eingaben kamen nicht richtig an. Bitte lade die Seite neu.", "error")
return RedirectResponse("/abstimmungen", status_code=303)
try:
poll = await siel._request("POST", "/api/polls", json=payload, user=user["name"])
except siel.SielError as exc:
DRAFTS[(user["id"], "poll")] = payload
flash(request, str(exc), "error")
return RedirectResponse("/abstimmungen#neu", status_code=303)
panel_db.log(user["id"], user["name"], "Abstimmung gestartet", poll["question"])
flash(request, "Die Abstimmung läuft im Discord.")
return RedirectResponse(f"/abstimmungen/{poll['id']}", status_code=303)
@app.get("/abstimmungen/{poll_id}", response_class=HTMLResponse)
async def poll_detail(request: Request, poll_id: int):
user = current_user(request)
require_area(user, "polls")
try:
poll = await siel._request("GET", f"/api/polls/{poll_id}")
except siel.SielError:
raise HTTPException(status_code=404, detail="Diese Abstimmung gibt es nicht (mehr).")
return render(request, "poll_detail.html", user, poll=poll, now=int(time.time()))
@app.post("/abstimmungen/{poll_id}/beenden")
async def poll_end(request: Request, poll_id: int):
user = current_user(request)
require_area(user, "polls")
await form_with_csrf(request)
try:
poll = await siel.post(f"/api/polls/{poll_id}/end", {})
panel_db.log(user["id"], user["name"], "Abstimmung beendet", poll["question"])
flash(request, "Die Abstimmung ist beendet.")
except siel.SielError as exc:
flash(request, str(exc), "error")
return RedirectResponse(f"/abstimmungen/{poll_id}", status_code=303)
@app.post("/abstimmungen/{poll_id}/loeschen")
async def poll_delete(request: Request, poll_id: int):
user = current_user(request)
require_area(user, "polls")
await form_with_csrf(request)
try:
await siel.delete(f"/api/polls/{poll_id}")
panel_db.log(user["id"], user["name"], "Abstimmung gelöscht", f"#{poll_id}")
flash(request, "Gelöscht – auch die Nachricht im Discord.")
except siel.SielError as exc:
flash(request, str(exc), "error")
return RedirectResponse("/abstimmungen", status_code=303)
if __name__ == "__main__": if __name__ == "__main__":
import uvicorn import uvicorn

View file

@ -39,6 +39,7 @@ AREAS = {
"reactionroles": "Reaktionsrollen", "reactionroles": "Reaktionsrollen",
"moderation": "Moderation", "moderation": "Moderation",
"tickets": "Tickets", "tickets": "Tickets",
"polls": "Abstimmungen",
"alliance": "Allianz", "alliance": "Allianz",
} }

View file

@ -395,3 +395,15 @@ input[type=number]:focus { outline: none; border-color: var(--gold); }
.pun-row { align-items: flex-start; } .pun-row { align-items: flex-start; }
} }
.input-label { width: 11rem; background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 0.35rem 0.55rem; } .input-label { width: 11rem; background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 0.35rem 0.55rem; }
/* ---------- Abstimmungen ---------- */
.field-wide { max-width: none; }
.poll-options { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.5rem; }
.poll-option { display: grid; grid-template-columns: 70px minmax(0, 1fr) auto; gap: 0.5rem; align-items: center; }
.poll-results { display: flex; flex-direction: column; gap: 0.8rem; margin: 0.75rem 0; }
.poll-result-head { display: flex; justify-content: space-between; gap: 1rem; margin-bottom: 0.3rem; }
.poll-bar { height: 10px; border-radius: 999px; background: var(--bg); border: 1px solid var(--border); overflow: hidden; }
.poll-bar span { display: block; height: 100%; width: 0; background: var(--text-muted); border-radius: 999px; }
.poll-top .poll-bar span { background: var(--gold); }
.actions-row { display: flex; gap: 0.6rem; flex-wrap: wrap; }
.actions-row form { margin: 0; }

72
static/js/polls.js Normal file
View file

@ -0,0 +1,72 @@
/* Abstimmungen: Balkenbreiten (CSP erlaubt keine style-Attribute) und das Formular fuer neue Abstimmungen. */
(function () {
'use strict';
for (const bar of document.querySelectorAll('.poll-bar span[data-pct]')) {
bar.style.width = Math.max(0, Math.min(100, Number(bar.dataset.pct) || 0)) + '%';
}
const raw = document.getElementById('poll-data');
if (!raw) return;
const { draft, roles } = JSON.parse(raw.textContent);
const { el } = window.SielEditor;
const form = document.getElementById('neu');
const list = document.getElementById('poll-options');
const addBtn = document.getElementById('poll-add');
const options = (draft && draft.options && draft.options.length ? draft.options : [{ label: '' }, { label: '' }])
.map((o) => (typeof o === 'string' ? { label: o, emoji: '' } : { label: o.label || '', emoji: o.emoji || '' }));
function paint() {
list.textContent = '';
options.forEach((o, idx) => {
const emoji = el('input', { type: 'text', class: 'emoji-input', maxlength: '80', placeholder: String(idx + 1) });
emoji.value = o.emoji;
emoji.addEventListener('input', () => { o.emoji = emoji.value.trim(); });
const label = el('input', { type: 'text', maxlength: '80', placeholder: 'Antwort ' + (idx + 1) });
label.value = o.label;
label.addEventListener('input', () => { o.label = label.value; });
const remove = el('button', { type: 'button', class: 'icon-btn danger', text: '✕', title: 'Entfernen', disabled: options.length <= 2 });
remove.addEventListener('click', () => { options.splice(idx, 1); paint(); });
list.append(el('div', { class: 'poll-option' }, emoji, label, remove));
});
addBtn.hidden = options.length >= 10;
}
addBtn.addEventListener('click', () => { options.push({ label: '', emoji: '' }); paint(); list.lastChild.querySelector('input:not(.emoji-input)').focus(); });
paint();
const roleBox = document.getElementById('poll-roles');
for (const r of roles.filter((x) => !x.managed)) {
const cb = el('input', { type: 'checkbox', value: r.id });
cb.checked = !!(draft && (draft.roles || []).includes(r.id));
const dot = el('span', { class: 'role-dot' });
if (r.color) dot.style.background = r.color;
roleBox.append(el('label', { class: 'role-item' }, cb, dot, r.name));
}
if (draft) {
document.getElementById('poll-question').value = draft.question || '';
document.getElementById('poll-description').value = draft.description || '';
document.getElementById('poll-max').value = draft.max_choices || 1;
document.getElementById('poll-live').checked = draft.live_results !== false;
document.getElementById('poll-anon').checked = !!draft.anonymous;
document.getElementById('poll-ping').value = draft.ping_role || '';
document.getElementById('poll-duration').value = draft.duration || '';
form.elements.channel_id.value = draft.channel_id || '';
}
form.addEventListener('submit', () => {
document.getElementById('poll-payload').value = JSON.stringify({
channel_id: form.elements.channel_id.value || null,
question: document.getElementById('poll-question').value,
description: document.getElementById('poll-description').value,
options: options.filter((o) => o.label.trim()),
duration: document.getElementById('poll-duration').value || null,
max_choices: Number(document.getElementById('poll-max').value) || 1,
live_results: document.getElementById('poll-live').checked,
anonymous: document.getElementById('poll-anon').checked,
ping_role: document.getElementById('poll-ping').value || null,
roles: Array.from(roleBox.querySelectorAll('input:checked')).map((i) => i.value),
});
});
})();

View file

@ -7,7 +7,7 @@
<title>{% block title %}Siel{% endblock %} · Elyos Allianz</title> <title>{% block title %}Siel{% endblock %} · Elyos Allianz</title>
<link rel="icon" type="image/png" sizes="32x32" href="/static/img/favicon-32.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/img/favicon-32.png">
<link rel="apple-touch-icon" href="/static/img/favicon-180.png"> <link rel="apple-touch-icon" href="/static/img/favicon-180.png">
<link rel="stylesheet" href="/static/css/panel.css?v=11"> <link rel="stylesheet" href="/static/css/panel.css?v=12">
</head> </head>
<body> <body>
{% if user %} {% if user %}
@ -28,7 +28,7 @@
{% endif %} {% endif %}
{% endfor %} {% endfor %}
<div class="nav-heading">Funktionen</div> <div class="nav-heading">Funktionen</div>
{% for area, label, href, ic in [("welcome", "Begrüßung", "/begruessung", "welcome"), ("reactionroles", "Reaktionsrollen", "/reaktionsrollen", "smile"), ("moderation", "Moderation", "/moderation", "shield"), ("tickets", "Tickets", "/tickets", "ticket"), ("alliance", "Allianz", "/allianz", "users")] %} {% for area, label, href, ic in [("welcome", "Begrüßung", "/begruessung", "welcome"), ("reactionroles", "Reaktionsrollen", "/reaktionsrollen", "smile"), ("moderation", "Moderation", "/moderation", "shield"), ("tickets", "Tickets", "/tickets", "ticket"), ("polls", "Abstimmungen", "/abstimmungen", "chart"), ("alliance", "Allianz", "/allianz", "users")] %}
{% if area in user.areas %} {% if area in user.areas %}
{% if href %} {% if href %}
<a href="{{ href }}" class="nav-link{% if path == href or path.startswith(href ~ "/") %} active{% endif %}">{{ icon(ic) }}<span>{{ label }}</span></a> <a href="{{ href }}" class="nav-link{% if path == href or path.startswith(href ~ "/") %} active{% endif %}">{{ icon(ic) }}<span>{{ label }}</span></a>

View file

@ -8,6 +8,7 @@
"shield": '<path d="M12 21c4.5-1.8 7-5.2 7-9.5V6l-7-3-7 3v5.5c0 4.3 2.5 7.7 7 9.5z"/>', "shield": '<path d="M12 21c4.5-1.8 7-5.2 7-9.5V6l-7-3-7 3v5.5c0 4.3 2.5 7.7 7 9.5z"/>',
"ticket": '<path d="M3 7a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 0 0 4v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3a2 2 0 0 0 0-4z"/><line x1="14" y1="5" x2="14" y2="7"/><line x1="14" y1="11" x2="14" y2="13"/><line x1="14" y1="17" x2="14" y2="19"/>', "ticket": '<path d="M3 7a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 0 0 4v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3a2 2 0 0 0 0-4z"/><line x1="14" y1="5" x2="14" y2="7"/><line x1="14" y1="11" x2="14" y2="13"/><line x1="14" y1="17" x2="14" y2="19"/>',
"users": '<path d="M16 19v-1.5a3.5 3.5 0 0 0-3.5-3.5h-5A3.5 3.5 0 0 0 4 17.5V19"/><circle cx="9" cy="8" r="3"/><path d="M20 19v-1.5a3.5 3.5 0 0 0-2.5-3.36"/><path d="M14.5 4.6a3 3 0 0 1 0 5.8"/>', "users": '<path d="M16 19v-1.5a3.5 3.5 0 0 0-3.5-3.5h-5A3.5 3.5 0 0 0 4 17.5V19"/><circle cx="9" cy="8" r="3"/><path d="M20 19v-1.5a3.5 3.5 0 0 0-2.5-3.36"/><path d="M14.5 4.6a3 3 0 0 1 0 5.8"/>',
"chart": '<line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/>',
"key": '<circle cx="7.5" cy="15.5" r="4.5"/><path d="m10.7 12.3 9.8-9.8"/><path d="m17 6 3 3"/><path d="m14.5 8.5 2 2"/>', "key": '<circle cx="7.5" cy="15.5" r="4.5"/><path d="m10.7 12.3 9.8-9.8"/><path d="m17 6 3 3"/><path d="m14.5 8.5 2 2"/>',
"list": '<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/>', "list": '<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/>',
"log-out": '<path d="M9 20H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3"/><path d="m14 16 4-4-4-4"/><path d="M18 12H9"/>', "log-out": '<path d="M9 20H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3"/><path d="m14 16 4-4-4-4"/><path d="M18 12H9"/>',

View file

@ -0,0 +1,70 @@
{% extends "base.html" %}
{% block title %}Abstimmung{% endblock %}
{% block content %}
<div class="page-head">
<a href="/abstimmungen" class="back-link">← Alle Abstimmungen</a>
<h1>📊 {{ poll.question }}
{% if poll.status == "open" %}<span class="tag tag-green">Läuft</span>{% else %}<span class="tag">Beendet</span>{% endif %}
</h1>
<p class="muted">
# {{ poll.channel_name or "?" }} · gestartet {{ poll.created_at | datetime }}{% if poll.created_by %} von {{ poll.created_by }}{% endif %}
· {% if poll.status == "open" %}{% if poll.ends_at %}endet {{ poll.ends_at | datetime }}{% else %}ohne Ende{% endif %}{% else %}beendet {{ poll.ended_at | datetime }}{% endif %}
{% if poll.message_url %}· <a href="{{ poll.message_url }}" target="_blank" rel="noopener">Im Discord öffnen</a>{% endif %}
</p>
</div>
{% if poll.description %}<p>{{ poll.description }}</p>{% endif %}
<section class="panel">
<h2>Ergebnis <span class="muted">· {{ poll.voters }} {{ "Person" if poll.voters == 1 else "Personen" }}</span></h2>
{% set total = poll.counts | sum %}
{% set top = poll.counts | max %}
<div class="poll-results">
{% for o in poll.options %}
{% set n = poll.counts[loop.index0] %}
{% set pct = (100 * n / total) | round | int if total else 0 %}
<div class="poll-result{% if n == top and total %} poll-top{% endif %}">
<div class="poll-result-head"><span>{{ o.emoji or loop.index ~ "." }} <strong>{{ o.label }}</strong></span><span>{{ pct }} % · {{ n }}</span></div>
<div class="poll-bar"><span data-pct="{{ pct }}"></span></div>
</div>
{% endfor %}
</div>
<p class="muted small">
{{ "Mehrere Stimmen pro Person (bis " ~ poll.max_choices ~ ")" if poll.max_choices > 1 else "Eine Stimme pro Person" }}
· {{ "anonym" if poll.anonymous else "nicht anonym" }}
· Ergebnis {{ "live sichtbar" if poll.live_results else "erst am Ende sichtbar" }}
</p>
</section>
{% if poll.votes is defined and poll.votes %}
<section class="panel">
<h2>Wer hat was gewählt</h2>
<div class="table-wrap">
<table class="table">
<thead><tr><th>Person</th><th>Antwort</th><th>Wann</th></tr></thead>
<tbody>
{% for v in poll.votes %}
<tr><td>{{ v.user_name }}</td><td>{{ poll.options[v.option_idx].label if v.option_idx < poll.options | length else "?" }}</td><td class="small">{{ v.voted_at | datetime }}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% elif poll.anonymous %}
<p class="muted small">Anonyme Abstimmung – wer was gewählt hat, wird nirgends angezeigt.</p>
{% endif %}
<div class="actions-row">
{% if poll.status == "open" %}
<form method="post" action="/abstimmungen/{{ poll.id }}/beenden" data-confirm="Abstimmung jetzt beenden? Danach kann niemand mehr abstimmen.">
<input type="hidden" name="csrf" value="{{ csrf }}">
<button type="submit" class="btn">Jetzt beenden</button>
</form>
{% endif %}
<form method="post" action="/abstimmungen/{{ poll.id }}/loeschen" data-confirm="Abstimmung löschen? Die Nachricht verschwindet auch aus dem Discord, die Stimmen sind weg.">
<input type="hidden" name="csrf" value="{{ csrf }}">
<button type="submit" class="btn btn-danger">Löschen</button>
</form>
</div>
<script src="/static/js/confirm.js?v=1"></script>
<script src="/static/js/polls.js?v=1"></script>
{% endblock %}

89
templates/polls.html Normal file
View file

@ -0,0 +1,89 @@
{% extends "base.html" %}
{% from "macros.html" import channel_select %}
{% block title %}Abstimmungen{% endblock %}
{% block content %}
<div class="page-head">
<h1>Abstimmungen</h1>
<p class="muted">Frage stellen, Antworten vorgeben, im Discord per Knopf abstimmen lassen. Schnell geht es auch mit <code>/abstimmung</code> direkt im Discord (für Moderatoren).</p>
</div>
{% if error %}<div class="flash flash-error">{{ error }}</div>{% endif %}
<section class="panel">
<h2>Laufende und beendete Abstimmungen</h2>
{% if polls %}
<div class="rr-list">
{% for p in polls %}
<div class="rr-row">
<div class="rr-main">
<a href="/abstimmungen/{{ p.id }}" class="rr-name">📊 {{ p.question }}</a>
<div class="muted small"># {{ p.channel_name or "?" }} · {{ p.options | length }} Antworten · {{ p.voters }} {{ "Person" if p.voters == 1 else "Personen" }} abgestimmt{% if p.anonymous %} · anonym{% endif %}</div>
{% if p.voters %}
{% set total = p.counts | sum %}
{% set top = p.counts | max %}
<div class="muted small">Vorne: {% for o in p.options %}{% if p.counts[loop.index0] == top %}<strong>{{ o.label }}</strong> ({{ (100 * top / total) | round | int }} %) {% endif %}{% endfor %}</div>
{% endif %}
</div>
<div class="rr-status">
{% if p.status == "open" %}<span class="tag tag-green">Läuft</span>
<div class="muted small">{% if p.ends_at %}bis {{ p.ends_at | datetime }}{% else %}ohne Ende{% endif %}</div>
{% else %}<span class="tag">Beendet</span>
<div class="muted small">{{ p.ended_at | datetime }}</div>{% endif %}
</div>
<div class="rr-actions">
<a href="/abstimmungen/{{ p.id }}" class="btn btn-sm btn-secondary">Ergebnis</a>
</div>
</div>
{% endfor %}
</div>
{% else %}
<p class="muted">Noch keine Abstimmung.</p>
{% endif %}
</section>
{% if guild %}
<script type="application/json" id="poll-data">{{ {"draft": draft, "roles": guild.roles} | tojson }}</script>
<form method="post" action="/abstimmungen/neu" class="panel" id="neu">
<input type="hidden" name="csrf" value="{{ csrf }}">
<input type="hidden" name="payload" id="poll-payload">
<h2>Neue Abstimmung</h2>
<div class="field-row">
<label class="field"><span>Kanal</span>
{{ channel_select("channel_id", guild.channels, None, empty="– Kanal wählen –") }}
</label>
<label class="field"><span>Dauer</span>
<select id="poll-duration">
{% for v, l in durations %}<option value="{{ v }}"{% if v == "86400" %} selected{% endif %}>{{ l }}</option>{% endfor %}
</select>
</label>
</div>
<label class="field field-wide"><span>Frage</span>
<input type="text" id="poll-question" maxlength="250" required placeholder="z. B. Welcher Tag passt euch für den nächsten Raid?">
</label>
<label class="field field-wide"><span>Beschreibung (optional)</span>
<textarea id="poll-description" rows="2" maxlength="1000"></textarea>
</label>
<div class="field field-wide"><span>Antworten (2 bis 10) – Emoji optional, ohne Emoji nummeriert Siel sie</span>
<div id="poll-options" class="poll-options"></div>
<button type="button" class="btn btn-sm btn-ghost" id="poll-add">+ Antwort hinzufügen</button>
</div>
<div class="field-row">
<label class="field"><span>Stimmen pro Person</span>
<input type="number" id="poll-max" min="1" max="10" value="1" class="input-sm">
</label>
<label class="field"><span>Rolle beim Start anpingen (optional)</span>
<select id="poll-ping"><option value="">– niemand –</option>
{% for r in guild.roles if not r.managed %}<option value="{{ r.id }}">{{ r.name }}</option>{% endfor %}
</select>
</label>
</div>
<label class="check"><input type="checkbox" id="poll-live" checked> Ergebnis schon während der Abstimmung zeigen</label><br>
<label class="check"><input type="checkbox" id="poll-anon"> Anonym – auch im Panel nicht zeigen, wer was gewählt hat</label>
<div class="field field-wide"><span>Nur diese Rollen dürfen abstimmen (keine gewählt = alle)</span>
<div class="role-list" id="poll-roles"></div>
</div>
<button type="submit" class="btn">Abstimmung starten</button>
</form>
<script src="/static/js/embed-editor.js?v=2"></script>
<script src="/static/js/polls.js?v=1"></script>
{% endif %}
{% endblock %}