From 1c712d0781bc551d9041b188896c442e55089e0e Mon Sep 17 00:00:00 2001 From: torsten Date: Fri, 23 Oct 2026 17:28:29 +0200 Subject: [PATCH] Robo Admin --- .gitignore | 1 + tippspiel/public/css/style.css | 12 + tippspiel/public/index.php | 81 ++- tippspiel/src/Core/ResultFetcher.php | 535 ++++++++++++++++++ tippspiel/src/Models/FetcherLog.php | 65 +++ tippspiel/src/Models/Season.php | 56 +- .../src/Views/admin/fetcher_activity.php | 64 +++ tippspiel/src/Views/admin/rounds.php | 15 +- tippspiel/src/Views/admin/seasons.php | 75 ++- tippspiel/src/Views/info/guide_admin.php | 41 +- tippspiel/src/Views/info/money_ranking.php | 2 + tippspiel/src/Views/partials/header.php | 21 +- tools/clear_account_fields.php | 48 ++ tools/deploy_test.py | 1 + tools/docker-compose.yml | 4 +- tools/export_accounts.php | 114 ++++ tools/fetch_results_apifootball.php | 19 + tools/fetch_results_openligadb.php | 19 + tools/schema.sql | 10 + tools/sync_live_to_test.sh | 66 ++- 20 files changed, 1194 insertions(+), 55 deletions(-) create mode 100644 tippspiel/src/Core/ResultFetcher.php create mode 100644 tippspiel/src/Models/FetcherLog.php create mode 100644 tippspiel/src/Views/admin/fetcher_activity.php create mode 100644 tools/clear_account_fields.php create mode 100644 tools/export_accounts.php create mode 100644 tools/fetch_results_apifootball.php create mode 100644 tools/fetch_results_openligadb.php diff --git a/.gitignore b/.gitignore index ee9bcce..2dbf64e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .aider* .DS_Store +tools/export_kontodaten_*.csv diff --git a/tippspiel/public/css/style.css b/tippspiel/public/css/style.css index 2d376c2..ccfdcaf 100644 --- a/tippspiel/public/css/style.css +++ b/tippspiel/public/css/style.css @@ -207,6 +207,18 @@ a:hover { color: var(--pitch-dark); } } .nav-dropdown-form button:hover { background: var(--pitch-light); } .nav-dropdown-form small { color: var(--muted); } +.nav-season-form { padding: 0.45em 1.1em; } +.nav-season-form label { + display: block; + margin-bottom: 0.25em; + font-family: var(--font-display); + font-weight: 700; + font-size: 0.72em; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--muted); +} +.nav-season-form select { width: 100%; } .nav-dropdown:hover .nav-dropdown-content, .nav-dropdown:focus-within .nav-dropdown-content { display: block; } diff --git a/tippspiel/public/index.php b/tippspiel/public/index.php index 6c99c53..77dfc9b 100644 --- a/tippspiel/public/index.php +++ b/tippspiel/public/index.php @@ -21,6 +21,7 @@ use App\Models\Roundmail; use App\Models\Setting; use App\Models\Team; use App\Models\Question; +use App\Models\FetcherLog; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $page = $_GET['page'] ?? null; @@ -57,6 +58,21 @@ if ($page === 'reminder') { echo "Fehler: " . $e->getMessage() . "\n"; } exit; +} elseif ($page === 'fetch_results') { + // Ergebnis-Fetcher von außen aufrufbar (z.B. cron-job.org), ohne Login. + header('Content-Type: text/plain; charset=UTF-8'); + try { + echo FetcherLog::deleteOld() . " alte Fetcher-Log-Einträge gelöscht.\n"; + echo "== Bundesliga/DFB-Pokal (openligadb) ==\n"; + echo \App\Core\ResultFetcher::openligadb(true); + echo "\n\n== International (API-Football) ==\n"; + echo \App\Core\ResultFetcher::apifootball(true); + echo "\n"; + } catch (\Throwable $e) { + http_response_code(500); + echo "Fehler: " . $e->getMessage() . "\n"; + } + exit; } elseif ($page === 'login') { // Wenn bereits eingeloggt, zur Startseite weiterleiten if (Auth::check()) { @@ -253,9 +269,9 @@ if ($page === 'reminder') { $locked = Round::isLocked(Game::getGamesByRound($round['id'])); require __DIR__ . '/../src/Views/tipps/game.php'; } elseif ($page === 'guide') { - // Info -> Anleitung: Regeln mit den Werten der aktiven Saison + // Info -> Anleitung: Regeln mit den Werten der angezeigten Saison Auth::requireLogin(); - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null; $maxIdenticalJokertipps = (int)($currentSeason['max_identical_jokertipps'] ?? Season::DEFAULT_MAX_IDENTICAL_JOKERTIPPS); $jackpot = $currentSeason ? (float)$currentSeason['jackpot'] : 0.0; @@ -271,7 +287,7 @@ if ($page === 'reminder') { } elseif ($page === 'info_quotas') { // Info -> Quoten (Legacy UsersController::show_payouts) Auth::requireLogin(); - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null; $activeUserCount = $currentSeason ? count(User::getPaid($currentSeason['id'])) : 0; $stake = $currentSeason ? (Quota::getMapBySeason($currentSeason['id'])['einsatz'] ?? 0) : 0; @@ -284,7 +300,7 @@ if ($page === 'reminder') { // Info -> Geldrangliste (Legacy UsersController::money_ranking / money_ranking_detail) Auth::requireLogin(); $user = Auth::user(); - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); if (!$currentSeason) { header('Location: /'); exit; @@ -317,7 +333,7 @@ if ($page === 'reminder') { Auth::requireLogin(); Auth::requireAdmin(); $user = Auth::user(); - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $result = null; $seasonStart = null; if ($currentSeason) { @@ -343,6 +359,21 @@ if ($page === 'reminder') { $currentMessage = Setting::getMessage(); require __DIR__ . '/../src/Views/admin/message.php'; +} elseif ($page === 'admin_fetcher_activity') { + // Aktivitätslog des Ergebnis-Fetchers (nur Admins) + Auth::requireLogin(); + Auth::requireAdmin(); + + $from = $_GET['from'] ?? date('Y-m-d', strtotime('-7 days')); + $to = $_GET['to'] ?? date('Y-m-d'); + if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) { + $from = date('Y-m-d', strtotime('-7 days')); + $to = date('Y-m-d'); + } + + $entries = FetcherLog::getRange($from, $to); + + require __DIR__ . '/../src/Views/admin/fetcher_activity.php'; } elseif ($page === 'settings') { // Eigene Spielerdaten (Legacy UsersController::useredit / storeUserEdit) Auth::requireLogin(); @@ -389,11 +420,19 @@ if ($page === 'reminder') { Auth::requireLogin(); Auth::requireAdmin(); - if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'set_registration') { - Setting::setRegistrationOpen(($_POST['registration_open'] ?? '') === '1'); + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $action = $_POST['action'] ?? ''; // Zurück zur Seite, auf der das Menü benutzt wurde (nur lokale Pfade) $return = (string)($_POST['return'] ?? ''); $isLocal = str_starts_with($return, '/') && !str_starts_with($return, '//'); + + if ($action === 'set_registration') { + Setting::setRegistrationOpen(($_POST['registration_open'] ?? '') === '1'); + } elseif ($action === 'set_view_season') { + // Persönliche Saison-Ansicht des Admins umschalten (wirkt nur auf ihn) + Season::setViewSeason($_POST['season_id'] ?? null); + } + header('Location: ' . ($isLocal ? $return : '/index.php?page=admin_users')); exit; } @@ -440,8 +479,10 @@ if ($page === 'reminder') { throw new \Exception("Saison konnte nicht erstellt werden."); } Quota::saveForSeason($newSeasonId, $quotasToSave); - Season::setCurrent($newSeasonId); - $_SESSION['admin_message'] = "Saison erfolgreich erstellt und als aktiv gesetzt."; + // Nur die persönliche Ansicht des Admins umschalten – die für + // alle Spieler aktive Saison bleibt unverändert. + Season::setViewSeason($newSeasonId); + $_SESSION['admin_message'] = "Saison erfolgreich erstellt und für dich als Ansicht gesetzt. Für alle Spieler bleibt die bisherige Saison aktiv."; } elseif ($seasonId) { Season::update($seasonId, $data); Quota::saveForSeason($seasonId, $quotasToSave); @@ -450,7 +491,11 @@ if ($page === 'reminder') { } } elseif ($action === 'set_current' && $seasonId) { Season::setCurrent($seasonId); - $_SESSION['admin_message'] = "Aktive Saison wurde geändert."; + Season::setViewSeason($seasonId); + $_SESSION['admin_message'] = "Saison wurde für alle Spieler als aktiv gesetzt."; + } elseif ($action === 'view' && $seasonId) { + Season::setViewSeason($seasonId); + $_SESSION['admin_message'] = "Saison wird jetzt nur für dich angezeigt."; } elseif ($action === 'delete' && $seasonId) { Season::delete($seasonId); $_SESSION['admin_message'] = "Saison wurde gelöscht."; @@ -480,6 +525,7 @@ if ($page === 'reminder') { $seasons = Season::getAll(); $currentSeason = Season::getCurrent(); + $viewSeason = Season::getViewSeason(); $editSeason = isset($_GET['edit_id']) ? Season::findById((int)$_GET['edit_id']) : null; $payouts = null; @@ -506,8 +552,9 @@ if ($page === 'reminder') { Auth::requireLogin(); Auth::requireAdmin(); - $currentSeason = Season::getCurrent(); - $seasonId = (int)($_GET['season_id'] ?? ($currentSeason['id'] ?? 0)); + $activeSeason = Season::getCurrent(); + $viewSeason = Season::getViewSeason(); + $seasonId = (int)($_GET['season_id'] ?? ($viewSeason ? (int)$viewSeason['id'] : 0)); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $roundId = (int)($_POST['round_id'] ?? 0); @@ -630,7 +677,7 @@ if ($page === 'reminder') { } $sender = Auth::user(); - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $html = Roundmail::textToHtml($text); $failed = Mailer::send($recipients['valid'], $topic, $html, $sender['email'] ?? null); $sent = array_values(array_diff($recipients['valid'], $failed)); @@ -661,7 +708,7 @@ if ($page === 'reminder') { $excludeReminders = ($_GET['hide_reminders'] ?? '') === '1'; if ($compose) { - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $tippableRound = $currentSeason ? Round::getFirstTippable($currentSeason['id']) : null; $recipientGroups = $currentSeason ? Roundmail::recipientGroups($currentSeason['id'], $tippableRound) : []; $baseUrl = rtrim(getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')), '/'); @@ -680,7 +727,7 @@ if ($page === 'reminder') { Auth::requireLogin(); Auth::requireAdmin(); - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $message = null; $error = null; @@ -801,7 +848,7 @@ if ($page === 'reminder') { } elseif ($page === 'ranking') { Auth::requireLogin(); try { - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); if (!$currentSeason) { throw new \Exception("Keine aktuelle Saison gefunden."); } @@ -936,7 +983,7 @@ if ($page === 'reminder') { } elseif ($page === 'home') { Auth::requireLogin(); try { - $currentSeason = Season::getCurrent(); + $currentSeason = Season::getViewSeason(); $message = Setting::getMessage(); if ($currentSeason) { diff --git a/tippspiel/src/Core/ResultFetcher.php b/tippspiel/src/Core/ResultFetcher.php new file mode 100644 index 0000000..3998650 --- /dev/null +++ b/tippspiel/src/Core/ResultFetcher.php @@ -0,0 +1,535 @@ + 'fc-heidenheim', + 'dsc arminia bielefeld' => 'arminia-bielefeld', + 'sv 07 elversberg' => 'sv-elversberg', + 'tsg 1899 hoffenheim ii' => 'tsg-hoffenheim-ii', + ]; + $out = []; + try { + $db = Database::getConnection(); + $now = time(); + $today = date('Y-m-d'); + $from = $today . ' 00:00:00'; + $to = date('Y-m-d 00:00:00', strtotime('+3 days')); + + $stmt = $db->prepare( + "SELECT g.id, g.team1, g.team2, g.kickoff, g.score1, g.score2, g.fetcher_matched, + r.name AS round_name, s.name AS season_name, + t1.key AS k1, t2.key AS k2, t1.type AS t1t, t2.type AS t2t + FROM games g + JOIN rounds r ON r.id = g.round_id + JOIN seasons s ON s.id = r.season_id + LEFT JOIN teams t1 ON t1.id = g.team1_id + LEFT JOIN teams t2 ON t2.id = g.team2_id + WHERE g.kickoff >= ? AND g.kickoff < ? + ORDER BY g.kickoff" + ); + $stmt->execute([$from, $to]); + $games = $stmt->fetchAll(\PDO::FETCH_ASSOC); + + $targets = []; + foreach ($games as $g) { + if (($g['t1t'] ?? '') !== 'club' || ($g['t2t'] ?? '') !== 'club') { + continue; + } + $targets[] = $g; + } + + $seasonYears = []; + foreach ($targets as $g) { + $seasonYears[self::seasonYearFor($g['kickoff'])] = true; + } + if (empty($seasonYears)) { + return 'Keine Vereins-Spiele im Fenster (heute +2 Tage).'; + } + + $lookup = []; + $unresolvedTeams = []; + foreach (self::LEAGUES as $league) { + foreach (array_keys($seasonYears) as $season) { + $matches = self::openligaGet("/getmatchdata/$league/$season"); + if ($matches === null) { + $out[] = "WARNUNG: Konnte $league/$season nicht laden."; + continue; + } + foreach ($matches as $m) { + $matchTs = strtotime((string)$m['matchDateTime']); + $finished = !empty($m['matchIsFinished']); + $score = null; + if ($finished) { + $end = null; + foreach ($m['matchResults'] ?? [] as $r) { + if ((int)$r['resultTypeID'] === 2) { + $end = $r; + } + } + if ($end !== null) { + $score = [(int)$end['pointsTeam1'], (int)$end['pointsTeam2']]; + } + } elseif ($matchTs !== false && $matchTs <= $now) { + $goals = $m['goals'] ?? []; + $last = end($goals); + $score = [$last ? (int)$last['scoreTeam1'] : 0, $last ? (int)$last['scoreTeam2'] : 0]; + } + // zukünftige Spiele: $score bleibt null, werden aber trotzdem + // in den Lookup aufgenommen (für die Erkennung/Roboter). + + $k1 = self::openligaTeamKey($m['team1'], $overrides); + $k2 = self::openligaTeamKey($m['team2'], $overrides); + if ($k1 === null) { + $unresolvedTeams[$m['team1']['teamName']] = true; + } + if ($k2 === null) { + $unresolvedTeams[$m['team2']['teamName']] = true; + } + if ($k1 === null || $k2 === null) { + continue; + } + $date = substr((string)$m['matchDateTime'], 0, 10); + $lookup[$k1 . '|' . $k2 . '|' . $date] = [ + 'score' => $score, 'finished' => $finished, + ]; + } + } + } + + $matched = 0; + $marked = 0; + $filled = 0; + $liveCount = 0; + $finalCount = 0; + $unmatched = []; + $mismatches = []; + $markStmt = $db->prepare( + "UPDATE games SET fetcher_matched = 1, updated_at = NOW() WHERE id = ? AND fetcher_matched <> 1" + ); + $updStmt = $db->prepare("UPDATE games SET score1 = ?, score2 = ?, updated_at = NOW() WHERE id = ?"); + + foreach ($targets as $g) { + $k1 = $g['k1']; + $k2 = $g['k2']; + if ($k1 === null || $k2 === null) { + continue; + } + $date = substr((string)$g['kickoff'], 0, 10); + $key = $k1 . '|' . $k2 . '|' . $date; + if (!isset($lookup[$key])) { + $unmatched[] = sprintf('%s vs %s (%s)', $g['team1'], $g['team2'], $date); + continue; + } + $matched++; + $row = $lookup[$key]; + $score = $row['score']; + $finished = $row['finished']; + + if ($check) { + if (!$finished) { + continue; + } + if ((int)$g['score1'] !== $score[0] || (int)$g['score2'] !== $score[1]) { + $mismatches[] = sprintf( + '%s vs %s (%s): openligadb %d:%d, DB %d:%d', + $g['team1'], $g['team2'], $date, $score[0], $score[1], + (int)$g['score1'], (int)$g['score2'] + ); + } + continue; + } + + // Erkennung (Roboter) dauerhaft merken. + if (!$g['fetcher_matched']) { + $marked++; + if ($apply) { + $markStmt->execute([$g['id']]); + FetcherLog::create(FetcherLog::ACTION_IDENTIFIED, sprintf('%s vs %s', $g['team1'], $g['team2'])); + } + } + + if ($score === null) { + continue; // noch kein Ergebnis (zukünftiges Spiel) + } + if ((int)$g['score1'] === $score[0] && (int)$g['score2'] === $score[1]) { + continue; + } + $kind = $finished ? 'Ende' : 'Live'; + $out[] = sprintf( + '%s vs %s (%s): %d:%d [%s]%s', + $g['team1'], $g['team2'], $date, $score[0], $score[1], $kind, + $apply ? '' : ' [Dry-Run]' + ); + if ($apply) { + $old = ((int)$g['score1'] >= 0 && (int)$g['score2'] >= 0) + ? sprintf('%d:%d', $g['score1'], $g['score2']) + : '-:-'; + $updStmt->execute([$score[0], $score[1], $g['id']]); + FetcherLog::create(FetcherLog::ACTION_RESULT, sprintf( + '%s vs %s: %s → %d:%d [%s]', + $g['team1'], $g['team2'], $old, $score[0], $score[1], $kind + )); + $filled++; + if ($finished) { + $finalCount++; + } else { + $liveCount++; + } + } + } + + $out[] = 'Zuordenbare Spiele: ' . $matched; + $out[] = 'Neu als erkannt markiert: ' . $marked . ($apply ? '' : ' [Dry-Run]'); + if ($apply) { + $out[] = 'Geschrieben: ' . $filled . ' (Live: ' . $liveCount . ', Endergebnis: ' . $finalCount . ')'; + } + if ($check) { + $out[] = 'Abweichungen zur DB: ' . count($mismatches); + foreach ($mismatches as $m) { + $out[] = ' - ' . $m; + } + } + if (!empty($unmatched)) { + $out[] = 'Nicht zugeordnet (' . count($unmatched) . '):'; + foreach ($unmatched as $u) { + $out[] = ' - ' . $u; + } + } + if (!empty($unresolvedTeams)) { + $out[] = 'Nicht aufgelöste openligadb-Teams:'; + foreach (array_keys($unresolvedTeams) as $name) { + $out[] = ' - ' . $name; + } + } + } catch (\Throwable $e) { + $out[] = 'Fehler: ' . $e->getMessage(); + } + return implode("\n", $out); + } + + /** + * Länderspiele + Europapokal über API-Football (api-sports.io). + * + * @param bool $apply false = Dry-Run, true = eintragen + * @param bool $check true = Gegenkontrolle gegen vorhandene Endergebnisse + * @return string Zusammenfassung als Text + */ + public static function apifootball(bool $apply = false, bool $check = false): string { + // "heute" muss der deutschen Ortszeit entsprechen (Kickoffs sind deutsch). + date_default_timezone_set('Europe/Berlin'); + $nameMap = [ + 'germany' => 'de', 'netherlands' => 'nl', 'italy' => 'it', 'belgium' => 'be', + 'england' => 'eng', 'spain' => 'es', 'czech republic' => 'cz', 'czechia' => 'cz', + 'croatia' => 'hr', 'greece' => 'gr', 'norway' => 'no', 'portugal' => 'pt', + 'france' => 'fr', 'turkey' => 'tr', 'turkiye' => 'tr', 'ireland' => 'ie', + 'austria' => 'at', 'denmark' => 'dk', 'serbia' => 'rs', 'cyprus' => 'cy', + 'latvia' => 'lv', 'andorra' => 'ad', 'argentina' => 'ar', 'armenia' => 'am', + 'bolivia' => 'bo', 'bosnia and herzegovina' => 'ba', 'bosnia-herzegovina' => 'ba', + 'brazil' => 'br', 'costa rica' => 'cr', 'ecuador' => 'ec', 'finland' => 'fi', + 'ghana' => 'gh', 'iceland' => 'is', 'israel' => 'il', 'japan' => 'jp', + 'cameroon' => 'cm', 'qatar' => 'qa', 'liechtenstein' => 'li', 'malta' => 'mt', + 'mexico' => 'mx', 'northern ireland' => 'gb-nir', 'north macedonia' => 'mk', + 'macedonia' => 'mk', 'poland' => 'pl', 'romania' => 'ro', 'russia' => 'ru', + 'san marino' => 'sm', 'scotland' => 'gb-sct', 'sweden' => 'se', + 'switzerland' => 'ch', 'senegal' => 'sn', 'slovakia' => 'sk', 'slovenia' => 'si', + 'south korea' => 'kr', 'suriname' => 'sr', 'ukraine' => 'ua', 'hungary' => 'hu', + 'uruguay' => 'uy', 'united states' => 'us', 'usa' => 'us', 'wales' => 'gb-wls', + 'bayern munich' => 'fc-bayern-muenchen', + 'paris saint germain' => 'paris-saint-germain', + ]; + + $internationalClubs = array_flip([ + 'arsenal', 'as-roma', 'atletico-madrid', 'barcelona', 'villarreal', 'manchester-city', + 'paris-saint-germain', 'psv', 'real-madrid', 'napoli', 'slovan-bratislava', 'fenerbahce', + 'bodo-glimt', 'como', 'fiorentina', 'ac-milan', 'ajax', 'as-monaco', 'aston-villa', + 'atalanta', 'athletic-bilbao', 'basaksehir', 'benfica', 'besiktas', 'real-betis', + 'celtic', 'club-brugge', 'crystal-palace', 'dinamo-zagreb', 'dynamo-kyiv', 'espanyol', + 'bologna', 'chelsea', 'getafe', 'copenhagen', 'liverpool', 'midtjylland', 'porto', + 'sevilla', 'valencia', 'ferencvaros', 'feyenoord', 'krasnodar', 'galatasaray', 'rangers', + 'inter-milan', 'juventus', 'gent', 'lazio', 'lokomotiv-moscow', 'maccabi-tel-aviv', + 'manchester-united', 'molde', 'newcastle', 'nottingham-forest', 'nice', 'olympiacos', + 'lyon', 'marseille', 'omonia', 'lille', 'paok', 'qarabag', 'rayo-vallecano', + 'rb-salzburg', 'real-sociedad', 'red-star-belgrade', 'shakhtar-donetsk', + 'sheriff-tiraspol', 'slavia-prague', 'sparta-prague', 'braga', 'sporting-cp', + 'sturm-graz', 'tottenham', 'west-ham', 'wolves', 'young-boys', 'zenit', + ]); + + $out = []; + try { + $key = getenv('APIFOOTBALL_KEY'); + if ($key === false || $key === '') { + return 'Fehler: APIFOOTBALL_KEY ist nicht gesetzt.'; + } + + $db = Database::getConnection(); + $today = date('Y-m-d'); + $from = $today . ' 00:00:00'; + $to = date('Y-m-d 00:00:00', strtotime('+3 days')); + + $stmt = $db->prepare( + "SELECT g.id, g.team1, g.team2, g.kickoff, g.score1, g.score2, g.fetcher_matched, + r.name AS round_name, s.name AS season_name, + t1.key AS k1, t2.key AS k2, t1.type AS t1t, t2.type AS t2t + FROM games g + JOIN rounds r ON r.id = g.round_id + JOIN seasons s ON s.id = r.season_id + LEFT JOIN teams t1 ON t1.id = g.team1_id + LEFT JOIN teams t2 ON t2.id = g.team2_id + WHERE g.kickoff >= ? AND g.kickoff < ? + ORDER BY g.kickoff" + ); + $stmt->execute([$from, $to]); + $games = $stmt->fetchAll(\PDO::FETCH_ASSOC); + + $targets = []; + foreach ($games as $g) { + $t1t = $g['t1t'] ?? ''; + $t2t = $g['t2t'] ?? ''; + if ($t1t === 'national' && $t2t === 'national') { + $targets[] = $g; + } elseif ($t1t === 'club' && $t2t === 'club' + && (isset($internationalClubs[$g['k1']]) || isset($internationalClubs[$g['k2']]))) { + $targets[] = $g; + } + } + + if (empty($targets)) { + return 'Keine Länderspiele/European-Cup-Spiele im Fenster (heute +2 Tage).'; + } + + $lookup = []; + // Free-Tier erlaubt nur "gestern..morgen", daher Fehler pro Datum tolerieren. + foreach ([$today, date('Y-m-d', strtotime('+1 day')), date('Y-m-d', strtotime('+2 days'))] as $date) { + $data = self::apiGet('/fixtures?date=' . $date, $key); + if ($data === null || isset($data['errors']['plan'])) { + continue; + } + foreach ($data['response'] ?? [] as $fx) { + $status = (string)($fx['fixture']['status']['short'] ?? ''); + $finished = in_array($status, ['FT', 'AET', 'PEN'], true); + $live = in_array($status, ['1H', 'HT', '2H', 'ET', 'BT', 'LIVE'], true); + $future = in_array($status, ['NS', 'TBD'], true); + if (!$finished && !$live && !$future) { + continue; + } + $score = null; + if ($finished || $live) { + $goals = $fx['goals'] ?? []; + if (!isset($goals['home']) || !isset($goals['away'])) { + continue; + } + $score = [(int)$goals['home'], (int)$goals['away']]; + } + + $k1 = self::apiTeamKey($fx['teams']['home'] ?? [], $nameMap); + $k2 = self::apiTeamKey($fx['teams']['away'] ?? [], $nameMap); + if ($k1 === null || $k2 === null) { + continue; + } + $dateKey = substr((string)$fx['fixture']['date'], 0, 10); + $lookup[$k1 . '|' . $k2 . '|' . $dateKey] = [ + 'score' => $score, 'finished' => $finished, + ]; + } + } + + $matched = 0; + $marked = 0; + $filled = 0; + $liveCount = 0; + $finalCount = 0; + $unmatched = []; + $mismatches = []; + $markStmt = $db->prepare( + "UPDATE games SET fetcher_matched = 1, updated_at = NOW() WHERE id = ? AND fetcher_matched <> 1" + ); + $updStmt = $db->prepare("UPDATE games SET score1 = ?, score2 = ?, updated_at = NOW() WHERE id = ?"); + + foreach ($targets as $g) { + $k1 = $g['k1']; + $k2 = $g['k2']; + if ($k1 === null || $k2 === null) { + continue; + } + $date = substr((string)$g['kickoff'], 0, 10); + $key = $k1 . '|' . $k2 . '|' . $date; + if (!isset($lookup[$key])) { + $unmatched[] = sprintf('%s vs %s (%s)', $g['team1'], $g['team2'], $date); + continue; + } + $matched++; + $row = $lookup[$key]; + $score = $row['score']; + $finished = $row['finished']; + + if ($check) { + if (!$finished) { + continue; + } + if ((int)$g['score1'] !== $score[0] || (int)$g['score2'] !== $score[1]) { + $mismatches[] = sprintf( + '%s vs %s (%s): API %d:%d, DB %d:%d', + $g['team1'], $g['team2'], $date, $score[0], $score[1], + (int)$g['score1'], (int)$g['score2'] + ); + } + continue; + } + + if (!$g['fetcher_matched']) { + $marked++; + if ($apply) { + $markStmt->execute([$g['id']]); + FetcherLog::create(FetcherLog::ACTION_IDENTIFIED, sprintf('%s vs %s', $g['team1'], $g['team2'])); + } + } + + if ($score === null) { + continue; + } + if ((int)$g['score1'] === $score[0] && (int)$g['score2'] === $score[1]) { + continue; + } + $kind = $finished ? 'Ende' : 'Live'; + $out[] = sprintf( + '%s vs %s (%s): %d:%d [%s]%s', + $g['team1'], $g['team2'], $date, $score[0], $score[1], $kind, + $apply ? '' : ' [Dry-Run]' + ); + if ($apply) { + $old = ((int)$g['score1'] >= 0 && (int)$g['score2'] >= 0) + ? sprintf('%d:%d', $g['score1'], $g['score2']) + : '-:-'; + $updStmt->execute([$score[0], $score[1], $g['id']]); + FetcherLog::create(FetcherLog::ACTION_RESULT, sprintf( + '%s vs %s: %s → %d:%d [%s]', + $g['team1'], $g['team2'], $old, $score[0], $score[1], $kind + )); + $filled++; + if ($finished) { + $finalCount++; + } else { + $liveCount++; + } + } + } + + $out[] = 'Zuordenbare Spiele: ' . $matched; + $out[] = 'Neu als erkannt markiert: ' . $marked . ($apply ? '' : ' [Dry-Run]'); + if ($apply) { + $out[] = 'Geschrieben: ' . $filled . ' (Live: ' . $liveCount . ', Endergebnis: ' . $finalCount . ')'; + } + if ($check) { + $out[] = 'Abweichungen zur DB: ' . count($mismatches); + foreach ($mismatches as $m) { + $out[] = ' - ' . $m; + } + } + if (!empty($unmatched)) { + $out[] = 'Nicht zugeordnet (' . count($unmatched) . '):'; + foreach ($unmatched as $u) { + $out[] = ' - ' . $u; + } + } + } catch (\Throwable $e) { + $out[] = 'Fehler: ' . $e->getMessage(); + } + return implode("\n", $out); + } + + private static function openligaGet(string $path): ?array { + $json = @file_get_contents(self::OPENLIGADB . $path); + if ($json === false) { + return null; + } + $data = json_decode($json, true); + return is_array($data) ? $data : null; + } + + private static function openligaTeamKey(array $teamObj, array $overrides): ?string { + $team = Team::resolve((string)($teamObj['teamName'] ?? '')); + if (!$team) { + $team = Team::resolve((string)($teamObj['shortName'] ?? '')); + } + if ($team) { + return $team['key']; + } + $normalized = Team::normalize((string)($teamObj['teamName'] ?? '')); + if ($normalized !== '' && isset($overrides[$normalized])) { + return $overrides[$normalized]; + } + return null; + } + + private static function seasonYearFor(string $kickoff): int { + $ts = strtotime($kickoff); + $year = (int)date('Y', $ts); + $month = (int)date('n', $ts); + return $month < 7 ? $year - 1 : $year; + } + + private static function apiGet(string $path, string $key): ?array { + $ctx = stream_context_create([ + 'http' => [ + 'header' => "x-apisports-key: $key\r\n", + 'ignore_errors' => true, + 'timeout' => 25, + ], + ]); + $json = @file_get_contents(self::API_BASE . $path, false, $ctx); + if ($json === false) { + return null; + } + $data = json_decode($json, true); + return is_array($data) ? $data : null; + } + + private static function apiTeamKey(array $teamObj, array $nameMap): ?string { + $name = (string)($teamObj['name'] ?? ''); + $team = Team::resolve($name); + if ($team) { + return $team['key']; + } + $normalized = Team::normalize($name); + if ($normalized !== '' && isset($nameMap[$normalized])) { + return $nameMap[$normalized]; + } + return null; + } +} diff --git a/tippspiel/src/Models/FetcherLog.php b/tippspiel/src/Models/FetcherLog.php new file mode 100644 index 0000000..3044941 --- /dev/null +++ b/tippspiel/src/Models/FetcherLog.php @@ -0,0 +1,65 @@ +prepare( + "INSERT INTO fetcher_log (created_at, action, message) VALUES (NOW(), ?, ?)" + ); + return $stmt->execute([$action, $message]); + } + + /** + * Alle Einträge im Zeitraum [fromDate, toDate] (jeweils ganze Tage), neueste zuerst. + * + * @param string $fromDate Y-m-d + * @param string $toDate Y-m-d + * @return array + */ + public static function getRange(string $fromDate, string $toDate) { + $db = Database::getConnection(); + $from = $fromDate . ' 00:00:00'; + $to = date('Y-m-d 00:00:00', strtotime($toDate . ' +1 day')); + $stmt = $db->prepare( + "SELECT * FROM fetcher_log WHERE created_at >= ? AND created_at < ? ORDER BY created_at DESC, id DESC" + ); + $stmt->execute([$from, $to]); + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } + + /** + * Löscht Einträge, die älter als RETENTION_DAYS Tage sind. + * + * @return int Anzahl gelöschter Einträge + */ + public static function deleteOld() { + $db = Database::getConnection(); + $stmt = $db->prepare( + "DELETE FROM fetcher_log WHERE created_at < NOW() - INTERVAL " . (int)self::RETENTION_DAYS . " DAY" + ); + $stmt->execute(); + return $stmt->rowCount(); + } +} diff --git a/tippspiel/src/Models/Season.php b/tippspiel/src/Models/Season.php index b7bbc5c..3183d21 100644 --- a/tippspiel/src/Models/Season.php +++ b/tippspiel/src/Models/Season.php @@ -16,8 +16,10 @@ class Season { const GAMES_PER_ROUND = 4; /** - * Holt die aktuell selektierte Saison (settings.current_season_id). - * Fallback: Die Saison mit der höchsten ID. + * Holt die global aktive Saison (settings.current_season_id), die für + * alle Spieler gilt. Fallback: Die Saison mit der höchsten ID. + * + * @return array|false */ public static function getCurrent() { $db = Database::getConnection(); @@ -37,6 +39,52 @@ class Season { return $stmt->fetch(); } + /** + * Holt die Saison, die der aktuelle Admin persönlich "ansehen" möchte. + * Diese Ansicht ist nur in der Session des Admins gespeichert und wirkt + * sich nicht auf andere Spieler aus. Fallback: die global aktive Saison. + * + * @return array|false + */ + public static function getViewSeason() { + $viewId = self::viewSeasonId(); + if ($viewId !== null) { + $season = self::findById($viewId); + if ($season) { + return $season; + } + unset($_SESSION['admin_view_season_id']); + } + return self::getCurrent(); + } + + /** + * Liefert die ID der persönlich ausgewählten Saison oder null, wenn keine + * persönliche Auswahl getroffen wurde (dann gilt die global aktive Saison). + * + * @return int|null + */ + public static function viewSeasonId() { + return isset($_SESSION['admin_view_season_id']) ? (int)$_SESSION['admin_view_season_id'] : null; + } + + /** + * Setzt die persönliche Saison-Ansicht des Admins (nur in dessen Session). + * $id = null/''/0 setzt die Ansicht zurück auf die global aktive Saison. + * + * @param int|string|null $id + * @return void + */ + public static function setViewSeason($id) { + if ($id === null || $id === '' || (int)$id <= 0) { + unset($_SESSION['admin_view_season_id']); + return; + } + if (self::findById((int)$id)) { + $_SESSION['admin_view_season_id'] = (int)$id; + } + } + /** * Holt alle Saisons. * @@ -197,6 +245,10 @@ class Season { $db->prepare($sql)->execute([$id]); } $db->commit(); + + if (self::viewSeasonId() === $id) { + unset($_SESSION['admin_view_season_id']); + } } catch (\Exception $e) { $db->rollBack(); throw $e; diff --git a/tippspiel/src/Views/admin/fetcher_activity.php b/tippspiel/src/Views/admin/fetcher_activity.php new file mode 100644 index 0000000..8cec1a4 --- /dev/null +++ b/tippspiel/src/Views/admin/fetcher_activity.php @@ -0,0 +1,64 @@ + ['Identifiziert', 'badge-identified'], + 'result' => ['Ergebnis geändert', 'badge-result'], +]; +?> + +

Robo-Admin Aktivität

+ +
+ + + + + + +
+ + +

Keine Aktivitäten im gewählten Zeitraum.

+ + + + + + + + + + + + + + + + + + + +
ZeitpunktHandlungBeschreibung
+ + + + + diff --git a/tippspiel/src/Views/admin/rounds.php b/tippspiel/src/Views/admin/rounds.php index 2409113..d1b38e8 100644 --- a/tippspiel/src/Views/admin/rounds.php +++ b/tippspiel/src/Views/admin/rounds.php @@ -33,7 +33,7 @@ $teamLogo = function ($name) { @@ -110,6 +110,11 @@ $teamLogo = function ($name) { : + + + + + @@ -146,6 +151,9 @@ $teamLogo = function ($name) { .round-admin textarea { width: 100%; max-width: 800px; } .round-admin .form-group { margin: 0.8em 0; } .round-admin .hint { color: #666; font-size: 0.8em; } +.fetcher-badge { margin-left: 0.5em; vertical-align: middle; cursor: help; } +.fa-robot.fetcher-badge { color: var(--pitch); } +.fetcher-unknown { color: var(--bronze); }