Commit graph

251 commits

Author SHA1 Message Date
Chris Parsons
2b680d7272
Replace isDraftable boolean with draftOn/draftOff date range (#263)
Fixes #262

* Replace isDraftable boolean with draftOn/draftOff date fields on sport seasons

Admins can now schedule when a sport season becomes available for drafting
by setting explicit open and close dates instead of a manual toggle.

https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc

* Address code review feedback on draft window implementation

- sports-data-sync: use unambiguous past placeholder dates for synced seasons,
  with a comment explaining the intent
- sports-season model: remove redundant top-level lte/gte imports (callback
  form already supplies them)
- _journal.json: add missing trailing newline
- sports-season test: mock ~/database/schema instead of stubbing all drizzle
  builder functions, matching the established pattern in the codebase
- admin list: compute today once in component body instead of per-row

https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc

* Fix: restore lte/gte imports removed in review cleanup

The relational query where-callback in this version of Drizzle does not
expose lte/gte as helper args, so they must be imported from drizzle-orm.
Removing them broke CI TypeScript.

https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 22:09:52 -04:00
Chris Parsons
fbeee4ed15
Refactor playoff event processing and improve code clarity (#261)
* Remove redundant processPlayoffEvent loop from finalize-bracket action

All bracket rounds are already processed (with scoring and Discord
notifications) as each match winner is set via set-winner/set-round-winners.
By the time the Finalize button is clicked, placements are current and
standings are up to date. The re-processing loop was firing recalculations
and Discord notifications once per round needlessly.

The finalize action now only assigns 0 points to non-bracket participants,
marks the event complete, and runs one final standings recalculation.

https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5

* Fix stale comment in finalize-bracket action

The template is now fetched only as a validity guard, not for round
order iteration (which was removed in the previous commit).

https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5

* Fix complete-round redundant Discord/recalculation and stale comment

complete-round was calling processPlayoffEvent without skipRecalculate,
firing recalculateAffectedLeagues and Discord even though each match
winner had already triggered those side effects via set-winner. Add
skipRecalculate: true to match the autoCompleteRoundIfDone pattern.

Also fix autoCompleteRoundIfDone comment which incorrectly said
"non-bracket eliminations are recorded" — that's a separate step in
finalize-bracket; processPlayoffEvent records bracket round placements.

https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 18:11:43 -04:00
Chris Parsons
a71e256bfd
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator

Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
  + Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* 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

* Consolidate server postgres connections into one shared pool

Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).

Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix and() bug and add Swiss loop safety guard

- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
  were using JS && instead of Drizzle and(), causing WHERE to filter only
  by participantId (not scoringEventId), which would update rows across
  all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
  prevent infinite loop if pairGroups returns no pairs

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix all remaining code review issues

- cs2-major-stage.ts: use schema column reference for stageEliminated
  in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
  results when a stage is complete (8 recorded eliminations), only
  simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
  simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
  React state (eliminatedChecked map) for checkbox show/hide logic;
  remove unused stageMap and unassignedParticipants variables

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars

- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
  optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix flaky Champions Stage stochastic test

The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.

Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 16:40:05 -04:00
Chris Parsons
1d3eb4aac2
Add inline edit for participant names on admin sports season page (#257)
Fixes #224

* Add inline edit for participant names on admin sports season page

Adds a pencil icon button next to each participant's delete button. Clicking
it switches the row into edit mode with an input field, a save (checkmark) and
cancel (X) button. Escape also cancels. Submits via intent="update-name" and
validates uniqueness within the season before persisting.

https://claude.ai/code/session_01Q94DWQ1HZEB9PJhGMArU8D

* Simplify edit state and surface edit errors to user

- Combine editingId + editingName into single editing: { id, name } | null state object
- Extract cancelEdit() helper called in 3 places instead of repeating setEditing(null)
- Tag all update-name action responses with intent: "update-name" so errors can be
  identified and routed correctly
- Show update-name errors inline below the edit input
- Guard single-add and bulk-add error displays against showing update-name errors

https://claude.ai/code/session_01Q94DWQ1HZEB9PJhGMArU8D

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-01 17:56:42 -07:00
Chris Parsons
c5ccee2225
Show events on multiple dates when games span requested date range (#254)
* Fix admin Games to Score panel missing bracket events

The panel was silently dropping bracket events in two cases:

1. When a bracket event had `scoringEvents.eventDate` set to a future
   round date (e.g. "April 5") but an individual game's `scheduledAt`
   was today, the old dedup code picked `eventDate` first and the
   component filter `displayDate === today` never matched.

2. When an event had games on both today and tomorrow, whichever row
   the unordered step-1 query returned first "won" — potentially hiding
   a today game from the today tab entirely.

Fix: replace the `Map<id, firstDate>` deduplication with
`Map<id, Set<date>>` that collects every requested date an event
qualifies for (via either `eventDate` or `gameDate`). The return uses
`flatMap` to emit one entry per (event, date) pair, so events with
games on multiple days now appear correctly in both tabs.

https://claude.ai/code/session_01QkFxCF4xmKjdVCNPysWDML

* Fix lint errors: replace .sort() with .toSorted() and remove non-null assertion

- Replace Array#sort() with Array#toSorted() in two places (unicorn rule)
- Remove non-null assertion on Map#get(); use early continue instead

https://claude.ai/code/session_01QkFxCF4xmKjdVCNPysWDML

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-01 13:39:03 -07:00
Chris Parsons
383315d0c3
Auto-eliminate non-group participants on group generation (#250)
When generating groups for a tournament (e.g. FIFA World Cup), any
participants in the sport season who were not assigned to a group are
now automatically marked as eliminated (finalPosition = 0) — the same
result as running "Reprocess Eliminations" manually.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 00:40:55 -07:00
Chris Parsons
005a5a82a7 Fix noisy and broken tests. 2026-03-31 15:53:43 -07:00
Chris Parsons
8c3663e01b
Add PDC World Darts Championship simulator with Elo-based bracket (#248)
Fixes #123

* Add PDC World Darts Championship simulator (128-player bracket)

- New DartsSimulator: 128-player single-elimination, 7 rounds with
  PDC-accurate best-of-sets formats (bo3/bo5/bo5/bo7/bo7/bo11/bo13).
  ELO_DIVISOR=500 via set-level Bernoulli model. Two simulation paths:
  Path A (bracket drawn) simulates from actual DB matches; Path B
  (pre-bracket) seeds top 32 by world ranking in fixed positions and
  randomly draws the remaining 96 per simulation run (50,000 iterations).
- darts_bracket added to simulatorTypeEnum and simulator registry.
- world_ranking nullable integer column added to participant_expected_values
  (migration 0067); batchSaveSourceElos now accepts and persists it.
- Admin route /admin/sports-seasons/:id/darts-elo: bulk import with format
  "Player Name, 2099, 1" (name, Elo, optional world ranking), fuzzy name
  matching, auto-runs simulation and updates EV/snapshots on save.
- DARTS_128 bracket template added (scoring starts at Quarterfinals).
- 30 unit tests: math helpers, bracket seeding structure, Path A/B integration.

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

* Review fixes: pre-compute hot-loop invariants, import normalizeName

- Pre-compute seededSlots and getSeededMatchOrder(32) before the 50k
  simulation loop — was being recomputed every iteration
- Pad unseeded pool to 96 once before the loop instead of inside it
- Inline bracket-building in the hot loop using pre-computed seededSlots;
  removes the per-iteration call to buildR1Bracket/getSeededMatchOrder
- Remove dead SEEDED_R1_PAIRS constant (was never referenced)
- Import normalizeName from ~/lib/fuzzy-match instead of redefining it locally

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

* Fix lint failures: unused vars, eqeqeq, toSorted

- Remove unused seededSet/unseededSet variables in test
- Replace != null with !== null && !== undefined (eqeqeq rule)
- Replace .sort() with .toSorted() in simulator and route (unicorn/no-array-sort)

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

* Fix TS2552: restore seededSet declaration removed during lint fix

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 15:37:28 -07:00
Chris Parsons
efbd28b446
Exclude completed playoff matches from upcoming events query (#247)
* Exclude scored bracket matches from upcoming events calendar

Add `eq(schema.playoffMatches.isComplete, false)` to the bracket-sports
query in `getUpcomingEventsForDraftedParticipants` so that individual
playoff matches already scored (isComplete = true) no longer appear on
the upcoming events calendar, even when the parent scoring event is still
open.

Also update the schema mock in upcoming-calendar.test.ts to include
`playoffMatches.isComplete` and add a test covering this behaviour.

https://claude.ai/code/session_01GMLmjN9mwoANfpgSciD7Bi

* Fix leaked mockReturnValueOnce in scored-match test

The new test only triggers one selectDistinct call (rows is empty so the
max-game-number lookup is skipped). The second mockReturnValueOnce was
never consumed, leaving a makeMaxGameChain value in the queue that was
then picked up by the subsequent "uses leftJoin" test, causing it to fail
with "leftJoin is not a function".

https://claude.ai/code/session_01GMLmjN9mwoANfpgSciD7Bi

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 10:08:25 -07:00
Chris Parsons
2b13e153d6 Initial storybook components. 2026-03-29 22:09:45 -07:00
Chris Parsons
c604dc9bc5
Fix tiebreaker incorrectly separating tied teams with pending participants, fixes #244 (#245)
Placement counts (used to break points ties) previously only included
fully-finalized participants. A team whose events all resolved first would
accumulate real placement counts while tied teams with pending events had
zeros, causing the tie to be broken in favour of whichever team finished
scoring first rather than on merit.

Fix: count a participant's current position toward the tiebreaker regardless
of isPartialScore. Their position is the best available signal; if it changes,
recalculateStandings reruns and ranks update naturally.

Also removes a redundant bounds check (finalPosition > 0 was already
asserted by the outer if-condition).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 16:59:13 -07:00
Chris Parsons
338979e0a8
Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator (#242)
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes #127

- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
  - Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
  - Partial group completion: completed matches replayed with real scores, remaining matches simulated
  - Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Increase Node heap to 4GB for unit tests in CI to prevent OOM

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests

Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 10:27:47 -07:00
Chris Parsons
611e1ccf0a
Show tied ranks with T prefix across standings and Discord (#239)
* Show tied ranks with T prefix across standings and Discord notifications, fixes #197

- Add buildTiedRankChecker() utility to standings-display.ts; replaces
  four copies of inline rank-count logic spread across components,
  the league home route, and the Discord service
- Prefix shared ranks with "T" (e.g. "T3") in StandingsTable (league
  panel), StandingsTable (full standings), the league home preview, and
  Discord webhook notifications
- Add useMemo wrapping in StandingsTable components so tie detection
  does not recompute on every render
- Fix compareTeamsForRanking to round total points to hundredths before
  comparing, preventing floating-point noise from producing spurious
  non-ties in the standings

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix discord test to expect escaped period in rank display

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 20:45:15 -07:00
Chris Parsons
8f55d0d135
Prevent duplicate participants within a sports season, fixes #69 (#236)
- Add unique index on (sports_season_id, name) in participants table
- findParticipantByName uses case-insensitive lower() comparison
- Single add: check for existing name before insert, return clear error
- Bulk add: load existing names once upfront (1 query vs N), dedup
  input case-insensitively, report skipped names in UI
- Fix golf-skills and surface-elo routes which called createParticipant
  without any duplicate guard (would have thrown DB constraint errors)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 01:09:04 -07:00
Chris Parsons
3c4ed67946
Add upcoming events pages and fix timezone filtering, fixes #213 (#235)
- Fix UTC midnight rollover bug: server now queries from yesterday UTC
  as a buffer; UpcomingCalendarPanel filters to local-today client-side
  via useEffect + Intl.DateTimeFormat, removing the need for any
  cookie or server-side timezone detection
- Cap homepage and league page panels at 6 events with a "View all" link
- Add /upcoming-events page (60-day view across all leagues)
- Add /leagues/:leagueId/upcoming-events page (60-day per-league view)
- Add emptyMessage prop to UpcomingCalendarPanel for context-specific copy
- Change getUpcomingEventsForDraftedParticipants to accept pre-computed
  date strings instead of Date objects

fixes #213

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 00:49:16 -07:00
Chris Parsons
29ea93ad6d
Add support page with Discord link and contact form, fixes #233 (#234)
- New /support route with Discord join button and contact form
- Contact form sends via Resend to support@brackt.com (email stays hidden from users)
- Spam protection: honeypot field + Cloudflare Turnstile verification
- Server-side input length limits (subject: 200, message: 5000 chars)
- Added Support nav link to navbar (desktop + mobile)

Fixes #233

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 17:17:49 -07:00
Chris Parsons
bde1e6e5f0
Add WNBA playoff simulator with SRS-based Elo ratings, fixes #125 (#231)
* Add WNBA playoff simulator with SRS-based Elo ratings, fixes #125

- New WNBASimulator: Monte Carlo (50k sims) projecting remaining regular
  season games → seeding → R1 Bo3 / Semis Bo5 / Finals Bo7 bracket
- Hybrid Elo sourcing: pre-season uses futures odds (ICM); once avg
  gamesPlayed ≥ 5, switches automatically to SRS-derived Elo
  (elo = 1500 + srs × 20)
- New WnbaStandingsAdapter: fetches ESPN standings + teams endpoints in
  parallel; includes zero-records for 2026 expansion teams (Portland
  Fire, Toronto Tempo) not yet in standings
- Added srs column to regular_season_standings (migration 0063);
  stored as net rating proxy (avgPointsFor − avgPointsAgainst)
- Added wnba_bracket to simulatorTypeEnum

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix missing afterEach import in wnba standings test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 00:34:51 -07:00
Chris Parsons
eca1508b3f
Improve admin dashboard stats and fix scoring event bugs (#230)
* Improve admin dashboard stats and fix scoring event date bugs, fixes #92

- Add "Seasons by Status" breakdown card (pre-draft / drafting / active / completed)
- Replace full-table fetches with COUNT queries for sports, sports seasons, and templates
- Fix bracket events with null eventDate disappearing from the Games to Score tabs by
  computing a displayDate from matched playoffMatchGames.scheduledAt in getEventsForDates
- Fix Today tab badge showing stale count when all events are scored
- Hide "Getting Started" checklist once the system has sports configured
- Use explicit "en-US" locale in formatEventTime for deterministic output

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix scoring-event-dashboard tests after select/sql changes

- Rename mockSelectDistinct → mockSelect to match implementation change
  from .selectDistinct() to .select()
- Add sql to drizzle-orm mock
- Update mock row shapes to include eventDate and gameDate fields
- Add two tests covering displayDate derivation from eventDate and gameDate

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 20:46:54 -07:00
Chris Parsons
2b48ef285d
Rework MLB simulator: RDif-based matchup probs, 2026 data, fixes #227 (#228)
Fixes #227

- Replace hardcoded Elo ratings with 2026 FanGraphs Depth Charts projected
  run differential (RDif) for all 30 teams
- Replace Elo formula with Bill James log5 using RDif → win rate conversion
- Restore p_div/p_wc from FanGraphs playoff odds (divTitle/wcTitle) for
  seeding draws — previously these were incorrectly derived from raw win
  rates, which gave the Dodgers only ~24% division win probability instead
  of the correct ~90%
- Add RDIF_DIVISOR constant to compress team strengths toward .500 for
  playoff parity; set to 8000 (Dodgers +137 → ~51.7% per-game win rate)
- Fix minimum team check: < 5 → < 6 (need 3 div winners + 3 wild cards)
- Fix Colorado Rockies p_div 0.000 → 0.001 for consistency
- Fix stale comments throughout; update tests

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 19:05:12 -07:00
Chris Parsons
2e2d8db777
Add MLB playoff simulator with AL/NL division standings, fixes #121 (#225)
* Add MLB playoff simulator with AL/NL division standings, fixes #121

- New `mlb-simulator.ts`: 50k Monte Carlo sim drawing division winners
  (weighted by p_div) and 3 WC teams per league, then simulating
  WC best-of-3 → DS best-of-5 → LCS best-of-7 → World Series.
  Elo parity factor 350; blends Vegas odds 30/70 when sourceOdds available.
- New `standings-sync/mlb.ts`: adapter for free statsapi.mlb.com API,
  mapping AL/NL conferences, division ranks, streaks, home/away/L10 splits.
- New `mlb-divisions` display mode in RegularSeasonStandings: shows 1 division
  winner per division section + Wild Card section with 3-spot playoff line,
  headings read "AL/NL League" instead of "Conference".
- Refactored buildNhlSections/buildMlbSections into shared buildDivisionSections
  (divisionSpots + wcSpots params); conferenceLabel now flows through group
  objects rather than being derived from displayMode in the render.
- DB migration 0062 adds `mlb_bracket` to simulator_type enum.
- 37 new tests across simulator, adapter, and component.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix flaky tennis simulator test: increase trials and lower threshold

500 trials with a ~3–5% expected win rate had enough variance to
occasionally land below the 0.03 threshold (~2% failure rate).
Bumping to 2000 trials reduces the std dev by 2x; lowering the
threshold to 0.02 keeps the assertion meaningful (still well above
random 0.78%) while eliminating the flakiness.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 08:47:02 -07:00
Chris Parsons
e62e9554c9
Add golf qualifying points simulator (Plackett-Luce Monte Carlo) (#223)
* Add golf QP simulator with Plackett-Luce model, fixes #120

- New `participant_golf_skills` table (migration 0061) for SG: Total and
  per-major American odds per player/season
- New `app/models/golf-skills.ts` with getGolfSkillsMap, getGolfSkillsForSeason,
  batchUpsertGolfSkills
- Full `GolfSimulator` implementation replacing the TODO stub: Plackett-Luce
  ranking model (PL_BETA=1.5, FIELD_SIZE=156), 10k Monte Carlo iterations,
  awards QP by finishing position, ranks by total QP across all 4 majors
- New admin route `sports-seasons/:id/golf-skills` with bulk CSV import,
  fuzzy name matching, per-player SG + per-major odds inputs; saves skills
  and auto-runs simulation on submit
- Simulator dropdown on sport admin sorted alphabetically; renamed to
  "Golf Qualifying Points Monte Carlo"
- Golf Skills button shown on sports season admin when simulator type is
  golf_qualifying_points
- Extract normalizeName/diceCoefficient to shared `app/lib/fuzzy-match.ts`,
  removing duplication from surface-elo and golf-skills routes
- Parallelize 4 DB queries in GolfSimulator.simulate() with Promise.all
- O(1) field array removal via swap-to-end + pop (was O(N) splice)
- Fix source tag: performance_model (not elo_simulation) for SG-based model
- 23 unit tests covering americanToImplied, getMajorOddsKey, resolveSkill,
  simulateMajor, and Monte Carlo calibration properties

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix oxlint errors: no-non-null-assertion and eqeqeq

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 21:46:02 -07:00
Chris Parsons
b81089879c
Fix while_on autodraft stalling between chain bursts, fixes #190 (#222)
The chain (checkAndTriggerNextAutodraft) picks consecutive while_on teams
immediately after a pick, but is capped at totalTeams iterations. Once the
cap is hit, the next while_on team had to wait for the full timer countdown
before their pick fired — which users experienced as autodraft intermittently
not working.

Root cause fix: the timer loop now detects while_on mode and triggers the
pick immediately (≤1 s) regardless of time remaining, bypassing the
countdown. A timer-update with timeRemaining:0 is emitted first so clients
don't see a frozen timer. If the chain already handled the pick, executeAutoPick
returns "Pick already made" and the timer moves on harmlessly.

Additional fixes:
- Add timerTickRunning guard so concurrent setInterval ticks (when a chain
  takes >1 s) don't race on the same pick slot
- Use onConflictDoNothing on the draft pick INSERT in executeAutoPick so a
  DB unique-constraint collision is treated as "Pick already made" rather
  than pausing the draft
- Cache draftSlots per season in the timer loop (slots never change during
  an active draft) — eliminates one DB query per tick
- currentPickNumber || 1 → ?? 1

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 19:09:38 -07:00
Chris Parsons
789408e428
Fix chess clock increment not applied to all pick types (#67 regression) (#220)
Fixes #220

When standard draft mode was added, the chess clock increment was
accidentally restricted to owner-only picks. Commissioner, admin, and
auto-picks stopped earning the increment, causing teams that timed out
to freeze at 0s and instant-autopick every subsequent round.

Fix:
- make-pick: all pick types earn the increment in chess clock mode
- force-manual-pick: same; deduplicate standard/chess-clock branches
  into a single update with mode-selected SQL; remove now-unused
  timerSnapshot query
- draft-utils executeAutoPick: restore increment for chess clock
  auto-picks; add missing seed insert when no timer row exists
- server/timer.ts: fix fallback initialization to use draftIncrementTime
  in standard mode (was always using draftInitialTime)
- leagues/$leagueId.tsx: show Draft Timer Mode in League Info panel

Tests:
- Update draft.make-pick.timer-mode to cover owner/commissioner/admin
  in both modes (commissioner section previously asserted frozen bank)
- Add draft.force-manual-pick.timer-mode for commissioner/admin force
  picks in both modes
- Add executeAutoPick.timer for timer-triggered auto-picks in both modes
- Update draft.force-manual-pick to reflect new chess clock behavior
- Replace fragile toHaveBeenCalledTimes(2) assertions with
  toHaveBeenCalledWith checks on the timer set call

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 17:00:32 -07:00
Chris Parsons
d7ba20d9ea
Add tennis Grand Slam simulator with surface Elo ratings, fixes #116 (#216)
Implements a Monte Carlo simulator for men's/women's tennis seasons scored
on the qualifying_points pattern. Simulates all 4 Grand Slam majors
(Australian Open, French Open, Wimbledon, US Open) using surface-specific
Elo ratings and ATP/WTA world rankings for seeding.

New table: participant_surface_elos — one row per (participant, season)
storing worldRanking, eloHard, eloClay, eloGrass.

Key design decisions:
- Seeding uses ATP/WTA world ranking (not Elo), matching real draw procedure
- Top 32 seeded with standard slot placement (1→0, 2→64, 3-4→quarters, etc.)
- QP per round with tie-splitting pre-applied: W=20, F=14, SF=9, QF=4, R16=1.5
- Completed majors read actual qualifyingPointsAwarded from eventResults
- 10,000 Monte Carlo simulations; column sums naturally 1.0 (no normalization)

Admin UI at /admin/sports-seasons/:id/surface-elo:
- 5-column grid (Player | Rank | Hard | Clay | Grass)
- Bulk import: "Name, ranking, hardElo, clayElo, grassElo" one per line
- Fuzzy name matching (bigram Dice coefficient) with "Did you mean?" suggestions
- Inline participant creation for unmatched names via useFetcher
- Saves Elos and auto-runs simulation on submit

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 23:59:35 -07:00
Chris Parsons
f4031d2a38
Fix standings upsert no-op: use EXCLUDED pseudo-table (#215)
* Fix upsert standings no-op: use EXCLUDED pseudo-table for conflict update

Drizzle's onConflictDoUpdate set block was referencing the existing table
columns instead of the incoming values, causing every sync to silently
overwrite records with their own current data (no-op).

Fixes #211

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add unit tests for regular-season-standings model

Covers upsertRegularSeasonStandings (empty-array short-circuit, value
mapping, syncedAt behaviour), upsertManualStanding, getRegularSeasonStandings
sorting, getLastSyncedAt, deleteRegularSeasonStandings, and
getParticipantStanding — 19 tests total.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 21:22:53 -07:00
Chris Parsons
784f6859e4 Fix oxlint eqeqeq error: use !== null && !== undefined
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 08:49:48 -07:00
Chris Parsons
1bdd5c3372 Add snooker bracket simulator and Elo ratings admin UI, fixes #119
- SnookerSimulator: Monte Carlo simulation of the 32-player World
  Championship bracket using per-frame Bernoulli win probabilities
  derived from Elo ratings (ELO_DIVISOR=700). Two paths: bracket-
  populated (respects completed matches) and pre-bracket (simulates
  qualifying, then seeds full draw).
- Admin route /sports-seasons/:id/elo-ratings: bulk-import and per-
  player Elo entry with fuzzy name matching; saves ratings and auto-
  runs the simulation in one action.
- schema: add snooker_bracket simulator type, source_elo column on
  participant_expected_values, unique index on (participant_id,
  sports_season_id).
- Fix batchSaveSourceElos to use INSERT ... ON CONFLICT DO UPDATE
  instead of N+1 SELECT+UPDATE loop.
- Fix existingElos returned as plain Record (Map doesn't survive JSON
  serialization through useLoaderData).
- Fix "How It Works" formula to show correct divisor (700, not 400).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 08:24:28 -07:00
Chris Parsons
e4285876ad Fix oxlint errors. 2026-03-22 20:41:44 -07:00
Chris Parsons
b672c50d78
Add sortable Sport and Participant columns to team breakdown table (#208)
- Sort by sport (secondary: participant) or participant name
- Extract SortableHeader component to reduce header button repetition
- Use toSorted() instead of slice().sort() (oxlint fix)
- Use localeCompare with sensitivity: 'base' for case-insensitive string sorts

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 20:30:17 -07:00
Chris Parsons
194f9087a3
Add sortable columns to draft picks table on manager page (#207)
* Add sortable columns to draft picks table on manager page

Pick # column sorts by pick number (asc by default), Points column
sorts by actual points then projected as tiebreaker (desc by default).
Clicking a column header toggles sort direction with visual indicators.

https://claude.ai/code/session_01XBnm7eKxerR7WjwrqqJPwe

* Fix code review issues in TeamScoreBreakdown sortable table

- Move SortIndicator out of render (avoids remount on every render)
- Extract sortPicks helper outside component
- Restore default sort: sport name then pick number (was lost in prior commit)
- Replace unicode arrow chars with Lucide ArrowUp/ArrowDown/ArrowUpDown icons
- Add aria-sort attributes to sortable column headers for accessibility
- Change w-[90px] to min-w-[90px] on Pick # column to avoid clipping
- Flatten nested div inside Points sort button

https://claude.ai/code/session_01XBnm7eKxerR7WjwrqqJPwe

* Fix pick sort to use pure pick number (matches tests)

The sport-grouped tiebreaker conflicted with the test contract for the
pick column. Tests expect ascending pick number = [1, 2, 3] regardless
of sport, so revert sortPicks to sort by pickNumber only for that column.

https://claude.ai/code/session_01XBnm7eKxerR7WjwrqqJPwe

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 19:20:01 -07:00
Chris Parsons
88e18412ec
Don't show Game #1 label for single-game matchups in calendar (#206)
* Don't show Game #1 label for single-game matchups in calendar

When a matchup has only one game, showing "Game #1" is redundant and
unhelpful. Only show game numbers when there are multiple games in a
matchup (gameKeys.size > 1). For single-game matchups, show just the
round name (or null if it matches the event name).

Closes #198

https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX

* Show game number for Game #2+ in series, hide Game #1 for single-game matchups

If a matchup has only one game (game #1), the number is redundant — show
just the round name. If game #2 or higher is upcoming, it clearly belongs
to a multi-game series, so show the game number to distinguish it.

https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX

* Fix Game #1 label for multi-game series when only Game #1 is in date window

Previously, Game #1 of a multi-game series showed no game number (e.g.
"Semifinals") if Game #2 fell outside the calendar date range. Since at
least 2 games are always entered for a series from the start, a second
un-date-filtered query now checks the max game number per event. If max
> 1, the event is a series and Game #1 is labelled accordingly
(e.g. "Semifinals Game #1").

https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX

* Show game number when multiple games from same series are in date window

The gameKeys.size > 1 branch previously showed only the round name,
contradicting the rule that multi-game series always show "Game #x".
Now shows the lowest game number visible in the window (e.g. both
Game #1 and #2 upcoming → "Semifinals Game #1").

https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX

* Split series games into individual calendar entries, each showing Game #x

Each game in a multi-game bracket series (e.g. Game #1 on Mar 23,
Game #2 on Mar 25) now appears as its own row on the calendar with its
own date and "Round Game #x" label. Single-game matchups are unchanged.

Grouping key changes from eventId to eventId|gameNumber for series events.
The max-game-number lookup now runs before grouping so the correct key
can be determined while processing each row.

https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX

* Cache isSeries per entry to avoid re-deriving it in the finalization loop

https://claude.ai/code/session_01CRrqu43FKHshpJt1NyrDdX

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 16:39:26 -07:00
Chris Parsons
8c5389909d
Redesign standings page with sortable table, 7-day change, and chart repositioned (#205)
* Redesign standings page with sortable table, 7-day change, and chart repositioned

- Move point progression chart below the standings table
- Replace separate Points/Projected/Placement columns with:
  - Single stacked "actual / projected" Points column (shared PointsDisplay component)
  - "7-Day Change" column showing points gained + rank change over past 7 days
- Remove Placement breakdown column
- Sort ties alphabetically by team name (rank sort only)
- All columns are sortable via new reusable useSortableData hook
- Add sevenDayPointChange to TeamStandingWithChange type and model

https://claude.ai/code/session_01CuCKFVYbpsKSQoFDcTYfY7

* Code review fixes: module-level comparators, correct type on SortableHead, handle negative point change, remove redundant spread

- Move comparators object to module level (closes over nothing, no useMemo needed)
- Use SortConfig<StandingRow> on SortableHead instead of inline duplicate type
- SevenDayChange: handle negative pointChange with correct sign and color
- Remove redundant sevenDayPointChange explicit assignment (already in ...standing spread)

https://claude.ai/code/session_01CuCKFVYbpsKSQoFDcTYfY7

* Update StandingsTable tests to match redesigned component

- Remove showPlacementBreakdown prop (no longer exists on component)
- Replace Placement Breakdown test suite with 7-Day Change column tests
- Update header assertion: "Placements" → "7-Day Change"
- Add tests for positive/negative point change display and rank change indicators
- Remove accessibility test for placement title attributes

https://claude.ai/code/session_01CuCKFVYbpsKSQoFDcTYfY7

* Fix movement indicator arrow count assertion to exclude sort header arrows

queryAllByText(/↑|↓/) was matching the active sort column's ↑ indicator.
Narrow to /[↑↓]\d/ so only movement indicators (↑1, ↓1) are counted.

https://claude.ai/code/session_01CuCKFVYbpsKSQoFDcTYfY7

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-22 11:05:13 -07:00
Chris Parsons
c1be92b2af
Add AFL season + finals simulator (closes #126) (#204)
Monte Carlo simulation of the 2026 AFL season and 10-team finals series.
Elo ratings are backsolved from Squiggle's projected season win totals using
the inverse formula: elo = 1500 - 450×log₁₀((1−wins/23)/(wins/23)).

- New `afl_bracket` simulator type (schema + migration)
- `afl-simulator.ts`: projects remaining regular season via Elo, seeds the
  AFL_10 finals bracket (Wildcard → QF/EF → SF → PF → Grand Final), and
  correctly tracks P5/P6 and P7/P8 as separate scoring tiers
- `afl.ts` standings sync adapter pulling from Squiggle API (no auth required)
- Finals line on standings display set to 10 for AFL seasons
- Substring name matching with longest-key-wins to prevent "Port Adelaide"
  colliding with "Adelaide" when matching "Port Adelaide Power"
- 27 unit tests covering bracket logic, column-sum guarantees, and name matching

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 01:57:39 -07:00
Chris Parsons
46a2e9c199
Tune NHL simulator: Vegas futures blending + parity factor calibration (closes #168) (#202)
- Add 70/30 Elo + Vegas futures blending for per-game win probability,
  mirroring the UCL simulator pattern; falls back to Elo-only when no
  sourceOdds are stored in participantExpectedValues
- Adjust PARITY_FACTOR to better match Vegas championship implied
  probabilities (COL was ~12% vs ~20% market expectation)
- Add 15 unit tests covering name normalization, team data lookup,
  parity-factor math, seeding probability sanity, and eliminated-team checks

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 00:14:18 -07:00
Chris Parsons
7093b22726
Simulate NBA remaining regular season games from standings (#201)
Replace static Basketball-Reference seed probability distributions
(p_1..p_10) with dynamic simulation of each team's remaining games
based on current standings from the DB.

- Load regularSeasonStandings in parallel with participants query
- Compute remainingGames = 82 - gamesPlayed per team
- Pre-compute per-game win probability (Elo vs average opponent 1500)
  on TeamEntry at construction time — not inside the hot loop
- Sort conference standings by projected wins to assign seeds, replacing
  the drawSeed() weighted-probability approach
- Conference resolved from standings table, falls back to TEAMS_DATA
- Strip all p_1..p_10 seed probability data from TEAMS_DATA
- Move simulateProjectedWins to module scope (no closure captures)
- Remove const N alias; use NUM_SIMULATIONS directly

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 23:37:20 -07:00
Chris Parsons
618bc57ec1
Replace console.* with structured logger, fix no-inferrable-types (closes #98) (#199)
- Add app/lib/logger.ts: dev passes through to console; prod routes errors
  to Sentry.captureException and warnings to Sentry.captureMessage, with
  extra context preserved. Uses captureMessage (not captureException) for
  string-only args to avoid fabricated stack traces.
- Add server/logger.ts: dev passes through; prod silences log/info but
  keeps warn/error on stderr (Sentry not initialized in that process).
- Replace all console.* calls across 44 app files and 4 server files.
- Upgrade no-console from warn → error in oxlint; exempt logger files and
  scripts/** via overrides.
- Add typescript/no-inferrable-types rule; fix violations in services and
  simulators. Exempt test files (intentional string widening for switch/if
  tests would break under literal type inference).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 13:41:39 -07:00
Chris Parsons
4bffa40606
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196)
* Fix no-shadow and consistent-function-scoping lint violations

Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint
warnings and promotes both rules to errors in .oxlintrc.json.

no-shadow: renamed Drizzle callback params (sports→s, matches→m,
seasons→s) to avoid shadowing outer imports; removed shadowed
destructures (eq, inArray) from where callbacks; renamed inner
template→bracketTemplate, prev→currentTimers, season→ss, name→teamName
(with name: teamName fix to preserve semantics).

consistent-function-scoping: moved formatDate, getRankBadge,
getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr,
elo (×2), weightedPick, sortByMatchNumber (×2) to module scope;
moved formatTime (×2), isValidLeagueName, getDraftTimes,
makeSeasonQueues to file scope in test files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix no-non-null-assertion lint violations and promote to error

Eliminates all 208 no-non-null-assertion warnings across 38 files.
Promotes typescript/no-non-null-assertion from warn to error in
.oxlintrc.json.

Fix patterns applied:
- Map.get(key)! after .has() check → extract with get() + null guard
- Map.get(key)! on pre-populated count maps → ?? 0 default
- .set(id, map.get(id)! + 1) increment → ?? 0 before adding
- participant1Id!/participant2Id! on DB matches → ?? "" fallback
- array.find()! in tests → guard + throw or expect().toBeDefined()
- bracketTemplateCache.get(id)! → null guard extract
- Various nullable field accesses → optional chain or ?? default

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers

Resolves all 9 remaining non-console lint warnings and promotes all
three rules to errors in .oxlintrc.json.

- prefer-add-event-listener: converted onchange/onclick/onload
  assignments to addEventListener in useDraftNotifications.ts and
  admin.data-sync.tsx; stored changeHandler ref for proper cleanup
  with removeEventListener
- no-unassigned-import: configured rule with allow list for legitimate
  side-effect imports (*.css, @testing-library/jest-dom,
  @testing-library/cypress/add-commands)
- require-module-specifiers: removed redundant `export {}` from
  cypress/support/e2e.ts (file already has an import)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix TypeScript errors from no-non-null-assertion fixes

Two fixes introduced by the non-null assertion cleanup produced type
errors:

- scoring-event.ts: `?? ""` was wrong type for a participant object map;
  restructured to explicit null guards so TypeScript can narrow correctly
- standings-sync/index.ts: `?? null` after name-match lookup lost the
  truthy guarantee, causing TS18047 on the write-back block; added
  `participant &&` guard before accessing its properties

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add npm run typecheck as Stop hook in Claude settings

Runs a full project typecheck at the end of each Claude turn so type
errors surface as feedback before the next message.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
Chris Parsons
e2b178221a
Add oxlint linting setup with zero errors (#194)
* Add oxlint and fix all lint errors

- Install oxlint, add .oxlintrc.json with rules for TypeScript/React
- Add npm run lint / lint:fix scripts
- Add Claude PostToolUse hook to run oxlint on every edited file
- Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array
- Fix no-array-index-key (use stable keys or suppress positional cases)
- Fix exhaustive-deps missing dependency in useEffect
- Promote exhaustive-deps and no-array-index-key to errors
- Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix no-explicit-any warnings and upgrade tsconfig to ES2023

- Replace all `any` types with proper types or `unknown` across ~20 files
- Add typed socket payload interfaces in draft route and useDraftSocket
- Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch)
- Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed
- Fix cascading type errors uncovered by removing any: Map.get narrowing,
  participant relation types, ChartDataPoint, Partial<NewSeason> indexing
- Add ParticipantResultWithParticipant type to participant-result model
- Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult)
- Fix duplicate getQPStandings import in sportsSeasonId.server.ts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Promote no-explicit-any to error

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
Chris Parsons
bcca8b76fa
Add regular season standings for NBA/NHL (fixes #89) (#192)
Adds live standings sync and display for bracket-based sports (NBA/NHL),
so league members can see W/L tables and which teams their opponents drafted
during the regular season — not just after the playoff bracket is set.

- New `regular_season_standings` table with upsert-on-conflict sync
- Standings sync service with NHL (api-web.nhle.com) and NBA (ESPN) adapters,
  externalId write-back for future syncs, and unmatched-team resolution UI
- `RegularSeasonStandings` component: flat (NBA) + division/wild-card (NHL) modes,
  playoff line, TeamOwnerBadge, projected Brackt points (EV), mobile horizontal scroll
- Admin "Sync Standings" card + "Resolve Unmatched" UI on sports season page
- Admin manual standings edit hatch at /admin/sports-seasons/:id/regular-standings
- Show standings above bracket until matches exist; below once bracket is set
- `normalize-team-name` utility extracted to shared lib

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 00:12:01 -07:00
Chris Parsons
2949ca733a
Add standard draft clock mode (#67) (#189)
Implements a new "standard" timer mode alongside the existing chess clock
mode. In standard mode the per-pick timer resets to a fixed value after
every pick (no carry-over), and the speed selector shows plain time values
instead of named chess-clock presets.

Key changes:
- Add `draft_timer_mode` enum column to `seasons` table (migration 0053)
- `draft.start`: standard mode seeds timers at `draftIncrementTime` (the
  per-pick value) rather than `draftInitialTime`
- `draft.make-pick`: three-way branch — standard resets, chess clock
  owner earns increment, commissioner/admin pick leaves bank frozen
- `draft.force-manual-pick`: commissioner picks never earn bank time;
  chess clock path uses a pre-pick snapshot to avoid a race window with
  the 1-second timer loop
- `executeAutoPick` in draft-utils: auto picks never earn bank time;
  chess clock path skips the DB update (timer already at 0)
- League creation and settings pages: mode-aware speed selector (raw
  seconds for standard, named presets for chess clock); shared
  `parseDraftSpeed` utility extracted to `app/lib/draft-timer.ts`
- Tests added for draft.start timer init and make-pick timer mode
  behavior; force-manual-pick tests updated for new timer semantics

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-20 21:36:39 -07:00
Chris Parsons
ebe06b2522
Improve drag handle UX in queue items with activator node (#188)
* Fix queue drag to only activate on handle and number, not entire row

Restricts drag listeners to the grab handle icon and order number badge
using setActivatorNodeRef, and removes touch-none from the whole row so
mobile users can scroll without accidentally reordering the queue.

https://claude.ai/code/session_01HPtNkL5m9xhYgtzWaGViSC

* Code review cleanup: use GripVertical icon and add drag activation constraint

- Replace inline SVG drag handle with GripVertical from lucide-react,
  which is already used project-wide
- Add activationConstraint (distance: 8px) to PointerSensor so a touch
  on the handle doesn't immediately hijack scroll before the user has
  moved far enough to signal intent to drag

https://claude.ai/code/session_01HPtNkL5m9xhYgtzWaGViSC

* Fix O(n²) lookup, memoize components and callbacks in QueueSection

- Build a participantMap (Map<id, participant>) with useMemo so each
  queue item lookup is O(1) instead of O(n) per render
- Memoize queueIds array for SortableContext to avoid churn
- Wrap handleDragEnd in useCallback so DndContext gets a stable reference
- Wrap SortableQueueItem in memo so it skips re-renders when props haven't
  changed (important since the parent re-renders every second during a
  live draft from timer-update socket events)
- Pass onRemoveFromQueue and onMakePick directly as props instead of
  creating new arrow functions per item per render; SortableQueueItem
  now calls them with the relevant id itself

https://claude.ai/code/session_01HPtNkL5m9xhYgtzWaGViSC

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-20 16:19:44 -07:00
Chris Parsons
3f3401f0d8
Recalculate league standings after EV simulation updates (#186)
* Force standings recalculation after EV simulation

After persisting updated EVs to participantExpectedValues, call
recalculateAffectedLeagues so that teamStandings.projectedPoints
(and all related standing fields) immediately reflect the new EV
rather than remaining stale until the next scoring event.

https://claude.ai/code/session_01S9Pk4wTSphANMhPWaURPTn

* Use recalculateStandings directly after EV simulation

Replaces recalculateAffectedLeagues (which carries Discord notification
and daily snapshot side effects) with a direct call to recalculateStandings
per affected fantasy season. This updates the cached projectedPoints in
teamStandings so the standings page stays in sync with the team page after
a simulation, without triggering unrelated side effects.

https://claude.ai/code/session_01S9Pk4wTSphANMhPWaURPTn

* Polish simulate route after code review

- Remove redundant db variable; use database() inline consistent with
  all other model calls in this file
- Parallelize standings recalculation with Promise.all
- Update file header comment to include the standings refresh step

https://claude.ai/code/session_01S9Pk4wTSphANMhPWaURPTn

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-20 14:39:05 -07:00
Chris Parsons
063834d8e6
Display team owner names in standings views (#184)
* Show team name + username in standings, extract TeamNameDisplay component

- Add TeamNameDisplay component that renders team name (as link) with owner username below, matching the league homepage style
- Update StandingsTable to use TeamNameDisplay with owner username shown below team name
- Update league homepage standings section to use TeamNameDisplay
- Add ownerName/teamOwnerId fields to TeamStanding type
- Extend getSeasonStandings to include teamOwnerId from team relation
- Fetch and attach owner display names in the full standings page loader

https://claude.ai/code/session_01EYgGnuTBaRVdBDapJRTxDZ

* Address code review: type hygiene, explicit types, parallel fetching, style fix

- Remove teamOwnerId from TeamStanding type (was an internal server concern, not display data)
- Remove teamOwnerId from getSeasonStandings return value
- Add TeamStandingWithChange interface extending TeamStanding with sevenDayRankChange/sevenDayOldRank fields
- Annotate getSevenDayStandingsChange with explicit Promise<TeamStandingWithChange[]> return type
- Re-export TeamStandingWithChange from models/standings.ts
- Standings loader: query teams table directly for ownerIds instead of relying on teamOwnerId in standings data
- Standings loader: parallelize all independent queries (standings, teams, progressionData, seasonComplete, completionPercentage) with Promise.all
- Restore font-medium on StandingsTable team TableCell

https://claude.ai/code/session_01EYgGnuTBaRVdBDapJRTxDZ

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 20:19:28 -07:00
Chris Parsons
fa0e798db7
Add "Games to Score" widget to admin dashboard (#183)
* Add "Games to Score" widget to admin dashboard

Shows scoring events for today and tomorrow in a tabbed card, with
status badges (Pending/Scored), a scored/total progress counter, and
direct "Score" / "View" links to each event's results page. Excludes
non-scoring schedule_event types so only actionable events surface.

- app/models/scoring-event.ts: add getEventsForDates() model function
  that queries scoringEvents joined with sportsSeasons/sport for a
  given list of date strings
- app/routes/admin._index.tsx: call getEventsForDates([today, tomorrow])
  in the loader and render the GamesToScore component below the stats row
- app/models/__tests__/scoring-event-dashboard.test.ts: 8 unit tests
  covering empty input, shape mapping, multi-date filtering, completed
  events, and the inArray where conditions

https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5

* Fix getEventsForDates to include bracket events by game scheduledAt

The previous implementation only matched on scoringEvents.eventDate,
which is often null for bracket events where individual game times are
set on playoffMatchGames.scheduledAt instead.

Switched to a two-step query mirroring getUpcomingEventsForDraftedParticipants:
1. selectDistinct event IDs via left joins through playoffMatches →
   playoffMatchGames, matching where eventDate IN dates OR any game's
   scheduledAt falls within the date range's timestamp bounds
2. findMany on the matched IDs with sportsSeason + sport relations

Updated tests to cover the two-step flow, leftJoin usage, and the
scheduledAt timestamp bounds appearing in the where clause.

https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5

* Document dual game date storage in CLAUDE.md

scoringEvents.eventDate and playoffMatchGames.scheduledAt both hold game
dates depending on the event type. Added a dedicated section under
Important Patterns explaining when each is used and the two-step
selectDistinct + findMany pattern required for correct date queries.

https://claude.ai/code/session_014zKK15o5RJfTaodLvnZpF5

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 19:25:37 -07:00
Chris Parsons
d271cc6792
Refactor standings notifications to show only changed teams (#182)
* Refine Discord webhook scoring notifications (fixes #180, #181)

- Filter scored matches to only show matchups where a manager scores
  Brackt points (winner drafted) or has a team eliminated (loser drafted);
  matches with no manager involvement are suppressed entirely.
- Escape Discord markdown characters (_*~`|\) in team names and usernames
  to prevent formatting issues (e.g. double-underscore names causing
  unintended underlines).
- Replace full standings with a "Standings Changes" section that shows
  only teams whose points changed, plus any teams whose rank shifted as a
  result, with ↑N / ↓N indicators for rank movement.
- Pass previousRanks map from scoring-calculator to the notification so
  rank-displaced teams (who didn't score points themselves) are included.
- Update test webhook in league settings to demonstrate rank changes and
  a sample scored match.
- Update all discord service tests to cover the new filtering, escaping,
  and standings-change behaviour.

https://claude.ai/code/session_01FciwfdG9Sfr5ZrXUHPeB18

* fix: only set winnerUsername when winning team's score actually changed

Previously, winnerUsername was set for any drafted winner regardless of
whether points were actually scored. This caused R64 wins (where the
scoring system may not award points until later rounds) to appear in
Discord's Scored Matches section even when no Brackt points were earned.

Now winnerUsername is only set when the winner's team's totalPoints
changed after recalculation. loserUsername (eliminations) is always set
when the loser is drafted, since being knocked out is always notable.

https://claude.ai/code/session_01FciwfdG9Sfr5ZrXUHPeB18

* Refactor Discord notification logic in scoring calculator

- Compute changedTeamIds once up front; derive hasChanges from it
  instead of duplicating the same iteration
- Merge usernameForParticipant and winnerUsernameForParticipant into a
  single function with a requireScoreChange flag
- Replace hasDraftedParticipantMatches with hasScoredMatchesToShow,
  which checks that at least one scoredMatch has a displayable username
  — prevents sending a contentless Discord embed when a drafted winner
  doesn't score any points and the loser isn't drafted
- Update inline comment to be sport-agnostic

https://claude.ai/code/session_01FciwfdG9Sfr5ZrXUHPeB18

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-19 15:52:57 -07:00
Chris Parsons
51a0a3ebba
Add isDraftable toggle to sport seasons (#165) (#178)
Admins can now enable/disable a sport season from appearing in league
creation and pre-draft league settings. Non-draftable seasons are hidden
from selection but remain visible (and checked) if already linked to an
existing pre-draft league. Leagues in draft status or beyond are unaffected.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 22:40:19 -07:00
Chris Parsons
a054247a55
Fix standings snapshot upsert: atomic writes, correct date, and event-driven updates (#177)
- Add unique index on (team_id, season_id, snapshot_date) in team_standings_snapshots
  so concurrent writes can't produce duplicate rows (migration 0051)
- Rewrite createDailySnapshot to use INSERT ... ON CONFLICT DO UPDATE inside a
  transaction, replacing the SELECT-then-insert/skip pattern (N+1 queries, race-prone)
- Remove early-exit guard in server/snapshots.ts background job so it always
  upserts rather than skipping seasons that already have a snapshot for today
- Call createDailySnapshot in recalculateAffectedLeagues after recalculateStandings,
  so every bracket score update refreshes today's snapshot; wrapped in try/catch so
  a snapshot failure can't block Discord notifications
- Also call createDailySnapshot from the admin rescore and finalize-bracket actions
- Fix UTC date bug: replace toISOString().split('T')[0] with local date parts in
  both standings.ts and server/snapshots.ts (and the 7-day lookback query)
- Convert all dynamic await import() calls in bracket.server.ts to static imports

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 22:15:28 -07:00
Chris Parsons
09b9b9bdad
Optimize user data fetching with batch queries and centralize display name logic (#176)
* Fall back to displayName when username is null for Discord webhook

Users who sign up via OAuth (Google, GitHub, etc.) without setting a
Clerk username have a null `username` field but always have a `displayName`
(computed from firstName+lastName or email). Previously, `usernameByClerkId`
was filtered to only include users with a non-null username, causing those
owners to appear without any identifier in Discord standings messages
(e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)").

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

* Extract getUserDisplayName helper and use consistently throughout

Add a single getUserDisplayName(user) function to app/models/user.ts that
encapsulates the username → displayName fallback logic. Replace 9 scattered
inline expressions across the codebase (owner-map, scoring-calculator,
league routes, settings, invite flow, draft API, Clerk webhook) with calls
to the shared helper.

No behaviour change — all existing logic preserved, just centralised.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

* Fix N+1 user queries in league loader and settings loader

Add findUsersByClerkIds() batch function to the user model and replace two
separate Promise.all+findUserByClerkId loops (one for owners, one for
commissioners) with a single inArray query in both $leagueId.server.ts and
$leagueId.settings.tsx. The merged query covers both owner and commissioner
IDs in one round-trip.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

* Fix N+1 user queries in buildOwnerMap

Replace the Promise.all+findUserByClerkId loop with a single
findUsersByClerkIds batch query, consistent with the league loader
and settings loader fixes.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
Chris Parsons
143698cb96
Fix NCAAM/NCAAW simulators: FF completion handling and validation hardening (#169)
Fixes the "slot is already filled" simulation error when First Four games
have already been played and their winners advanced to the Round of 64.

Changes:
- Fix FF→R64 validation to allow a filled R64 slot when the corresponding
  First Four match is already complete (the original bug)
- Fix isComplete guard for E8/FF/Championship: derive loser from stored
  participant IDs when loserId is null rather than re-simulating a real game
- Add round count validation for all rounds (R32 16, S16 8, E8 4, FF 2, Champ 1)
  to catch malformed brackets before the hot sim loop instead of producing
  silent garbage output
- Add participant1Id null check in the First Four path (mirrors the no-FF path)
- Add console.warn when participant IDs are missing from DB (fall-back to
  average strength instead of crashing)
- Import NCAA_68.regions from bracket-templates.ts instead of duplicating the
  hardcoded fallback in each simulator
- Fix duplicate step-9 comment number in ncaam-simulator.ts

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 01:37:55 -07:00
Chris Parsons
6f5ea35952
Add NHL playoff simulator and fix simulator dropdown (#166)
Closes #115

- Add `NHLSimulator` using NHL's divisional bracket format (top 3 per
  division + 2 wildcards per conference, best-of-7 series, parity
  factor 800). Elo ratings and seeding probabilities sourced from
  elo.harvitronix.com/nhl/2025-2026 as of March 18, 2026.
- Add `nhl_bracket` to `simulatorTypeEnum` with migration.
- Register `NHLSimulator` in the simulator registry.
- Fix simulator type dropdown in admin to auto-generate from the
  registry instead of a hardcoded list, so new simulators appear
  automatically without a separate UI change.

Code review fixes applied to the simulator:
- Narrow `weightedPick` key type to the five seeding probability fields
  (was `keyof NhlTeamData`, allowing `"elo"` which would silently
  corrupt results)
- Remove uniform-random fallback in `weightedPick` — zero-weight draws
  now return `undefined` and are skipped, preventing eliminated teams
  from becoming wildcards
- Exclude unrecognized participants entirely (with a console warning)
  instead of silently routing them into the Eastern wildcard pool
- Replace the confusing for-of loop over both conferences (with unused
  `champ` variable and `!`-suppressed unitialized vars) with two
  explicit sequential East/West blocks
- Track `effectiveN` for skipped degenerate draws so probability
  denominators stay accurate; throw if all iterations are skipped

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 01:23:53 -07:00