LuminaWebsite/admin/dues_action.php
Maaxxs 785eab611e Legion dues: an admin page tracks who paid, with a rhythm, exemptions and suspended cycles
Asked for: the legion collects dues in Kina; a separate, purely administrative page to set a cycle and an
amount, tick off who has paid, exempt members for one or more cycles and suspend a cycle for everyone. On
the site it is called "Legionsbeiträge" and the currency "Kina", like everywhere else.

- includes/dues.php: settings dues_amount/_unit/_every/_start/_anchor (every 1-12 weeks or months). The
  cycles (dues_cycles) form a series from the anchor (months on the same day, in shorter months the last
  one) and exist up to the running one plus the next. Until something is ticked or suspended, a new setting
  rebuilds all cycles; afterwards a new amount applies to the coming cycles (optionally the running one) and
  a new rhythm starts after the last cycle that has begun or has data. The amount also takes 500k, 1,5kk or
  2 Mio.
- Who owes: every active account that was a member when the cycle started (Discord join, else account
  creation), unless exempt or the cycle is suspended; a ticked payment always counts. Former members only
  show up with payments in the visible cycles.
- admin/dues.php: key figures (running cycle, paid, collected of expected, arrears), a table of members x
  the last six cycles with paging, a click toggles a payment (dues_entries with who and when; without
  reload via assets/js/dues.js, the button sends the state it sets), search and filters (open, paid,
  exempt, arrears), suspend/resume per cycle with an optional reason, exemptions (dues_exemptions:
  members, from which cycle, 1-12 cycles or until further notice, reason; end or delete) and the settings.
  On phones the table opens at the running cycle, the exemption list stacks.
- admin/dues_action.php: settings, toggle (JSON with the redrawn cell, column figures, arrears and key
  figures), cycle, exempt_add/_end/_delete. Settings, suspensions and exemptions go to the audit log and the
  Discord log channel, ticks only to the audit log (area "Legionsbeiträge"); ticking is exempt from the
  general form rate limit.
- New right dues.manage (Administrator and the groups with roles.manage), menu item in the admin section
  with a coins icon, schema version 61 (tables also in sql/schema.sql).
- Privacy: privacy policy (what is stored, only the leadership sees it, account deletion), data export
  section legionsbeitraege, account deletion removes exemptions and keeps payments without the name, data
  reset area.
- Patch notes (leadership) and README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:33:22 +02:00

239 lines
14 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
/**
* 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.
*/
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/dues.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');
}
redirect('/admin/dues.php');