Erster Durchstich mit updates
This commit is contained in:
parent
d3fd60b548
commit
3331f08091
60 changed files with 693 additions and 195 deletions
472
tippspiel/src/Models/Tipp.php
Normal file
472
tippspiel/src/Models/Tipp.php
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
<?php
|
||||
|
||||
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
|
||||
* @param int $tipp2 Getippte Tore Team 2
|
||||
* @param bool $joker Ob der Joker für diesen Tipp gesetzt wurde
|
||||
* @return int Die erreichten Punkte
|
||||
*/
|
||||
public static function getScoreLocal($goals1, $goals2, $tipp1, $tipp2, $joker) {
|
||||
$score = 0;
|
||||
|
||||
// Wenn noch kein Ergebnis vorliegt (-1 bedeutet in der DB meistens noch nicht gespielt)
|
||||
if ($tipp1 == -1 || $tipp2 == -1 || $goals1 == -1 || $goals2 == -1) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$tippTendenz = $tipp1 - $tipp2;
|
||||
if ($tippTendenz > 0) { $tippTendenz = 1; }
|
||||
if ($tippTendenz < 0) { $tippTendenz = -1; }
|
||||
|
||||
$gameTendenz = $goals1 - $goals2;
|
||||
if ($gameTendenz < 0) { $gameTendenz = -1; }
|
||||
if ($gameTendenz > 0) { $gameTendenz = 1; }
|
||||
|
||||
// Tendenz richtig
|
||||
if ($tippTendenz == $gameTendenz) {
|
||||
$score = 1;
|
||||
}
|
||||
|
||||
// Genaues Ergebnis richtig (gibt 2 Grundpunkte + Bonus)
|
||||
if (($tipp1 == $goals1) && ($tipp2 == $goals2)) {
|
||||
$bonus = max(0, $goals1 + $goals2 - 3);
|
||||
$score = 2 + $bonus;
|
||||
}
|
||||
|
||||
// Joker verdoppelt die Punktzahl
|
||||
if ($joker == true) {
|
||||
$score = $score * 2;
|
||||
}
|
||||
|
||||
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 (portiert aus Legacy Tipp::trendCol).
|
||||
*
|
||||
* - "col_tendenz" = richtige Tendenz (grau)
|
||||
* - "col_exact" = richtiges Ergebnis (orange)
|
||||
* - "col_joker_exact" = richtiges Ergebnis mit Joker (rot)
|
||||
* - "" = kein Treffer, nicht getippt oder noch kein Ergebnis
|
||||
*/
|
||||
public static function getCol($goals1, $goals2, $tipp1, $tipp2, $joker) {
|
||||
if ($tipp1 == -1 || $tipp2 == -1 || $goals1 == -1 || $goals2 == -1) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (self::isExact($goals1, $goals2, $tipp1, $tipp2)) {
|
||||
return $joker ? "col_joker_exact" : "col_exact";
|
||||
}
|
||||
|
||||
$tippSign = $tipp1 <=> $tipp2;
|
||||
$gameSign = $goals1 <=> $goals2;
|
||||
|
||||
return $tippSign === $gameSign ? "col_tendenz" : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Speichert einen einzelnen Tipp (Legacy TippsController::store).
|
||||
*
|
||||
* Regeln wie bei saveRound(): Runde nicht gesperrt, Joker-Limit pro Ergebnis und Saison.
|
||||
* Wird der Joker gesetzt, wird er von den anderen Tipps der Runde entfernt.
|
||||
*
|
||||
* @param int $userId
|
||||
* @param int $gameId
|
||||
* @param mixed $score1
|
||||
* @param mixed $score2
|
||||
* @param bool $joker
|
||||
* @return string|null Fehlermeldung oder null bei Erfolg
|
||||
*/
|
||||
public static function saveSingle($userId, $gameId, $score1, $score2, $joker) {
|
||||
$db = Database::getConnection();
|
||||
|
||||
$stmt = $db->prepare(
|
||||
"SELECT g.round_id, r.season_id, s.max_identical_jokertipps
|
||||
FROM games g
|
||||
JOIN rounds r ON r.id = g.round_id
|
||||
JOIN seasons s ON s.id = r.season_id
|
||||
WHERE g.id = ?"
|
||||
);
|
||||
$stmt->execute([$gameId]);
|
||||
$info = $stmt->fetch();
|
||||
if (!$info) {
|
||||
return "Spiel nicht gefunden.";
|
||||
}
|
||||
$roundId = (int)$info['round_id'];
|
||||
|
||||
if (Round::isLocked(Game::getGamesByRound($roundId))) {
|
||||
return "Die Runde ist bereits gesperrt, Tipps können nicht mehr geändert werden.";
|
||||
}
|
||||
|
||||
$options = ['options' => ['min_range' => 0, 'max_range' => self::MAX_GOALS]];
|
||||
$s1 = filter_var($score1, FILTER_VALIDATE_INT, $options);
|
||||
$s2 = filter_var($score2, FILTER_VALIDATE_INT, $options);
|
||||
if ($s1 === false || $s2 === false) {
|
||||
return "Bitte ein gültiges Ergebnis (0-" . self::MAX_GOALS . ") eintragen.";
|
||||
}
|
||||
|
||||
if ($joker) {
|
||||
$jokerResult = $s1 . ':' . $s2;
|
||||
$usage = self::getJokerUsage($userId, $info['season_id'], $roundId);
|
||||
$limit = (int)$info['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()"
|
||||
);
|
||||
$stmt->execute([$userId, $gameId, $s1, $s2, $joker ? 1 : 0]);
|
||||
|
||||
if ($joker) {
|
||||
$stmt = $db->prepare(
|
||||
"UPDATE tipps t JOIN games g ON g.id = t.game_id
|
||||
SET t.joker = 0, t.updated_at = NOW()
|
||||
WHERE t.user_id = ? AND g.round_id = ? AND t.game_id <> ? AND t.joker = 1"
|
||||
);
|
||||
$stmt->execute([$userId, $roundId, $gameId]);
|
||||
}
|
||||
$db->commit();
|
||||
} catch (\Exception $e) {
|
||||
$db->rollBack();
|
||||
error_log("Tipp::saveSingle fehlgeschlagen: " . $e->getMessage());
|
||||
return "Der Tipp konnte 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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue