Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav, which always links to the generic elo-ratings page. Extended elo-ratings to conditionally show world ranking fields for simulator types that need it (darts_bracket, cs2_major_qualifying_points), then deleted the redundant sport-specific pages. https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
This commit is contained in:
parent
08b17b1b37
commit
f949338ed7
4 changed files with 154 additions and 998 deletions
|
|
@ -99,14 +99,6 @@ export default [
|
|||
"sports-seasons/:id/surface-elo",
|
||||
"routes/admin.sports-seasons.$id.surface-elo.tsx"
|
||||
),
|
||||
route(
|
||||
"sports-seasons/:id/darts-elo",
|
||||
"routes/admin.sports-seasons.$id.darts-elo.tsx"
|
||||
),
|
||||
route(
|
||||
"sports-seasons/:id/cs-elo",
|
||||
"routes/admin.sports-seasons.$id.cs-elo.tsx"
|
||||
),
|
||||
route(
|
||||
"sports-seasons/:id/golf-skills",
|
||||
"routes/admin.sports-seasons.$id.golf-skills.tsx"
|
||||
|
|
|
|||
|
|
@ -1,457 +0,0 @@
|
|||
import { Form, redirect, useLoaderData, useActionData, useNavigation } from 'react-router';
|
||||
import type { Route } from './+types/admin.sports-seasons.$id.cs-elo';
|
||||
|
||||
import { logger } from '~/lib/logger';
|
||||
import { findSportsSeasonById, updateSportsSeason } from '~/models/sports-season';
|
||||
import { findParticipantsBySportsSeasonId } from '~/models/participant';
|
||||
import {
|
||||
getAllParticipantEVsForSeason,
|
||||
batchSaveSourceElos,
|
||||
batchUpsertParticipantEVs,
|
||||
} from '~/models/participant-expected-value';
|
||||
import { batchUpsertParticipantEvSnapshots } from '~/models/ev-snapshot';
|
||||
import { getSimulator, type SimulatorType } from '~/services/simulations/registry';
|
||||
import { calculateEV } from '~/services/ev-calculator';
|
||||
import { DEFAULT_SCORING_RULES } from '~/lib/scoring-types';
|
||||
import { recalculateStandings } from '~/models/scoring-calculator';
|
||||
import { database } from '~/database/context';
|
||||
import * as schema from '~/database/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { Button } from '~/components/ui/button';
|
||||
import { Input } from '~/components/ui/input';
|
||||
import { Label } from '~/components/ui/label';
|
||||
import { Textarea } from '~/components/ui/textarea';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '~/components/ui/card';
|
||||
import { useState } from 'react';
|
||||
import { Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
|
||||
import { normalizeName } from '~/lib/fuzzy-match';
|
||||
|
||||
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
|
||||
return [{ title: `CS2 Elo & HLTV Rankings — ${data?.sportsSeason?.name ?? "Sports Season"} - Brackt Admin` }];
|
||||
}
|
||||
|
||||
export async function loader({ params }: Route.LoaderArgs) {
|
||||
const sportsSeasonId = params.id;
|
||||
|
||||
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
|
||||
if (!sportsSeason) {
|
||||
throw new Response('Sports season not found', { status: 404 });
|
||||
}
|
||||
|
||||
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
||||
const existingEVs = await getAllParticipantEVsForSeason(sportsSeasonId);
|
||||
|
||||
const existingData: Record<string, { elo: number | null; ranking: number | null }> = {};
|
||||
for (const ev of existingEVs) {
|
||||
existingData[ev.participantId] = {
|
||||
elo: ev.sourceElo ?? null,
|
||||
ranking: ev.worldRanking ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
return { sportsSeason, participants, existingData };
|
||||
}
|
||||
|
||||
interface ActionData {
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export async function action({ request, params }: Route.ActionArgs) {
|
||||
const sportsSeasonId = params.id;
|
||||
const formData = await request.formData();
|
||||
|
||||
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
|
||||
if (!sportsSeason) {
|
||||
return { success: false, message: 'Sports season not found' };
|
||||
}
|
||||
|
||||
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
||||
|
||||
const eloInputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number; worldRanking?: number | null }> = [];
|
||||
for (const participant of participants) {
|
||||
const eloVal = formData.get(`elo_${participant.id}`) as string;
|
||||
const rankVal = formData.get(`rank_${participant.id}`) as string;
|
||||
|
||||
if (eloVal && eloVal.trim() !== '') {
|
||||
const elo = Number(eloVal);
|
||||
if (!isNaN(elo) && elo > 0) {
|
||||
const ranking = rankVal && rankVal.trim() !== '' ? Number(rankVal) : null;
|
||||
eloInputs.push({
|
||||
participantId: participant.id,
|
||||
sportsSeasonId,
|
||||
sourceElo: elo,
|
||||
worldRanking: ranking && !isNaN(ranking) && ranking > 0 ? ranking : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (eloInputs.length === 0) {
|
||||
return { success: false, message: 'Please enter an Elo rating for at least one team' };
|
||||
}
|
||||
|
||||
if (!sportsSeason.sport?.simulatorType) {
|
||||
return { success: false, message: 'This sport has no simulator type configured. Set one on the sport in the admin panel.' };
|
||||
}
|
||||
|
||||
if (sportsSeason.simulationStatus === 'running') {
|
||||
return { success: false, message: 'A simulation is already running. Please wait.' };
|
||||
}
|
||||
|
||||
await batchSaveSourceElos(eloInputs);
|
||||
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'running' });
|
||||
|
||||
try {
|
||||
const simulator = getSimulator(sportsSeason.sport.simulatorType as SimulatorType);
|
||||
const results = await simulator.simulate(sportsSeasonId);
|
||||
|
||||
if (results.length === 0) {
|
||||
throw new Error('Simulation returned no results.');
|
||||
}
|
||||
|
||||
const simulatedIds = new Set(results.map(r => r.participantId));
|
||||
const ZERO_PROBS = {
|
||||
probFirst: 0, probSecond: 0, probThird: 0, probFourth: 0,
|
||||
probFifth: 0, probSixth: 0, probSeventh: 0, probEighth: 0,
|
||||
};
|
||||
const evInputs = [
|
||||
...results.map(r => ({
|
||||
participantId: r.participantId,
|
||||
sportsSeasonId,
|
||||
probabilities: r.probabilities,
|
||||
scoringRules: DEFAULT_SCORING_RULES,
|
||||
source: 'elo_simulation' as const,
|
||||
})),
|
||||
...participants
|
||||
.filter(p => !simulatedIds.has(p.id))
|
||||
.map(p => ({
|
||||
participantId: p.id,
|
||||
sportsSeasonId,
|
||||
probabilities: ZERO_PROBS,
|
||||
scoringRules: DEFAULT_SCORING_RULES,
|
||||
source: 'elo_simulation' as const,
|
||||
})),
|
||||
];
|
||||
|
||||
await batchUpsertParticipantEVs(evInputs);
|
||||
|
||||
const seasonSports = await database().query.seasonSports.findMany({
|
||||
where: eq(schema.seasonSports.sportsSeasonId, sportsSeasonId),
|
||||
});
|
||||
await Promise.all(seasonSports.map(({ seasonId }) => recalculateStandings(seasonId)));
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
await batchUpsertParticipantEvSnapshots(
|
||||
results.map(r => ({
|
||||
participantId: r.participantId,
|
||||
sportsSeasonId,
|
||||
snapshotDate: today,
|
||||
probFirst: r.probabilities.probFirst,
|
||||
probSecond: r.probabilities.probSecond,
|
||||
probThird: r.probabilities.probThird,
|
||||
probFourth: r.probabilities.probFourth,
|
||||
probFifth: r.probabilities.probFifth,
|
||||
probSixth: r.probabilities.probSixth,
|
||||
probSeventh: r.probabilities.probSeventh,
|
||||
probEighth: r.probabilities.probEighth,
|
||||
calculatedEV: calculateEV(r.probabilities, DEFAULT_SCORING_RULES),
|
||||
source: r.source,
|
||||
}))
|
||||
);
|
||||
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'idle' });
|
||||
} catch (error) {
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'failed' });
|
||||
logger.error('Error running CS2 major simulation:', error);
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Simulation failed',
|
||||
};
|
||||
}
|
||||
|
||||
return redirect(`/admin/sports-seasons/${sportsSeasonId}/expected-values`);
|
||||
}
|
||||
|
||||
export default function AdminSportsSeasonCsElo() {
|
||||
const { sportsSeason, participants, existingData } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
|
||||
const [eloValues, setEloValues] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
participants.forEach(p => {
|
||||
const d = existingData[p.id];
|
||||
if (d?.elo !== null && d?.elo !== undefined) initial[p.id] = d.elo.toString();
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
const [rankValues, setRankValues] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
participants.forEach(p => {
|
||||
const d = existingData[p.id];
|
||||
if (d?.ranking !== null && d?.ranking !== undefined) initial[p.id] = d.ranking.toString();
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
const [bulkText, setBulkText] = useState('');
|
||||
const [parseResults, setParseResults] = useState<{
|
||||
matched: Array<{ participantId: string; name: string; elo: number; ranking: number | null; inputName: string }>;
|
||||
unmatched: Array<{ inputName: string; elo: number; ranking: number | null }>;
|
||||
} | null>(null);
|
||||
|
||||
function findParticipantMatch(inputName: string) {
|
||||
const normalizedInput = normalizeName(inputName);
|
||||
const normalized = participants.map(p => ({ p, n: normalizeName(p.name) }));
|
||||
|
||||
const exact = normalized.find(({ n }) => n === normalizedInput);
|
||||
if (exact) return exact.p;
|
||||
|
||||
const contains = normalized.find(({ n }) => n.includes(normalizedInput) || normalizedInput.includes(n));
|
||||
if (contains) return contains.p;
|
||||
|
||||
const inputWords = normalizedInput.split(' ').filter(w => w.length > 2);
|
||||
const overlap = normalized.find(({ n }) => {
|
||||
const pWords = n.split(' ').filter(w => w.length > 2);
|
||||
const shared = inputWords.filter(w => pWords.includes(w));
|
||||
return shared.length > 0 && shared.length >= Math.min(inputWords.length, pWords.length) * 0.5;
|
||||
});
|
||||
|
||||
return overlap?.p ?? null;
|
||||
}
|
||||
|
||||
function parseBulkText() {
|
||||
const lines = bulkText.split('\n');
|
||||
const matched: typeof parseResults extends null ? never : NonNullable<typeof parseResults>['matched'] = [];
|
||||
const unmatched: typeof parseResults extends null ? never : NonNullable<typeof parseResults>['unmatched'] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
const match = /^(.+?)[\s,:\t]+(\d{3,5})(?:[\s,:\t]+(\d{1,3}))?\s*$/.exec(trimmed);
|
||||
if (!match) continue;
|
||||
|
||||
const inputName = match[1].trim();
|
||||
const elo = parseInt(match[2], 10);
|
||||
const ranking = match[3] ? parseInt(match[3], 10) : null;
|
||||
|
||||
if (isNaN(elo) || elo < 500 || elo > 5000) continue;
|
||||
if (ranking !== null && (isNaN(ranking) || ranking < 1 || ranking > 256)) continue;
|
||||
|
||||
const participant = findParticipantMatch(inputName);
|
||||
if (participant && !seen.has(participant.id)) {
|
||||
seen.add(participant.id);
|
||||
matched.push({ participantId: participant.id, name: participant.name, elo, ranking, inputName });
|
||||
} else if (!participant) {
|
||||
unmatched.push({ inputName, elo, ranking });
|
||||
}
|
||||
}
|
||||
|
||||
setParseResults({ matched, unmatched });
|
||||
}
|
||||
|
||||
function applyMatches() {
|
||||
if (!parseResults) return;
|
||||
const newElos = { ...eloValues };
|
||||
const newRanks = { ...rankValues };
|
||||
for (const m of parseResults.matched) {
|
||||
newElos[m.participantId] = m.elo.toString();
|
||||
if (m.ranking !== null) {
|
||||
newRanks[m.participantId] = m.ranking.toString();
|
||||
}
|
||||
}
|
||||
setEloValues(newElos);
|
||||
setRankValues(newRanks);
|
||||
setParseResults(null);
|
||||
setBulkText('');
|
||||
}
|
||||
|
||||
const isSubmitting = navigation.state === 'submitting';
|
||||
|
||||
const sortedParticipants = [...participants].toSorted((a, b) => {
|
||||
const rankA = rankValues[a.id] ? parseInt(rankValues[a.id], 10) : null;
|
||||
const rankB = rankValues[b.id] ? parseInt(rankValues[b.id], 10) : null;
|
||||
if (rankA !== null && rankB !== null) return rankA - rankB;
|
||||
if (rankA !== null) return -1;
|
||||
if (rankB !== null) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold mb-2">CS2 Team Elo & HLTV Rankings</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{sportsSeason.sport.name} — {sportsSeason.name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<CardTitle>Bulk Import</CardTitle>
|
||||
<CardDescription>
|
||||
Paste one team per line. Format:{' '}
|
||||
<code>Team Name, 1850, 5</code> (name, Elo, HLTV ranking).
|
||||
HLTV ranking is optional — omit it and the simulator will use Elo order for stage seeding.
|
||||
Team names are fuzzy-matched to participants.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Textarea
|
||||
placeholder={`Natus Vincere, 1850, 1\nFaZe Clan, 1820, 2\nVitality, 1800, 3`}
|
||||
value={bulkText}
|
||||
onChange={e => { setBulkText(e.target.value); setParseResults(null); }}
|
||||
rows={10}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button type="button" variant="outline" onClick={parseBulkText} disabled={!bulkText.trim()}>
|
||||
Parse
|
||||
</Button>
|
||||
|
||||
{parseResults && (
|
||||
<div className="space-y-3">
|
||||
{parseResults.matched.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-emerald-400 mb-2">
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
Matched ({parseResults.matched.length})
|
||||
</div>
|
||||
<div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 divide-y divide-emerald-500/20 text-sm">
|
||||
{parseResults.matched.map(m => (
|
||||
<div key={m.participantId} className="flex justify-between px-3 py-1.5">
|
||||
<span className="text-muted-foreground">{m.inputName}</span>
|
||||
<span className="font-medium">
|
||||
{m.name} → Elo {m.elo}{m.ranking !== null ? `, Rank #${m.ranking}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{parseResults.unmatched.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-amber-700 mb-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
Not matched ({parseResults.unmatched.length}) — enter manually below
|
||||
</div>
|
||||
<div className="rounded-md border border-amber-200 bg-amber-50 divide-y divide-amber-100 text-sm">
|
||||
{parseResults.unmatched.map(u => (
|
||||
<div key={u.inputName} className="flex justify-between px-3 py-1.5">
|
||||
<span>{u.inputName}</span>
|
||||
<span className="font-medium">
|
||||
Elo {u.elo}{u.ranking !== null ? `, Rank #${u.ranking}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{parseResults.matched.length > 0 && (
|
||||
<Button type="button" onClick={applyMatches}>
|
||||
Apply {parseResults.matched.length} matched entries to form
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Team Elo & HLTV Rankings</CardTitle>
|
||||
<CardDescription>
|
||||
Enter each team's Elo rating and HLTV world ranking. Rankings determine which
|
||||
Swiss stage a team enters (1–8 = Stage 3/Legends, 9–16 = Stage 2/Challengers,
|
||||
17–32 = Stage 1/Opening). Saving will automatically run the simulation and update
|
||||
expected values.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form method="post" className="space-y-4">
|
||||
<div className="grid grid-cols-[1fr_100px_80px] gap-x-3 gap-y-2 items-center text-xs font-medium text-muted-foreground mb-1">
|
||||
<span>Team</span>
|
||||
<span>Elo</span>
|
||||
<span>HLTV #</span>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{sortedParticipants.map(participant => (
|
||||
<div key={participant.id} className="grid grid-cols-[1fr_100px_80px] gap-x-3 items-center">
|
||||
<Label htmlFor={`elo_${participant.id}`} className="truncate text-sm">
|
||||
{participant.name}
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
id={`elo_${participant.id}`}
|
||||
name={`elo_${participant.id}`}
|
||||
placeholder="1800"
|
||||
value={eloValues[participant.id] ?? ''}
|
||||
onChange={e =>
|
||||
setEloValues(prev => ({ ...prev, [participant.id]: e.target.value }))
|
||||
}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
name={`rank_${participant.id}`}
|
||||
placeholder="—"
|
||||
value={rankValues[participant.id] ?? ''}
|
||||
onChange={e =>
|
||||
setRankValues(prev => ({ ...prev, [participant.id]: e.target.value }))
|
||||
}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{actionData && !actionData.success && actionData.message && (
|
||||
<div className="text-sm text-destructive">{actionData.message}</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isSubmitting ? 'Saving & Running Simulation...' : 'Save & Run Simulation'}
|
||||
</Button>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>How It Works</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-2">
|
||||
<ol className="list-decimal list-inside space-y-2">
|
||||
<li>Save Elo ratings and HLTV rankings for all teams</li>
|
||||
<li>Rankings determine stage entry (1–8 = Stage 3 Legends, 9–16 = Stage 2 Challengers, 17–32 = Stage 1 Opening)</li>
|
||||
<li>Per-game win probability: p = 1 / (1 + 10^(−ΔElo/400))</li>
|
||||
<li>Swiss stages use Bernoulli series model (Bo1 for Stages 1–2, Bo3 for Stage 3)</li>
|
||||
<li>Champions Stage: 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)</li>
|
||||
<li>Run 10,000 Monte Carlo simulations of the full major</li>
|
||||
<li>Stage 3 exits ranked by W-L record for QP sub-placement (2-3 > 1-3 > 0-3)</li>
|
||||
<li>QP accumulates across both majors; teams ranked 1st–8th by total QP</li>
|
||||
</ol>
|
||||
<div className="mt-4 text-muted-foreground text-xs space-y-1">
|
||||
<div>Stage assignments from event setup override rank-based inference.</div>
|
||||
<div>Once the official field is announced, assign teams to stages in the event setup page.</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,470 +0,0 @@
|
|||
import { Form, redirect, useLoaderData, useActionData, useNavigation } from 'react-router';
|
||||
import type { Route } from './+types/admin.sports-seasons.$id.darts-elo';
|
||||
|
||||
import { logger } from '~/lib/logger';
|
||||
import { findSportsSeasonById, updateSportsSeason } from '~/models/sports-season';
|
||||
import { findParticipantsBySportsSeasonId } from '~/models/participant';
|
||||
import {
|
||||
getAllParticipantEVsForSeason,
|
||||
batchSaveSourceElos,
|
||||
batchUpsertParticipantEVs,
|
||||
} from '~/models/participant-expected-value';
|
||||
import { batchUpsertParticipantEvSnapshots } from '~/models/ev-snapshot';
|
||||
import { getSimulator, type SimulatorType } from '~/services/simulations/registry';
|
||||
import { calculateEV } from '~/services/ev-calculator';
|
||||
import { DEFAULT_SCORING_RULES } from '~/lib/scoring-types';
|
||||
import { recalculateStandings } from '~/models/scoring-calculator';
|
||||
import { database } from '~/database/context';
|
||||
import * as schema from '~/database/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { Button } from '~/components/ui/button';
|
||||
import { Input } from '~/components/ui/input';
|
||||
import { Label } from '~/components/ui/label';
|
||||
import { Textarea } from '~/components/ui/textarea';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '~/components/ui/card';
|
||||
import { useState } from 'react';
|
||||
import { Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
|
||||
import { normalizeName } from '~/lib/fuzzy-match';
|
||||
|
||||
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
|
||||
return [{ title: `Darts Elo & Rankings — ${data?.sportsSeason?.name ?? "Sports Season"} - Brackt Admin` }];
|
||||
}
|
||||
|
||||
export async function loader({ params }: Route.LoaderArgs) {
|
||||
const sportsSeasonId = params.id;
|
||||
|
||||
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
|
||||
if (!sportsSeason) {
|
||||
throw new Response('Sports season not found', { status: 404 });
|
||||
}
|
||||
|
||||
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
||||
const existingEVs = await getAllParticipantEVsForSeason(sportsSeasonId);
|
||||
|
||||
const existingData: Record<string, { elo: number | null; ranking: number | null }> = {};
|
||||
for (const ev of existingEVs) {
|
||||
existingData[ev.participantId] = {
|
||||
elo: ev.sourceElo ?? null,
|
||||
ranking: ev.worldRanking ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
return { sportsSeason, participants, existingData };
|
||||
}
|
||||
|
||||
interface ActionData {
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export async function action({ request, params }: Route.ActionArgs) {
|
||||
const sportsSeasonId = params.id;
|
||||
const formData = await request.formData();
|
||||
|
||||
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
|
||||
if (!sportsSeason) {
|
||||
return { success: false, message: 'Sports season not found' };
|
||||
}
|
||||
|
||||
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
||||
|
||||
// Parse Elo ratings and world rankings from form
|
||||
const eloInputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number; worldRanking?: number | null }> = [];
|
||||
for (const participant of participants) {
|
||||
const eloVal = formData.get(`elo_${participant.id}`) as string;
|
||||
const rankVal = formData.get(`rank_${participant.id}`) as string;
|
||||
|
||||
if (eloVal && eloVal.trim() !== '') {
|
||||
const elo = Number(eloVal);
|
||||
if (!isNaN(elo) && elo > 0) {
|
||||
const ranking = rankVal && rankVal.trim() !== '' ? Number(rankVal) : null;
|
||||
eloInputs.push({
|
||||
participantId: participant.id,
|
||||
sportsSeasonId,
|
||||
sourceElo: elo,
|
||||
worldRanking: ranking && !isNaN(ranking) && ranking > 0 ? ranking : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (eloInputs.length === 0) {
|
||||
return { success: false, message: 'Please enter an Elo rating for at least one participant' };
|
||||
}
|
||||
|
||||
if (!sportsSeason.sport?.simulatorType) {
|
||||
return { success: false, message: 'This sport has no simulator type configured. Set one on the sport in the admin panel.' };
|
||||
}
|
||||
|
||||
if (sportsSeason.simulationStatus === 'running') {
|
||||
return { success: false, message: 'A simulation is already running. Please wait.' };
|
||||
}
|
||||
|
||||
// Persist Elo ratings and world rankings
|
||||
await batchSaveSourceElos(eloInputs);
|
||||
|
||||
// Auto-run simulation
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'running' });
|
||||
|
||||
try {
|
||||
const simulator = getSimulator(sportsSeason.sport.simulatorType as SimulatorType);
|
||||
const results = await simulator.simulate(sportsSeasonId);
|
||||
|
||||
if (results.length === 0) {
|
||||
throw new Error('Simulation returned no results.');
|
||||
}
|
||||
|
||||
// Zero out any participants not in simulation results
|
||||
const simulatedIds = new Set(results.map(r => r.participantId));
|
||||
const ZERO_PROBS = {
|
||||
probFirst: 0, probSecond: 0, probThird: 0, probFourth: 0,
|
||||
probFifth: 0, probSixth: 0, probSeventh: 0, probEighth: 0,
|
||||
};
|
||||
const evInputs = [
|
||||
...results.map(r => ({
|
||||
participantId: r.participantId,
|
||||
sportsSeasonId,
|
||||
probabilities: r.probabilities,
|
||||
scoringRules: DEFAULT_SCORING_RULES,
|
||||
source: 'elo_simulation' as const,
|
||||
})),
|
||||
...participants
|
||||
.filter(p => !simulatedIds.has(p.id))
|
||||
.map(p => ({
|
||||
participantId: p.id,
|
||||
sportsSeasonId,
|
||||
probabilities: ZERO_PROBS,
|
||||
scoringRules: DEFAULT_SCORING_RULES,
|
||||
source: 'elo_simulation' as const,
|
||||
})),
|
||||
];
|
||||
|
||||
await batchUpsertParticipantEVs(evInputs);
|
||||
|
||||
// Refresh projected points in team standings
|
||||
const seasonSports = await database().query.seasonSports.findMany({
|
||||
where: eq(schema.seasonSports.sportsSeasonId, sportsSeasonId),
|
||||
});
|
||||
await Promise.all(seasonSports.map(({ seasonId }) => recalculateStandings(seasonId)));
|
||||
|
||||
// EV snapshot
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
await batchUpsertParticipantEvSnapshots(
|
||||
results.map(r => ({
|
||||
participantId: r.participantId,
|
||||
sportsSeasonId,
|
||||
snapshotDate: today,
|
||||
probFirst: r.probabilities.probFirst,
|
||||
probSecond: r.probabilities.probSecond,
|
||||
probThird: r.probabilities.probThird,
|
||||
probFourth: r.probabilities.probFourth,
|
||||
probFifth: r.probabilities.probFifth,
|
||||
probSixth: r.probabilities.probSixth,
|
||||
probSeventh: r.probabilities.probSeventh,
|
||||
probEighth: r.probabilities.probEighth,
|
||||
calculatedEV: calculateEV(r.probabilities, DEFAULT_SCORING_RULES),
|
||||
source: r.source,
|
||||
}))
|
||||
);
|
||||
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'idle' });
|
||||
} catch (error) {
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'failed' });
|
||||
logger.error('Error running darts simulation:', error);
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Simulation failed',
|
||||
};
|
||||
}
|
||||
|
||||
return redirect(`/admin/sports-seasons/${sportsSeasonId}/expected-values`);
|
||||
}
|
||||
|
||||
export default function AdminSportsSeasonDartsElo() {
|
||||
const { sportsSeason, participants, existingData } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
|
||||
const [eloValues, setEloValues] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
participants.forEach(p => {
|
||||
const d = existingData[p.id];
|
||||
if (d?.elo !== null && d?.elo !== undefined) initial[p.id] = d.elo.toString();
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
const [rankValues, setRankValues] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
participants.forEach(p => {
|
||||
const d = existingData[p.id];
|
||||
if (d?.ranking !== null && d?.ranking !== undefined) initial[p.id] = d.ranking.toString();
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
// Bulk import state: "Player Name, 2099, 1" format (name, elo, optional world ranking)
|
||||
const [bulkText, setBulkText] = useState('');
|
||||
const [parseResults, setParseResults] = useState<{
|
||||
matched: Array<{ participantId: string; name: string; elo: number; ranking: number | null; inputName: string }>;
|
||||
unmatched: Array<{ inputName: string; elo: number; ranking: number | null }>;
|
||||
} | null>(null);
|
||||
|
||||
function findParticipantMatch(inputName: string) {
|
||||
const normalizedInput = normalizeName(inputName);
|
||||
const normalized = participants.map(p => ({ p, n: normalizeName(p.name) }));
|
||||
|
||||
const exact = normalized.find(({ n }) => n === normalizedInput);
|
||||
if (exact) return exact.p;
|
||||
|
||||
const contains = normalized.find(({ n }) => n.includes(normalizedInput) || normalizedInput.includes(n));
|
||||
if (contains) return contains.p;
|
||||
|
||||
const inputWords = normalizedInput.split(' ').filter(w => w.length > 2);
|
||||
const overlap = normalized.find(({ n }) => {
|
||||
const pWords = n.split(' ').filter(w => w.length > 2);
|
||||
const shared = inputWords.filter(w => pWords.includes(w));
|
||||
return shared.length > 0 && shared.length >= Math.min(inputWords.length, pWords.length) * 0.5;
|
||||
});
|
||||
|
||||
return overlap?.p ?? null;
|
||||
}
|
||||
|
||||
function parseBulkText() {
|
||||
// Formats supported:
|
||||
// "Player Name, 2099, 1" (name, elo, world ranking)
|
||||
// "Player Name, 2099" (name, elo — ranking omitted)
|
||||
// "Player Name: 2099: 1" (colon-separated)
|
||||
const lines = bulkText.split('\n');
|
||||
const matched: typeof parseResults extends null ? never : NonNullable<typeof parseResults>['matched'] = [];
|
||||
const unmatched: typeof parseResults extends null ? never : NonNullable<typeof parseResults>['unmatched'] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
// Match "Name, Elo" or "Name, Elo, Ranking" (comma, colon, or tab separated)
|
||||
const match = /^(.+?)[\s,:\t]+(\d{3,5})(?:[\s,:\t]+(\d{1,3}))?\s*$/.exec(trimmed);
|
||||
if (!match) continue;
|
||||
|
||||
const inputName = match[1].trim();
|
||||
const elo = parseInt(match[2], 10);
|
||||
const ranking = match[3] ? parseInt(match[3], 10) : null;
|
||||
|
||||
if (isNaN(elo) || elo < 500 || elo > 5000) continue;
|
||||
if (ranking !== null && (isNaN(ranking) || ranking < 1 || ranking > 256)) continue;
|
||||
|
||||
const participant = findParticipantMatch(inputName);
|
||||
if (participant && !seen.has(participant.id)) {
|
||||
seen.add(participant.id);
|
||||
matched.push({ participantId: participant.id, name: participant.name, elo, ranking, inputName });
|
||||
} else if (!participant) {
|
||||
unmatched.push({ inputName, elo, ranking });
|
||||
}
|
||||
}
|
||||
|
||||
setParseResults({ matched, unmatched });
|
||||
}
|
||||
|
||||
function applyMatches() {
|
||||
if (!parseResults) return;
|
||||
const newElos = { ...eloValues };
|
||||
const newRanks = { ...rankValues };
|
||||
for (const m of parseResults.matched) {
|
||||
newElos[m.participantId] = m.elo.toString();
|
||||
if (m.ranking !== null) {
|
||||
newRanks[m.participantId] = m.ranking.toString();
|
||||
}
|
||||
}
|
||||
setEloValues(newElos);
|
||||
setRankValues(newRanks);
|
||||
setParseResults(null);
|
||||
setBulkText('');
|
||||
}
|
||||
|
||||
const isSubmitting = navigation.state === 'submitting';
|
||||
|
||||
// Sort participants for display: by current rank (ascending), then unranked alphabetically
|
||||
const sortedParticipants = [...participants].toSorted((a, b) => {
|
||||
const rankA = rankValues[a.id] ? parseInt(rankValues[a.id], 10) : null;
|
||||
const rankB = rankValues[b.id] ? parseInt(rankValues[b.id], 10) : null;
|
||||
if (rankA !== null && rankB !== null) return rankA - rankB;
|
||||
if (rankA !== null) return -1;
|
||||
if (rankB !== null) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold mb-2">Darts Elo & World Rankings</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{sportsSeason.sport.name} — {sportsSeason.name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Bulk Import */}
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<CardTitle>Bulk Import</CardTitle>
|
||||
<CardDescription>
|
||||
Paste one player per line. Format:{' '}
|
||||
<code>Player Name, 2099, 1</code> (name, Elo, world ranking).
|
||||
World ranking is optional — omit it and the simulator will use Elo order for seeding.
|
||||
Player names are fuzzy-matched to participants.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Textarea
|
||||
placeholder={`Luke Littler, 2099, 1\nMichael van Gerwen, 1950, 2\nLuke Humphries, 1947, 3`}
|
||||
value={bulkText}
|
||||
onChange={e => { setBulkText(e.target.value); setParseResults(null); }}
|
||||
rows={10}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button type="button" variant="outline" onClick={parseBulkText} disabled={!bulkText.trim()}>
|
||||
Parse
|
||||
</Button>
|
||||
|
||||
{parseResults && (
|
||||
<div className="space-y-3">
|
||||
{parseResults.matched.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-emerald-400 mb-2">
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
Matched ({parseResults.matched.length})
|
||||
</div>
|
||||
<div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 divide-y divide-emerald-500/20 text-sm">
|
||||
{parseResults.matched.map(m => (
|
||||
<div key={m.participantId} className="flex justify-between px-3 py-1.5">
|
||||
<span className="text-muted-foreground">{m.inputName}</span>
|
||||
<span className="font-medium">
|
||||
{m.name} → Elo {m.elo}{m.ranking !== null ? `, Rank #${m.ranking}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{parseResults.unmatched.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-amber-700 mb-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
Not matched ({parseResults.unmatched.length}) — enter manually below
|
||||
</div>
|
||||
<div className="rounded-md border border-amber-200 bg-amber-50 divide-y divide-amber-100 text-sm">
|
||||
{parseResults.unmatched.map(u => (
|
||||
<div key={u.inputName} className="flex justify-between px-3 py-1.5">
|
||||
<span>{u.inputName}</span>
|
||||
<span className="font-medium">
|
||||
Elo {u.elo}{u.ranking !== null ? `, Rank #${u.ranking}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{parseResults.matched.length > 0 && (
|
||||
<Button type="button" onClick={applyMatches}>
|
||||
Apply {parseResults.matched.length} matched entries to form
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Player Elo & Rankings</CardTitle>
|
||||
<CardDescription>
|
||||
Enter each player's Darts Elo and world ranking. World ranking determines bracket seeding
|
||||
(top 32 seeded, rest randomly drawn). Saving will automatically run the simulation and
|
||||
update expected values.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form method="post" className="space-y-4">
|
||||
<div className="grid grid-cols-[1fr_100px_80px] gap-x-3 gap-y-2 items-center text-xs font-medium text-muted-foreground mb-1">
|
||||
<span>Player</span>
|
||||
<span>Elo</span>
|
||||
<span>Rank #</span>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{sortedParticipants.map(participant => (
|
||||
<div key={participant.id} className="grid grid-cols-[1fr_100px_80px] gap-x-3 items-center">
|
||||
<Label htmlFor={`elo_${participant.id}`} className="truncate text-sm">
|
||||
{participant.name}
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
id={`elo_${participant.id}`}
|
||||
name={`elo_${participant.id}`}
|
||||
placeholder="1800"
|
||||
value={eloValues[participant.id] ?? ''}
|
||||
onChange={e =>
|
||||
setEloValues(prev => ({ ...prev, [participant.id]: e.target.value }))
|
||||
}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
name={`rank_${participant.id}`}
|
||||
placeholder="—"
|
||||
value={rankValues[participant.id] ?? ''}
|
||||
onChange={e =>
|
||||
setRankValues(prev => ({ ...prev, [participant.id]: e.target.value }))
|
||||
}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{actionData && !actionData.success && actionData.message && (
|
||||
<div className="text-sm text-destructive">{actionData.message}</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isSubmitting ? 'Saving & Running Simulation...' : 'Save & Run Simulation'}
|
||||
</Button>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>How It Works</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-2">
|
||||
<ol className="list-decimal list-inside space-y-2">
|
||||
<li>Save Elo ratings and world rankings for all 128 players</li>
|
||||
<li>Top 32 seeds placed in fixed bracket positions; remaining 96 randomly drawn per simulation</li>
|
||||
<li>Per-set win probability: p = 1 / (1 + e^(−ΔElo/500))</li>
|
||||
<li>Match win probability via Bernoulli sets model for each round's best-of length</li>
|
||||
<li>Run 50,000 Monte Carlo simulations of the full bracket</li>
|
||||
<li>Distribute probabilities across 1st–8th place buckets</li>
|
||||
<li>Calculate expected fantasy value per player</li>
|
||||
</ol>
|
||||
<div className="mt-4 text-muted-foreground text-xs space-y-1">
|
||||
<div>Round formats: R1 bo3, R2/R3 bo5, R4/QF bo7, SF bo11, Final bo13</div>
|
||||
<div>If world ranking is omitted, players are seeded by Elo order.</div>
|
||||
<div>Once the bracket draw is announced, add players to the bracket event for live simulation.</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -30,7 +30,15 @@ import {
|
|||
} from '~/components/ui/card';
|
||||
import { useState } from 'react';
|
||||
import { Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
|
||||
import { normalizeName } from '~/lib/fuzzy-match';
|
||||
|
||||
// Simulator types that use worldRanking in addition to sourceElo
|
||||
const RANKING_SIMULATOR_TYPES = new Set(['darts_bracket', 'cs2_major_qualifying_points']);
|
||||
|
||||
function rankingLabel(simulatorType: string | null | undefined): string {
|
||||
if (simulatorType === 'cs2_major_qualifying_points') return 'HLTV Rank';
|
||||
return 'World Rank';
|
||||
}
|
||||
|
||||
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
|
||||
return [{ title: `Elo Ratings — ${data?.sportsSeason?.name ?? "Sports Season"} - Brackt Admin` }];
|
||||
|
|
@ -48,14 +56,17 @@ export async function loader({ params }: Route.LoaderArgs) {
|
|||
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
||||
const existingEVs = await getAllParticipantEVsForSeason(sportsSeasonId);
|
||||
|
||||
const existingElos: Record<string, number> = {};
|
||||
const existingData: Record<string, { elo: number | null; ranking: number | null }> = {};
|
||||
for (const ev of existingEVs) {
|
||||
if (ev.sourceElo !== null && ev.sourceElo !== undefined) {
|
||||
existingElos[ev.participantId] = ev.sourceElo;
|
||||
}
|
||||
existingData[ev.participantId] = {
|
||||
elo: ev.sourceElo ?? null,
|
||||
ranking: ev.worldRanking ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
return { sportsSeason, participants, existingElos };
|
||||
const usesRanking = RANKING_SIMULATOR_TYPES.has(sportsSeason.sport?.simulatorType ?? '');
|
||||
|
||||
return { sportsSeason, participants, existingData, usesRanking };
|
||||
}
|
||||
|
||||
interface ActionData {
|
||||
|
|
@ -73,18 +84,30 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
}
|
||||
|
||||
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
|
||||
const usesRanking = RANKING_SIMULATOR_TYPES.has(sportsSeason.sport?.simulatorType ?? '');
|
||||
|
||||
// Parse Elo ratings from form
|
||||
const eloInputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number }> = [];
|
||||
const eloInputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number; worldRanking?: number | null }> = [];
|
||||
for (const participant of participants) {
|
||||
const val = formData.get(`elo_${participant.id}`) as string;
|
||||
if (val && val.trim() !== '') {
|
||||
const elo = Number(val);
|
||||
const eloVal = formData.get(`elo_${participant.id}`) as string;
|
||||
const rankVal = formData.get(`rank_${participant.id}`) as string;
|
||||
|
||||
if (eloVal && eloVal.trim() !== '') {
|
||||
const elo = Number(eloVal);
|
||||
if (!isNaN(elo) && elo > 0) {
|
||||
if (usesRanking) {
|
||||
const ranking = rankVal && rankVal.trim() !== '' ? Number(rankVal) : null;
|
||||
eloInputs.push({
|
||||
participantId: participant.id,
|
||||
sportsSeasonId,
|
||||
sourceElo: elo,
|
||||
worldRanking: ranking && !isNaN(ranking) && ranking > 0 ? ranking : null,
|
||||
});
|
||||
} else {
|
||||
eloInputs.push({ participantId: participant.id, sportsSeasonId, sourceElo: elo });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (eloInputs.length === 0) {
|
||||
return { success: false, message: 'Please enter an Elo rating for at least one participant' };
|
||||
|
|
@ -98,10 +121,8 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
return { success: false, message: 'A simulation is already running. Please wait.' };
|
||||
}
|
||||
|
||||
// Persist Elo ratings
|
||||
await batchSaveSourceElos(eloInputs);
|
||||
|
||||
// Auto-run simulation
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'running' });
|
||||
|
||||
try {
|
||||
|
|
@ -112,8 +133,6 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
throw new Error('Simulation returned no results.');
|
||||
}
|
||||
|
||||
// Zero out any participants not in simulation results
|
||||
const allParticipants = participants;
|
||||
const simulatedIds = new Set(results.map(r => r.participantId));
|
||||
const ZERO_PROBS = {
|
||||
probFirst: 0, probSecond: 0, probThird: 0, probFourth: 0,
|
||||
|
|
@ -127,7 +146,7 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
scoringRules: DEFAULT_SCORING_RULES,
|
||||
source: 'elo_simulation' as const,
|
||||
})),
|
||||
...allParticipants
|
||||
...participants
|
||||
.filter(p => !simulatedIds.has(p.id))
|
||||
.map(p => ({
|
||||
participantId: p.id,
|
||||
|
|
@ -140,13 +159,11 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
|
||||
await batchUpsertParticipantEVs(evInputs);
|
||||
|
||||
// Refresh projected points in team standings
|
||||
const seasonSports = await database().query.seasonSports.findMany({
|
||||
where: eq(schema.seasonSports.sportsSeasonId, sportsSeasonId),
|
||||
});
|
||||
await Promise.all(seasonSports.map(({ seasonId }) => recalculateStandings(seasonId)));
|
||||
|
||||
// EV snapshot
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
await batchUpsertParticipantEvSnapshots(
|
||||
results.map(r => ({
|
||||
|
|
@ -169,7 +186,7 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'idle' });
|
||||
} catch (error) {
|
||||
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'failed' });
|
||||
logger.error('Error running snooker simulation:', error);
|
||||
logger.error('Error running simulation:', error);
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Simulation failed',
|
||||
|
|
@ -179,31 +196,33 @@ export async function action({ request, params }: Route.ActionArgs) {
|
|||
return redirect(`/admin/sports-seasons/${sportsSeasonId}/expected-values`);
|
||||
}
|
||||
|
||||
function normalizeName(name: string): string {
|
||||
return name.toLowerCase().replace(/[^a-z0-9\s]/g, '').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
export default function AdminSportsSeasonEloRatings() {
|
||||
const { sportsSeason, participants, existingElos } = useLoaderData<typeof loader>();
|
||||
const { sportsSeason, participants, existingData, usesRanking } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
|
||||
const [eloValues, setEloValues] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
participants.forEach(p => {
|
||||
const existing = existingElos[p.id];
|
||||
if (existing !== undefined && existing !== null) {
|
||||
initial[p.id] = existing.toString();
|
||||
}
|
||||
const d = existingData[p.id];
|
||||
if (d?.elo !== null && d?.elo !== undefined) initial[p.id] = d.elo.toString();
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
const [rankValues, setRankValues] = useState<Record<string, string>>(() => {
|
||||
const initial: Record<string, string> = {};
|
||||
participants.forEach(p => {
|
||||
const d = existingData[p.id];
|
||||
if (d?.ranking !== null && d?.ranking !== undefined) initial[p.id] = d.ranking.toString();
|
||||
});
|
||||
return initial;
|
||||
});
|
||||
|
||||
// Bulk import state: "Player Name, 2450" format one per line
|
||||
const [bulkText, setBulkText] = useState('');
|
||||
const [parseResults, setParseResults] = useState<{
|
||||
matched: Array<{ participantId: string; name: string; elo: number; inputName: string }>;
|
||||
unmatched: Array<{ inputName: string; elo: number }>;
|
||||
matched: Array<{ participantId: string; name: string; elo: number; ranking: number | null; inputName: string }>;
|
||||
unmatched: Array<{ inputName: string; elo: number; ranking: number | null }>;
|
||||
} | null>(null);
|
||||
|
||||
function findParticipantMatch(inputName: string) {
|
||||
|
|
@ -227,30 +246,33 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
}
|
||||
|
||||
function parseBulkText() {
|
||||
// Format: "Player Name, 2450" or "Player Name: 2450" or "Player Name 2450"
|
||||
const lines = bulkText.split('\n');
|
||||
const matched: Array<{ participantId: string; name: string; elo: number; inputName: string }> = [];
|
||||
const unmatched: Array<{ inputName: string; elo: number }> = [];
|
||||
const matched: Array<{ participantId: string; name: string; elo: number; ranking: number | null; inputName: string }> = [];
|
||||
const unmatched: Array<{ inputName: string; elo: number; ranking: number | null }> = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
// Match "Name, 2450" or "Name: 2450" or "Name 2450" (Elo is a 4-digit integer)
|
||||
const match = /^(.+?)[\s,:\t]+(\d{3,5})\s*$/.exec(trimmed);
|
||||
// Match "Name, Elo" or "Name, Elo, Ranking" (comma/colon/tab separated)
|
||||
const match = usesRanking
|
||||
? /^(.+?)[\s,:\t]+(\d{3,5})(?:[\s,:\t]+(\d{1,3}))?\s*$/.exec(trimmed)
|
||||
: /^(.+?)[\s,:\t]+(\d{3,5})\s*$/.exec(trimmed);
|
||||
if (!match) continue;
|
||||
|
||||
const inputName = match[1].trim();
|
||||
const elo = parseInt(match[2], 10);
|
||||
const ranking = usesRanking && match[3] ? parseInt(match[3], 10) : null;
|
||||
|
||||
if (isNaN(elo) || elo < 500 || elo > 5000) continue;
|
||||
|
||||
const participant = findParticipantMatch(inputName);
|
||||
if (participant && !seen.has(participant.id)) {
|
||||
seen.add(participant.id);
|
||||
matched.push({ participantId: participant.id, name: participant.name, elo, inputName });
|
||||
matched.push({ participantId: participant.id, name: participant.name, elo, ranking, inputName });
|
||||
} else if (!participant) {
|
||||
unmatched.push({ inputName, elo });
|
||||
unmatched.push({ inputName, elo, ranking });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -259,16 +281,33 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
|
||||
function applyMatches() {
|
||||
if (!parseResults) return;
|
||||
const newValues = { ...eloValues };
|
||||
const newElos = { ...eloValues };
|
||||
const newRanks = { ...rankValues };
|
||||
for (const m of parseResults.matched) {
|
||||
newValues[m.participantId] = m.elo.toString();
|
||||
newElos[m.participantId] = m.elo.toString();
|
||||
if (m.ranking !== null) newRanks[m.participantId] = m.ranking.toString();
|
||||
}
|
||||
setEloValues(newValues);
|
||||
setEloValues(newElos);
|
||||
setRankValues(newRanks);
|
||||
setParseResults(null);
|
||||
setBulkText('');
|
||||
}
|
||||
|
||||
const isSubmitting = navigation.state === 'submitting';
|
||||
const simulatorType = sportsSeason.sport?.simulatorType ?? null;
|
||||
const rankLabel = rankingLabel(simulatorType);
|
||||
|
||||
// When ranking is available, sort by rank ascending, then unranked alphabetically
|
||||
const sortedParticipants = usesRanking
|
||||
? [...participants].toSorted((a, b) => {
|
||||
const rankA = rankValues[a.id] ? parseInt(rankValues[a.id], 10) : null;
|
||||
const rankB = rankValues[b.id] ? parseInt(rankValues[b.id], 10) : null;
|
||||
if (rankA !== null && rankB !== null) return rankA - rankB;
|
||||
if (rankA !== null) return -1;
|
||||
if (rankB !== null) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: participants;
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-8">
|
||||
|
|
@ -284,13 +323,29 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
<CardHeader>
|
||||
<CardTitle>Bulk Import</CardTitle>
|
||||
<CardDescription>
|
||||
{usesRanking ? (
|
||||
<>
|
||||
Paste one entry per line. Format:{' '}
|
||||
<code>Name, Elo, {rankLabel}</code> (ranking is optional — omit it and the simulator
|
||||
will use Elo order for seeding). Names are fuzzy-matched to participants.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Paste Elo ratings one per line. Format: <code>Player Name, 2450</code>. Player names
|
||||
are fuzzy-matched to participants. Elo values should be in the 2000–2900 range for snooker.
|
||||
are fuzzy-matched to participants.
|
||||
</>
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Textarea
|
||||
placeholder={`Judd Trump, 2594\nRonnie O'Sullivan, 2441\nMark Selby, 2432`}
|
||||
placeholder={
|
||||
usesRanking
|
||||
? simulatorType === 'cs2_major_qualifying_points'
|
||||
? `Natus Vincere, 1850, 1\nFaZe Clan, 1820, 2\nVitality, 1810, 3`
|
||||
: `Luke Littler, 2099, 1\nMichael van Gerwen, 1950, 2\nLuke Humphries, 1947, 3`
|
||||
: `Judd Trump, 2594\nRonnie O'Sullivan, 2441\nMark Selby, 2432`
|
||||
}
|
||||
value={bulkText}
|
||||
onChange={e => { setBulkText(e.target.value); setParseResults(null); }}
|
||||
rows={8}
|
||||
|
|
@ -312,7 +367,10 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
{parseResults.matched.map(m => (
|
||||
<div key={m.participantId} className="flex justify-between px-3 py-1.5">
|
||||
<span className="text-muted-foreground">{m.inputName}</span>
|
||||
<span className="font-medium">{m.name} → {m.elo}</span>
|
||||
<span className="font-medium">
|
||||
{m.name} → Elo {m.elo}
|
||||
{usesRanking && m.ranking !== null ? `, ${rankLabel} #${m.ranking}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -329,7 +387,10 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
{parseResults.unmatched.map(u => (
|
||||
<div key={u.inputName} className="flex justify-between px-3 py-1.5">
|
||||
<span>{u.inputName}</span>
|
||||
<span className="font-medium">{u.elo}</span>
|
||||
<span className="font-medium">
|
||||
Elo {u.elo}
|
||||
{usesRanking && u.ranking !== null ? `, ${rankLabel} #${u.ranking}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -349,29 +410,58 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Player Elo Ratings</CardTitle>
|
||||
<CardTitle>
|
||||
{usesRanking ? `Player Elo & ${rankLabel}s` : 'Player Elo Ratings'}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Enter each player's current Elo rating. Saving will automatically run the simulation
|
||||
and update expected values. Snooker Elo typically ranges from ~2000 (qualifier level)
|
||||
to ~2600 (world-class).
|
||||
{usesRanking
|
||||
? `Enter each player's Elo and ${rankLabel}. Saving will automatically run the simulation and update expected values.`
|
||||
: 'Enter each player\'s current Elo rating. Saving will automatically run the simulation and update expected values.'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form method="post" className="space-y-4">
|
||||
<div className="space-y-3">
|
||||
{participants.map(participant => (
|
||||
<div key={participant.id} className="grid grid-cols-2 gap-4 items-center">
|
||||
<Label htmlFor={`elo_${participant.id}`}>{participant.name}</Label>
|
||||
{usesRanking && (
|
||||
<div className="grid grid-cols-[1fr_100px_90px] gap-x-3 gap-y-1 items-center text-xs font-medium text-muted-foreground">
|
||||
<span>Player</span>
|
||||
<span>Elo</span>
|
||||
<span>{rankLabel} #</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
{sortedParticipants.map(participant => (
|
||||
<div
|
||||
key={participant.id}
|
||||
className={usesRanking
|
||||
? 'grid grid-cols-[1fr_100px_90px] gap-x-3 items-center'
|
||||
: 'grid grid-cols-2 gap-4 items-center'}
|
||||
>
|
||||
<Label htmlFor={`elo_${participant.id}`} className="truncate text-sm">
|
||||
{participant.name}
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
id={`elo_${participant.id}`}
|
||||
name={`elo_${participant.id}`}
|
||||
placeholder="2450"
|
||||
placeholder={usesRanking ? '1800' : '2450'}
|
||||
value={eloValues[participant.id] ?? ''}
|
||||
onChange={e =>
|
||||
setEloValues(prev => ({ ...prev, [participant.id]: e.target.value }))
|
||||
}
|
||||
className={usesRanking ? 'h-8 text-sm' : undefined}
|
||||
/>
|
||||
{usesRanking && (
|
||||
<Input
|
||||
type="number"
|
||||
name={`rank_${participant.id}`}
|
||||
placeholder="—"
|
||||
value={rankValues[participant.id] ?? ''}
|
||||
onChange={e =>
|
||||
setRankValues(prev => ({ ...prev, [participant.id]: e.target.value }))
|
||||
}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -394,17 +484,18 @@ export default function AdminSportsSeasonEloRatings() {
|
|||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-2">
|
||||
<ol className="list-decimal list-inside space-y-2">
|
||||
<li>Save Elo ratings for all participants</li>
|
||||
<li>Compute per-frame win probability: p = 1 / (1 + e^(−ΔElo/700))</li>
|
||||
<li>Compute match win probability using the Bernoulli frame model for each round's best-of length</li>
|
||||
<li>Run 50,000 Monte Carlo simulations of the full bracket</li>
|
||||
<li>Save Elo ratings{usesRanking ? ` and ${rankLabel}s` : ''} for all participants</li>
|
||||
<li>Compute per-game win probability from Elo difference</li>
|
||||
<li>Compute match win probability using the Bernoulli model for each round's format</li>
|
||||
<li>Run Monte Carlo simulations of the full event</li>
|
||||
<li>Distribute probabilities across 1st–8th place buckets</li>
|
||||
<li>Calculate expected fantasy value per player</li>
|
||||
</ol>
|
||||
<div className="mt-4 text-muted-foreground text-xs space-y-1">
|
||||
<div>Round frames: R32 best-of-19, R16/QF best-of-25, SF best-of-33, Final best-of-35</div>
|
||||
<div>World rankings (for pre-bracket draws) are hardcoded in the simulator.</div>
|
||||
{usesRanking && (
|
||||
<div className="mt-4 text-muted-foreground text-xs">
|
||||
{rankLabel} is optional — if omitted, the simulator uses Elo order for seeding.
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue