diff --git a/src/features/tournaments/server.ts b/src/features/tournaments/server.ts index 8fdbf81..5219101 100644 --- a/src/features/tournaments/server.ts +++ b/src/features/tournaments/server.ts @@ -436,10 +436,64 @@ async function calculateGroupStandings(groupId: string): Promise>(); + + for (const match of completedMatches) { + if (!match.home || !match.away) continue; + + if (!h2hRecords.has(match.home.id)) { + h2hRecords.set(match.home.id, new Map()); + } + if (!h2hRecords.has(match.away.id)) { + h2hRecords.set(match.away.id, new Map()); + } + + const homeH2H = h2hRecords.get(match.home.id)!; + const awayH2H = h2hRecords.get(match.away.id)!; + + if (!homeH2H.has(match.away.id)) { + homeH2H.set(match.away.id, { wins: 0, cupDiff: 0 }); + } + if (!awayH2H.has(match.home.id)) { + awayH2H.set(match.home.id, { wins: 0, cupDiff: 0 }); + } + + const homeRecord = homeH2H.get(match.away.id)!; + const awayRecord = awayH2H.get(match.home.id)!; + + const cupDiff = match.home_cups - match.away_cups; + homeRecord.cupDiff += cupDiff; + awayRecord.cupDiff -= cupDiff; + + if (match.home_cups > match.away_cups) { + homeRecord.wins++; + } else { + awayRecord.wins++; + } + } + const sortedStandings = Array.from(standings.values()).sort((a, b) => { if (b.wins !== a.wins) return b.wins - a.wins; + if (b.cup_differential !== a.cup_differential) return b.cup_differential - a.cup_differential; - return b.cups_for - a.cups_for; + + if (b.cups_for !== a.cups_for) return b.cups_for - a.cups_for; + + const aH2H = h2hRecords.get(a.team.id); + const bH2H = h2hRecords.get(b.team.id); + + if (aH2H && bH2H) { + const aVsB = aH2H.get(b.team.id); + const bVsA = bH2H.get(a.team.id); + + if (aVsB && bVsA) { + if (aVsB.wins !== bVsA.wins) return bVsA.wins - aVsB.wins; + + if (aVsB.cupDiff !== -bVsA.cupDiff) return aVsB.cupDiff - (-bVsA.cupDiff); + } + } + + return a.team.id.localeCompare(b.team.id); }); sortedStandings.forEach((standing, index) => {