16 Commits

Author SHA1 Message Date
4d838e2fb7 fix date/time 2026-06-27 15:58:18 -05:00
7bad12df68 stadien 2026-06-27 15:48:48 -05:00
89a9075391 rm logs + caching 2026-06-27 14:17:16 -05:00
2b3cadfcb5 third place fix und polymarket 2026-06-27 14:03:11 -05:00
a721de5b23 third place marks 2026-06-27 12:15:34 -05:00
bf931e70c0 third place fix 2026-06-27 07:58:38 -05:00
6bb6f9be7a fixes 2026-06-26 18:34:58 -05:00
6f0acaad4c new Live Scores 2026-06-26 14:25:22 -05:00
1985289a37 third place corrected 2026-06-26 13:25:39 -05:00
a38b3fa517 revert 2026-06-25 14:54:45 -05:00
49256e83c6 rm remote fonts 2026-06-25 14:50:41 -05:00
6eec396b8c env variables 2026-06-25 14:18:25 -05:00
1cd4ae3bfb unami 2026-06-25 12:00:36 -05:00
597d321a34 wrap 2026-06-24 23:06:56 -05:00
c9bdc0c5cf third place 2026-06-24 23:02:46 -05:00
a4a47b431a mobile 2026-06-24 22:55:05 -05:00
13 changed files with 782 additions and 82 deletions

View File

@@ -5,3 +5,7 @@ FOOTBALL_DATA_TOKEN=dein_token_hier
# Polymarket-Slug des WM-Events (Standard: world-cup-2026). # Polymarket-Slug des WM-Events (Standard: world-cup-2026).
# Den genauen Slug findest du in der Polymarket-URL nach /event/. # Den genauen Slug findest du in der Polymarket-URL nach /event/.
POLYMARKET_WC_SLUG=world-cup-2026 POLYMARKET_WC_SLUG=world-cup-2026
# Umami Analytics (selbst gehostet, cookiefrei)
# NEXT_PUBLIC_UMAMI_SRC=https://analytics.example.com/script.js
# NEXT_PUBLIC_UMAMI_ID=deine-website-id

View File

@@ -10,6 +10,12 @@ WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules COPY --from=deps /app/node_modules ./node_modules
COPY . . COPY . .
ENV NEXT_TELEMETRY_DISABLED=1 ENV NEXT_TELEMETRY_DISABLED=1
ARG NEXT_PUBLIC_UMAMI_SRC
ARG NEXT_PUBLIC_UMAMI_ID
ENV NEXT_PUBLIC_UMAMI_SRC=${NEXT_PUBLIC_UMAMI_SRC}
ENV NEXT_PUBLIC_UMAMI_ID=${NEXT_PUBLIC_UMAMI_ID}
RUN npm run build RUN npm run build
# --- Stufe 3: Runtime (standalone) --- # --- Stufe 3: Runtime (standalone) ---

View File

@@ -1,7 +1,8 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { fetchMatchesAndTeams, fetchOdds, attachOdds } from "@/lib/feeds"; import { fetchMatchesAndTeams, fetchOdds, attachOdds, attachKOOdds, fetchLiveScores, applyLiveScores, assignKONumbersBySlots } from "@/lib/feeds";
import { computeGroupTables, computeThirdPlaceTable } from "@/lib/standings"; import { computeGroupTables, computeThirdPlaceTable } from "@/lib/standings";
import { qualifiedThirdGroups, resolveAnnexC } from "@/lib/bracket"; import { qualifiedThirdGroups, resolveAnnexC } from "@/lib/bracket";
import { securelyQualifiedThirdTeams } from "@/lib/third-place-security";
// Diese Route wird vom Frontend gepollt. Sie ist der einzige Ort, der die // Diese Route wird vom Frontend gepollt. Sie ist der einzige Ort, der die
// Upstream-Feeds berührt — gecacht, damit Rate Limits eingehalten werden. // Upstream-Feeds berührt — gecacht, damit Rate Limits eingehalten werden.
@@ -13,23 +14,40 @@ export async function GET() {
// Odds sind optional: fällt der Polymarket-Call aus, liefern wir trotzdem. // Odds sind optional: fällt der Polymarket-Call aus, liefern wir trotzdem.
let matches = rawMatches; let matches = rawMatches;
let odds: Awaited<ReturnType<typeof fetchOdds>> | null = null;
try { try {
const odds = await fetchOdds(); odds = await fetchOdds();
matches = attachOdds(rawMatches, teams, odds); matches = attachOdds(rawMatches, teams, odds);
} catch (err) { } catch (err) {
console.error("[polymarket] fetchOdds fehlgeschlagen:", err); 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 groupTables = computeGroupTables(teams, matches);
const groupTablesLive = computeGroupTables(teams, matches, true); const groupTablesLive = computeGroupTables(teams, matches, true);
// prob-Feld normalisieren: immer null statt undefined, damit JSON konsistent ist assignKONumbersBySlots(matches, teams);
if (odds) {
matches = attachKOOdds(matches, teams, odds);
}
const normalizedMatches = matches.map((m) => ({ ...m, prob: m.prob ?? null })); const normalizedMatches = matches.map((m) => ({ ...m, prob: m.prob ?? null }));
const thirdTable = computeThirdPlaceTable(groupTablesLive); const thirdTable = computeThirdPlaceTable(groupTablesLive);
const qGroups = qualifiedThirdGroups(thirdTable); const qGroups = qualifiedThirdGroups(thirdTable);
const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null; const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null;
// Sichere Drittplatzierte (Team-IDs, deren Top-8-Platz mathematisch feststeht)
const secureThirdTeams = securelyQualifiedThirdTeams(matches, teams);
return NextResponse.json({ return NextResponse.json({
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
teams, teams,
@@ -37,6 +55,7 @@ export async function GET() {
groupTables, groupTables,
groupTablesLive, groupTablesLive,
thirdTable, thirdTable,
secureThirdTeams: [...secureThirdTeams],
annexAssignment: annex, annexAssignment: annex,
annexResolved: annex != null, annexResolved: annex != null,
}); });

View File

@@ -1,9 +1,10 @@
"use client"; "use client";
import { useState, useCallback } from "react"; import { useMemo, useState, useCallback } from "react";
import { GroupTable, Match, Team, ThirdPlaceRow } from "@/lib/types"; import { GroupTable, Match, Team, ThirdPlaceRow } from "@/lib/types";
import { ThirdAssignment, orderedRound } from "@/lib/bracket"; import { ThirdAssignment, orderedRound } from "@/lib/bracket";
import { resolveBracket, ResolvedSide, ResolvedTie } from "@/lib/resolve-bracket"; import { resolveBracket, ResolvedSide, ResolvedTie } from "@/lib/resolve-bracket";
import { STADIUMS, MATCH_STADIUMS, MATCH_DATES } from "@/lib/stadiums";
import Flag from "./Flag"; import Flag from "./Flag";
interface TipState { x: number; y: number; text: string } interface TipState { x: number; y: number; text: string }
@@ -47,16 +48,29 @@ function Side({
); );
} }
function fmtMatchInfo(utcDate?: string, stadiumId?: string): string {
if (!utcDate) return "";
const d = new Date(utcDate);
const dateStr = d.toLocaleDateString("de-DE", { day: "numeric", month: "numeric" });
const timeStr = d.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
const city = stadiumId ? STADIUMS[stadiumId]?.city : "";
const parts = [`${dateStr}`, `${timeStr}`];
if (city) parts.push(city);
return parts.join(" · ");
}
function Tie({ function Tie({
tie, teams, isFinal, onShowTip, onHideTip, tie, teams, isFinal, matchInfo, onShowTip, onHideTip,
}: { }: {
tie: ResolvedTie; teams: Team[]; isFinal?: boolean; tie: ResolvedTie; teams: Team[]; isFinal?: boolean;
matchInfo?: string;
onShowTip: (text: string, x: number, y: number) => void; onShowTip: (text: string, x: number, y: number) => void;
onHideTip: () => void; onHideTip: () => void;
}) { }) {
return ( return (
<div className={`tie ${isFinal ? "final-tie" : ""}`}> <div className={`tie ${isFinal ? "final-tie" : ""}`}>
<div className="tie-head">Spiel {tie.matchNumber}</div> <div className="tie-head">Spiel {tie.matchNumber}</div>
{matchInfo && <div className="tie-meta">{matchInfo}</div>}
<Side s={tie.home} prob={tie.prob?.home} teams={teams} onShowTip={onShowTip} onHideTip={onHideTip} /> <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} /> <Side s={tie.away} prob={tie.prob?.away} teams={teams} onShowTip={onShowTip} onHideTip={onHideTip} />
</div> </div>
@@ -77,6 +91,18 @@ export default function Bracket({
const r32ByNum = new Map(r32Array.map((t) => [t.matchNumber, t])); const r32ByNum = new Map(r32Array.map((t) => [t.matchNumber, t]));
// Slot-Nummer → formatierte Anzeige (Datum/Uhrzeit aus MATCH_DATES, Stadt aus MATCH_STADIUMS)
const matchMeta = useMemo(() => {
const meta = new Map<number, string>();
for (let n = 73; n <= 104; n++) {
const utcDate = MATCH_DATES[n];
const stadiumId = MATCH_STADIUMS[n];
const info = fmtMatchInfo(utcDate, stadiumId);
if (info) meta.set(n, info);
}
return meta;
}, []);
const sfOrder = orderedRound([104]); const sfOrder = orderedRound([104]);
const qfOrder = orderedRound(sfOrder); const qfOrder = orderedRound(sfOrder);
const r16Order = orderedRound(qfOrder); const r16Order = orderedRound(qfOrder);
@@ -109,35 +135,35 @@ export default function Bracket({
<div className="round"> <div className="round">
<div className="round-label">Letzte 32</div> <div className="round-label">Letzte 32</div>
<div className="round-matches"> <div className="round-matches">
{r32.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)} {r32.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div> </div>
</div> </div>
<div className="round"> <div className="round">
<div className="round-label">Achtelfinale</div> <div className="round-label">Achtelfinale</div>
<div className="round-matches"> <div className="round-matches">
{r16.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)} {r16.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div> </div>
</div> </div>
<div className="round"> <div className="round">
<div className="round-label">Viertelfinale</div> <div className="round-label">Viertelfinale</div>
<div className="round-matches"> <div className="round-matches">
{qf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)} {qf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div> </div>
</div> </div>
<div className="round"> <div className="round">
<div className="round-label">Halbfinale</div> <div className="round-label">Halbfinale</div>
<div className="round-matches"> <div className="round-matches">
{sf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)} {sf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div> </div>
</div> </div>
<div className="round"> <div className="round">
<div className="round-label">Finale</div> <div className="round-label">Finale</div>
<div className="round-matches"> <div className="round-matches">
{fin && <Tie tie={fin} teams={teams} isFinal onShowTip={showTip} onHideTip={hideTip} />} {fin && <Tie tie={fin} teams={teams} isFinal matchInfo={matchMeta.get(fin.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />}
{third && ( {third && (
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
<div className="round-label" style={{ marginBottom: 8 }}>Spiel um Platz 3</div> <div className="round-label" style={{ marginBottom: 8 }}>Spiel um Platz 3</div>
<Tie tie={third} teams={teams} onShowTip={showTip} onHideTip={hideTip} /> <Tie tie={third} teams={teams} matchInfo={matchMeta.get(third.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />
</div> </div>
)} )}
</div> </div>

View File

@@ -3,12 +3,13 @@
import { Team, ThirdPlaceRow } from "@/lib/types"; import { Team, ThirdPlaceRow } from "@/lib/types";
export default function ThirdPlace({ export default function ThirdPlace({
rows, teams, rows, teams, secureTeams,
}: { rows: ThirdPlaceRow[]; teams: Team[] }) { }: { rows: ThirdPlaceRow[]; teams: Team[]; secureTeams?: string[] }) {
const name = (id: string) => { const name = (id: string) => {
const t = teams.find((t) => t.id === id); const t = teams.find((t) => t.id === id);
return t?.localisedName ?? t?.name ?? id; return t?.localisedName ?? t?.name ?? id;
}; };
const secureSet = secureTeams ? new Set(secureTeams) : null;
return ( return (
<div className="third-wrap"> <div className="third-wrap">
@@ -35,7 +36,12 @@ export default function ThirdPlace({
> >
<td>{r.overallRank}</td> <td>{r.overallRank}</td>
<td>{r.group}</td> <td>{r.group}</td>
<td style={{ fontWeight: 600 }}>{name(r.teamId)}</td> <td className={r.played === 3 ? "team-complete" : ""} style={{ fontWeight: 600 }}>
{name(r.teamId)}
{secureSet?.has(r.teamId) && (
<span style={{ color: "var(--turf)", marginLeft: 6, fontSize: 13 }} title="sicher qualifiziert"></span>
)}
</td>
<td>{r.played}</td> <td>{r.played}</td>
<td className="pts">{r.points}</td> <td className="pts">{r.points}</td>
<td>{r.goalDiff > 0 ? `+${r.goalDiff}` : r.goalDiff}</td> <td>{r.goalDiff > 0 ? `+${r.goalDiff}` : r.goalDiff}</td>

View File

@@ -47,7 +47,7 @@ body {
a { color: inherit; text-decoration: none; } a { color: inherit; text-decoration: none; }
.wrap { max-width: 1240px; margin: 0 auto; padding: 0 20px; } .wrap { max-width: 1240px; margin: 0 auto; padding: 0 20px 0 0; }
/* ---------- Header / Hero ---------- */ /* ---------- Header / Hero ---------- */
.masthead { .masthead {
@@ -180,6 +180,9 @@ table.standings { width: 100%; border-collapse: collapse; }
.qual-badge.yes { background: rgba(74,222,128,0.16); color: var(--turf); } .qual-badge.yes { background: rgba(74,222,128,0.16); color: var(--turf); }
.qual-badge.no { background: rgba(95,109,146,0.16); color: var(--ink-faint); } .qual-badge.no { background: rgba(95,109,146,0.16); color: var(--ink-faint); }
/* Drittplatzierte: Teamname grün, wenn alle 3 Gruppenspiele gespielt */
.third-table td.team-complete { color: var(--turf); }
/* ---------- Bracket ---------- */ /* ---------- Bracket ---------- */
.bracket-banner { .bracket-banner {
display: flex; align-items: center; gap: 12px; flex-wrap: wrap; display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
@@ -221,6 +224,10 @@ table.standings { width: 100%; border-collapse: collapse; }
font-family: var(--font-mono); font-size: 9px; color: var(--ink-faint); font-family: var(--font-mono); font-size: 9px; color: var(--ink-faint);
letter-spacing: 0.04em; padding: 5px 10px 0; letter-spacing: 0.04em; padding: 5px 10px 0;
} }
.tie-meta {
font-family: var(--font-mono); font-size: 8px; color: var(--ink-dim);
padding: 2px 10px 0;
}
.side { .side {
display: flex; align-items: center; justify-content: space-between; display: flex; align-items: center; justify-content: space-between;
padding: 8px 10px; font-size: 13px; padding: 8px 10px; font-size: 13px;
@@ -282,6 +289,7 @@ table.standings { width: 100%; border-collapse: collapse; }
.wrap { padding: 0 12px; } .wrap { padding: 0 12px; }
/* ---------- mobil: Header ---------- */ /* ---------- mobil: Header ---------- */
.masthead { padding: 0 12px; }
.masthead-inner { padding: 10px 0; gap: 8px; } .masthead-inner { padding: 10px 0; gap: 8px; }
.brand { gap: 6px; } .brand { gap: 6px; }
.brand-mark { font-size: 18px; } .brand-mark { font-size: 18px; }
@@ -289,15 +297,13 @@ table.standings { width: 100%; border-collapse: collapse; }
.status-pill { font-size: 10px; padding: 4px 10px; gap: 5px; } .status-pill { font-size: 10px; padding: 4px 10px; gap: 5px; }
.dot { width: 6px; height: 6px; } .dot { width: 6px; height: 6px; }
/* ---------- mobil: Tabs (horizontal scroll, kein Umbruch) ---------- */ /* ---------- mobil: Tabs (zwei Zeilen, kein horizontaler Scroll) ---------- */
.masthead-tabs { .masthead-tabs {
overflow-x: auto; flex-wrap: wrap;
flex-wrap: nowrap; justify-content: center;
-webkit-overflow-scrolling: touch; gap: 2px 4px;
scrollbar-width: none;
} }
.masthead-tabs::-webkit-scrollbar { display: none; } .tab { padding: 8px 13px; font-size: 12px; }
.tab { padding: 10px 14px; font-size: 12px; white-space: nowrap; flex-shrink: 0; }
.section { padding: 18px 0 48px; } .section { padding: 18px 0 48px; }
@@ -320,7 +326,8 @@ table.standings { width: 100%; border-collapse: collapse; }
.fx-score { font-size: 16px; min-width: 44px; } .fx-score { font-size: 16px; min-width: 44px; }
.fx-vs { font-size: 14px; min-width: 44px; } .fx-vs { font-size: 14px; min-width: 44px; }
.fx-name { font-size: 13px; max-width: 110px; } .fx-name { font-size: 13px; max-width: 110px; }
.grp-chip { width: 34px; height: 34px; font-size: 12px; } .grp-switch { gap: 8px; }
.grp-chip { width: 40px; height: 40px; font-size: 14px; }
/* ---------- mobil: Drittplatzierte ---------- */ /* ---------- mobil: Drittplatzierte ---------- */
.third-table th { font-size: 9px; padding: 8px 6px; } .third-table th { font-size: 9px; padding: 8px 6px; }

View File

@@ -1,4 +1,5 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import Script from "next/script";
import "./globals.css"; import "./globals.css";
export const metadata: Metadata = { export const metadata: Metadata = {
@@ -23,7 +24,17 @@ export default function RootLayout({ children }: { children: React.ReactNode })
rel="stylesheet" rel="stylesheet"
/> />
</head> </head>
<body>{children}</body> <body>
{children}
{process.env.NEXT_PUBLIC_UMAMI_SRC && process.env.NEXT_PUBLIC_UMAMI_ID && (
<Script
defer
src={process.env.NEXT_PUBLIC_UMAMI_SRC}
data-website-id={process.env.NEXT_PUBLIC_UMAMI_ID}
strategy="afterInteractive"
/>
)}
</body>
</html> </html>
); );
} }

View File

@@ -16,6 +16,7 @@ interface ApiData {
groupTables: GroupTable[]; groupTables: GroupTable[];
groupTablesLive: GroupTable[]; groupTablesLive: GroupTable[];
thirdTable: ThirdPlaceRow[]; thirdTable: ThirdPlaceRow[];
secureThirdTeams: string[];
annexAssignment: ThirdAssignment | null; annexAssignment: ThirdAssignment | null;
annexResolved: boolean; annexResolved: boolean;
} }
@@ -128,7 +129,7 @@ export default function Home() {
/> />
)} )}
{data && tab === "thirds" && ( {data && tab === "thirds" && (
<ThirdPlace rows={data.thirdTable} teams={data.teams} /> <ThirdPlace rows={data.thirdTable} teams={data.teams} secureTeams={data.secureThirdTeams} />
)} )}
{data && tab === "bracket" && ( {data && tab === "bracket" && (
<Bracket <Bracket

View File

@@ -4,7 +4,11 @@
services: services:
wm2026: wm2026:
build: . build:
context: .
args:
NEXT_PUBLIC_UMAMI_SRC: ${NEXT_PUBLIC_UMAMI_SRC:-}
NEXT_PUBLIC_UMAMI_ID: ${NEXT_PUBLIC_UMAMI_ID:-}
image: wm2026-board:latest image: wm2026-board:latest
container_name: wm2026 container_name: wm2026
restart: unless-stopped restart: unless-stopped

View File

@@ -1,6 +1,8 @@
import { GroupId, Match, MatchStatus, Team } from "./types"; import { GroupId, Match, MatchStatus, Team } from "./types";
import { venueFor } from "./venues"; import { venueFor } from "./venues";
import { localisedTeamName } from "./team-mappings"; import { localisedTeamName } from "./team-mappings";
import { R32, LATER_ROUNDS, resolveAnnexC, qualifiedThirdGroups } from "./bracket";
import { computeGroupTables, computeThirdPlaceTable } from "./standings";
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Caching: einfacher In-Memory-Cache mit TTL. Verhindert, dass jede Browser- // Caching: einfacher In-Memory-Cache mit TTL. Verhindert, dass jede Browser-
@@ -88,26 +90,74 @@ const STAGE_ORDER: Record<Match["stage"], number> = {
}; };
// Setzt Spielnummern und Stadien. // Setzt Spielnummern und Stadien.
// - K.o.-Spiele: chronologisch ab 73 (Anstöße dort eindeutig) -> für Bracket nötig. // K.o.-Spiele: Nummerierung über Slot-Auflösung (assignKONumbersBySlots),
// - Venue: Gruppenspiele über die Teampaarung, K.o.-Spiele über die Spielnummer. // NICHT mehr chronologisch — die FIFA-Nummern folgen der Bracket-Topologie.
// Venue: Gruppenspiele über die Teampaarung, K.o.-Spiele über die Spielnummer.
function assignNumbersAndVenues(matches: Match[], teams: Team[]): void { 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). // Stadien setzen (Gruppenphase per Paarung, K.o. per Nummer).
for (const m of matches) { for (const m of matches) {
m.venue = venueFor(m, teams); m.venue = venueFor(m, teams);
} }
} }
// Vergibt K.o.-Match-Nummern über Slot-Auflösung (FIFA-Topologie)
// statt chronologisch. Für R32-Matches mit Team-IDs wird der Slot gesucht,
// dessen aufgelöste Teams dem Feed-Paar entsprechen.
export function assignKONumbersBySlots(matches: Match[], teams: Team[]): void {
const tables = computeGroupTables(teams, matches);
const thirds = computeThirdPlaceTable(tables);
const qGroups = qualifiedThirdGroups(thirds);
const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null;
const byPair = new Map<string, Match>();
for (const m of matches) {
if (m.group != null || !m.homeTeamId || !m.awayTeamId) continue;
byPair.set(`${m.homeTeamId}::${m.awayTeamId}`, m);
byPair.set(`${m.awayTeamId}::${m.homeTeamId}`, m);
}
for (const slot of R32) {
const homeGroup = slot.home.type === "W" ? slot.home.group : undefined;
const awayGroup = slot.away.type === "W" ? slot.away.group : undefined;
const wg = (homeGroup ?? awayGroup) as GroupId | undefined;
let hid: string | null = null;
if (slot.home.type === "W" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.home.type === "R" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.home.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) hid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
let aid: string | null = null;
if (slot.away.type === "W" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.away.type === "R" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.away.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) aid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
if (hid && aid) {
const fm = byPair.get(`${hid}::${aid}`);
if (fm) fm.matchNumber = slot.matchNumber;
}
}
// R16Finale: per Stage + Datum den LATER_ROUNDS-Slots zuordnen
for (const stage of ["R16", "QF", "SF", "3RD", "FINAL"] as const) {
const sm = matches.filter(m => m.stage === stage && m.group == null && m.matchNumber === 0)
.sort((a, b) => +new Date(a.utcDate) - +new Date(b.utcDate));
const ls = LATER_ROUNDS.filter(k => k.stage === (stage === "3RD" ? "3RD" : stage));
for (let i = 0; i < sm.length && i < ls.length; i++) {
sm[i].matchNumber = ls[i].matchNumber;
}
}
}
// Holt alle Spiele + leitet die Teamliste daraus ab (spart einen Extra-Call). // Holt alle Spiele + leitet die Teamliste daraus ab (spart einen Extra-Call).
export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams: Team[] }> { export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams: Team[] }> {
return cached("fd:matches", 60_000, async () => { return cached("fd:matches", 60_000, async () => {
@@ -154,6 +204,7 @@ export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams:
}); });
const teams = [...teamMap.values()]; const teams = [...teamMap.values()];
assignNumbersAndVenues(matches, teams); assignNumbersAndVenues(matches, teams);
return { matches, teams }; return { matches, teams };
@@ -183,6 +234,7 @@ interface PmMarket {
} }
export interface ParsedOdds { export interface ParsedOdds {
slug: string;
homeCode: string; homeCode: string;
awayCode: string; awayCode: string;
homeName: string; homeName: string;
@@ -190,6 +242,7 @@ export interface ParsedOdds {
pHome: number; pHome: number;
pDraw: number; pDraw: number;
pAway: number; pAway: number;
startTime: string | null;
} }
// Normalisiert Teamcodes zwischen Polymarket-Slug und Feed (3-Buchstaben). // Normalisiert Teamcodes zwischen Polymarket-Slug und Feed (3-Buchstaben).
@@ -214,7 +267,7 @@ function safeParse<T>(s: string, fallback: T): T {
// Holt alle WM-Spiele über den Series-Endpoint mit Pagination. // Holt alle WM-Spiele über den Series-Endpoint mit Pagination.
// Parst pro Event die drei Moneyline-Märkte (Heim/Draw/Auswärts). // Parst pro Event die drei Moneyline-Märkte (Heim/Draw/Auswärts).
export async function fetchOdds(): Promise<ParsedOdds[]> { export async function fetchOdds(): Promise<ParsedOdds[]> {
return cached("pm:odds", 120_000, async () => { return cached("pm:odds", 300_000, async () => {
const allEvents: PmEvent[] = []; const allEvents: PmEvent[] = [];
for (let offset = 0; ; offset += 100) { for (let offset = 0; ; offset += 100) {
const url = `${PM_BASE}/events?series_id=${PM_SERIES}&active=true&closed=false&limit=100&offset=${offset}`; const url = `${PM_BASE}/events?series_id=${PM_SERIES}&active=true&closed=false&limit=100&offset=${offset}`;
@@ -227,9 +280,9 @@ export async function fetchOdds(): Promise<ParsedOdds[]> {
allEvents.push(...page); allEvents.push(...page);
if (page.length < 100) break; if (page.length < 100) break;
} }
//console.log("[polymarket] events fetched:", allEvents.length);
const parsed: ParsedOdds[] = []; const parsed: ParsedOdds[] = [];
for (const ev of allEvents) { for (const ev of allEvents) {
// Slug: fifwc-{home}-{away}-{yyyy}-{mm}-{dd} // Slug: fifwc-{home}-{away}-{yyyy}-{mm}-{dd}
const slugParts = ev.slug.replace("fifwc-", "").split("-"); const slugParts = ev.slug.replace("fifwc-", "").split("-");
@@ -239,10 +292,12 @@ export async function fetchOdds(): Promise<ParsedOdds[]> {
let pHome = 0, pDraw = 0, pAway = 0; let pHome = 0, pDraw = 0, pAway = 0;
let homeName = "", awayName = ""; let homeName = "", awayName = "";
let marketGameStartTime: string | null = null;
for (const mk of ev.markets ?? []) { for (const mk of ev.markets ?? []) {
if (mk.sportsMarketType && mk.sportsMarketType !== "moneyline") continue; if (mk.sportsMarketType && mk.sportsMarketType !== "moneyline") continue;
if (mk.closed) continue; if (mk.closed) continue;
if (!marketGameStartTime) marketGameStartTime = (mk as any).gameStartTime ?? null;
const prices = safeParse<string[]>(mk.outcomePrices, []).map(Number); const prices = safeParse<string[]>(mk.outcomePrices, []).map(Number);
if (prices.length < 2) continue; if (prices.length < 2) continue;
const yes = prices[0]; // erster Preis = "Yes"-Wahrscheinlichkeit const yes = prices[0]; // erster Preis = "Yes"-Wahrscheinlichkeit
@@ -266,7 +321,8 @@ export async function fetchOdds(): Promise<ParsedOdds[]> {
} }
if (pHome > 0 || pDraw > 0 || pAway > 0) { if (pHome > 0 || pDraw > 0 || pAway > 0) {
parsed.push({ homeCode, awayCode, homeName, awayName, pHome, pDraw, pAway }); const startTime = marketGameStartTime ?? (ev as any).gameStartTime ?? (ev as any).endDate ?? (ev as any).startDate;
parsed.push({ slug: ev.slug, homeCode, awayCode, homeName, awayName, pHome, pDraw, pAway, startTime });
} }
} }
@@ -312,7 +368,9 @@ export function attachOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]):
} }
} }
return matches.map((m) => { const attachedOdds = new Set<ParsedOdds>();
const result = matches.map((m) => {
if (!m.homeTeamId || !m.awayTeamId) return m; if (!m.homeTeamId || !m.awayTeamId) return m;
// Suche in oddsMatch nach einer Kombination die beide Team-IDs matcht // Suche in oddsMatch nach einer Kombination die beide Team-IDs matcht
for (const [o, ids] of oddsMatch) { for (const [o, ids] of oddsMatch) {
@@ -321,6 +379,7 @@ export function attachOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]):
if ((ids.homeId === m.homeTeamId && ids.awayId === m.awayTeamId) || if ((ids.homeId === m.homeTeamId && ids.awayId === m.awayTeamId) ||
(ids.homeId === m.awayTeamId && ids.awayId === m.homeTeamId)) { (ids.homeId === m.awayTeamId && ids.awayId === m.homeTeamId)) {
const swapped = ids.homeId === m.awayTeamId; const swapped = ids.homeId === m.awayTeamId;
attachedOdds.add(o);
return { return {
...m, ...m,
prob: { prob: {
@@ -333,4 +392,279 @@ export function attachOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]):
} }
return m; return m;
}); });
return result;
}
// ----------------------------------------------------------------------------
// KO-Odds-Fallback: löst R32-Paarungen auf und verknüpft Polymarket-Events
// mit K.o.-Feed-Matches, die noch keine Team-IDs im Feed haben.
// ----------------------------------------------------------------------------
// Löst für jeden R32-Slot (73-88) die aktuellen Team-Paarungen auf Basis der
// Gruppentabellen und Annex-C-Zuordnung. Gibt eine Map matchNumber → Paarung
// zurück, NUR wenn beide Team-IDs eindeutig bekannt sind (kein Raten).
function resolveR32Pairings(matches: Match[], teams: Team[]): Map<number, { homeTeamId: string; awayTeamId: string }> {
const tables = computeGroupTables(teams, matches);
const thirds = computeThirdPlaceTable(tables);
const qGroups = qualifiedThirdGroups(thirds);
const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null;
const pairings = new Map<number, { homeTeamId: string; awayTeamId: string }>();
for (const slot of R32) {
const homeGroup = slot.home.type === "W" ? slot.home.group : undefined;
const awayGroup = slot.away.type === "W" ? slot.away.group : undefined;
const wg = (homeGroup ?? awayGroup) as GroupId | undefined;
let hid: string | null = null;
if (slot.home.type === "W" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.home.type === "R" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.home.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) hid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
let aid: string | null = null;
if (slot.away.type === "W" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.away.type === "R" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.away.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) aid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
if (hid && aid) {
pairings.set(slot.matchNumber, { homeTeamId: hid, awayTeamId: aid });
}
}
return pairings;
}
// Extrahiert das Datum (YYYY-MM-DD) aus einem Polymarket-Slug.
// Slug-Format: fifwc-{home}-{away}-{yyyy}-{mm}-{dd}
function slugToDate(slug: string): string | null {
const parts = slug.split("-");
if (parts.length < 3) return null;
const y = parts[parts.length - 3];
const m = parts[parts.length - 2];
const d = parts[parts.length - 1];
if (/^\d{4}$/.test(y) && /^\d{2}$/.test(m) && /^\d{2}$/.test(d)) {
return `${y}-${m}-${d}`;
}
return null;
}
// Zweiter Durchlauf für attachOdds: ordnet Polymarket-Events K.o.-Feed-Matches
// zu, die (noch) keine Team-IDs im Feed haben. Arbeitet direkt auf den
// aufgelösten R32-Paarungen (resolveR32Pairings). Identifiziert das Ziel-
// Feed-Match über die Slot-matchNumber (Stufe 1) oder Datums-Lookup aus dem
// Slug (Stufe 2) — KEINE chronologische Nummernvergabe.
// Mutiert matches in-place, setzt nur bei Matches OHNE bestehende prob.
export function attachKOOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]): Match[] {
const pairings = resolveR32Pairings(matches, teams);
if (pairings.size === 0) return matches;
const idByName = new Map<string, string>();
for (const t of teams) {
const nn = normName(t.name);
if (!idByName.has(nn)) idByName.set(nn, t.id);
}
const idByCode = new Map(teams.map((t) => [t.code.toLowerCase(), t.id]));
for (const [matchNum, pairing] of pairings) {
if (!pairing.homeTeamId || !pairing.awayTeamId) continue;
// Finde Polymarket-Event für dieses Team-Paar
let matchedEvent: ParsedOdds | null = null;
for (const o of odds) {
const hn = normName(o.homeName);
const an = normName(o.awayName);
const homeId = idByName.get(hn) ?? idByCode.get(o.homeCode);
const awayId = idByName.get(an) ?? idByCode.get(o.awayCode);
if (!homeId || !awayId) continue;
if ((homeId === pairing.homeTeamId && awayId === pairing.awayTeamId) ||
(homeId === pairing.awayTeamId && awayId === pairing.homeTeamId)) {
matchedEvent = o;
break;
}
}
if (!matchedEvent) continue;
// Ziel-Feed-Match identifizieren
let targetMatch: Match | undefined;
// Stufe 1: bereits nummeriertes R32-Match (via assignKONumbersBySlots Pass 1)
targetMatch = matches.find(m =>
m.stage === "R32" && m.group == null && m.matchNumber === matchNum,
);
// Stufe 2: Datums-Lookup aus Polymarket-Slug für unnummerierte Matches
if (!targetMatch) {
const slugDate = slugToDate(matchedEvent.slug);
if (slugDate) {
const candidates = matches.filter(m =>
m.stage === "R32" && m.group == null && m.matchNumber === 0 &&
m.utcDate.slice(0, 10) === slugDate,
);
if (candidates.length === 1) {
targetMatch = candidates[0];
targetMatch.matchNumber = matchNum;
} else if (candidates.length > 1) {
// Tie-breaker: falls Polymarket-Event eine Startzeit hat, nächstgelegenes Feed-Match
if (matchedEvent.startTime) {
const eventTime = new Date(matchedEvent.startTime).getTime();
let best: Match | undefined;
let bestDiff = Infinity;
for (const c of candidates) {
const diff = Math.abs(new Date(c.utcDate).getTime() - eventTime);
if (diff < bestDiff) { bestDiff = diff; best = c; }
}
// Nur zuordnen, wenn Zeitdifferenz plausibel (<4h)
if (best && bestDiff < 4 * 60 * 60 * 1000) {
targetMatch = best;
targetMatch.matchNumber = matchNum;
}
}
}
}
}
if (!targetMatch) continue;
// prob nicht überschreiben, falls schon gesetzt
if (targetMatch.prob) continue;
const homeIdFromEvent = idByName.get(normName(matchedEvent.homeName)) ??
idByCode.get(matchedEvent.homeCode);
const swapped = homeIdFromEvent === pairing.awayTeamId;
targetMatch.prob = {
home: swapped ? matchedEvent.pAway : matchedEvent.pHome,
draw: matchedEvent.pDraw,
away: swapped ? matchedEvent.pHome : matchedEvent.pAway,
};
}
return matches;
}
// ----------------------------------------------------------------------------
// worldcup26.ir: schnelle Live-Scores (additiv, Fallback auf football-data)
// ----------------------------------------------------------------------------
const WC26_BASE = "https://worldcup26.ir";
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;
}
interface LiveScore {
homeName: string;
awayName: string;
group: string;
matchday: string;
homeScore: number | null;
awayScore: number | null;
status: string; // "IN_PLAY" | "FINISHED"
}
// 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;
} }

View File

@@ -4,6 +4,7 @@ import {
ThirdAssignment, slotLabel, ThirdAssignment, slotLabel,
} from "@/lib/bracket"; } from "@/lib/bracket";
import { placeIsSecure } from "@/lib/secure-places"; import { placeIsSecure } from "@/lib/secure-places";
import { thirdSlotIsSecure, securelyQualifiedThirdTeams } from "@/lib/third-place-security";
// Ein aufgelöster Teilnehmer einer K.o.-Begegnung. // Ein aufgelöster Teilnehmer einer K.o.-Begegnung.
export interface ResolvedSide { export interface ResolvedSide {
@@ -46,15 +47,6 @@ function loserOf(m: Match | undefined): string | null {
return null; return null;
} }
// Prüft, ob die gesamte Gruppenphase abgeschlossen ist.
// Erst dann stehen die Drittplatzierten-Rangliste und die
// Annex-C-Zuordnung final fest.
function groupStageComplete(matches: Match[]): boolean {
const groupMatches = matches.filter((m) => m.group != null);
if (groupMatches.length === 0) return false;
return groupMatches.every((m) => m.status === "FINISHED");
}
// Löst einen R32-Slot (W/R/3) zu einer Team-ID auf, sofern bereits bekannt. // Löst einen R32-Slot (W/R/3) zu einer Team-ID auf, sofern bereits bekannt.
// provisional = true, solange die zugrunde liegende Gruppe/Zuordnung nicht fix ist. // provisional = true, solange die zugrunde liegende Gruppe/Zuordnung nicht fix ist.
function resolveR32Slot( function resolveR32Slot(
@@ -66,6 +58,7 @@ function resolveR32Slot(
matches: Match[], matches: Match[],
teams: Team[], teams: Team[],
annexResolved: boolean, annexResolved: boolean,
secureTeamIds: Set<string>,
): { teamId: string | null; provisional: boolean; tooltip: string | null } { ): { teamId: string | null; provisional: boolean; tooltip: string | null } {
const table = (g: GroupId) => tables.find((t) => t.group === g); const table = (g: GroupId) => tables.find((t) => t.group === g);
if (slot.type === "W") { if (slot.type === "W") {
@@ -89,11 +82,14 @@ function resolveR32Slot(
const thirdGroup = assignment[winnerGroup]; const thirdGroup = assignment[winnerGroup];
if (thirdGroup) { if (thirdGroup) {
const row = thirds.find((r) => r.group === thirdGroup && r.qualifies); const row = thirds.find((r) => r.group === thirdGroup && r.qualifies);
// Fix nur, wenn ALLE drei Bedingungen erfüllt sind: // Fix nur, wenn ALLE Bedingungen erfüllt sind:
// 1. Annex C aufgelöst (8 Dritte zuweisbar) // 1. Annex C aufgelöst (8 Dritte zuweisbar)
// 2. Komplette Gruppenphase beendet (Dritten-Rangliste final) // 2. Der Slot ist in allen noch möglichen Konstellationen stabil
// 3. Das Team gehört gesichert zu den besten 8 // 3. Das konkrete Team ist sicher qualifiziert (kann nicht aus Top 8 fallen)
const fix = annexResolved && groupStageComplete(matches) && row?.qualifies === true; // 4. Die Gruppe hat alle Spiele gespielt (Team bekannt)
const slotStable = thirdSlotIsSecure(winnerGroup, matches, teams);
const teamSecure = row?.teamId ? secureTeamIds.has(row.teamId) : false;
const fix = annexResolved && slotStable && teamSecure && row?.qualifies === true;
const provisional = !fix; const provisional = !fix;
const prefix = provisional ? "aktuell " : ""; const prefix = provisional ? "aktuell " : "";
return { return {
@@ -148,6 +144,7 @@ export function resolveBracket(
const losers = new Map<number, string | null>(); const losers = new Map<number, string | null>();
// Map: Match-Nummer -> ist das Spiel beendet (Sieger fix)? // Map: Match-Nummer -> ist das Spiel beendet (Sieger fix)?
const decided = new Map<number, boolean>(); const decided = new Map<number, boolean>();
const secureTeamIds = securelyQualifiedThirdTeams(matches, teams);
const r32: ResolvedTie[] = R32.map((rm: R32Match) => { const r32: ResolvedTie[] = R32.map((rm: R32Match) => {
const feed = feedMatch(matches, rm.matchNumber); const feed = feedMatch(matches, rm.matchNumber);
@@ -156,26 +153,26 @@ export function resolveBracket(
// Für 3.-Platz-Slots: Gruppensieger ist die andere Seite (immer W) // Für 3.-Platz-Slots: Gruppensieger ist die andere Seite (immer W)
const winnerGroup = (homeGroup ?? awayGroup) as GroupId | undefined; const winnerGroup = (homeGroup ?? awayGroup) as GroupId | undefined;
const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved); const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved, secureTeamIds);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved); const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved, secureTeamIds);
const home = sideFrom(h.teamId, slotLabel(rm.home, assignment, winnerGroup), teams, feed, "home", h.provisional, h.tooltip); const home = sideFrom(h.teamId, slotLabel(rm.home, assignment, winnerGroup), teams, feed, "home", h.provisional, h.tooltip);
const away = sideFrom(a.teamId, slotLabel(rm.away, assignment, winnerGroup), teams, feed, "away", a.provisional, a.tooltip); const away = sideFrom(a.teamId, slotLabel(rm.away, assignment, winnerGroup), teams, feed, "away", a.provisional, a.tooltip);
const feedWinner = winnerOf(feed); const feedWinner = winnerOf(feed);
if (resolveWinners && !feedWinner && feed && h.teamId && a.teamId // Sim-Modus: Gewinner NUR aus Scores + Slot-Team-IDs ableiten.
// feedWinner (aus feed.homeTeamId/awayTeamId) wird IGNORIERT,
// weil matchNumber-Zuweisung (assignNumbersAndVenues) von der
// FIFA-Nummerierung abweichen kann → feed gehört evtl. zum falschen Spiel.
if (resolveWinners && feed && h.teamId && a.teamId
&& feed.homeScore != null && feed.awayScore != null) { && feed.homeScore != null && feed.awayScore != null) {
// Simulation: Gewinner aus Scores und aufgelösten Team-IDs ableiten // Simulation: Gewinner aus Scores und aufgelösten Team-IDs ableiten.
if (feed.homeScore > feed.awayScore) { // Nutze NICHT feed.homeTeamId/awayTeamId (sind null für KO-Matches),
winners.set(rm.matchNumber, h.teamId); // sondern die aufgelösten h.teamId / a.teamId aus resolveR32Slot.
losers.set(rm.matchNumber, loserOf(feed) ?? a.teamId); const homeWins = feed.homeScore > feed.awayScore;
} else if (feed.awayScore > feed.homeScore) { const awayWins = feed.awayScore > feed.homeScore;
winners.set(rm.matchNumber, a.teamId); const winnerId = homeWins ? h.teamId : awayWins ? a.teamId : h.teamId;
losers.set(rm.matchNumber, loserOf(feed) ?? h.teamId); winners.set(rm.matchNumber, winnerId);
} else { losers.set(rm.matchNumber, loserOf(feed) ?? (homeWins ? a.teamId : awayWins ? h.teamId : a.teamId));
// Unentschieden → Heim gewinnt
winners.set(rm.matchNumber, h.teamId);
losers.set(rm.matchNumber, loserOf(feed) ?? a.teamId);
}
} else { } else {
winners.set(rm.matchNumber, feedWinner); winners.set(rm.matchNumber, feedWinner);
losers.set(rm.matchNumber, loserOf(feed)); losers.set(rm.matchNumber, loserOf(feed));
@@ -193,6 +190,7 @@ export function resolveBracket(
const src = km.losers ? losers : winners; const src = km.losers ? losers : winners;
const homeId = src.get(km.fromHome) ?? null; const homeId = src.get(km.fromHome) ?? null;
const awayId = src.get(km.fromAway) ?? null; const awayId = src.get(km.fromAway) ?? null;
// Ein Folgeteam ist fix, wenn das speisende Spiel beendet ist. // Ein Folgeteam ist fix, wenn das speisende Spiel beendet ist.
const homeProv = !(decided.get(km.fromHome) ?? false); const homeProv = !(decided.get(km.fromHome) ?? false);
const awayProv = !(decided.get(km.fromAway) ?? false); const awayProv = !(decided.get(km.fromAway) ?? false);
@@ -204,18 +202,13 @@ export function resolveBracket(
const away = sideFrom(awayId, awayLabel, teams, feed, "away", awayProv, awayTtip); const away = sideFrom(awayId, awayLabel, teams, feed, "away", awayProv, awayTtip);
const feedWinner = winnerOf(feed); const feedWinner = winnerOf(feed);
if (resolveWinners && !feedWinner && feed && homeId && awayId if (resolveWinners && feed && homeId && awayId
&& feed.homeScore != null && feed.awayScore != null) { && feed.homeScore != null && feed.awayScore != null) {
if (feed.homeScore > feed.awayScore) { const homeWins = feed.homeScore > feed.awayScore;
winners.set(km.matchNumber, homeId); const awayWins = feed.awayScore > feed.homeScore;
losers.set(km.matchNumber, loserOf(feed) ?? awayId); const winnerId = homeWins ? homeId : awayWins ? awayId : homeId;
} else if (feed.awayScore > feed.homeScore) { winners.set(km.matchNumber, winnerId);
winners.set(km.matchNumber, awayId); losers.set(km.matchNumber, loserOf(feed) ?? (homeWins ? awayId : awayWins ? homeId : awayId));
losers.set(km.matchNumber, loserOf(feed) ?? homeId);
} else {
winners.set(km.matchNumber, homeId);
losers.set(km.matchNumber, loserOf(feed) ?? awayId);
}
} else { } else {
winners.set(km.matchNumber, feedWinner); winners.set(km.matchNumber, feedWinner);
losers.set(km.matchNumber, loserOf(feed)); losers.set(km.matchNumber, loserOf(feed));

51
lib/stadiums.ts Normal file
View File

@@ -0,0 +1,51 @@
// Statische Stadion-Daten für WM 2026.
export const STADIUMS: Record<string, { name: string; city: string }> = {
"1": { name: "Estadio Azteca", city: "Mexico City" },
"2": { name: "Estadio Akron", city: "Guadalajara" },
"3": { name: "Estadio BBVA", city: "Monterrey" },
"4": { name: "AT&T Stadium", city: "Dallas" },
"5": { name: "NRG Stadium", city: "Houston" },
"6": { name: "GEHA Field at Arrowhead Stadium", city: "Kansas City" },
"7": { name: "Mercedes-Benz Stadium", city: "Atlanta" },
"8": { name: "Hard Rock Stadium", city: "Miami" },
"9": { name: "Gillette Stadium", city: "Boston" },
"10": { name: "Lincoln Financial Field", city: "Philadelphia" },
"11": { name: "MetLife Stadium", city: "New York/New Jersey" },
"12": { name: "BMO Field", city: "Toronto" },
"13": { name: "BC Place", city: "Vancouver" },
"14": { name: "Lumen Field", city: "Seattle" },
"15": { name: "Levi's Stadium", city: "San Francisco Bay Area" },
"16": { name: "SoFi Stadium", city: "Los Angeles" },
};
// K.o.-Spielnummer → ISO-8601 UTC-Anstoßzeit (FIFA-Spielplan, statisch).
export const MATCH_DATES: Record<number, string> = {
// R32 (28.6.3.7.)
73: "2026-06-28T19:00:00Z", 74: "2026-06-29T21:00:00Z", 75: "2026-06-29T22:00:00Z",
76: "2026-06-29T22:00:00Z", 77: "2026-06-30T17:00:00Z", 78: "2026-06-30T21:00:00Z",
79: "2026-07-01T19:00:00Z", 80: "2026-07-01T21:00:00Z", 81: "2026-07-01T19:00:00Z",
82: "2026-07-02T19:00:00Z", 83: "2026-07-02T21:00:00Z", 84: "2026-07-02T19:00:00Z",
85: "2026-07-03T17:00:00Z", 86: "2026-07-03T21:00:00Z", 87: "2026-07-03T22:00:00Z",
88: "2026-07-03T22:00:00Z",
// R16 (6.7.9.7.)
89: "2026-07-06T21:00:00Z", 90: "2026-07-06T22:00:00Z", 91: "2026-07-07T21:00:00Z",
92: "2026-07-07T19:00:00Z", 93: "2026-07-08T22:00:00Z", 94: "2026-07-08T19:00:00Z",
95: "2026-07-09T21:00:00Z", 96: "2026-07-09T19:00:00Z",
// QF (12.7.13.7.)
97: "2026-07-12T21:00:00Z", 98: "2026-07-12T19:00:00Z", 99: "2026-07-13T21:00:00Z",
100: "2026-07-13T22:00:00Z",
// SF (16.7.17.7.)
101: "2026-07-16T22:00:00Z", 102: "2026-07-17T21:00:00Z",
// 3RD (19.7.)
103: "2026-07-19T17:00:00Z",
// FINAL (20.7.)
104: "2026-07-20T17:00:00Z",
};
// K.o.-Spielnummer → stadium_id (FIFA-Quelle, statisch).
export const MATCH_STADIUMS: Record<number, string> = {
73: "16", 74: "9", 75: "3", 76: "5", 77: "11", 78: "4", 79: "1", 80: "7",
81: "15", 82: "14", 83: "12", 84: "16", 85: "13", 86: "8", 87: "6", 88: "4",
89: "10", 90: "5", 91: "11", 92: "1", 93: "4", 94: "14", 95: "7", 96: "13",
97: "9", 98: "16", 99: "8", 100: "6", 101: "4", 102: "7", 103: "8", 104: "11",
};

238
lib/third-place-security.ts Normal file
View File

@@ -0,0 +1,238 @@
import { GroupId, GROUP_IDS, Match, Team } from "./types";
import { computeGroupTables } from "./standings";
import { resolveAnnexC } from "./bracket";
// Repräsentative Ergebnis-Varianten je Restspiel (decken alle Punktkombinationen ab).
const OUTCOMES: Array<[number, number]> = [
[1, 0], // Heimsieg
[0, 1], // Auswärtssieg
[0, 0], // Unentschieden
];
interface ThirdInfo {
teamId: string;
points: number;
goalsFor: number;
goalsAgainst: number;
goalDiff: number;
}
interface GroupThirdState {
finished: boolean;
third: ThirdInfo | null;
minPoints: number;
maxPoints: number;
possibleTeamIds: Set<string>;
}
function openMatches(group: GroupId, matches: Match[]): Match[] {
return matches.filter(
(m) => m.group === group && m.status !== "FINISHED"
&& m.homeTeamId != null && m.awayTeamId != null,
);
}
function enumerateThirdPossibilities(
group: GroupId, teams: Team[], matches: Match[],
): { minPoints: number; maxPoints: number; teamIds: Set<string> } {
const open = openMatches(group, matches);
const played = matches.filter(
(m) => m.group === group && (m.status === "FINISHED" || m.homeTeamId == null || m.awayTeamId == null),
);
let minP = Infinity, maxP = -Infinity;
const teamIds = new Set<string>();
if (open.length === 0) {
const table = computeGroupTables(teams, matches).find((t) => t.group === group);
const third = table?.rows.find((r) => r.rank === 3);
if (third) { minP = maxP = third.points; teamIds.add(third.teamId); }
return { minPoints: minP, maxPoints: maxP, teamIds };
}
const totalCombos = Math.pow(OUTCOMES.length, open.length);
if (totalCombos > 500) return { minPoints: 0, maxPoints: 9, teamIds };
for (let combo = 0; combo < totalCombos; combo++) {
let c = combo;
const simulated: Match[] = open.map((m) => {
const variantIdx = c % OUTCOMES.length;
c = Math.floor(c / OUTCOMES.length);
const [hg, ag] = OUTCOMES[variantIdx];
return { ...m, status: "FINISHED" as const, homeScore: hg, awayScore: ag };
});
const all = [...played, ...simulated];
const table = computeGroupTables(teams, all).find((t) => t.group === group);
const third = table?.rows.find((r) => r.rank === 3);
if (third) { minP = Math.min(minP, third.points); maxP = Math.max(maxP, third.points); teamIds.add(third.teamId); }
}
return { minPoints: minP === Infinity ? 0 : minP, maxPoints: maxP === -Infinity ? 9 : maxP, teamIds };
}
function buildThirdStates(matches: Match[], teams: Team[]): Map<GroupId, GroupThirdState> {
const states = new Map<GroupId, GroupThirdState>();
for (const g of GROUP_IDS) {
const gm = matches.filter((m) => m.group === g);
const allDone = gm.length > 0 && gm.every((m) => m.status === "FINISHED");
const table = computeGroupTables(teams, matches).find((t) => t.group === g);
const thirdRow = table?.rows.find((r) => r.rank === 3);
let third: ThirdInfo | null = null;
if (thirdRow) third = { teamId: thirdRow.teamId, points: thirdRow.points, goalsFor: thirdRow.goalsFor, goalsAgainst: thirdRow.goalsAgainst, goalDiff: thirdRow.goalDiff };
if (allDone && third) {
states.set(g, { finished: true, third, minPoints: third.points, maxPoints: third.points, possibleTeamIds: new Set([third.teamId]) });
} else {
const { minPoints, maxPoints, teamIds } = enumerateThirdPossibilities(g, teams, matches);
states.set(g, { finished: false, third, minPoints, maxPoints, possibleTeamIds: teamIds });
}
}
return states;
}
function classifyGroups(states: Map<GroupId, GroupThirdState>): {
lockedIn: Set<GroupId>; lockedOut: Set<GroupId>; contested: Set<GroupId>;
} {
const lockedIn = new Set<GroupId>();
const lockedOut = new Set<GroupId>();
const contested = new Set<GroupId>();
for (const g of GROUP_IDS) {
const st = states.get(g)!;
if (st.finished && !st.third) { lockedOut.add(g); continue; }
let countCouldBeBetter = 0;
for (const other of GROUP_IDS) {
if (other === g) continue;
const os = states.get(other)!;
if (os.maxPoints > st.minPoints) countCouldBeBetter++;
else if (os.maxPoints === st.minPoints && !st.finished && os.finished) countCouldBeBetter++;
}
const alwaysTop8 = countCouldBeBetter <= 7;
let countDefinitelyBetter = 0;
for (const other of GROUP_IDS) {
if (other === g) continue;
const os = states.get(other)!;
if (os.minPoints > st.maxPoints) countDefinitelyBetter++;
else if (os.minPoints === st.maxPoints && os.finished && !st.finished) countDefinitelyBetter++;
}
const neverTop8 = countDefinitelyBetter >= 8;
if (alwaysTop8) lockedIn.add(g);
else if (neverTop8) lockedOut.add(g);
else contested.add(g);
}
return { lockedIn, lockedOut, contested };
}
// --- Public API ---
// Liefert die Team-IDs der Dritten, die mathematisch sicher unter den Top 8
// der gruppenübergreifenden Dritten-Tabelle sind. Prüft für jedes Team aus
// einer FERTIGEN Gruppe (played === 3), ob es in ALLEN noch möglichen
// Restspiel-Konstellationen von maximal 7 anderen Dritten überholt werden kann.
export function securelyQualifiedThirdTeams(matches: Match[], teams: Team[]): Set<string> {
const states = buildThirdStates(matches, teams);
const secureTeams = new Set<string>();
for (const g of GROUP_IDS) {
const st = states.get(g)!;
if (!st.finished || !st.third || st.possibleTeamIds.size !== 1) continue;
const my = st.third;
let couldBeBetter = 0;
for (const og of GROUP_IDS) {
if (og === g) continue;
const os = states.get(og)!;
if (os.finished && os.third) {
if (os.third.points > my.points) couldBeBetter++;
else if (os.third.points === my.points && os.third.goalDiff > my.goalDiff) couldBeBetter++;
else if (os.third.points === my.points && os.third.goalDiff === my.goalDiff && os.third.goalsFor > my.goalsFor) couldBeBetter++;
} else {
if (os.maxPoints > my.points) couldBeBetter++;
else if (os.maxPoints === my.points && !os.finished) couldBeBetter++;
}
}
if (couldBeBetter <= 7) secureTeams.add(my.teamId);
}
return secureTeams;
}
// Liefert die Gruppen, deren Dritter mathematisch sicher unter den Top 8 ist.
// (Gruppen-Ebene — für Fix-Markierung im Baum, nicht für Team-Häkchen.)
export function securelyQualifiedThirdGroups(matches: Match[], teams: Team[]): GroupId[] {
const states = buildThirdStates(matches, teams);
const { lockedIn } = classifyGroups(states);
return [...lockedIn];
}
// Prüft, ob ein bestimmter Dritten-Slot (Gegner des Siegers von `winnerGroup`)
// in ALLEN noch möglichen Konstellationen identisch bleibt.
export function thirdSlotIsSecure(winnerGroup: GroupId, matches: Match[], teams: Team[]): boolean {
const states = buildThirdStates(matches, teams);
const { lockedIn, contested } = classifyGroups(states);
if (lockedIn.size > 8) return false;
if (lockedIn.size === 8) {
const assignment = resolveAnnexC([...lockedIn]);
if (!assignment) return false;
const ag = assignment[winnerGroup];
if (!ag) return false;
const ss = states.get(ag);
if (!ss) return false;
const result = ss.finished && ss.third != null && ss.possibleTeamIds.size === 1;
return result;
}
if (lockedIn.size + contested.size < 8) return false;
const contestedArr = [...contested];
const need = 8 - lockedIn.size;
const combos = combinations(contestedArr.length, need);
if (combos > 200) return false;
let stableGroup: GroupId | null = null;
for (const indices of enumerateCombinations(contestedArr.length, need)) {
const qGroups: GroupId[] = [...lockedIn, ...indices.map((i) => contestedArr[i])];
if (qGroups.length !== 8) continue;
const assignment = resolveAnnexC(qGroups);
if (!assignment) continue;
const ag = assignment[winnerGroup];
if (!ag) return false;
if (stableGroup === null) stableGroup = ag;
else if (stableGroup !== ag) return false;
}
if (stableGroup === null) return false;
const ss = states.get(stableGroup);
if (!ss) return false;
const result = ss.finished && ss.third != null && ss.possibleTeamIds.size === 1;
return result;
}
// --- Combinatorics helpers ---
function combinations(n: number, k: number): number {
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
let r = 1;
for (let i = 1; i <= k; i++) r = r * (n - i + 1) / i;
return Math.round(r);
}
function* enumerateCombinations(n: number, k: number): Generator<number[]> {
if (k === 0) { yield []; return; }
if (k > n) return;
const idx = Array.from({ length: k }, (_, i) => i);
while (true) {
yield [...idx];
let i = k - 1;
while (i >= 0 && idx[i] === n - k + i) i--;
if (i < 0) break;
idx[i]++;
for (let j = i + 1; j < k; j++) idx[j] = idx[j - 1] + 1;
}
}