feat: port legacy season, tipp scoring and user logic to models

Co-authored-by: aider (anthropic/claude-opus-5-5) <aider@aider.chat>
This commit is contained in:
torsten 2026-10-04 20:57:52 +02:00
parent f00770f73f
commit 7ecd38cb20
3 changed files with 630 additions and 93 deletions

View file

@ -2,12 +2,31 @@
namespace App\Models;
use App\Core\Database;
/**
* Tipps und Punktewertung (portiert aus Legacy App\Tipp und TippsController).
*
* Konvention: Ein fehlender Eintrag in `tipps` bedeutet "nicht getippt"
* (gleichwertig zum Legacy-Platzhalter -1:-1). Einträge werden erst beim
* Speichern angelegt (Upsert über den Unique-Key user_id/game_id).
*/
class Tipp {
/** Bonus, wenn in einer Runde jedes Spiel mindestens Tendenz-Punkte bringt */
const ALL_HITS_BONUS = 2;
/** Maximal erlaubte Toranzahl pro Team bei der Eingabe */
const MAX_GOALS = 99;
/**
* Berechnet die Punkte für einen Tipp im Vergleich zum echten Ergebnis.
* Portiert aus der alten Laravel-Anwendung.
*
*
* - Richtige Tendenz: 1 Punkt
* - Exaktes Ergebnis: 2 Punkte + max(0, Gesamttore - 3)
* - Joker verdoppelt
*
* @param int $goals1 Tore Team 1
* @param int $goals2 Tore Team 2
* @param int $tipp1 Getippte Tore Team 1
@ -50,6 +69,16 @@ class Tipp {
return $score;
}
/**
* Prüft, ob ein Tipp das exakte Ergebnis getroffen hat.
*/
public static function isExact($goals1, $goals2, $tipp1, $tipp2) {
if ($tipp1 == -1 || $tipp2 == -1 || $goals1 == -1 || $goals2 == -1) {
return false;
}
return $tipp1 == $goals1 && $tipp2 == $goals2;
}
/**
* Gibt die CSS-Klasse für die Farbe des Tipps zurück (fürs Frontend)
*/
@ -84,4 +113,290 @@ class Tipp {
// Kein Treffer
return "";
}
/**
* Wertet die Tipps eines Benutzers für eine Runde aus.
*
* @param array $games Spiele der Runde (Zeilen aus `games`)
* @param array $tippsByGameId Tipps des Benutzers, game_id => Zeile aus `tipps`
* @return array [
* 'points' => Rundenpunkte inkl. Bonus (+2 wenn alle Spiele punkten),
* 'hits' => Anzahl Spiele mit Punkten,
* 'exact' => Anzahl exakter Treffer (für Tagessieg),
* 'joker_value' => Wert eines exakten Joker-Treffers (für Tagessieg), 0 wenn keiner,
* ]
*/
public static function evaluateRound(array $games, array $tippsByGameId) {
$points = 0;
$hits = 0;
$exact = 0;
$jokerValue = 0;
foreach ($games as $game) {
$tipp = $tippsByGameId[$game['id']] ?? null;
$goals1 = (int)$game['score1'];
$goals2 = (int)$game['score2'];
$tipp1 = $tipp ? (int)$tipp['score1'] : -1;
$tipp2 = $tipp ? (int)$tipp['score2'] : -1;
$joker = $tipp ? (bool)$tipp['joker'] : false;
$gamePoints = self::getScoreLocal($goals1, $goals2, $tipp1, $tipp2, $joker);
$points += $gamePoints;
if ($gamePoints > 0) {
$hits++;
}
if (self::isExact($goals1, $goals2, $tipp1, $tipp2)) {
$exact++;
if ($joker) {
// Legacy: Jokersieg mit mehr Toren zählt mehr
$jokerValue = max($jokerValue, max(0, $goals1 + $goals2 - 3) + 1);
}
}
}
if (count($games) > 0 && $hits === count($games)) {
$points += self::ALL_HITS_BONUS;
}
return [
'points' => $points,
'hits' => $hits,
'exact' => $exact,
'joker_value' => $jokerValue,
];
}
/**
* Vergleicht zwei Rundenauswertungen nach Tagessieg-Regel (absteigend, für usort):
* 1. Anzahl exakter Treffer, 2. Wert des exakten Joker-Treffers.
* (Bei mehr als 6 Tagessiegern entscheiden zusätzlich die Rundenpunkte - das
* erledigt die Ranglistenberechnung.)
*
* @return int <0 wenn $a besser ist, >0 wenn $b besser ist, 0 bei Gleichstand
*/
public static function compareDayScore(array $a, array $b) {
return [$b['exact'], $b['joker_value']] <=> [$a['exact'], $a['joker_value']];
}
/**
* Holt die Tipps eines Benutzers für eine Runde.
*
* @return array game_id => Zeile aus `tipps`
*/
public static function findByUserAndRound($userId, $roundId) {
$db = Database::getConnection();
$stmt = $db->prepare(
"SELECT t.* FROM tipps t
JOIN games g ON g.id = t.game_id
WHERE t.user_id = ? AND g.round_id = ?"
);
$stmt->execute([$userId, $roundId]);
$result = [];
foreach ($stmt->fetchAll() as $row) {
$result[$row['game_id']] = $row;
}
return $result;
}
/**
* Holt alle Tipps aller Benutzer für eine Runde.
*
* @return array user_id => [game_id => Zeile aus `tipps`]
*/
public static function findByRound($roundId) {
$db = Database::getConnection();
$stmt = $db->prepare(
"SELECT t.* FROM tipps t
JOIN games g ON g.id = t.game_id
WHERE g.round_id = ?"
);
$stmt->execute([$roundId]);
$result = [];
foreach ($stmt->fetchAll() as $row) {
$result[$row['user_id']][$row['game_id']] = $row;
}
return $result;
}
/**
* Zählt, wie oft ein Benutzer in einer Saison welches Ergebnis mit Joker getippt hat.
*
* @param int $userId
* @param int $seasonId
* @param int|null $excludeRoundId Diese Runde nicht mitzählen (beim Speichern der Runde)
* @param int|null $upToRoundId Nur Runden bis einschließlich dieser ID (für die Anzeige)
* @return array "2:1" => Anzahl, absteigend sortiert
*/
public static function getJokerUsage($userId, $seasonId, $excludeRoundId = null, $upToRoundId = null) {
$db = Database::getConnection();
$sql = "SELECT CONCAT(t.score1, ':', t.score2) AS result, COUNT(*) AS cnt
FROM tipps t
JOIN games g ON g.id = t.game_id
JOIN rounds r ON r.id = g.round_id
WHERE t.user_id = ? AND t.joker = 1 AND r.season_id = ?";
$params = [$userId, $seasonId];
if ($excludeRoundId !== null) {
$sql .= " AND r.id <> ?";
$params[] = $excludeRoundId;
}
if ($upToRoundId !== null) {
$sql .= " AND r.id <= ?";
$params[] = $upToRoundId;
}
$sql .= " GROUP BY result ORDER BY cnt DESC, result ASC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
return array_map('intval', $stmt->fetchAll(\PDO::FETCH_KEY_PAIR));
}
/**
* Formatiert die Joker-Nutzung für die Anzeige, z.B. "3x2:1, 1x1:0".
*/
public static function formatJokerUsage(array $usage) {
$parts = [];
foreach ($usage as $result => $count) {
$parts[] = $count . 'x' . $result;
}
return implode(', ', $parts);
}
/**
* Speichert alle Tipps eines Benutzers für eine Runde (atomar).
*
* Regeln (aus dem Legacy-Code):
* - Eine Runde ist gesperrt, sobald eines ihrer Spiele gesperrt ist (1 Min. vor Anpfiff).
* - Pro Runde genau ein Joker (oder keiner).
* - Dasselbe Ergebnis darf pro Saison höchstens max_identical_jokertipps-mal
* mit Joker getippt werden (die aktuelle Runde zählt dabei nicht mit).
*
* @param int $userId
* @param int $roundId
* @param array $scores game_id => ['score1' => .., 'score2' => ..] für alle Spiele der Runde
* @param int|null $jokerGameId game_id des Joker-Tipps oder null
* @return string|null Fehlermeldung oder null bei Erfolg
*/
public static function saveRound($userId, $roundId, array $scores, $jokerGameId) {
$db = Database::getConnection();
$stmt = $db->prepare(
"SELECT r.season_id, s.max_identical_jokertipps
FROM rounds r JOIN seasons s ON s.id = r.season_id
WHERE r.id = ?"
);
$stmt->execute([$roundId]);
$round = $stmt->fetch();
if (!$round) {
return "Runde nicht gefunden.";
}
$games = Game::getGamesByRound($roundId);
if (empty($games)) {
return "Diese Runde enthält keine Spiele.";
}
foreach ($games as $game) {
if (Game::isLocked($game['kickoff'])) {
return "Die Runde ist bereits gesperrt, Tipps können nicht mehr geändert werden.";
}
}
// Eingaben validieren
$validated = [];
foreach ($games as $game) {
$input = $scores[$game['id']] ?? null;
$s1 = filter_var($input['score1'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => self::MAX_GOALS]]);
$s2 = filter_var($input['score2'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => self::MAX_GOALS]]);
if ($s1 === false || $s2 === false) {
return "Bitte für alle Spiele ein gültiges Ergebnis (0-" . self::MAX_GOALS . ") eintragen: "
. $game['team1'] . " - " . $game['team2'];
}
$validated[$game['id']] = [$s1, $s2];
}
if ($jokerGameId !== null) {
$jokerGameId = (int)$jokerGameId;
if (!isset($validated[$jokerGameId])) {
return "Der Joker muss auf ein Spiel dieser Runde gesetzt werden.";
}
// Joker-Limit pro Ergebnis und Saison
$jokerResult = $validated[$jokerGameId][0] . ':' . $validated[$jokerGameId][1];
$usage = self::getJokerUsage($userId, $round['season_id'], $roundId);
$limit = (int)$round['max_identical_jokertipps'];
if (($usage[$jokerResult] ?? 0) >= $limit) {
return "Das Ergebnis $jokerResult wurde in dieser Saison bereits "
. $usage[$jokerResult] . "-mal mit Joker getippt (Maximum: $limit).";
}
}
$db->beginTransaction();
try {
$stmt = $db->prepare(
"INSERT INTO tipps (user_id, game_id, score1, score2, joker, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, NOW(), NOW())
ON DUPLICATE KEY UPDATE
score1 = VALUES(score1),
score2 = VALUES(score2),
joker = VALUES(joker),
updated_at = NOW()"
);
foreach ($validated as $gameId => [$s1, $s2]) {
$stmt->execute([$userId, $gameId, $s1, $s2, $gameId === $jokerGameId ? 1 : 0]);
}
$db->commit();
} catch (\Exception $e) {
$db->rollBack();
error_log("Tipp::saveRound fehlgeschlagen: " . $e->getMessage());
return "Die Tipps konnten nicht gespeichert werden.";
}
return null;
}
/**
* Ermittelt, welche Benutzer in einer Runde noch Tipps oder den Joker vergessen haben
* (für Admin-Benutzerliste, Startseiten-Hinweis, Rundmail-Empfänger und Erinnerungen).
*
* @param int $roundId
* @param array $userIds
* @return array ['tipps' => [user_id, ...], 'joker' => [user_id, ...]]
*/
public static function getMissing($roundId, array $userIds) {
$gameCount = count(Game::getGamesByRound($roundId));
$db = Database::getConnection();
$stmt = $db->prepare(
"SELECT t.user_id,
SUM(t.score1 >= 0 AND t.score2 >= 0) AS tipped,
MAX(t.joker) AS has_joker
FROM tipps t
JOIN games g ON g.id = t.game_id
WHERE g.round_id = ?
GROUP BY t.user_id"
);
$stmt->execute([$roundId]);
$status = [];
foreach ($stmt->fetchAll() as $row) {
$status[$row['user_id']] = $row;
}
$missing = ['tipps' => [], 'joker' => []];
foreach ($userIds as $userId) {
$row = $status[$userId] ?? null;
if (!$row || (int)$row['tipped'] < $gameCount) {
$missing['tipps'][] = $userId;
}
if (!$row || !(int)$row['has_joker']) {
$missing['joker'][] = $userId;
}
}
return $missing;
}
}