Asked for: "bei den Legionsbeiträgen soll der bot auch die leute drauf erinnern dass ihr beitrag fällig ist ...
die nachricht ist frei definierbar über die website (mit markierungen und erwähnungen) ... eine standardnachricht,
welche zur Legion passt" and "es soll wenn man die seite aufruft standardmäßig die von uns definierte reihenfolge
angezeigt werden".
Dues reminders (includes/dues_reminders.php, admin/dues.php "Erinnerungen per Discord"):
- Who: everyone still open in the running cycle with a linked Discord - not who paid, is exempt or sits in a
suspended cycle. Automatic (switch, off by default) at the start of the cycle and/or N days before its end, at
a set hour (settings dues_remind_*); a missed moment is caught up for 24 hours at most, so switching it on in the
middle of a cycle sends nothing. "Jetzt erinnern" for everyone open right now and "Testnachricht an mich" with
the text from the form, saved or not.
- The text is free: Discord formatting, placeholders {name}, {erwähnung}, {betrag}, {zyklus}, {bis}, mentions of
members and channels (channel list from the bot API), toolbar and live preview with the own values
(assets/js/dues-remind.js). The default text greets with "Arieluma" and is stored empty so improvements arrive.
- Flow: the bot (new cogs/dues_reminders.py, already deployed) asks bot_api.php?action=dues_reminders every minute;
the website queues due reminders in dues_reminders (at most once per member, cycle and kind) and hands out the
waiting ones with the finished text, the bot sends them without pings and reports back via
action=dues_reminders_done, then logs to the log channel. The text is dropped after sending, the log stays 90
days. The section lists the runs of the running cycle with delivered and not deliverable (with reason).
- Schema version 64 (table also in sql/schema.sql); privacy policy (what is stored, the bot, retention), data export
section, account deletion, data reset, audit log; patch notes and README.
Premades:
- The page opens in the order the leadership set: own premades are no longer pulled to the top. A chosen sort only
lives in the address (?sort=) - it survives a reload, not a new visit; the former browser entry
lumina_premades_sort is removed (and left the privacy policy). Patch notes of the sort and order entries adjusted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
304 lines
18 KiB
PHP
304 lines
18 KiB
PHP
<?php
|
||
/**
|
||
* Legionsbeitraege aendern (admin/dues.php, includes/dues.php, nur dues.manage): Einstellungen speichern, Zahlungen
|
||
* abhaken (per fetch mit JSON-Antwort: die neu gezeichneten Felder), Zyklen fuer alle aussetzen und fortsetzen,
|
||
* Befreiungen eintragen, beenden und loeschen - und die Erinnerungen per Discord (includes/dues_reminders.php):
|
||
* Einstellungen samt Text, "Jetzt erinnern" und eine Testnachricht an sich selbst.
|
||
*/
|
||
require_once __DIR__ . '/../includes/bootstrap.php';
|
||
require_once __DIR__ . '/../includes/dues.php';
|
||
require_once __DIR__ . '/../includes/dues_reminders.php';
|
||
require_permission('dues.manage');
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||
redirect('/admin/dues.php');
|
||
}
|
||
verify_csrf();
|
||
|
||
$pdo = db();
|
||
$action = (string) ($_POST['action'] ?? '');
|
||
$wantsJson = !empty($_SERVER['HTTP_X_REQUESTED_WITH']);
|
||
$today = date('Y-m-d');
|
||
// Zurueck zu den Zyklen, die gerade zu sehen waren
|
||
$bis = (int) ($_POST['bis'] ?? 0);
|
||
$page = '/admin/dues.php' . ($bis > 0 ? '?bis=' . $bis : '');
|
||
|
||
$json = static function (array $data): void {
|
||
header('Content-Type: application/json; charset=UTF-8');
|
||
echo json_encode($data, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
};
|
||
$fail = static function (string $message, string $anchor = '') use ($wantsJson, $json, $page): void {
|
||
if ($wantsJson) {
|
||
$json(['ok' => false, 'error' => $message]);
|
||
}
|
||
set_flash('error', $message);
|
||
redirect($page . $anchor);
|
||
};
|
||
$cycleById = static function (int $id): ?array {
|
||
return dues_cycles()[$id] ?? null;
|
||
};
|
||
$period = static fn (array $cycle): string => dues_period_label($cycle['starts_on'], $cycle['ends_on']);
|
||
|
||
switch ($action) {
|
||
case 'settings':
|
||
$old = dues_settings();
|
||
$amount = dues_parse_kina((string) ($_POST['amount'] ?? ''));
|
||
if ($amount === null) {
|
||
$fail('Den Betrag verstehe ich nicht – z. B. 500000, 500.000 oder 500k.', '#einstellungen');
|
||
}
|
||
$unit = (string) ($_POST['unit'] ?? '');
|
||
$every = (int) ($_POST['every'] ?? 0);
|
||
if (!isset(DUES_UNITS[$unit]) || $every < 1 || $every > DUES_EVERY_MAX) {
|
||
$fail('Rhythmus: alle 1 bis ' . DUES_EVERY_MAX . ' Wochen oder Monate.', '#einstellungen');
|
||
}
|
||
$settings = ['amount' => $amount, 'unit' => $unit, 'every' => $every, 'start' => $old['start'], 'anchor' => $old['anchor']];
|
||
$applyCurrent = false;
|
||
if (!dues_has_data()) {
|
||
$start = dues_date($_POST['start'] ?? null);
|
||
if ($start === null || $start < dues_day_shift($today, -366) || $start > dues_day_shift($today, 366)) {
|
||
$fail('Der erste Zyklus muss höchstens ein Jahr vor oder nach heute beginnen.', '#einstellungen');
|
||
}
|
||
// Noch nichts abgehakt oder ausgesetzt: alle Zyklen neu berechnen
|
||
$pdo->exec('DELETE FROM dues_cycles');
|
||
$settings['start'] = $start;
|
||
$settings['anchor'] = $start;
|
||
} else {
|
||
if ($unit !== $old['unit'] || $every !== $old['every']) {
|
||
// Was schon laeuft oder Daten hat, bleibt - danach beginnt die Reihe im neuen Rhythmus
|
||
$keep = $pdo->prepare(
|
||
'SELECT MAX(c.ends_on) FROM dues_cycles c
|
||
WHERE c.starts_on <= ? OR c.suspended = 1 OR EXISTS (SELECT 1 FROM dues_entries e WHERE e.cycle_id = c.id)'
|
||
);
|
||
$keep->execute([$today]);
|
||
$keepEnd = $keep->fetchColumn();
|
||
if (is_string($keepEnd)) {
|
||
$pdo->prepare('DELETE FROM dues_cycles WHERE starts_on > ?')->execute([$keepEnd]);
|
||
$settings['anchor'] = dues_day_shift($keepEnd, 1);
|
||
}
|
||
}
|
||
// Der Betrag gilt fuer die kommenden Zyklen, auf Wunsch auch fuer den laufenden
|
||
$pdo->prepare('UPDATE dues_cycles SET amount = ? WHERE starts_on > ?')->execute([$amount, $today]);
|
||
if (!empty($_POST['apply_current'])) {
|
||
$applyCurrent = true;
|
||
$pdo->prepare('UPDATE dues_cycles SET amount = ? WHERE starts_on <= ? AND ends_on >= ? AND suspended = 0')->execute([$amount, $today, $today]);
|
||
}
|
||
}
|
||
dues_settings_store($settings);
|
||
dues_sync($settings);
|
||
|
||
$changed = static fn (string $new, string $before): string => $new . ($before !== '' && $before !== $new ? ' (vorher ' . $before . ')' : '');
|
||
admin_log(dues_configured($old) ? '⚙️ Legionsbeiträge geändert' : '⚙️ Legionsbeiträge eingerichtet', [
|
||
'Beitrag' => $changed(dues_kina($amount), $old['amount'] > 0 ? dues_kina($old['amount']) : ''),
|
||
'Rhythmus' => $changed(dues_rhythm_label($unit, $every), dues_configured($old) ? dues_rhythm_label($old['unit'], $old['every']) : ''),
|
||
'Erster Zyklus' => (new DateTimeImmutable((string) $settings['start']))->format('d.m.Y'),
|
||
'Laufender Zyklus' => $applyCurrent ? 'neuer Betrag übernommen' : '',
|
||
], 'info', 'dues');
|
||
if (!dues_configured($old)) {
|
||
['current' => $current, 'next' => $next] = dues_current(dues_cycles());
|
||
set_flash('success', 'Legionsbeiträge eingerichtet – ' . ($current !== null
|
||
? 'der laufende Zyklus geht vom ' . $period($current) . '.'
|
||
: 'der erste Zyklus beginnt am ' . (new DateTimeImmutable((string) $settings['start']))->format('d.m.Y') . '.'));
|
||
} else {
|
||
set_flash('success', 'Einstellungen gespeichert.');
|
||
}
|
||
redirect('/admin/dues.php');
|
||
|
||
case 'toggle':
|
||
// Zahlung abhaken (…:1) oder zuruecknehmen (…:0) - der Knopf schickt den Zustand, den er herstellt
|
||
$parts = explode(':', (string) ($_POST['cell'] ?? ''));
|
||
$cycleId = (int) ($parts[0] ?? 0);
|
||
$userId = (int) ($parts[1] ?? 0);
|
||
$paid = ($parts[2] ?? '1') !== '0';
|
||
$cycle = $cycleById($cycleId);
|
||
$userStmt = $pdo->prepare('SELECT id FROM users WHERE id = ?');
|
||
$userStmt->execute([$userId]);
|
||
if ($cycle === null || !$userStmt->fetchColumn()) {
|
||
$fail('Diesen Zyklus oder dieses Mitglied gibt es nicht (mehr) – lade die Seite neu.', '#zahlungen');
|
||
}
|
||
if ($paid) {
|
||
$stmt = $pdo->prepare('INSERT IGNORE INTO dues_entries (cycle_id, user_id, updated_by) VALUES (?, ?, ?)');
|
||
$stmt->execute([$cycleId, $userId, (int) current_user()['id']]);
|
||
} else {
|
||
$stmt = $pdo->prepare('DELETE FROM dues_entries WHERE cycle_id = ? AND user_id = ?');
|
||
$stmt->execute([$cycleId, $userId]);
|
||
}
|
||
if ($stmt->rowCount() > 0) {
|
||
// Nur ins Audit-Log, nicht in den Discord-Log-Kanal - beim Abhaken kommt ein Klick nach dem anderen
|
||
audit_store($paid ? '💰 Legionsbeitrag abgehakt' : '↩️ Legionsbeitrag zurückgenommen', [
|
||
'Mitglied' => admin_log_user($userId),
|
||
'Zyklus' => $period($cycle),
|
||
'Betrag' => dues_kina($cycle['amount']),
|
||
], 'info', 'dues');
|
||
}
|
||
if ($wantsJson) {
|
||
$cycles = dues_cycles();
|
||
['current' => $current, 'next' => $next] = dues_current($cycles);
|
||
$focus = $current ?? $next;
|
||
$entries = dues_entries();
|
||
$exemptions = dues_exemptions();
|
||
$members = dues_members(array_merge([$userId], array_keys($entries[$cycleId] ?? []), $focus !== null ? array_keys($entries[$focus['id']] ?? []) : []));
|
||
$member = $members[$userId];
|
||
$arrears = dues_arrears($cycles, $members, $entries, $exemptions);
|
||
$json([
|
||
'ok' => true,
|
||
'cell' => dues_cell_html($cycles[$cycleId], $member, dues_status($cycles[$cycleId], $member, $entries, $exemptions), $entries, $exemptions),
|
||
'stats' => dues_cycle_stats_html($cycles[$cycleId], dues_cycle_totals($cycles[$cycleId], $members, $entries, $exemptions)),
|
||
'arrears' => dues_arrears_html($userId, $arrears[$userId]),
|
||
'arrears_count' => $arrears[$userId]['count'],
|
||
'focus_status' => $focus !== null ? dues_status($focus, $member, $entries, $exemptions) : '',
|
||
'summary' => dues_summary_html($focus, $focus !== null ? dues_cycle_totals($focus, $members, $entries, $exemptions) : null, $arrears),
|
||
]);
|
||
}
|
||
redirect($page . '#zahlungen');
|
||
|
||
case 'cycle':
|
||
// Zyklus fuer alle aussetzen oder wieder fortsetzen (Knoepfe im Kopf der Tabelle)
|
||
[$op, $id] = array_pad(explode(':', (string) ($_POST['cycle'] ?? '')), 2, '');
|
||
$cycle = $cycleById((int) $id);
|
||
if ($cycle === null || !in_array($op, ['suspend', 'resume'], true)) {
|
||
$fail('Diesen Zyklus gibt es nicht (mehr).', '#zahlungen');
|
||
}
|
||
if ($op === 'suspend') {
|
||
$note = mb_substr(trim(preg_replace('/\s+/u', ' ', (string) ($_POST['note'] ?? '')) ?? ''), 0, 255);
|
||
$pdo->prepare('UPDATE dues_cycles SET suspended = 1, note = ? WHERE id = ?')->execute([$note !== '' ? $note : null, $cycle['id']]);
|
||
admin_log('⏸️ Legionsbeitrag ausgesetzt', ['Zyklus' => $period($cycle), 'Grund' => $note], 'info', 'dues');
|
||
set_flash('success', 'Zyklus ' . $period($cycle) . ' ausgesetzt – niemand muss zahlen.');
|
||
} else {
|
||
$pdo->prepare('UPDATE dues_cycles SET suspended = 0, note = NULL WHERE id = ?')->execute([$cycle['id']]);
|
||
admin_log('▶️ Legionsbeitrag wieder fällig', ['Zyklus' => $period($cycle)], 'info', 'dues');
|
||
set_flash('success', 'Im Zyklus ' . $period($cycle) . ' wird der Beitrag wieder fällig.');
|
||
}
|
||
redirect($page . '#zahlungen');
|
||
|
||
case 'exempt_add':
|
||
$userIds = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['user_ids'] ?? [])))));
|
||
if (!$userIds) {
|
||
$fail('Wähle mindestens ein Mitglied aus.', '#befreiungen');
|
||
}
|
||
$userStmt = $pdo->prepare(
|
||
"SELECT id FROM users WHERE status = 'active' AND id IN (" . implode(',', array_fill(0, count($userIds), '?')) . ')'
|
||
);
|
||
$userStmt->execute($userIds);
|
||
$userIds = array_map('intval', $userStmt->fetchAll(PDO::FETCH_COLUMN));
|
||
if (!$userIds) {
|
||
$fail('Diese Mitglieder gibt es nicht (mehr).', '#befreiungen');
|
||
}
|
||
// Ab dem gewaehlten Zyklus fuer so viele Zyklen (0 = bis auf Weiteres) - auch fuer kuenftige aus der Vorschau
|
||
$from = dues_date($_POST['from'] ?? null);
|
||
$count = (int) ($_POST['cycles'] ?? 1);
|
||
$choices = dues_cycle_choices(dues_cycles(), dues_settings());
|
||
$index = array_search($from, array_column($choices, 'starts_on'), true);
|
||
if ($from === null || $index === false || $count < 0 || $count > DUES_EXEMPT_MAX_CYCLES) {
|
||
$fail('Diesen Zyklus gibt es nicht – lade die Seite neu.', '#befreiungen');
|
||
}
|
||
$endsOn = $count === 0 ? null : ($choices[$index + $count - 1]['ends_on'] ?? null);
|
||
if ($count > 0 && $endsOn === null) {
|
||
$fail('So weit im Voraus geht es nicht – wähle weniger Zyklen oder „bis auf Weiteres“.', '#befreiungen');
|
||
}
|
||
$note = mb_substr(trim(preg_replace('/\s+/u', ' ', (string) ($_POST['note'] ?? '')) ?? ''), 0, 255);
|
||
$insert = $pdo->prepare('INSERT INTO dues_exemptions (user_id, starts_on, ends_on, note, created_by) VALUES (?, ?, ?, ?, ?)');
|
||
foreach ($userIds as $userId) {
|
||
$insert->execute([$userId, $from, $endsOn, $note !== '' ? $note : null, (int) current_user()['id']]);
|
||
}
|
||
$label = dues_exemption_label(['starts_on' => $from, 'ends_on' => $endsOn]);
|
||
admin_log('🕊️ Von Legionsbeiträgen befreit', [
|
||
'Mitglieder' => implode(', ', array_map('admin_log_user', $userIds)),
|
||
'Zeitraum' => $label . ($count > 0 ? ' (' . $count . ($count === 1 ? ' Zyklus' : ' Zyklen') . ')' : ''),
|
||
'Grund' => $note,
|
||
], 'info', 'dues');
|
||
set_flash('success', (count($userIds) === 1 ? 'Ein Mitglied' : count($userIds) . ' Mitglieder') . ' befreit: ' . $label . '.');
|
||
redirect($page . '#befreiungen');
|
||
|
||
case 'exempt_end':
|
||
case 'exempt_delete':
|
||
$stmt = $pdo->prepare('SELECT id, user_id, starts_on, ends_on FROM dues_exemptions WHERE id = ?');
|
||
$stmt->execute([(int) ($_POST['id'] ?? 0)]);
|
||
$exemption = $stmt->fetch();
|
||
if (!$exemption) {
|
||
$fail('Diese Befreiung gibt es nicht (mehr).', '#befreiungen');
|
||
}
|
||
$who = admin_log_user((int) $exemption['user_id']);
|
||
// Beenden: Sie gilt noch bis zum Ende des laufenden Zyklus, ab dem naechsten nicht mehr. Hat sie noch gar nicht
|
||
// begonnen, ist das dasselbe wie loeschen.
|
||
if ($action === 'exempt_end' && $exemption['starts_on'] <= $today) {
|
||
$currentEnd = dues_current_end(dues_cycles());
|
||
if ($exemption['ends_on'] !== null && $exemption['ends_on'] <= $currentEnd) {
|
||
set_flash('info', 'Diese Befreiung endet schon mit dem laufenden Zyklus.');
|
||
redirect($page . '#befreiungen');
|
||
}
|
||
$pdo->prepare('UPDATE dues_exemptions SET ends_on = ? WHERE id = ?')->execute([$currentEnd, (int) $exemption['id']]);
|
||
admin_log('🕊️ Befreiung beendet', ['Mitglied' => $who, 'Zeitraum' => dues_exemption_label(['starts_on' => $exemption['starts_on'], 'ends_on' => $currentEnd])], 'info', 'dues');
|
||
set_flash('success', 'Befreiung beendet – ab dem nächsten Zyklus ist der Beitrag wieder fällig.');
|
||
} else {
|
||
$pdo->prepare('DELETE FROM dues_exemptions WHERE id = ?')->execute([(int) $exemption['id']]);
|
||
admin_log('🗑️ Befreiung gelöscht', ['Mitglied' => $who, 'Zeitraum' => dues_exemption_label($exemption)], 'warning', 'dues');
|
||
set_flash('success', 'Befreiung gelöscht.');
|
||
}
|
||
redirect($page . '#befreiungen');
|
||
|
||
case 'remind_settings':
|
||
// Erinnerungen per Discord (includes/dues_reminders.php): automatisch ja/nein, wann, Uhrzeit und der Text
|
||
$old = dues_remind_settings();
|
||
$remind = [
|
||
'enabled' => !empty($_POST['enabled']),
|
||
'start' => !empty($_POST['remind_start']),
|
||
'before' => max(0, min(DUES_REMIND_BEFORE_MAX, (int) ($_POST['before'] ?? 0))),
|
||
'hour' => max(0, min(23, (int) ($_POST['hour'] ?? 18))),
|
||
'message' => dues_remind_clean_message($_POST['message'] ?? ''),
|
||
];
|
||
if ($remind['message'] === '') {
|
||
$fail('Die Nachricht darf nicht leer sein – mit „Standardtext“ bekommst du den Vorschlag zurück.', '#erinnerungen');
|
||
}
|
||
if ($remind['enabled'] && !$remind['start'] && $remind['before'] === 0) {
|
||
$fail('Wähle, wann der Bot erinnern soll: zu Beginn des Zyklus, vor seinem Ende oder beides.', '#erinnerungen');
|
||
}
|
||
dues_remind_settings_store($remind);
|
||
admin_log('🔔 Erinnerungen an Legionsbeiträge ' . ($remind['enabled'] === $old['enabled'] ? 'geändert' : ($remind['enabled'] ? 'eingeschaltet' : 'ausgeschaltet')), [
|
||
'Automatisch' => $remind['enabled'] ? dues_remind_when_label($remind) : 'aus',
|
||
'Nachricht' => $remind['message'] !== $old['message'] ? 'geändert' : '',
|
||
], 'info', 'dues');
|
||
set_flash('success', $remind['enabled']
|
||
? 'Gespeichert – der Bot erinnert ' . dues_remind_when_label($remind) . '.'
|
||
: 'Gespeichert. Automatisch erinnert der Bot erst, wenn du es einschaltest – „Jetzt erinnern“ geht trotzdem.');
|
||
redirect('/admin/dues.php#erinnerungen');
|
||
|
||
case 'remind_now':
|
||
// Alle, die im laufenden Zyklus noch offen sind, bekommen in der naechsten Minute eine PN (der Bot fragt jede Minute)
|
||
$current = dues_current(dues_cycles())['current'];
|
||
if ($current === null || $current['suspended']) {
|
||
$fail('Gerade läuft kein Zyklus, in dem jemand zahlen muss.', '#erinnerungen');
|
||
}
|
||
$found = dues_remind_recipients($current);
|
||
if (!$found['recipients']) {
|
||
$fail($found['without_discord']
|
||
? 'Wer noch offen ist, hat kein Discord verknüpft – der Bot kann niemanden erreichen.'
|
||
: 'Im laufenden Zyklus ist niemand mehr offen.', '#erinnerungen');
|
||
}
|
||
$count = dues_remind_queue($current, 'manual', $found['recipients'], dues_remind_settings()['message'], (int) current_user()['id']);
|
||
admin_log('🔔 An Legionsbeiträge erinnert', [
|
||
'Zyklus' => $period($current),
|
||
'Mitglieder' => implode(', ', array_column($found['recipients'], 'name')),
|
||
'Ohne Discord' => implode(', ', $found['without_discord']),
|
||
], 'info', 'dues');
|
||
set_flash('success', ($count === 1 ? 'Ein Mitglied bekommt' : $count . ' Mitglieder bekommen') . ' in der nächsten Minute eine PN vom Bot.'
|
||
. ($found['without_discord'] ? ' Ohne Discord und deshalb ohne PN: ' . implode(', ', $found['without_discord']) . '.' : ''));
|
||
redirect('/admin/dues.php#erinnerungen');
|
||
|
||
case 'remind_test':
|
||
// Testnachricht an sich selbst - mit dem Text aus dem Formular, auch wenn er noch nicht gespeichert ist
|
||
$me = current_user();
|
||
if (empty($me['discord_id'])) {
|
||
$fail('Verknüpfe zuerst dein Discord in „Mein Profil“ – sonst kann dir der Bot nicht schreiben.', '#erinnerungen');
|
||
}
|
||
$message = dues_remind_clean_message($_POST['message'] ?? '');
|
||
['current' => $current, 'next' => $next] = dues_current(dues_cycles());
|
||
dues_remind_queue($current ?? $next, 'test', [(int) $me['id'] => [
|
||
'name' => (string) (($me['display_name'] ?? '') !== '' ? $me['display_name'] : $me['username']),
|
||
'discord_id' => (string) $me['discord_id'],
|
||
]], $message !== '' ? $message : dues_remind_settings()['message'], (int) $me['id']);
|
||
set_flash('success', 'Die Testnachricht ist unterwegs – der Bot schickt sie dir in der nächsten Minute per PN. Gespeichert ist damit noch nichts.');
|
||
redirect('/admin/dues.php#erinnerungen');
|
||
}
|
||
|
||
redirect('/admin/dues.php');
|