Compare commits

...

2 Commits

Author SHA1 Message Date
d982ff1068 KO Bracket fixed 2026-06-29 23:30:26 -05:00
6811fc8161 Korrekturen bei KO Spiele 2026-06-29 22:52:42 -05:00
6 changed files with 177 additions and 215 deletions

View File

@@ -1,5 +1,5 @@
import { NextResponse } from "next/server";
import { fetchMatchesAndTeams, fetchOdds, attachOdds, attachKOOdds, fetchLiveScores, applyLiveScores, assignKONumbersBySlots, fetchKOLiveData, attachKOLiveData } from "@/lib/feeds";
import { fetchMatchesAndTeams, fetchOdds, attachOdds, attachKOOdds, fetchFifaScores, applyFifaScores, assignKONumbersBySlots } from "@/lib/feeds";
import { computeGroupTables, computeThirdPlaceTable } from "@/lib/standings";
import { qualifiedThirdGroups, resolveAnnexC } from "@/lib/bracket";
import { securelyQualifiedThirdTeams } from "@/lib/third-place-security";
@@ -22,31 +22,23 @@ export async function GET() {
console.error("[polymarket] fetchOdds fehlgeschlagen:", err);
}
// Live-Scores von worldcup26.ir (additiv, Fallback auf football-data)
try {
const liveScores = await fetchLiveScores();
matches = applyLiveScores(matches, teams, liveScores);
} catch (err) {
console.warn("[worldcup26] fetchLiveScores fehlgeschlagen:", err instanceof Error ? err.message : err);
}
const groupTables = computeGroupTables(teams, matches);
const groupTablesLive = computeGroupTables(teams, matches, true);
// FIFA-Live-Scores (additiv, Fallback auf football-data)
assignKONumbersBySlots(matches, teams);
if (odds) {
matches = attachKOOdds(matches, teams, odds);
}
// KO-Live-Daten (Tore, Minute) von worldcup26
try {
const koGames = await fetchKOLiveData();
matches = attachKOLiveData(matches, teams, koGames);
const fifaData = await fetchFifaScores();
matches = applyFifaScores(matches, teams, fifaData);
} catch (err) {
console.warn("[worldcup26] KO-Live-Daten fehlgeschlagen:", err instanceof Error ? err.message : err);
console.warn("[fifa] Scores fehlgeschlagen:", err instanceof Error ? err.message : err);
}
const groupTables = computeGroupTables(teams, matches);
const groupTablesLive = computeGroupTables(teams, matches, true);
const normalizedMatches = matches.map((m) => ({ ...m, prob: m.prob ?? null }));
const thirdTable = computeThirdPlaceTable(groupTablesLive);

View File

@@ -75,6 +75,11 @@ function Tie({
</div>
<Side s={tie.home} prob={tie.prob?.home} teams={teams} onShowTip={onShowTip} onHideTip={onHideTip} />
<Side s={tie.away} prob={tie.prob?.away} teams={teams} onShowTip={onShowTip} onHideTip={onHideTip} />
{tie.homePenalty != null && tie.awayPenalty != null && (
<div className="tie-meta" style={{ padding: "2px 10px 4px", textAlign: "center" }}>
({tie.homePenalty}:{tie.awayPenalty} i.E.)
</div>
)}
</div>
);
}

View File

@@ -17,7 +17,11 @@ function fmtTime(iso: string): string {
function scoreDisplay(m: Match): string {
if (m.status === "SCHEDULED" || (m.homeScore == null && m.awayScore == null)) return " : ";
return `${m.homeScore ?? 0} : ${m.awayScore ?? 0}`;
const base = `${m.homeScore ?? 0} : ${m.awayScore ?? 0}`;
if (m.homePenalty != null && m.awayPenalty != null) {
return `${base} (${m.homePenalty}:${m.awayPenalty} i.E.)`;
}
return base;
}
function statusLabel(m: Match): string {

View File

@@ -1,4 +1,4 @@
import { GroupId, GoalEvent, Match, MatchStatus, Team } from "./types";
import { GroupId, Match, MatchStatus, Team } from "./types";
import { venueFor } from "./venues";
import { localisedTeamName } from "./team-mappings";
import { R32, LATER_ROUNDS, resolveAnnexC, qualifiedThirdGroups } from "./bracket";
@@ -556,221 +556,146 @@ export function attachKOOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]
}
// ----------------------------------------------------------------------------
// worldcup26.ir: schnelle Live-Scores (additiv, Fallback auf football-data)
// FIFA-API: Live-Scores, Elfmeterschießen, Spielminute
// ----------------------------------------------------------------------------
const WC26_BASE = "https://worldcup26.ir";
const FIFA_BASE = "https://api.fifa.com/api/v3";
const FIFA_SEASON = "285023";
interface Wc26Game {
home_team_name_en?: string;
away_team_name_en?: string;
group?: string;
matchday?: string;
home_score?: string;
away_score?: string;
time_elapsed?: string;
home_scorers?: string;
away_scorers?: string;
current_minute?: string;
// FIFA-Code → App-Code (nur Abweichungen; sonst identisch)
const FIFA_CODE_OVERRIDE: Record<string, string> = {
CRO: "HRV", // Kroatien
POR: "PRT", // Portugal
SUI: "CHE", // Schweiz
};
function fifaCodeToAppCode(fifaCode: string): string {
return FIFA_CODE_OVERRIDE[fifaCode] ?? fifaCode;
}
interface LiveScore {
homeName: string;
awayName: string;
group: string;
matchday: string;
interface FifaTeamBlock {
IdTeam: string; // FIFA-Team-ID
Abbreviation: string; // FIFA-Code (z.B. PAR, CRO)
}
interface FifaMatch {
MatchNumber: number;
Home: FifaTeamBlock | null;
Away: FifaTeamBlock | null;
HomeTeamScore: number | null;
AwayTeamScore: number | null;
HomeTeamPenaltyScore: number | null;
AwayTeamPenaltyScore: number | null;
MatchStatus: number; // 0=finished, 1=scheduled, else=live
MatchTime: string | null; // z.B. "132'"
ResultType: number | null; // 1=regular, 2=penalties
Winner?: string | null; // Team-ID des Siegers
}
interface FifaScores {
homeScore: number | null;
awayScore: number | null;
status: string; // "IN_PLAY" | "FINISHED"
homePenalty: number | null;
awayPenalty: number | null;
resultType: number | null;
status: MatchStatus;
matchTime: string | null;
winnerTeamId: string | null;
}
// Ruft alle Spiele von worldcup26.ir ab.
export async function fetchLiveScores(): Promise<LiveScore[]> {
const res = await fetch(`${WC26_BASE}/get/games`, {
cache: "no-store",
headers: { "User-Agent": "wm2026-board/1.0" },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`worldcup26 ${res.status}`);
const data = (await res.json()) as { games: Wc26Game[] };
const games = data.games ?? [];
const scores: LiveScore[] = [];
for (const g of games) {
if (!g.home_team_name_en || !g.away_team_name_en) continue;
const hScore = parseScore(g.home_score);
const aScore = parseScore(g.away_score);
let status = "";
switch (g.time_elapsed) {
case "live": status = "IN_PLAY"; break;
case "finished": status = "FINISHED"; break;
default: continue; // notstarted → überspringen
}
// Nur anwenden, wenn mindestens ein Score vorhanden ist
if (hScore == null && aScore == null) continue;
scores.push({
homeName: g.home_team_name_en,
awayName: g.away_team_name_en,
group: g.group ?? "",
matchday: String(g.matchday ?? ""),
homeScore: hScore,
awayScore: aScore,
status,
});
}
console.log("[worldcup26] spiele:", scores.length);
return scores;
}
function parseScore(s: string | undefined): number | null {
if (!s || s === "null") return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
// Wendet worldcup26-Live-Scores auf football-data-Matches an.
// Matching über normalisierte Teamnamen + group + matchday.
export function applyLiveScores(
matches: Match[], teams: Team[], liveScores: LiveScore[],
): Match[] {
// Build lookup: normName(home)::normName(away)::group::matchday → match
// Für Group-Phase ist die Paarung eindeutig (jedes Paar spielt 1x).
const byPair = new Map<string, Match>();
for (const m of matches) {
if (m.group == null) continue; // nur Gruppenphase
if (!m.homeTeamId || !m.awayTeamId) continue;
const ht = teams.find((t) => t.id === m.homeTeamId);
const at = teams.find((t) => t.id === m.awayTeamId);
if (!ht || !at) continue;
const hn = normName(ht.name);
const an = normName(at.name);
// Beide Richtungen
byPair.set(`${hn}::${an}::${m.group}`, m);
byPair.set(`${an}::${hn}::${m.group}`, m);
}
const result = [...matches];
let applied = 0;
for (const ls of liveScores) {
const hn = normName(ls.homeName);
const an = normName(ls.awayName);
const key = `${hn}::${an}::${ls.group}`;
const fdMatch = byPair.get(key);
if (!fdMatch) continue;
const idx = result.findIndex((m) => m.id === fdMatch.id);
if (idx < 0) continue;
result[idx] = {
...result[idx],
homeScore: ls.homeScore ?? result[idx].homeScore,
awayScore: ls.awayScore ?? result[idx].awayScore,
status: ls.status as Match["status"],
};
applied++;
}
if (applied > 0) console.log("[worldcup26] auf matches angewandt:", applied);
return result;
}
// Holt KO-Live-Daten von worldcup26 (Tore, Minute) und hängt sie an die Feed-Matches.
export async function fetchKOLiveData(): Promise<Wc26Game[]> {
try {
const res = await fetch(`${WC26_BASE}/get/games`, {
// Holt Live-Scores von der FIFA-API. Gibt Map MatchNumber → Scores + FIFA-ID→App-Code-Map zurück.
export async function fetchFifaScores(): Promise<{
scores: Map<number, FifaScores>;
fifaIdToAppCode: Map<string, string>;
}> {
return cached("fifa:scores", 45_000, async () => {
const url = `${FIFA_BASE}/calendar/matches?language=de&count=500&idSeason=${FIFA_SEASON}`;
const res = await fetch(url, {
cache: "no-store",
headers: { "User-Agent": "wm2026-board/1.0" },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`worldcup26 ${res.status}`);
const data = (await res.json()) as { games: Wc26Game[] };
return (data.games ?? []).filter(g => {
const grp = (g.group ?? "").toUpperCase();
return grp === "" || grp === "R32" || grp === "R16" || grp === "QF" || grp === "SF" || grp === "3RD" || grp === "FINAL" || grp === "FINALIST";
});
} catch {
return [];
}
}
if (!res.ok) throw new Error(`fifa ${res.status}`);
const data = (await res.json()) as { Results: FifaMatch[] };
const scores = new Map<number, FifaScores>();
const fifaIdToAppCode = new Map<string, string>();
// Hängt worldcup26-KO-Live-Daten an die Matches an (Tore, Minute, Scores).
export function attachKOLiveData(matches: Match[], teams: Team[], koGames: Wc26Game[]): Match[] {
if (koGames.length === 0) return matches;
for (const fm of data.Results ?? []) {
// Team-Mapping sammeln
for (const tb of [fm.Home, fm.Away]) {
if (tb && !fifaIdToAppCode.has(tb.IdTeam)) {
fifaIdToAppCode.set(tb.IdTeam, fifaCodeToAppCode(tb.Abbreviation));
}
}
const nameById = new Map<string, string>();
for (const t of teams) {
const nn = normName(t.name);
if (!nameById.has(nn)) nameById.set(nn, t.id);
}
return matches.map((m) => {
if (m.group != null) return m; // nur K.o.-Spiele
const hId = m.homeTeamId;
const aId = m.awayTeamId;
const hName = hId ? teams.find(t => t.id === hId)?.name : null;
const aName = aId ? teams.find(t => t.id === aId)?.name : null;
// Finde worldcup26-Spiel über Teamnamen
const wm = koGames.find(g => {
if (!hName || !aName) return false;
const gh = normName(g.home_team_name_en ?? "");
const ga = normName(g.away_team_name_en ?? "");
return (gh === normName(hName) && ga === normName(aName)) ||
(gh === normName(aName) && ga === normName(hName));
});
if (!wm) return m;
const result = { ...m };
// Live-Score + Status
if (wm.time_elapsed === "live" || wm.time_elapsed === "finished") {
result.status = wm.time_elapsed === "finished" ? "FINISHED" : "IN_PLAY";
const hs = parseScore(wm.home_score);
const as = parseScore(wm.away_score);
if (hs != null) result.homeScore = hs;
if (as != null) result.awayScore = as;
let status: MatchStatus;
switch (fm.MatchStatus) {
case 0: status = "FINISHED"; break;
case 1: status = "SCHEDULED"; break;
default: status = "LIVE"; break;
}
scores.set(fm.MatchNumber, {
homeScore: fm.HomeTeamScore,
awayScore: fm.AwayTeamScore,
homePenalty: fm.HomeTeamPenaltyScore,
awayPenalty: fm.AwayTeamPenaltyScore,
resultType: fm.ResultType,
status,
matchTime: fm.MatchTime,
winnerTeamId: fm.Winner ?? null,
});
}
// Spielminute
if (wm.current_minute) {
const min = parseInt(wm.current_minute, 10);
if (!isNaN(min)) result.minute = min;
}
// Torereignisse aus home_scorers / away_scorers parsen (Format: "{\"Name Minute'\"}")
const goals: GoalEvent[] = [];
if (wm.home_scorers) parseScorers(wm.home_scorers, "home", goals);
if (wm.away_scorers) parseScorers(wm.away_scorers, "away", goals);
if (goals.length > 0) {
goals.sort((a, b) => a.minute - b.minute);
result.goals = goals;
}
return result;
return { scores, fifaIdToAppCode };
});
}
// Parst worldcup26-Scorer-String: "{\"Casemiro 56'\"}" oder "{\"Player 12'\",\"Other 34'\"}"
function parseScorers(raw: string, team: "home" | "away", out: GoalEvent[]): void {
if (!raw || raw === "{}") return;
const cleaned = raw.replace(/[{}"\\]/g, "").trim();
if (!cleaned) return;
const parts = cleaned.split(",");
for (const p of parts) {
const m = /^(.+?)\s+([0-9+]+)'?(?:\s*\(.*?\))?\s*$/.exec(p.trim());
if (m) {
const name = m[1].trim();
const minStr = m[2];
let minute = 0;
const plusIdx = minStr.indexOf("+");
if (plusIdx >= 0) {
minute = parseInt(minStr.slice(0, plusIdx), 10) + parseInt(minStr.slice(plusIdx + 1), 10);
// Wendet FIFA-Live-Scores auf Matches an (MatchNumber als exakter Schlüssel).
export function applyFifaScores(
matches: Match[], teams: Team[],
fifaData: { scores: Map<number, FifaScores>; fifaIdToAppCode: Map<string, string> },
): Match[] {
const { scores: fifaMap, fifaIdToAppCode } = fifaData;
if (fifaMap.size === 0) return matches;
// Baue App-Code → App-Team-ID Map
const appCodeToId = new Map<string, string>();
for (const t of teams) {
if (t.code) appCodeToId.set(t.code.toLowerCase(), t.id);
}
let applied = 0;
const result = matches.map((m) => {
const fs = fifaMap.get(m.matchNumber);
if (!fs) return m;
const r = { ...m };
if (fs.homeScore != null) r.homeScore = fs.homeScore;
if (fs.awayScore != null) r.awayScore = fs.awayScore;
if (fs.homePenalty != null) r.homePenalty = fs.homePenalty;
if (fs.awayPenalty != null) r.awayPenalty = fs.awayPenalty;
// FIFA-ID → App-Team-ID auflösen
if (fs.winnerTeamId) {
const appCode = fifaIdToAppCode.get(fs.winnerTeamId);
if (appCode) {
const appTeamId = appCodeToId.get(appCode.toLowerCase());
if (appTeamId) {
r.winnerTeamId = appTeamId;
} else {
console.warn("[fifa] Winner-Team-Code nicht in App-Teams:", appCode, "| matchNumber:", m.matchNumber);
}
} else {
minute = parseInt(minStr, 10);
}
if (!isNaN(minute)) {
out.push({ scorer: name, minute, team });
console.warn("[fifa] FIFA-Winner-ID nicht in Team-Map:", fs.winnerTeamId, "| matchNumber:", m.matchNumber);
}
}
}
console.log("[FIFA-WINNER]", "matchNumber:", m.matchNumber,
"| fifa.Winner:", fs.winnerTeamId,
"| status:", r.status,
"| homeScore:", r.homeScore, "| awayScore:", r.awayScore,
"| homePenalty:", r.homePenalty, "| awayPenalty:", r.awayPenalty,
"| -> m.winnerTeamId gesetzt:", r.winnerTeamId);
if (fs.matchTime) {
const min = parseInt(fs.matchTime, 10);
if (!isNaN(min)) r.minute = min;
}
r.status = fs.status;
applied++;
return r;
});
if (applied > 0) console.log("[fifa] scores angewandt:", applied);
return result;
}

View File

@@ -24,6 +24,8 @@ export interface ResolvedTie {
away: ResolvedSide;
status: string;
prob?: { home: number; draw: number | null; away: number } | null;
homePenalty?: number | null;
awayPenalty?: number | null;
}
// Findet das tatsächliche Spiel (aus dem Feed) zu einer FIFA-Match-Nummer.
@@ -34,13 +36,29 @@ function feedMatch(matches: Match[], num: number): Match | undefined {
// Bestimmt den Sieger eines abgeschlossenen Spiels (Feed) als Team-ID.
function winnerOf(m: Match | undefined): string | null {
if (!m || m.status !== "FINISHED") return null;
if (m.winnerTeamId) return m.winnerTeamId;
if (m.homeScore == null || m.awayScore == null) return null;
if (m.homeScore > m.awayScore) return m.homeTeamId;
if (m.awayScore > m.homeScore) return m.awayTeamId;
return null; // Unentschieden -> Elfmeter; Feed liefert i.d.R. Sieger separat
return null;
}
let _winnerDbg = true; // Nur einmal loggen
function winnerDbg(m: Match | undefined, result: string | null, ctx: string): void {
if (!_winnerDbg || !m || m.matchNumber !== 74) return;
_winnerDbg = false;
console.log("[WINNER-OF]", ctx,
"| matchNumber:", m.matchNumber,
"| winnerTeamId:", m.winnerTeamId,
"| homeScore:", m.homeScore, "| awayScore:", m.awayScore,
"| status:", m.status,
"| ergebnis (zurückgegebener sieger):", result);
}
function loserOf(m: Match | undefined): string | null {
if (!m || m.status !== "FINISHED") return null;
if (m.winnerTeamId) {
return m.homeTeamId === m.winnerTeamId ? m.awayTeamId : m.homeTeamId;
}
if (m.homeScore == null || m.awayScore == null) return null;
if (m.homeScore > m.awayScore) return m.awayTeamId;
if (m.awayScore > m.homeScore) return m.homeTeamId;
@@ -159,6 +177,7 @@ export function resolveBracket(
const away = sideFrom(a.teamId, slotLabel(rm.away, assignment, winnerGroup), teams, feed, "away", a.provisional, a.tooltip);
const feedWinner = winnerOf(feed);
winnerDbg(feed, feedWinner, "resolveR32Slot");
// Sim-Modus: Gewinner NUR aus Scores + Slot-Team-IDs ableiten.
// feedWinner (aus feed.homeTeamId/awayTeamId) wird IGNORIERT,
// weil matchNumber-Zuweisung (assignNumbersAndVenues) von der
@@ -178,9 +197,16 @@ export function resolveBracket(
losers.set(rm.matchNumber, loserOf(feed));
}
decided.set(rm.matchNumber, feed?.status === "FINISHED");
if (rm.matchNumber === 74) {
console.log("[PROPAGATE]", "von matchNumber:", rm.matchNumber,
"| feedWinner:", feedWinner,
"| -> in winners map unter key:", rm.matchNumber,
"| ziel z.B. slot 89 fromHome:", 74);
}
return {
matchNumber: rm.matchNumber, stage: "R32",
home, away, status: feed?.status ?? "SCHEDULED", prob: feed?.prob,
homePenalty: feed?.homePenalty, awayPenalty: feed?.awayPenalty,
};
});
@@ -190,6 +216,12 @@ export function resolveBracket(
const src = km.losers ? losers : winners;
const homeId = src.get(km.fromHome) ?? null;
const awayId = src.get(km.fromAway) ?? null;
if (km.matchNumber === 89) {
console.log("[PROPAGATE]", "ziel slot:", km.matchNumber,
"| fromHome:", km.fromHome, "| fromAway:", km.fromAway,
"| homeId (aus winners):", homeId,
"| awayId (aus winners):", awayId);
}
// Ein Folgeteam ist fix, wenn das speisende Spiel beendet ist.
const homeProv = !(decided.get(km.fromHome) ?? false);
@@ -217,6 +249,7 @@ export function resolveBracket(
later[km.matchNumber] = {
matchNumber: km.matchNumber, stage: km.stage,
home, away, status: feed?.status ?? "SCHEDULED", prob: feed?.prob,
homePenalty: feed?.homePenalty, awayPenalty: feed?.awayPenalty,
};
}

View File

@@ -39,6 +39,9 @@ export interface Match {
awayTeamId: string | null;
homeScore: number | null;
awayScore: number | null;
homePenalty?: number | null; // Elfmeterschießen (FIFA-API)
awayPenalty?: number | null;
winnerTeamId?: string | null; // FIFA-Winner (auch bei Elfmeterschießen)
// Wahrscheinlichkeiten 0..1 (Polymarket), falls vorhanden
prob?: { home: number; draw: number; away: number } | null;
venue?: string | null; // Austragungsort