import { Form, redirect, useLoaderData, useActionData, useNavigation } from 'react-router'; import type { Route } from './+types/admin.sports-seasons.$id.futures-odds'; import { findSportsSeasonById } from '~/models/sports-season'; import { findParticipantsBySportsSeasonId } from '~/models/participant'; import { getAllParticipantEVsForSeason } from '~/models/participant-expected-value'; 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 { calculateICMFromOdds, icmResultToArray, } from '~/services/icm-calculator'; import { upsertParticipantEV } from '~/models/participant-expected-value'; import { Loader2, Info, CheckCircle2, AlertCircle } from 'lucide-react'; 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); // Create map of participant ID to existing odds (if source is futures_odds) const existingOdds = new Map( existingEVs .filter(ev => ev.source === 'futures_odds' && ev.sourceOdds !== null) .map(ev => [ev.participantId, ev.sourceOdds]) ); return { sportsSeason: sportsSeason as typeof sportsSeason & { sport: { id: string; name: string; type: string; slug: string } }, participants, existingOdds, }; } interface ActionData { success?: boolean; message?: string; preview?: { participantId: string; participantName: string; odds: number; probabilities: number[]; }[]; } export async function action({ request, params }: Route.ActionArgs) { const sportsSeasonId = params.id; const formData = await request.formData(); const intent = formData.get('intent') as string; const sportsSeason = await findSportsSeasonById(sportsSeasonId); if (!sportsSeason) { return { success: false, message: 'Sports season not found' }; } const participants = await findParticipantsBySportsSeasonId(sportsSeasonId); // Parse odds from form const futuresOdds: Array<{ participantId: string; odds: number; name: string }> = []; for (const participant of participants) { const oddsValue = formData.get(`odds_${participant.id}`) as string; if (oddsValue && oddsValue.trim() !== '') { const odds = Number(oddsValue); if (!isNaN(odds)) { futuresOdds.push({ participantId: participant.id, odds, name: participant.name, }); } } } if (futuresOdds.length === 0) { return { success: false, message: 'Please enter odds for at least one participant' }; } try { // Calculate ICM probabilities from odds const icmResults = calculateICMFromOdds( futuresOdds.map(({ participantId, odds }) => ({ participantId, odds })) ); if (intent === 'preview') { // Return preview data const preview = futuresOdds.map(({ participantId, odds, name }) => { const icmResult = icmResults.get(participantId)!; return { participantId, participantName: name, odds, probabilities: icmResultToArray(icmResult), }; }); return { success: true, preview }; } if (intent === 'save') { // Use default scoring rules (EVs will be recalculated per league) const scoringRules = { pointsFor1st: 100, pointsFor2nd: 70, pointsFor3rd: 50, pointsFor4th: 40, pointsFor5th: 25, pointsFor6th: 25, pointsFor7th: 15, pointsFor8th: 15, }; // Save probabilities from preview (passed through form) // This ensures saved values match exactly what user saw in preview for (const { participantId, odds } of futuresOdds) { // Read probabilities from form data (preview results) const probFirst = parseFloat(formData.get(`prob_first_${participantId}`) as string) || 0; const probSecond = parseFloat(formData.get(`prob_second_${participantId}`) as string) || 0; const probThird = parseFloat(formData.get(`prob_third_${participantId}`) as string) || 0; const probFourth = parseFloat(formData.get(`prob_fourth_${participantId}`) as string) || 0; const probFifth = parseFloat(formData.get(`prob_fifth_${participantId}`) as string) || 0; const probSixth = parseFloat(formData.get(`prob_sixth_${participantId}`) as string) || 0; const probSeventh = parseFloat(formData.get(`prob_seventh_${participantId}`) as string) || 0; const probEighth = parseFloat(formData.get(`prob_eighth_${participantId}`) as string) || 0; // Use upsertParticipantEV (not WithNormalization) because ICM probabilities // are already correct - they sum to <1.0 for teams unlikely to finish top 8 await upsertParticipantEV({ participantId, sportsSeasonId: sportsSeasonId, probabilities: { probFirst, probSecond, probThird, probFourth, probFifth, probSixth, probSeventh, probEighth, }, scoringRules, source: 'futures_odds', sourceOdds: odds, }); } return redirect(`/admin/sports-seasons/${sportsSeasonId}/expected-values`); } return { success: false, message: 'Invalid intent' }; } catch (error) { console.error('Error generating probabilities:', error); return { success: false, message: error instanceof Error ? error.message : 'Failed to generate probabilities', }; } } function normalizeName(name: string): string { return name.toLowerCase().replace(/[^a-z0-9\s]/g, '').replace(/\s+/g, ' ').trim(); } export default function AdminSportsSeasonFuturesOdds() { const { sportsSeason, participants, existingOdds } = useLoaderData(); const actionData = useActionData(); const navigation = useNavigation(); // Initialize odds values from existing data const [oddsValues, setOddsValues] = useState>(() => { const initial: Record = {}; participants.forEach(p => { const existingOdd = existingOdds.get(p.id); if (existingOdd !== undefined && existingOdd !== null) { initial[p.id] = existingOdd.toString(); } }); return initial; }); // Bulk import state const [bulkText, setBulkText] = useState(''); const [parseResults, setParseResults] = useState<{ matched: Array<{ participantId: string; name: string; odds: number; inputName: string }>; unmatched: Array<{ inputName: string; odds: number }>; } | null>(null); function findParticipantMatch(inputName: string) { const normalizedInput = normalizeName(inputName); // Pre-compute normalized names once for all three passes const normalized = participants.map(p => ({ p, n: normalizeName(p.name) })); // Exact match const exact = normalized.find(({ n }) => n === normalizedInput); if (exact) return exact.p; // Contains match (one contains the other) const contains = normalized.find(({ n }) => n.includes(normalizedInput) || normalizedInput.includes(n)); if (contains) return contains.p; // Word-overlap match (at least half the significant words overlap) 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'); // Match lines that end with an American-style odds number (+/- then 2–6 digits) const oddsPattern = /^(.+?)\s+([+-]\d{2,6})\s*$/; const matched: Array<{ participantId: string; name: string; odds: number; inputName: string }> = []; const unmatched: Array<{ inputName: string; odds: number }> = []; const seenParticipants = new Set(); for (const line of lines) { const trimmed = line.trim(); if (!trimmed || trimmed.length < 3) continue; const match = oddsPattern.exec(trimmed); if (!match) continue; const inputName = match[1].trim(); const odds = parseInt(match[2], 10); if (isNaN(odds)) continue; const participant = findParticipantMatch(inputName); if (participant && !seenParticipants.has(participant.id)) { seenParticipants.add(participant.id); matched.push({ participantId: participant.id, name: participant.name, odds, inputName }); } else if (!participant) { unmatched.push({ inputName, odds }); } } setParseResults({ matched, unmatched }); } function applyMatches() { if (!parseResults) return; const newOdds = { ...oddsValues }; for (const m of parseResults.matched) { newOdds[m.participantId] = m.odds.toString(); } setOddsValues(newOdds); setParseResults(null); setBulkText(''); } const isSubmitting = navigation.state === 'submitting'; const isGenerating = isSubmitting && navigation.formData?.get('intent') === 'preview'; const isSaving = isSubmitting && navigation.formData?.get('intent') === 'save'; return (

Futures Odds Entry

{sportsSeason.sport.name} - {sportsSeason.name}

{/* Bulk Import */} Bulk Import Paste odds from FanDuel, DraftKings, OddsChecker, or any site. Each line should end with American odds (e.g. Kansas City Chiefs +450). Team names are fuzzy-matched to participants.