LuminaWebsite/includes/raid_attendance.php
Maaxxs c4f94bf84a Member feedback: raid input checks and fixed raid points, premades in the raid form, live raid page, Lumina-style dialogs, leadership calendar entries, class-based weapon picker, map and tactics fixes
- Raids: "Max. Spieler" only whole numbers up to groups x 5 (max. 10 groups / 50), gearscore only a number; fixed +1 Lumipunkt per participation, other values only with the new raids.points permission; pick an existing premade per group when creating a raid; unchanged legacy values no longer block editing
- Raid page updates itself every 15 s while visible (raids_live.php, cards rendered by includes/raid_card.php), open editors and confirm dialogs are kept
- Restore takes the new raid_id from the bot (archived messages are now deleted in Discord) and moves settings, attendance and awards; website signups send the server display name
- Premades: dissolve by leadership needs a reason, lead gets DMs on join/assign/decline/remove (source/actor_id sent to the bot), transfer picker skips players who already lead a group, website accept keeps the one-group rule, no commas in names
- Site-wide Lumina dialog (assets/js/confirm-dialog.js) replaces confirm/prompt/alert via data-confirm; error flashes are a dialog you confirm with OK
- Calendar: audience per entry (all / leadership takes part / internal) with the new calendar.leadership permission; day cells list all entries and scroll
- Gear planner: main-hand picker filtered by the set's class, mismatches marked, "keine Klasse" option, link to an external skill/Daevanion plan per set
- Map: correct kisk icons (Elyos on Verteron/Abyss, Altgard fixed), per-map max zoom and bounded panning, German texts, data source note
- Tactics: toolbar as a uniform grid, whole-tactic copy, automatic versions with restore and a 90-day trash, official tactics protected
- Global thin gold scrollbars, readable hover colours, "Sedes Luminis" spelling, patch notes and README, schema version 34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 16:12:18 +02:00

389 lines
15 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
require_once __DIR__ . '/raids_api.php';
require_once __DIR__ . '/contributions.php';
/**
* Anwesenheit bei Raids und automatische Lumipunkte beim Archivieren.
*
* Die Raids selbst liegen beim Bot (Raid-API). Hier auf der Website liegen nur Zusaetze, die
* ueber die raid_id (= Discord-Nachrichten-ID) zugeordnet sind: die Punkte-Einstellungen
* (raid_settings) und die Anwesenheitsliste (raid_attendance, je Discord-ID).
*/
// Nur noch anwesend/abwesend. Alte Eintraege "excused" (Entschuldigt) gelten als nicht erfasst
// und verschwinden beim naechsten Speichern der Liste; die Spalte kennt den Wert weiterhin.
const RAID_ATTENDANCE_STATUSES = [
'present' => 'Anwesend',
'absent' => 'Abwesend',
];
// Lumipunkte pro Raid: fest +1 fuer jede Teilnahme, kein Abzug. Andere Werte (bis 10) legt nur
// fest, wer raids.points hat (die Sedes Luminis).
const RAID_POINTS_DEFAULT_PRESENT = 1;
const RAID_POINTS_DEFAULT_ABSENT = 0;
const RAID_POINTS_MAX = 10;
// Seit diesem Tag gilt der feste Punkt auch fuer Raids, die im Discord erstellt wurden (die Website
// legt ihre Einstellungen dann beim ersten Anzeigen an). Aeltere Raids bleiben, wie sie waren.
const RAID_POINTS_DEFAULT_SINCE = '2026-09-23 00:00:00';
/** Liefert die Fehlermeldung, wenn die Punkte fuer einen Raid nicht zwischen 0 und 10 liegen. */
function raid_points_error(int $present, int $absent): ?string
{
if ($present < 0 || $present > RAID_POINTS_MAX || $absent < 0 || $absent > RAID_POINTS_MAX) {
return 'Lumipunkte: 0 bis ' . RAID_POINTS_MAX . ' pro Raid.';
}
return null;
}
/** "+1 Lumipunkt pro Teilnahme, kein Abzug" - fuer alle, die die Werte nicht selbst festlegen. */
function raid_points_summary(int $present, int $absent): string
{
if ($present <= 0 && $absent <= 0) {
return 'Keine automatischen Lumipunkte';
}
$text = $present > 0 ? '+' . $present . ' Lumipunkt' . ($present === 1 ? '' : 'e') . ' pro Teilnahme' : 'Keine Punkte für die Teilnahme';
return $text . ($absent > 0 ? ', −' . $absent . ' bei Abwesenheit' : ', kein Abzug');
}
/** Ganze Zahl aus einem Formularwert - oder null, wenn es keine ist. */
function raid_points_input($value): ?int
{
$raw = is_int($value) ? (string) $value : trim((string) $value);
return ctype_digit($raw) ? (int) $raw : null;
}
/**
* Wann wurde der Raid erstellt? Die raid_id ist die ID der Discord-Nachricht (Snowflake) - in
* ihr steckt der Zeitpunkt (Millisekunden seit 2015).
*/
function raid_created_at(int $raidId): int
{
return intdiv(($raidId >> 22) + 1420070400000, 1000);
}
/**
* Legt fuer neue Raids ohne eigene Einstellungen (z.B. im Discord erstellt) den festen Punkt
* (+1 pro Teilnahme) an, damit auch sie beim Archivieren Lumipunkte bringen.
*
* @param array<int, int|string> $raidIds
*/
function raid_settings_ensure_defaults(array $raidIds): void
{
$since = strtotime(RAID_POINTS_DEFAULT_SINCE);
$ids = [];
foreach ($raidIds as $raidId) {
$raidId = (int) $raidId;
if ($raidId > 0 && raid_created_at($raidId) >= $since) {
$ids[$raidId] = true;
}
}
if (empty($ids)) {
return;
}
try {
$pdo = db();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT raid_id FROM raid_settings WHERE raid_id IN ($placeholders)");
$stmt->execute(array_keys($ids));
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $existing) {
unset($ids[(int) $existing]);
}
$insert = $pdo->prepare('INSERT IGNORE INTO raid_settings (raid_id, points_present, points_absent) VALUES (?, ?, ?)');
foreach (array_keys($ids) as $raidId) {
$insert->execute([$raidId, RAID_POINTS_DEFAULT_PRESENT, RAID_POINTS_DEFAULT_ABSENT]);
}
} catch (PDOException $e) {
// Nicht kritisch - beim naechsten Aufruf erneut.
}
}
/** @return array{points_present: int, points_absent: int, auto_processed_at: ?string, auto_result: ?string, attendance_checked_at: ?string, checked_by: ?string} */
function raid_settings_get(int $raidId): array
{
$stmt = db()->prepare(
"SELECT s.points_present, s.points_absent, s.auto_processed_at, s.auto_result, s.attendance_checked_at,
COALESCE(NULLIF(u.display_name, ''), u.username) AS checked_by
FROM raid_settings s LEFT JOIN users u ON u.id = s.attendance_checked_by
WHERE s.raid_id = ?"
);
$stmt->execute([$raidId]);
$row = $stmt->fetch();
return [
'points_present' => (int) ($row['points_present'] ?? 0),
'points_absent' => (int) ($row['points_absent'] ?? 0),
'auto_processed_at' => $row['auto_processed_at'] ?? null,
'auto_result' => $row['auto_result'] ?? null,
'attendance_checked_at' => $row['attendance_checked_at'] ?? null,
'checked_by' => $row['checked_by'] ?? null,
];
}
/**
* Alle Einstellungen auf einmal (fuer die Raid-Uebersicht).
*
* @return array<string, array<string, mixed>> raid_id => Einstellungen
*/
function raid_settings_all(): array
{
$settings = [];
foreach (db()->query('SELECT * FROM raid_settings')->fetchAll() as $row) {
$settings[(string) $row['raid_id']] = $row;
}
return $settings;
}
function raid_settings_save_points(int $raidId, int $present, int $absent): void
{
db()->prepare(
'INSERT INTO raid_settings (raid_id, points_present, points_absent) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE points_present = VALUES(points_present), points_absent = VALUES(points_absent)'
)->execute([$raidId, $present, $absent]);
}
/**
* Die Raid-API postet die Discord-Nachricht neu, wenn sie geloescht wurde - dann aendert sich
* die raid_id. Einstellungen, Anwesenheit und Vergaben ziehen mit um.
*/
function raid_rename_id(int $oldId, int $newId): void
{
if ($oldId === $newId || $newId <= 0) {
return;
}
$pdo = db();
$pdo->beginTransaction();
try {
// Hat eine andere Seite fuer die neue ID inzwischen schon den festen Punkt angelegt (unberuehrt),
// weicht diese Zeile den Einstellungen des Raids.
$hasOld = $pdo->prepare('SELECT 1 FROM raid_settings WHERE raid_id = ?');
$hasOld->execute([$oldId]);
if ($hasOld->fetchColumn()) {
$pdo->prepare('DELETE FROM raid_settings WHERE raid_id = ? AND auto_processed_at IS NULL AND attendance_checked_at IS NULL')
->execute([$newId]);
$pdo->prepare('UPDATE IGNORE raid_settings SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
}
$pdo->prepare('UPDATE IGNORE raid_attendance SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
$pdo->prepare('UPDATE contribution_awards SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
}
/**
* Anwesenheitsliste eines Raids.
*
* @return array<string, array{status: string, name: string}> Discord-ID => Eintrag
*/
function raid_attendance_get(int $raidId): array
{
$stmt = db()->prepare('SELECT discord_id, name, status FROM raid_attendance WHERE raid_id = ?');
$stmt->execute([$raidId]);
$list = [];
foreach ($stmt->fetchAll() as $row) {
$list[(string) $row['discord_id']] = ['status' => (string) $row['status'], 'name' => (string) $row['name']];
}
return $list;
}
/**
* Anmeldungen eines Raids, aufgeteilt: in einer Gruppe, auf der Ersatzbank, abgemeldet.
* Ausstehende Premade-Einladungen zaehlen nicht als Anmeldung.
*
* @return array{groups: array<int, array>, bench: array<int, array>, declined: array<int, array>}
*/
function raid_signups_split(array $raid): array
{
$split = ['groups' => [], 'bench' => [], 'declined' => []];
foreach ((array) ($raid['signups'] ?? []) as $signup) {
$group = (int) ($signup['group'] ?? 0);
if ($group < 0) {
$split['declined'][] = $signup;
} elseif (($signup['class'] ?? '') === 'Ausstehend') {
continue;
} elseif ($group === 0) {
$split['bench'][] = $signup;
} else {
$split['groups'][] = $signup;
}
}
return $split;
}
/**
* Aktive Website-Konten je Discord-ID.
*
* @return array<string, int> Discord-ID => user_id
*/
function raid_user_ids_by_discord(): array
{
$map = [];
$rows = db()->query("SELECT id, discord_id FROM users WHERE status = 'active' AND discord_id IS NOT NULL")->fetchAll();
foreach ($rows as $row) {
$map[(string) $row['discord_id']] = (int) $row['id'];
}
return $map;
}
/** Wurden fuer diesen Raid schon Lumipunkte vergeben (von Hand oder automatisch)? */
function raid_has_awards(int $raidId): bool
{
$stmt = db()->prepare('SELECT 1 FROM contribution_awards WHERE raid_id = ? LIMIT 1');
$stmt->execute([$raidId]);
return (bool) $stmt->fetchColumn();
}
/**
* Automatische Lumipunkte fuer archivierte Raids.
*
* Laeuft bei jedem Aufruf der Raid- und Punkteseiten und direkt nach dem Archivieren - so
* werden auch Raids erfasst, die im Discord ueber den Knopf archiviert wurden (die Website
* erfaehrt davon sonst nichts). Kosten: eine Abfrage, solange nichts offen ist.
*
* - Schon Punkte fuer den Raid vergeben? Dann entfaellt die Automatik.
* - Anwesenheitsliste gefuehrt: Anwesende bekommen die Punkte, Abwesende den Abzug.
* - Keine Liste: alle, die in einer Gruppe angemeldet waren, bekommen die Punkte (kein Abzug).
*
* @param array<int, array<string, mixed>>|null $raids Bereits geladene Raids (spart eine API-Abfrage)
* @return array<int, string> Meldungen je verarbeitetem Raid
*/
function raid_process_auto_points(?array $raids = null): array
{
if ($raids !== null) {
raid_settings_ensure_defaults(array_map(static fn (array $raid) => $raid['raid_id'] ?? 0, $raids));
}
try {
$pending = db()->query(
'SELECT raid_id, points_present, points_absent FROM raid_settings
WHERE auto_processed_at IS NULL AND (points_present > 0 OR points_absent > 0)'
)->fetchAll();
} catch (PDOException $e) {
return [];
}
if (empty($pending)) {
return [];
}
// Nur archivierte Raids zaehlen. Sind die mitgegebenen Raids nicht alle dabei, frisch laden.
$raidsById = [];
foreach ((array) $raids as $raid) {
$raidsById[(string) ($raid['raid_id'] ?? '')] = $raid;
}
$missing = array_filter($pending, static fn (array $p): bool => !isset($raidsById[(string) $p['raid_id']]));
if (!empty($missing)) {
try {
foreach (fetch_raids('all') as $raid) {
$raidsById[(string) ($raid['raid_id'] ?? '')] = $raid;
}
} catch (Throwable $e) {
return []; // Raid-API nicht erreichbar - beim naechsten Aufruf erneut
}
}
$messages = [];
$userIds = null;
foreach ($pending as $setting) {
$raidId = (int) $setting['raid_id'];
$raid = $raidsById[(string) $raidId] ?? null;
if ($raid === null || (empty($raid['archived']) && empty($raid['archived_at']))) {
continue; // noch aktiv (oder geloescht) - nichts zu tun
}
$messages[] = raid_run_auto_points($raidId, $raid, (int) $setting['points_present'], (int) $setting['points_absent'], $userIds);
}
return $messages;
}
/** Vergibt die automatischen Punkte fuer einen archivierten Raid und merkt sich das Ergebnis. */
function raid_run_auto_points(int $raidId, array $raid, int $pointsPresent, int $pointsAbsent, ?array &$userIds): string
{
$pdo = db();
$title = (string) ($raid['title'] ?? 'Raid');
$timestamp = (int) ($raid['timestamp'] ?? 0);
$awardedAt = $timestamp > 0 ? date('Y-m-d H:i:s', $timestamp) : date('Y-m-d H:i:s');
// Gegen doppelte Vergabe bei gleichzeitigen Seitenaufrufen: Zeile sperren und erneut pruefen.
$pdo->beginTransaction();
$lock = $pdo->prepare('SELECT auto_processed_at FROM raid_settings WHERE raid_id = ? FOR UPDATE');
$lock->execute([$raidId]);
if ($lock->fetchColumn() !== null) {
$pdo->commit();
return '';
}
$finish = static function (string $result) use ($pdo, $raidId): string {
$pdo->prepare('UPDATE raid_settings SET auto_processed_at = NOW(), auto_result = ? WHERE raid_id = ?')
->execute([mb_substr($result, 0, 255), $raidId]);
$pdo->commit();
return $result;
};
if (raid_has_awards($raidId)) {
return $finish('Übersprungen: Für „' . $title . '“ wurden schon vorher Punkte vergeben.');
}
$userIds ??= raid_user_ids_by_discord();
$attendance = raid_attendance_get($raidId);
$present = [];
$absent = [];
if (!empty($attendance)) {
foreach ($attendance as $discordId => $entry) {
$userId = $userIds[$discordId] ?? null;
if ($userId === null) {
continue;
}
if ($entry['status'] === 'present') {
$present[] = $userId;
} elseif ($entry['status'] === 'absent') {
$absent[] = $userId;
}
}
} else {
foreach (raid_signups_split($raid)['groups'] as $signup) {
$userId = $userIds[(string) ($signup['user_id'] ?? '')] ?? null;
if ($userId !== null) {
$present[] = $userId;
}
}
}
$present = array_values(array_unique($present));
$absent = array_values(array_unique($absent));
$insertAward = $pdo->prepare(
"INSERT INTO contribution_awards (category, title, note, raid_id, awarded_at, created_by) VALUES ('raid', ?, ?, ?, ?, NULL)"
);
$insertEntry = $pdo->prepare('INSERT INTO contribution_entries (award_id, user_id, points) VALUES (?, ?, ?)');
$parts = [];
if ($pointsPresent > 0 && !empty($present)) {
$insertAward->execute([mb_substr($title, 0, 150), 'Automatisch beim Archivieren' . (empty($attendance) ? ' (ohne Anwesenheitsliste: alle Teilnehmer)' : ''), $raidId, $awardedAt]);
$awardId = (int) $pdo->lastInsertId();
foreach ($present as $userId) {
$insertEntry->execute([$awardId, $userId, $pointsPresent]);
}
$parts[] = count($present) . '× +' . $pointsPresent;
}
if ($pointsAbsent > 0 && !empty($absent)) {
$insertAward->execute([mb_substr('Abwesend: ' . $title, 0, 150), 'Automatisch beim Archivieren', $raidId, $awardedAt]);
$awardId = (int) $pdo->lastInsertId();
foreach ($absent as $userId) {
$insertEntry->execute([$awardId, $userId, -$pointsAbsent]);
}
$parts[] = count($absent) . '× −' . $pointsAbsent;
}
return $finish(empty($parts)
? 'Keine automatischen Punkte für „' . $title . '“: niemand mit Website-Konto zu berücksichtigen.'
: 'Automatische Lumipunkte für „' . $title . '“ vergeben: ' . implode(', ', $parts) . '.');
}
/** Ist fuer den Bot-Rueckkanal ein gemeinsamer Schluessel eingetragen? (config.php: bot_callback.key) */
function bot_callback_key(): ?string
{
$config = require __DIR__ . '/../config.php';
$key = (string) ($config['bot_callback']['key'] ?? '');
return strlen($key) >= 16 ? $key : null;
}