LuminaWebsite/includes/activity_points.php
Maaxxs 5aaf44eaec Consilium Elyseum: allied legions get their own view - own raids, calendar entries, member tab and shared live map sessions
Asked for: alliances ("Consilium Elyseum") with their own view, a member-list tab with the allied legions and their
members, an own raid area, a calendar that shows them only alliance entries, and live map sessions the legion can
share with them - watching only, or drawing only with an extra permission. There is one Discord role "Consilium
Elyseum" for all allies, so which legion each ally belongs to is stored on the website.

- Permissions consilium.view / consilium.draw / consilium.manage. An account with consilium.view but without
  dashboard.view is a guest of the Consilium (consilium_only(), sql_is_consilium_only()) and sees only the alliance
  area; raids, calendar and map stay restricted even with extra rights like raids.view or map.view.
- includes/consilium.php; consilium.php is the allies' start page instead of the dashboard (next raids and entries,
  legions, running shared map sessions); admin/consilium.php: setup hints, allied legions, member assignment.
  users.consilium_legion_id, table consilium_legions (schema 69); allies pick their legion under Mein Profil.
- Members: new tab "Consilium Elyseum" (legions with their members), the only tab allies see. Legion-only lists
  (dues, Lumipunkte, member pickers, raid and activity points) leave allies out.
- Raids: two areas, legion and Consilium, told apart by the Discord channel ("Consilium-Raids" under Verwaltung ->
  Discord-Bot, settings.consilium_raid_channel; the bot API returns channel_id). Allies only see and sign up for
  Consilium raids, which give no Lumipunkte; raids created in the Consilium area are posted to its channel.
- Calendar: audience "Consilium Elyseum". Allies see only those entries and the Consilium raids (also in their iCal
  subscription), their own entries are always Consilium entries; the public calendar shows no Consilium raids; the
  legion sees them marked with 🤝.
- Map: whoever may edit a public tactic shares its running live session with the Consilium (consilium_share, logged).
  The share lives in the bot's live relay and only for that session: it ends with "Freigabe beenden" or 60 s after
  the last legion member left; making the tactic private or deleting it ends it as well. Allies see only running
  shared sessions under Karte (and on their start page), join and watch; with consilium.draw they add strokes,
  areas, points and text - no figures, nothing moved, erased or undone, no tactics, steps, copies or history.
  Enforced in tactics_api.php (guest branch: shared tactics only, only live_token and shape_create) and in the relay
  (guest tickets, event whitelist, guests are disconnected when the share ends). Needs the bot update (api.py,
  database/db.py, live_tactics.py).
- Navigation, privacy page, patch note, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 01:36:49 +02:00

143 lines
6.1 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);
/**
* Lumipunkte fuer "Ich bin da" beim Aktivitaetscheck.
*
* Den Check selbst verwaltet der Bot (includes/activity_api.php). Die Website merkt sich hier je
* Check die Punkte und vergibt sie einmal, sobald der Check abgeschlossen ist - egal ob er auf der
* Website beendet wurde oder der Bot ihn nach Ablauf der Frist geschlossen hat. Wie bei den
* Raid-Punkten passiert das beim naechsten Aufruf von Dashboard, Lumipunkte- oder Aktivitaetsseite.
*/
require_once __DIR__ . '/activity_api.php';
require_once __DIR__ . '/contributions.php';
/** Punkte fuer einen neuen Check merken (Frist = spaetester Zeitpunkt, ab dem nachgesehen wird). */
function activity_points_save(int $checkId, int $points, int $deadline): void
{
if ($checkId <= 0 || $points <= 0) {
return;
}
db()->prepare(
'INSERT INTO activity_settings (check_id, points_present, deadline_at) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE points_present = VALUES(points_present), deadline_at = VALUES(deadline_at)'
)->execute([$checkId, $points, date('Y-m-d H:i:s', $deadline)]);
}
/** @return array{points_present: int, processed_at: ?string, result: ?string}|null */
function activity_points_get(int $checkId): ?array
{
try {
$stmt = db()->prepare('SELECT points_present, processed_at, result FROM activity_settings WHERE check_id = ?');
$stmt->execute([$checkId]);
$row = $stmt->fetch();
} catch (PDOException $e) {
return null;
}
return $row ? ['points_present' => (int) $row['points_present'], 'processed_at' => $row['processed_at'], 'result' => $row['result']] : null;
}
/**
* Offene Punkte vergeben: alle Checks, deren Frist vorbei ist (oder den einen, der gerade auf der
* Website beendet wurde), beim Bot nachsehen und bei "abgeschlossen" die Punkte gutschreiben.
*
* @param int|null $checkId nur diesen Check (sofort, ohne auf die Frist zu warten)
* @param array|null $detail schon geladene Daten des Checks (spart die Abfrage beim Bot)
* @return string[] Meldungen je verarbeitetem Check
*/
function activity_process_points(?int $checkId = null, ?array $detail = null): array
{
try {
$pending = $checkId !== null
? db()->prepare('SELECT check_id, points_present FROM activity_settings WHERE processed_at IS NULL AND check_id = ?')
: db()->prepare('SELECT check_id, points_present FROM activity_settings WHERE processed_at IS NULL AND deadline_at <= NOW()');
$pending->execute($checkId !== null ? [$checkId] : []);
$rows = $pending->fetchAll();
} catch (PDOException $e) {
return []; // Tabelle kommt erst mit dem naechsten Schema-Abgleich
}
$messages = [];
foreach ($rows as $row) {
$id = (int) $row['check_id'];
try {
$check = ($detail !== null && (int) ($detail['check_id'] ?? 0) === $id)
? $detail
: (activity_api_request('GET', '/' . $id)['check'] ?? null);
} catch (Throwable $e) {
continue; // Bot nicht erreichbar - beim naechsten Aufruf erneut
}
$message = activity_award_points($id, (int) $row['points_present'], $check);
if ($message !== '') {
$messages[] = $message;
}
}
return $messages;
}
/** Punkte fuer einen Check gutschreiben (einmalig, per Zeilensperre gegen Doppelvergabe). */
function activity_award_points(int $checkId, int $points, ?array $check): string
{
$status = (string) ($check['status'] ?? '');
if ($check !== null && $status === 'open') {
return ''; // laeuft noch (Frist gerade erst vorbei, der Bot schliesst gleich)
}
$pdo = db();
$pdo->beginTransaction();
$lock = $pdo->prepare('SELECT processed_at FROM activity_settings WHERE check_id = ? FOR UPDATE');
$lock->execute([$checkId]);
if ($lock->fetchColumn() !== null) {
$pdo->commit();
return '';
}
$finish = static function (string $result) use ($pdo, $checkId): string {
$pdo->prepare('UPDATE activity_settings SET processed_at = NOW(), result = ? WHERE check_id = ?')
->execute([mb_substr($result, 0, 255), $checkId]);
$pdo->commit();
return $result;
};
if ($check === null) {
return $finish('Keine Punkte: Der Check existiert beim Bot nicht mehr.');
}
$title = (string) ($check['title'] ?? 'Aktivitätscheck');
if ($status === 'cancelled') {
return $finish('Keine Punkte für „' . $title . '“: Der Check wurde abgebrochen.');
}
// Wer "Ich bin da" gewaehlt hat und ein Website-Konto mit Discord-Verknuepfung besitzt
$discordIds = [];
foreach ($check['responses'] ?? [] as $response) {
if (($response['status'] ?? '') === 'present' && !empty($response['user_id'])) {
$discordIds[] = (string) $response['user_id'];
}
}
$userIds = [];
if ($discordIds) {
// Nur die Legion - Verbuendete aus dem Consilium sammeln keine Lumipunkte
$stmt = $pdo->prepare("SELECT u.id FROM users u WHERE u.status = 'active' AND " . sql_is_legion_member('u')
. ' AND u.discord_id IN (' . implode(',', array_fill(0, count($discordIds), '?')) . ')');
$stmt->execute(array_values(array_unique($discordIds)));
$userIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
}
if (!$userIds) {
return $finish('Keine Punkte für „' . $title . '“: niemand mit „Ich bin da“ und Website-Konto.');
}
$closedAt = (int) ($check['closed_at'] ?? 0);
$pdo->prepare(
"INSERT INTO contribution_awards (category, title, note, awarded_at, created_by) VALUES ('activity', ?, ?, ?, NULL)"
)->execute([
mb_substr($title, 0, 150),
'Automatisch für „Ich bin da“ beim Aktivitätscheck',
date('Y-m-d H:i:s', $closedAt > 0 ? $closedAt : time()),
]);
$awardId = (int) $pdo->lastInsertId();
$insert = $pdo->prepare('INSERT INTO contribution_entries (award_id, user_id, points) VALUES (?, ?, ?)');
foreach ($userIds as $userId) {
$insert->execute([$awardId, $userId, $points]);
}
return $finish('Lumipunkte für „' . $title . '“ vergeben: ' . count($userIds) . '× +' . $points . '.');
}