* Fix flex spot count in draft room Teams Drafted view
The flexSpots column in the database defaults to 0 and was never
populated, causing the Teams Drafted grid to always show "0 of 0 flex".
Calculate numFlexPicks dynamically in the loader as
max(0, draftRounds - seasonSports.length) so teams see the correct
flex count (e.g. 7 rounds - 5 sports = 2 flex).
https://claude.ai/code/session_01CSzF4aWuyppGBDqM4MJmhc
* Clean up draft room flex calculation area
- Fix bug: force pick dialog now uses its own isolated search/sport
filter state so it no longer mutates the main participants tab filters
- TeamsDraftedGrid: remove dead first pass in flexPicksByTeam memo,
trim season prop to numFlexPicks only, drop unused type field from
picks sport shape
- Loader: derive userAutodraftSettings from already-loaded
autodraftSettings list, eliminating a redundant DB query
- Extract shared transformedPicks, transformedParticipants, and
seasonSportsData into their own useMemos so both eligibility memos
reuse them instead of duplicating the work
- Memoize draftGrid, draftedParticipantIds, and uniqueSports which
were being recomputed on every render
https://claude.ai/code/session_01CSzF4aWuyppGBDqM4MJmhc
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Include participant EV/futures data in data sync export/import
The export now includes the full participantExpectedValues records
(placement probabilities, source, sourceOdds) alongside participants.
On import, EV records are upserted in merge mode and created fresh in
replace mode (cascade handles cleanup). Backward-compatible with older
exports that lack the participantExpectedValues field.
https://claude.ai/code/session_01TVzuuDR7jPtmihaXTrsX7B
* Address all data-sync code review findings
- Wrap importSportsDataFromJSON in a db.transaction() so any mid-import
failure rolls back cleanly instead of leaving partial data
- Add zod validation of imported JSON before any DB writes, giving a
clear error on malformed/incompatible files
- Fix N+1 queries: build participantIdMap during participant import so
the EV and results sections resolve IDs from memory, not extra queries
- Fix merge mode silently skipping existing participants — now updates
shortName, externalId, and expectedValue
- Add participantResults to export/import (was deleted in replace mode
but never exported, so results were permanently lost)
- Restore calculatedAt timestamp on EV import instead of defaulting to
now(); stored as ISO string in the export for portability
- Document that onDelete:cascade covers participantExpectedValues and
participantResults when participants is deleted; remove the now-
redundant explicit participantResults delete from replace mode
- Bump export version to 1.1; old v1.0 files still import cleanly since
participantExpectedValues, participantResults, and calculatedAt are
all optional in the zod schema
- Collapse all six DB fetches in exportSportsDataToJSON into one
Promise.all for parallel execution
- Add countAllParticipants() and countAllParticipantEVs() model funcs
- Show Participants and EV Records counts on the dashboard stat cards
- Replace raw DOM form creation/submit in handleImport with useFetcher,
giving proper loading state, no full-page reload, and type-safe data
- Remove dead export intent handler from the action function
https://claude.ai/code/session_01TVzuuDR7jPtmihaXTrsX7B
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add push notifications implementation plan
Documents the approach for adding a browser Notification API toggle
to the draft page sidebar, including files to create/modify and
edge cases to handle.
https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69
* Add browser push notifications toggle to draft page
Adds a Notifications toggle in the draft sidebar (below Autodraft)
that uses the Browser Notification API to alert users when a pick is
made or when it's their turn, while the tab is not focused.
- New useDraftNotifications hook for state, permission, and localStorage
- New NotificationSettings component with Switch toggle
- Fires "It's your turn to pick!" when the next pick is the user's
- Fires "{Team} picked {Player}" for all other picks
- Gracefully hides toggle when Notification API is unavailable
https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69
* Fix all code review issues with push notifications
- Extract snake draft order calculation to shared getTeamForPick()
helper in lib/draft-order.ts, removing the duplicated logic
- Fix notification firing on user's own picks (guard with team id check)
- Fix notification firing after draft is complete (early return)
- Use a ref for sendNotification to prevent full socket handler
re-registration every time the toggle is changed
- Add permission drift listener via Permissions API so the UI reacts
if the user revokes notification permission in browser settings
- Add SSR guard for document.hidden in sendNotification
- Remove redundant isSupported prop from NotificationSettings;
derive unsupported state from permissionState === "unsupported"
- Move NotificationSettings out of QueueSection prop-drilling path;
render it via a new settingsSection slot on DraftSidebar instead
https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69
* Fix second round of notification code review issues
- Add My Turn Only / All Picks mode granularity so users can choose
to only be notified when it's their pick, or for every pick
- Remove double top-border by stripping leftover border-t/pt-4/mt-4
wrapper from NotificationSettings (now provided by DraftSidebar)
- Remove unused isSupported from hook return value
- Add n.onclick = () => window.focus() so clicking a notification
brings the draft tab back into focus
- Scope localStorage keys to userId to avoid shared-browser conflicts
(keys now: draftNotifications-{userId}-{seasonId})
- Add notificationsModeRef alongside sendNotificationRef so mode
changes don't trigger full socket handler re-registration
https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69
---------
Co-authored-by: Claude <noreply@anthropic.com>
The loader was grabbing seasonSports[0] blindly instead of filtering by
the current league, causing a 404 when the first linked fantasy season
belonged to a different league.
https://claude.ai/code/session_01Mq6BqFhiYFuJyDcc8ueVJc
Co-authored-by: Claude <noreply@anthropic.com>
When draftSlots is empty (pre-draft state), dividing by zero caused
Math.ceil to return Infinity. Guard the division to fall back to round 1.
https://claude.ai/code/session_017mLmGc5wTrESaDeRQHkSPy
Co-authored-by: Claude <noreply@anthropic.com>
* Show leagues where user is a member regardless of team assignment
The homepage now uses a union query to show leagues where the user
either has a team in the current season OR is a commissioner. Previously,
commissioners without a team could not see their leagues on the homepage.
https://claude.ai/code/session_01E3ugKTfatkEc5TcDGXvHiW
* Fix stale empty state card title in home route
Update 'No Active Leagues' to 'No Leagues' to match the updated
description which is now about membership rather than active seasons.
https://claude.ai/code/session_01E3ugKTfatkEc5TcDGXvHiW
* Fix union import: use two queries with JS deduplication
drizzle-orm 0.36.x does not export a standalone union() function.
Replace with two awaited queries merged via a Map (dedup by id),
then sorted by createdAt descending in JS.
https://claude.ai/code/session_01E3ugKTfatkEc5TcDGXvHiW
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Update how-to-play scoring rules to match standard scoring
- Update placement points: 1st 100, 2nd 70, 3rd-4th 45, 5th-8th 20
- Add Counter-Strike to the special majors scoring section alongside Golf & Tennis
- Add qualifying points breakdown (8/5/3/2/1) per major tournament
https://claude.ai/code/session_01JUAqVZgo7M7XRBLzpeaWpH
* Fix scoring to show all 8 individual placements correctly
Display each placement (1st-8th) with its own point value rather than
grouping/averaging: 100, 70, 50, 40, 25, 25, 15, 15
https://claude.ai/code/session_01JUAqVZgo7M7XRBLzpeaWpH
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add implementation plan for commissioner-without-team feature
https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3
* Allow commissioners to exist without owning a team
- Add opt-out checkbox on league creation ("I want to play in this league")
so the creator can be commissioner-only without claiming a team
- Add Commissioner Management card to league settings with add/remove
commissioner UI; guards against removing the last commissioner
- Add countCommissionersByLeagueId model helper for the last-commissioner guard
- Show "No team" indicator on the league homepage next to commissioners
who don't own a team in the current season
https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3
* Fix code review issues in commissioner management
- Add success/error feedback banners to commissioner add/remove actions
- Gate allUsers query to admin-only (prevents exposing all users to non-admin commissioners)
- Prevent commissioner self-removal in both action (server) and UI (client)
- Add "(you)" label next to current user in commissioner list
- Remove all unnecessary `any` type casts in favor of inferred types
https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3
* Allow commissioners to add league members as co-commissioners
Non-admin commissioners can now add users who already own a team in
the league as co-commissioners. Admins still see the full user list.
Previously the add-commissioner form was admin-only.
https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Hide EV column from draft board available participants table
https://claude.ai/code/session_016oJK1gmWZ48YWEZmVqm6f9
* Clean up dead expectedValue references after hiding EV column
- Remove expectedValue from AvailableParticipantsSection interface
- Remove EV column from Force Manual Pick commissioner dialog
- Remove expectedValue from participants loader SELECT and parsing step
- Retain ORDER BY expectedValue for default sort order
https://claude.ai/code/session_016oJK1gmWZ48YWEZmVqm6f9
---------
Co-authored-by: Claude <noreply@anthropic.com>
* fix: remove probability sum validation and add batch save with total EV
- Remove the requirement that manual probabilities sum to 1.0, allowing
partial distributions (e.g. when a participant has <100% chance of top 8)
- Replace per-row save buttons with a single "Save All" button that submits
all participants at once
- Add a Total EV row at the bottom of the table summing all participant EVs
- Update action to batch process all participants from a single form submission
https://claude.ai/code/session_01WHRynBCcugSK7HHEmN6Yuy
* fix: validate participantIds server-side instead of trusting form input
Fetch participants from the DB in the action using the season ID from
the URL params, eliminating the untrusted participantIds hidden field.
Remove the now-unused hidden input from the frontend form.
https://claude.ai/code/session_01WHRynBCcugSK7HHEmN6Yuy
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add bulk import to futures odds page
Adds a textarea where admins can paste odds from FanDuel, DraftKings,
OddsChecker, or any site. A client-side parser extracts American odds
from each line and fuzzy-matches team names to participants (exact,
substring, and word-overlap matching). Shows matched/unmatched results
before applying to the individual input fields.
https://claude.ai/code/session_01JvgcqKSJZ36bEztfg6CkWP
* Code review fixes for futures-odds page
- Remove unused upsertParticipantEVWithNormalization import
- Remove debug console.log statements left in save action
- Move normalizeName to module level (pure function, no component deps)
- Pre-compute normalized participant names once in findParticipantMatch
instead of re-normalizing across three separate passes
- Fix array index key on unmatched list to use composite string key
- Drop unused result variable from upsertParticipantEV call
https://claude.ai/code/session_01JvgcqKSJZ36bEztfg6CkWP
---------
Co-authored-by: Claude <noreply@anthropic.com>
* feat: sync odds-based EV to participants table for draft room ranking
When admin enters futures odds or manual probabilities, the calculated EV
is now synced from participantExpectedValues to participants.expectedValue.
This closes the gap where EVs were calculated but never reflected in the
draft room ranking. Also changes expectedValue from integer to decimal(10,2)
for better precision, and displays "—" for participants with no odds data.
https://claude.ai/code/session_01JWG2zg2EMzCn6RgEufPC1T
* fix: correct expectedValue type to string in participants route
Missed instance of `expectedValue: 0` (number) that failed typecheck
after schema change from integer to decimal.
https://claude.ai/code/session_01JWG2zg2EMzCn6RgEufPC1T
---------
Co-authored-by: Claude <noreply@anthropic.com>
- ICM tests: fix single participant, zero probabilities, and 2-participant
tests to account for simulation only filling min(participants, 8) positions
- TeamScoreBreakdown tests: use getAllByText for "150.0" which now appears
in both the header and the Actual Points summary card
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The implementation and rest of the system (ICM calculator, probability
updater) use decimals (0-1) for probabilities, but the tests were using
percentages (0-100). Updated tests and docs to match.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add FIFA_48 bracket template with 12 groups of 4, knockout stage of 32
- Add tournament groups schema, model, and GroupStageDisplay component
- Add projected/expected value scoring to standings and team breakdowns
- Add docker-compose for local PostgreSQL development
- Move DRAFT_ORDER_IMPLEMENTATION.md to plans directory
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Added loader and action functions for managing expected values in sports seasons.
- Implemented UI for recalculating probabilities based on participant results.
- Created a service to update probabilities after results are finalized, including handling finished and unfinished participants.
- Developed tests for the probability updater service to ensure correct functionality.
- Introduced a preview feature to show potential changes before applying updates.
Implements Phase 5.2 of the EV system with Harville-Malmuth Independent Chip Model
for calculating participant placement probabilities from futures odds.
## Key Features
### ICM Probability Calculator
- Implements Harville-Malmuth method for distributing probabilities
- Converts American odds to championship probabilities
- Generates P(1st) through P(8th) for all participants
- Column-normalized: each placement sums to 100% across all teams
- Works with any number of participants (not limited to 8)
### Admin UI - Futures Odds Entry
- Enter American odds (e.g., +550, -200) for championship futures
- Live preview of ICM-calculated probability distributions
- Displays all 8 placement probabilities
- Persists odds for editing on subsequent visits
- Automatic probability normalization (removes bookmaker vig)
### Database Schema Updates
- Renamed participant_expected_values.season_id → sports_season_id
- Updated foreign key to reference sports_seasons instead of seasons
- Added source_odds field to store original futures odds
- Migration 0025: Column rename and FK update
- Migration 0026: Add source_odds field
### Model Layer
- participant-expected-value: CRUD operations for probability distributions
- Supports multiple probability sources (manual, futures_odds, elo_simulation)
- Automatic EV calculation based on league scoring rules
- Probability validation and normalization
### Service Layer
- icm-calculator: Harville-Malmuth probability distribution
- probability-engine: Odds conversion and Elo utilities (for future use)
- bracket-simulator: Monte Carlo simulation (for future hybrid approach)
- ev-calculator: Expected value computation from probabilities
## Technical Details
- Uses exponential decay favoring top positions for strong teams
- Preserves championship probability ordering in final distributions
- Row sums vary (strong teams ~100%, weak teams lower)
- All probabilities between 0-1, mathematically valid
- Comprehensive test suite: 97 tests passing
## Future Enhancements
- Hybrid approach: ICM pre-playoffs, bracket simulation during playoffs
- Integration with league-specific scoring rules
- Historical probability tracking for accuracy analysis
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Added recharts dependency to package.json for data visualization.
- Implemented PointProgressionChart component to display team point progression over time.
- Updated scoring-system.md to reflect completion of historical views and added implementation notes.
- Created unit tests for PointProgressionChart to ensure correct rendering and data handling.
- Developed season completion detection and percentage calculation functions in season-helpers.server.ts.
- Added tests for season completion logic and point progression data formatting.
- Enhanced league loader to fetch necessary data for current season and teams.
- Created `TeamScoreBreakdown` component to display all drafted participants, their placements, and points.
- Added new route for team breakdown at `/leagues/:leagueId/standings/:seasonId/teams/:teamId`.
- Enhanced `getTeamScoreBreakdown` model to include `sportsSeasonId` for grouping.
- Updated `StandingsTable` to include clickable team name links.
- Added functionality to finalize brackets in playoff events, including error handling and recalculating standings.
- Implemented tests for `TeamScoreBreakdown` component to ensure proper rendering and functionality.
- Updated routing to support new team breakdown feature and ensure seamless navigation.
- Added a new route for league standings: `/leagues/:leagueId/standings/:seasonId`
- Implemented the `StandingsTable` component to display team standings with ranking, points, and placement breakdown.
- Integrated tiebreaker logic for ranking teams based on total points and placements.
- Enhanced the league home page with a link to view standings.
- Updated scoring system documentation to reflect the new standings features.
- Added comprehensive tests for tiebreaker logic and `StandingsTable` component.
- Created shared types for standings to be used in both server and client code.
- Added `QualifyingPointsStandings` component to display standings based on qualifying points.
- Introduced scoring rules and projected points calculation for participants.
- Implemented tie handling for rankings and displayed appropriate UI elements based on finalization status.
- Created tests for qualifying points configuration, accumulation logic, ranking logic, and scoring workflow.
- Developed scoring calculator tests to validate fantasy points conversion from qualifying points.
- Established qualifying points management functions including initialization, retrieval, updating, and resetting of points.
- Introduced `generateStandardSeeding()` function to create proper tournament matchups (e.g., 1v16, 8v9).
- Added comprehensive tests for 4, 8, 16, and 32-team brackets to ensure correct seeding and balance.
- Updated testing instructions to reflect new features and improvements in bracket generation.
- Fixed issues with sequential seeding and ensured all matchups sum to n+1 for balance.
- Implemented batch winner selection and duplicate participant prevention for improved user experience.
- Enhanced fantasy points display on event pages for better visibility of participant results.
- Added a comprehensive plan for bracket expansion, including support for 4, 8, 16, 32, and 68 team formats.
- Introduced a template-based bracket system with predefined templates for NCAA March Madness, NFL Playoffs, NBA Playoffs, and simple brackets.
- Updated UI flow for bracket creation, allowing admins to select templates and assign participants flexibly.
- Enhanced database schema to accommodate new scoring rules and bracket templates.
- Proposed updates to scoring logic to handle non-scoring rounds and participant placements correctly.
- Documented implementation phases for gradual rollout of new features.
- Addressed critical bugs in the playoff event processing and scoring logic, ensuring proper advancement and scoring rules across multiple leagues.
- Created ScoringRulesEditor component with 8 placement point inputs
- Added scoring-types.ts for shared client/server types
- Integrated scoring rules into league settings page
- Integrated scoring rules into league creation form
- Added validation for point values (0-1000 range)
- Disabled editing in settings after draft starts
- Included helpful tips and preview display
Phase 1.3 complete
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
The timer system runs outside the request context and uses its own database
connection. This fix allows isParticipantDrafted to accept an optional db
parameter so it works in both request handlers and timer contexts.
Fixes: DatabaseContext not set error during autopick
- Add scoringPattern and eventType enums for 4 scoring patterns
(single_elimination_playoff, page_playoff, season_standings, qualifying_points)
- Add 8 placement point fields to seasons table (1st-8th) with defaults
- Add scoring pattern fields to sportsSeasons table (scoringPattern, totalMajors, etc.)
- Create 10 new tables:
- scoring_events: Individual games, tournaments, races
- event_results: Participant results per event
- playoff_matches: Bracket tracking for playoffs
- participant_qualifying_totals: QP aggregation for golf/tennis
- qualifying_point_config: Configurable QP values per sport
- team_sport_scores: Aggregated scores per sport
- team_standings: Current standings with tiebreakers
- team_standings_snapshots: Daily snapshots for 7-day tracking
- participant_expected_values: EV calculations per league
- participant_season_results: F1 current points tracking
- Add all necessary relations for new tables
- Update test fixtures with new required scoring fields