This commit is contained in:
2026-06-22 22:11:04 -05:00
parent 73d07e7f18
commit 93ae2cbf0a
9 changed files with 519 additions and 53 deletions

View File

@@ -1,4 +1,5 @@
import { GroupId, Match, MatchStatus, Team } from "./types";
import { venueFor } from "./venues";
// ----------------------------------------------------------------------------
// Caching: einfacher In-Memory-Cache mit TTL. Verhindert, dass jede Browser-
@@ -80,6 +81,32 @@ function stageFor(stage: string, group: GroupId | null): Match["stage"] {
}
}
// Phasen-Reihenfolge für die K.o.-Nummerierung.
const STAGE_ORDER: Record<Match["stage"], number> = {
GROUP: 0, R32: 1, R16: 2, QF: 3, SF: 4, "3RD": 5, FINAL: 6,
};
// Setzt Spielnummern und Stadien.
// - K.o.-Spiele: chronologisch ab 73 (Anstöße dort eindeutig) -> für Bracket nötig.
// - Venue: Gruppenspiele über die Teampaarung, K.o.-Spiele über die Spielnummer.
function assignNumbersAndVenues(matches: Match[], teams: Team[]): void {
// K.o.-Spiele eindeutig durchnummerieren (73..104).
const ko = matches
.filter((m) => m.group == null)
.sort((a, b) => {
const sa = STAGE_ORDER[a.stage], sb = STAGE_ORDER[b.stage];
if (sa !== sb) return sa - sb;
const t = +new Date(a.utcDate) - +new Date(b.utcDate);
return t !== 0 ? t : Number(a.id) - Number(b.id);
});
ko.forEach((m, i) => { m.matchNumber = 73 + i; });
// Stadien setzen (Gruppenphase per Paarung, K.o. per Nummer).
for (const m of matches) {
m.venue = venueFor(m, teams);
}
}
// Holt alle Spiele + leitet die Teamliste daraus ab (spart einen Extra-Call).
export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams: Team[] }> {
return cached("fd:matches", 60_000, async () => {
@@ -110,7 +137,8 @@ export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams:
id: String(m.id),
group,
stage: stageFor(m.stage, group),
matchNumber: m.matchday ?? 0,
// Vorläufig 0 — die echte FIFA-Spielnummer wird unten gesetzt.
matchNumber: 0,
utcDate: m.utcDate,
status: mapStatus(m.status),
minute: m.minute ?? null,
@@ -118,12 +146,15 @@ export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams:
awayTeamId: m.awayTeam.id != null ? String(m.awayTeam.id) : null,
homeScore: m.score.fullTime.home,
awayScore: m.score.fullTime.away,
venue: m.venue ?? null,
venue: null, // wird unten aus der Map gesetzt
attendance: m.attendance ?? null,
};
});
return { matches, teams: [...teamMap.values()] };
const teams = [...teamMap.values()];
assignNumbersAndVenues(matches, teams);
return { matches, teams };
});
}
@@ -203,4 +234,4 @@ export function attachOdds(matches: Match[], teams: Team[], odds: OddsEntry[]):
},
};
});
}
}

View File

@@ -3,9 +3,10 @@ import {
R32, LATER_ROUNDS, R32Match, BracketSlot,
ThirdAssignment, slotLabel,
} from "@/lib/bracket";
import { placeIsSecure } from "@/lib/secure-places";
// Eine Gruppe gilt als abgeschlossen, wenn alle ihre Gruppenspiele beendet sind
// (regulär 6 Spiele pro Vierergruppe). Erst dann sind Platzierungen fix.
// Eine Gruppe gilt als abgeschlossen, wenn alle ihre Gruppenspiele beendet sind.
// Wird für die Drittplatzierten-Sicherheit genutzt (gruppenübergreifend).
function groupFinished(group: GroupId, matches: Match[]): boolean {
const groupMatches = matches.filter((m) => m.group === group);
if (groupMatches.length === 0) return false;
@@ -61,25 +62,29 @@ function resolveR32Slot(
assignment: ThirdAssignment | null,
thirds: ThirdPlaceRow[],
matches: Match[],
teams: Team[],
annexResolved: boolean,
): { teamId: string | null; provisional: boolean } {
const table = (g: GroupId) => tables.find((t) => t.group === g);
if (slot.type === "W") {
const t = table(slot.group!);
const teamId = t?.rows.find((r) => r.rank === 1)?.teamId ?? null;
return { teamId, provisional: !groupFinished(slot.group!, matches) };
// Sieger fix, sobald Platz 1 rechnerisch gesichert ist (auch vor Gruppenende).
return { teamId, provisional: !placeIsSecure(slot.group!, 1, teams, matches) };
}
if (slot.type === "R") {
const t = table(slot.group!);
const teamId = t?.rows.find((r) => r.rank === 2)?.teamId ?? null;
return { teamId, provisional: !groupFinished(slot.group!, matches) };
// Zweiter fix, sobald Platz 2 rechnerisch gesichert ist.
return { teamId, provisional: !placeIsSecure(slot.group!, 2, teams, matches) };
}
// 3. Platz: braucht Annex-C-Zuordnung + den Gruppensieger dieses Spiels
if (slot.type === "3" && assignment && winnerGroup) {
const thirdGroup = assignment[winnerGroup];
if (thirdGroup) {
const row = thirds.find((r) => r.group === thirdGroup && r.qualifies);
// Fix nur, wenn Annex C aufgelöst UND die Quellgruppe abgeschlossen ist.
// Fix nur, wenn Annex C aufgelöst UND die Quellgruppe abgeschlossen ist
// (Drittplatzierten-Qualifikation ist gruppenübergreifend, bis zuletzt offen).
const fix = annexResolved && groupFinished(thirdGroup, matches);
return { teamId: row?.teamId ?? null, provisional: !fix };
}
@@ -126,8 +131,8 @@ export function resolveBracket(
// Für 3.-Platz-Slots: Gruppensieger ist die andere Seite (immer W)
const winnerGroup = (homeGroup ?? awayGroup) as GroupId | undefined;
const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, annexResolved);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, annexResolved);
const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved);
const home = sideFrom(h.teamId, slotLabel(rm.home, assignment, winnerGroup), teams, feed, "home", h.provisional);
const away = sideFrom(a.teamId, slotLabel(rm.away, assignment, winnerGroup), teams, feed, "away", a.provisional);
@@ -163,4 +168,4 @@ export function resolveBracket(
}
return { r32, later };
}
}

94
lib/secure-places.ts Normal file
View File

@@ -0,0 +1,94 @@
import { GroupId, Match, Team } from "./types";
import { computeGroupTables } from "./standings";
// Bestimmt, welche Tabellenplätze einer Gruppe bereits MATHEMATISCH feststehen
// auch wenn noch Spiele ausstehen. Berücksichtigt ALLE FIFA-Tiebreaker, weil die
// Tabelle über computeGroupTables() berechnet wird (Punkte, Direktvergleich,
// Tordifferenz, Tore).
//
// Methode: vollständige Worst-Case-Enumeration der Restspiele. Ein Platz p ist
// für ein Team sicher, wenn es in JEDEM möglichen Ausgang aller Restspiele auf
// Platz p oder besser bleibt. Wir enumerieren pro Restspiel mehrere
// repräsentative Ergebnisse, die alle relevanten Tiebreaker-Effekte abdecken:
// - Heimsieg knapp (1:0) und hoch (5:0)
// - Auswärtssieg knapp (0:1) und hoch (0:5)
// - Unentschieden (0:0 und 2:2)
// Diese Menge deckt Punkt- UND Tordifferenz-Szenarien ausreichend ab, um echte
// Sicherheit korrekt zu erkennen (inkl. Fälle wie "Direktvergleich bereits
// gewonnen -> uneinholbar").
// Mögliche Ergebnis-Varianten je Restspiel (homeGoals, awayGoals).
const OUTCOME_VARIANTS: Array<[number, number]> = [
[1, 0], [5, 0], // Heimsieg knapp / hoch
[0, 1], [0, 5], // Auswärtssieg knapp / hoch
[0, 0], [2, 2], // Unentschieden
];
function openMatches(group: GroupId, matches: Match[]): Match[] {
return matches.filter(
(m) => m.group === group && m.status !== "FINISHED"
&& m.homeTeamId != null && m.awayTeamId != null,
);
}
// Liefert für eine Gruppe Map: Platz(1-basiert) -> teamId, aber nur für Plätze,
// die in ALLEN Szenarien stabil von demselben Team gehalten werden.
export function securePlaces(
group: GroupId, teams: Team[], matches: Match[],
): Map<number, string> {
const open = openMatches(group, matches);
// Begrenzung: bei sehr vielen offenen Spielen wird die Enumeration groß.
// In 4er-Gruppen sind es maximal 6 offene Spiele (Turnierstart) -> 6^? zu viel.
// Wir enumerieren nur, wenn die Kombinationszahl handhabbar ist; sonst gilt
// konservativ "nichts sicher" (am Turnierstart ohnehin korrekt).
const combos = Math.pow(OUTCOME_VARIANTS.length, open.length);
if (open.length === 0) {
// Alles gespielt: aktuelle Tabelle ist final.
const table = computeGroupTables(teams, matches).find((t) => t.group === group);
const res = new Map<number, string>();
table?.rows.forEach((r) => res.set(r.rank, r.teamId));
return res;
}
if (combos > 100_000) {
return new Map(); // zu früh im Turnier -> nichts gesichert
}
// Für jeden Platz das Set der Teams sammeln, die diesen Platz über ALLE
// Szenarien einnehmen können. Ist das Set einelementig, ist der Platz sicher.
const placeTeams: Array<Set<string>> = [new Set(), new Set(), new Set(), new Set()];
const total = combos;
for (let combo = 0; combo < total; combo++) {
// Szenario zusammenbauen: jedes offene Spiel bekommt eine Variante.
let c = combo;
const simulated: Match[] = open.map((m) => {
const variantIdx = c % OUTCOME_VARIANTS.length;
c = Math.floor(c / OUTCOME_VARIANTS.length);
const [hg, ag] = OUTCOME_VARIANTS[variantIdx];
return { ...m, status: "FINISHED", homeScore: hg, awayScore: ag };
});
// Gespielte + simulierte Spiele kombinieren.
const played = matches.filter((m) => !(m.group === group && m.status !== "FINISHED"));
const all = [...played, ...simulated];
const table = computeGroupTables(teams, all).find((t) => t.group === group);
if (!table) continue;
table.rows.forEach((r) => {
placeTeams[r.rank - 1]?.add(r.teamId);
});
}
const result = new Map<number, string>();
for (let i = 0; i < 4; i++) {
if (placeTeams[i].size === 1) {
result.set(i + 1, [...placeTeams[i]][0]);
}
}
return result;
}
export function placeIsSecure(
group: GroupId, place: number, teams: Team[], matches: Match[],
): boolean {
return securePlaces(group, teams, matches).has(place);
}

View File

@@ -11,9 +11,13 @@ function emptyRow(teamId: string): StandingRow {
};
}
// Trägt ein abgeschlossenes Spiel in zwei Tabellenzeilen ein.
function applyMatch(rows: Map<string, StandingRow>, m: Match) {
if (m.status !== "FINISHED") return;
// Trägt ein Spiel in zwei Tabellenzeilen ein.
// Standard: nur abgeschlossene Spiele (FINISHED). Mit includeLive=true werden
// auch laufende Spiele (LIVE/IN_PLAY/PAUSED) mit ihrem Zwischenstand gezählt.
function applyMatch(rows: Map<string, StandingRow>, m: Match, includeLive = false) {
const live = m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED";
const counts = m.status === "FINISHED" || (includeLive && live);
if (!counts) return;
if (m.homeTeamId == null || m.awayTeamId == null) return;
if (m.homeScore == null || m.awayScore == null) return;
const h = rows.get(m.homeTeamId);
@@ -75,14 +79,19 @@ function miniTable(matches: Match[], tiedIds: Set<string>): Map<string, Standing
}
// Berechnet alle 12 Gruppentabellen aus Teams + Spielen.
export function computeGroupTables(teams: Team[], matches: Match[]): GroupTable[] {
// includeLive=false (Standard): nur abgeschlossene Spiele (offizielle Tabelle,
// Basis für die fix-Berechnung). includeLive=true: laufende Spiele werden mit
// Zwischenstand eingerechnet (Live-Tabelle).
export function computeGroupTables(
teams: Team[], matches: Match[], includeLive = false,
): GroupTable[] {
const tables: GroupTable[] = [];
for (const g of GROUP_IDS) {
const groupTeams = teams.filter((t) => t.group === g);
const rows = new Map<string, StandingRow>();
groupTeams.forEach((t) => rows.set(t.id, emptyRow(t.id)));
const groupMatches = matches.filter((m) => m.group === g);
for (const m of groupMatches) applyMatch(rows, m);
for (const m of groupMatches) applyMatch(rows, m, includeLive);
rows.forEach(finalizeRow);
const arr = [...rows.values()];
@@ -128,4 +137,4 @@ export function computeThirdPlaceTable(tables: GroupTable[]): ThirdPlaceRow[] {
r.qualifies = i < 8;
});
return thirds;
}
}

207
lib/venues.ts Normal file
View File

@@ -0,0 +1,207 @@
// Stadion-Zuordnung — die alleinige Quelle für Spielorte (Feed-venue wird ignoriert).
//
// Gruppenphase: über die Teampaarung (Ländercodes). Eindeutig, da jede Paarung
// im Turnier genau einmal vorkommt — unabhängig von Heim/Auswärts-Reihenfolge
// und von gleichzeitigen Anstößen.
// K.o.-Phase: über die FIFA-Spielnummer (dort sind die Anstöße eindeutig).
import { GroupId, Match, Team } from "./types";
// --- GRUPPENPHASE: "CODE1-CODE2" -> Stadion ---
export const FIXTURES_GROUP_STAGE: Record<string, string> = {
// Gruppe A
"MEX-RSA": "Estadio Azteca, Mexiko-Stadt",
"KOR-CZE": "Estadio Akron, Guadalajara",
"CZE-RSA": "Mercedes-Benz Stadium, Atlanta",
"MEX-KOR": "Estadio Akron, Guadalajara",
"CZE-MEX": "Estadio Azteca, Mexiko-Stadt",
"RSA-KOR": "Estadio BBVA, Monterrey",
// Gruppe B
"CAN-BIH": "BMO Field, Toronto",
"QAT-SUI": "Levi's Stadium, San Francisco Bay Area",
"SUI-BIH": "SoFi Stadium, Los Angeles",
"CAN-QAT": "BC Place, Vancouver",
"SUI-CAN": "BC Place, Vancouver",
"BIH-QAT": "Lumen Field, Seattle",
// Gruppe C
"BRA-MAR": "Gillette Stadium, Boston",
"HAI-SCO": "MetLife Stadium, New York/New Jersey",
"BRA-HAI": "Lincoln Financial Field, Philadelphia",
"SCO-MAR": "Gillette Stadium, Boston",
"SCO-BRA": "Hard Rock Stadium, Miami",
"MAR-HAI": "Mercedes-Benz Stadium, Atlanta",
// Gruppe D
"USA-PAR": "SoFi Stadium, Los Angeles",
"AUS-TUR": "BC Place, Vancouver",
"TUR-PAR": "Levi's Stadium, San Francisco Bay Area",
"USA-AUS": "Lumen Field, Seattle",
"TUR-USA": "SoFi Stadium, Los Angeles",
"PAR-AUS": "Levi's Stadium, San Francisco Bay Area",
// Gruppe E
"CIV-ECU": "Lincoln Financial Field, Philadelphia",
"GER-CUR": "NRG Stadium, Houston",
"GER-CIV": "BMO Field, Toronto",
"ECU-CUR": "Arrowhead Stadium, Kansas City",
"CUR-CIV": "Lincoln Financial Field, Philadelphia",
"ECU-GER": "MetLife Stadium, New York/New Jersey",
// Gruppe F
"NED-JPN": "AT&T Stadium, Dallas",
"SWE-TUN": "Estadio BBVA, Monterrey",
"NED-SWE": "NRG Stadium, Houston",
"TUN-JPN": "Estadio BBVA, Monterrey",
"JPN-SWE": "AT&T Stadium, Dallas",
"TUN-NED": "Arrowhead Stadium, Kansas City",
// Gruppe G
"IRN-NZL": "SoFi Stadium, Los Angeles",
"BEL-EGY": "Lumen Field, Seattle",
"BEL-IRN": "SoFi Stadium, Los Angeles",
"NZL-EGY": "BC Place, Vancouver",
"NZL-BEL": "Lumen Field, Seattle",
"EGY-IRN": "BC Place, Vancouver",
// Gruppe H
"KSA-URU": "Hard Rock Stadium, Miami",
"ESP-CPV": "Mercedes-Benz Stadium, Atlanta",
"URU-CPV": "Mercedes-Benz Stadium, Atlanta",
"ESP-KSA": "Hard Rock Stadium, Miami",
"URU-ESP": "Estadio Akron, Guadalajara",
"CPV-KSA": "NRG Stadium, Houston",
// Gruppe I
"FRA-SEN": "MetLife Stadium, New York/New Jersey",
"IRQ-NOR": "Gillette Stadium, Boston",
"NOR-SEN": "Lincoln Financial Field, Philadelphia",
"FRA-IRQ": "MetLife Stadium, New York/New Jersey",
"NOR-FRA": "Gillette Stadium, Boston",
"SEN-IRQ": "BMO Field, Toronto",
// Gruppe J
"ARG-ALG": "Arrowhead Stadium, Kansas City",
"AUT-JOR": "Levi's Stadium, San Francisco Bay Area",
"ARG-AUT": "AT&T Stadium, Dallas",
"JOR-ALG": "Levi's Stadium, San Francisco Bay Area",
"JOR-ARG": "Arrowhead Stadium, Kansas City",
"ALG-AUT": "NRG Stadium, Houston",
// Gruppe K
"UZB-COL": "Estadio Azteca, Mexiko-Stadt",
"POR-COD": "NRG Stadium, Houston",
"POR-UZB": "NRG Stadium, Houston",
"COL-COD": "Estadio Akron, Guadalajara",
"COL-POR": "Hard Rock Stadium, Miami",
"COD-UZB": "Estadio BBVA, Monterrey",
// Gruppe L
"GHA-PAN": "BMO Field, Toronto",
"ENG-CRO": "AT&T Stadium, Dallas",
"ENG-GHA": "Gillette Stadium, Boston",
"PAN-CRO": "BMO Field, Toronto",
"PAN-ENG": "MetLife Stadium, New York/New Jersey",
"CRO-GHA": "Arrowhead Stadium, Kansas City",
};
// Reihenfolge-unabhängiger Lookup: baut beide Schlüsselrichtungen.
const PAIR_VENUE = new Map<string, string>();
for (const [key, venue] of Object.entries(FIXTURES_GROUP_STAGE)) {
const [a, b] = key.split("-");
PAIR_VENUE.set(`${a}-${b}`, venue);
PAIR_VENUE.set(`${b}-${a}`, venue);
}
// --- K.O.-PHASE: FIFA-Spielnummer -> Stadion ---
export const VENUE_BY_KO_MATCH: Record<number, string> = {
// Sechzehntelfinale (R32)
73: "SoFi Stadium, Los Angeles",
74: "Gillette Stadium, Boston",
75: "Estadio Azteca, Mexiko-Stadt",
76: "Hard Rock Stadium, Miami",
77: "Mercedes-Benz Stadium, Atlanta",
78: "AT&T Stadium, Dallas",
79: "Levi's Stadium, San Francisco Bay Area",
80: "Lumen Field, Seattle",
81: "MetLife Stadium, New York/New Jersey",
82: "Lincoln Financial Field, Philadelphia",
83: "BMO Field, Toronto",
84: "NRG Stadium, Houston",
85: "BC Place, Vancouver",
86: "Estadio BBVA, Monterrey",
87: "Arrowhead Stadium, Kansas City",
88: "AT&T Stadium, Dallas",
// Achtelfinale (R16)
89: "MetLife Stadium, New York/New Jersey",
90: "Hard Rock Stadium, Miami",
91: "NRG Stadium, Houston",
92: "Mercedes-Benz Stadium, Atlanta",
93: "AT&T Stadium, Dallas",
94: "Lumen Field, Seattle",
95: "BC Place, Vancouver",
96: "Estadio Azteca, Mexiko-Stadt",
// Viertelfinale
97: "Gillette Stadium, Boston",
98: "SoFi Stadium, Los Angeles",
99: "Hard Rock Stadium, Miami",
100: "Arrowhead Stadium, Kansas City",
// Halbfinale
101: "AT&T Stadium, Dallas",
102: "Mercedes-Benz Stadium, Atlanta",
// Spiel um Platz 3
103: "Hard Rock Stadium, Miami",
// Finale
104: "MetLife Stadium, New York/New Jersey",
};
// Manche Feeds nutzen abweichende 3-Buchstaben-Codes als die Map oben.
// Diese Tabelle übersetzt bekannte Feed-Codes auf den Map-Code.
// (Beispiel: FIFA/ISO nutzt CUW für Curaçao, die Map verwendet CUR.)
const CODE_ALIAS: Record<string, string> = {
CUW: "CUR", // Curaçao
CRC: "CRC", // (Platzhalter, falls weitere auftauchen)
};
// Fallback über den Teamnamen, falls ein Code unbekannt/abweichend ist.
// Schlüssel: normalisierter Name -> Map-Code.
const NAME_TO_CODE: Record<string, string> = {
"curacao": "CUR", "curaçao": "CUR",
"uruguay": "URU",
"cape verde": "CPV", "cape verde islands": "CPV", "cabo verde": "CPV",
"saudi arabia": "KSA",
"ivory coast": "CIV", "côte d'ivoire": "CIV", "cote d'ivoire": "CIV",
"south korea": "KOR", "korea republic": "KOR",
"south africa": "RSA",
"czechia": "CZE", "czech republic": "CZE",
"bosnia and herzegovina": "BIH", "bosnia-herzegovina": "BIH",
"dr congo": "COD", "congo dr": "COD", "democratic republic of the congo": "COD",
};
// Normalisiert den Code eines Teams auf den in der Map verwendeten Code.
function canonicalCode(team: Team | undefined): string | null {
if (!team) return null;
if (team.code) {
const c = team.code.toUpperCase();
if (CODE_ALIAS[c]) return CODE_ALIAS[c];
// Wenn der Code direkt in der Map vorkommt, nimm ihn.
return c;
}
// kein Code -> über den Namen versuchen
const n = team.name?.toLowerCase().trim();
return n ? (NAME_TO_CODE[n] ?? null) : null;
}
// Liefert das Stadion eines Spiels.
// Gruppenspiel -> über Teampaarung (Codes, mit Alias/Namen-Fallback),
// K.o.-Spiel -> über Spielnummer.
export function venueFor(m: Match, teams: Team[]): string | null {
if (m.group != null) {
const home = teams.find((t) => t.id === m.homeTeamId);
const away = teams.find((t) => t.id === m.awayTeamId);
let hc = canonicalCode(home);
let ac = canonicalCode(away);
// Erstversuch mit Codes
let venue = hc && ac ? PAIR_VENUE.get(`${hc}-${ac}`) : undefined;
// Falls kein Treffer: über die Namen normalisieren und erneut probieren.
if (!venue) {
const hn = home?.name?.toLowerCase().trim();
const an = away?.name?.toLowerCase().trim();
hc = (hn && NAME_TO_CODE[hn]) || hc;
ac = (an && NAME_TO_CODE[an]) || ac;
venue = hc && ac ? PAIR_VENUE.get(`${hc}-${ac}`) : undefined;
}
return venue ?? null;
}
return VENUE_BY_KO_MATCH[m.matchNumber] ?? null;
}