LuminaWebsite/includes/raid_attendance.php
Maaxxs fe1561f4f7 Raids: attendance list, automatic points on archive, reminder callback
Each raid gets an attendance list for raids.manage (present, absent, excused)
with quick actions, members added by hand and a "checked" mark with who and
when. The contribution form can now select a raid's present members for
points or its absent members for a deduction.

Raids can carry points for present members and a deduction for absent ones
(raid_settings). When a raid is archived - on the website or via the button
in Discord, detected on the next raid or contribution page view - the site
awards them once: by attendance if a list exists, otherwise to everyone in a
group without deduction, and not at all if points were already given for
that raid. Settings, attendance and awards follow a raid_id change when the
API re-posts a deleted message.

bot_api.php lets the bot ask which signed-up members have raids.manage when a
raid starts (shared key in config.php bot_callback.key); the bot then sends
them a DM with a link to the list. The bot side lives in the separate bot
repository (cogs/attendance.py).

Also fixes contribution_awards.raid_id being too small for Discord IDs (it
is widened automatically) and raid IDs losing precision in the contribution
form's JavaScript, which kept the raid preselection from ever matching.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 09:52:34 +02:00

290 lines
11 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 Beitragspunkte 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).
*/
const RAID_ATTENDANCE_STATUSES = [
'present' => 'Anwesend',
'absent' => 'Abwesend',
'excused' => 'Entschuldigt',
];
/** @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->prepare('UPDATE raid_settings SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
$pdo->prepare('UPDATE 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]);
}
/**
* 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 Beitragspunkte 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 Beitragspunkte 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
{
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 Beitragspunkte 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;
}