Make a "major" (golf/tennis/CS2) scored once on its canonical tournament
and fan out to every linked sports_season window and league.
Fan-out & completion (app/services/sync-tournament-results.ts):
- syncTournamentResults now marks each synced window's event complete
(gated by markComplete), recalculates affected leagues, and counts
recalc failures so a stale league can't hide behind a "completed" badge
- syncMajorFromPrimaryEvent promotes a primary window's derived results to
canonical tournament_results (deleting rows for dropped placements) and
fans out to siblings; fanOutMajorIfPrimary guards on the primary
- placement removals now propagate (stale rows reset to filler)
Primary-event model (scoring_events.is_primary, migration 0122):
- getPrimaryEventForTournament / isReadOnlySibling / ensurePrimaryEvent /
setPrimaryEvent; event creation auto-seeds a primary for bracket majors;
"Make primary" button on the tournament page
- per-window event/bracket/cs2 pages are read-only for non-primary linked
events (not-participating stays editable)
Tennis Grand Slam bracket (tennis_128 template + TEMPLATE_ROUND_CONFIG):
- bracket-scored qualifying major via the existing bracket pipeline
- simulator conditions in-progress EV on the real bracket (honoring
completed matches, walkover for withdrawals), QP derived from config,
round structure read from the template; CS2 + tennis share resolveStructureSource
Backfill (scripts/backfill-major-linking.ts): one-time idempotent reconcile
of existing majors (link orphans, designate primary, promote canonical, sync).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Surface projected final points on the full standings page and restructure
the rank/point change indicators so columns align cleanly on desktop and
mobile.
- StatHelpers: stacked label/value/delta columns with a per-row reservable
delta line; merge rank/point indicators into a single DeltaBadge;
parameterize StatDivider height.
- StandingsPreview: opt-in `showProjected` column (projected points only),
gated on participants remaining; reserve the delta line only when a row
actually moved (no stray em-dashes).
- Full standings page: pass projected data + showProjected (hidden when the
season is complete).
- League home: fetch via getSevenDayStandingsChange so the preview shows the
same 7-day rank/point changes as the full standings page.
- LeagueRow: top-align stats and restore h-8 dividers so the shared-component
changes don't alter the league list rows.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The CS2 Major EV simulation silently discarded the Champions Stage
bracket for IEM Cologne 2026: the bracket seeded "Team Spirit" in QF1
while the stage assignments listed the (different) "Spirit Academy", so
the realBracket gate found an out-of-field participant and rejected the
whole bracket. The phantom "Spirit Academy" also left a stray
event_results row (33 rows for 32 teams).
The existing "Reset all" button only cleared cs2_major_stage_results, so
re-entering couldn't remove the phantom result or its cached QP total.
Add resetCs2Event, which also deletes the event's event_results and
recomputes the affected participants' cached QP totals — all inside a
single transaction so a mid-operation failure can't leave the event in a
torn state. It deliberately preserves the Champions Stage bracket so
re-entry realigns the stage data to it. The reset button now confirms
and states that results/QP are cleared too.
Tests: resetCs2Event clear+recompute behavior, and a simulator
regression pinning that one out-of-field QF participant disables the
whole bracket.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
## Summary
- 0-3 teams in Stage 3 were being assigned slots 9–10 (high QP) when marked eliminated before other Stage 3 teams, because `computeStage3ExitQP` filled from slot 9 upward using only the teams passed in
- 1-3 teams had the same problem when marked before 2-3 teams
- Fix: gate all Stage 3 QP computation on `stage3Exits.length === STAGE3_TOTAL_EXITS` (8) — partial saves write 0 QP as a placeholder, and correct QP/placements are assigned once all 8 exits are known
- As belt-and-suspenders, `computeStage3ExitQP` now places 0-wins teams from the bottom of the slot range so the function itself is correct even if called with a partial set
## Test plan
- [ ] Run `npm run test:run -- app/models/__tests__/cs2-major-stage.test.ts` — all 17 tests pass
- [ ] Mark 2 Stage 3 teams as 0-3 eliminated and save — confirm they show 0 QP (not 2 QP)
- [ ] Mark all 8 Stage 3 exits and save — confirm 0-3 teams get slots 15–16 QP, 1-3 teams get slots 12–14 QP split correctly
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #89
- Reposition admin mobile bar from top-0/z-10 to top-16/z-40 so it
sits below the main Navbar instead of behind it
- Make Sheet controlled so the drawer closes when a nav link is tapped
- Pass onNavigate callback to AdminNavLinks to close Sheet on navigation
https://claude.ai/code/session_01F7rJW6gpaXMiSF3wQYrmhC
- IndyCar points were showing as 0 because ESPN uses 'championshipPts' not 'points'
as the stat name; add it as primary key in the fallback chain
- Rename season_standings card title from sportSeasonName to "${name} Standings"
- Remove non-finalized subtext from SeasonStandings CardDescription
- Restore finalized-season badge (season complete / top-8 points locked) which
was dropped when removing the subtext; derive from sportsSeason.status at the
component level instead of the loader so the dead seasonIsFinalized field is
also removed from the loader return
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary
- Deletes 12 `it("calls onX with correct args")` test blocks from `MiniDraftGrid.test.tsx` and `DraftGridSection.test.tsx`
- Removes now-unused `import userEvent` from both files
## Why
`userEvent.setup().click()` hangs indefinitely on Radix UI `ContextMenu` items in jsdom — pointer-event and animation checks stall waiting for CSS transitions that never fire `transitionend` in the test environment. This caused a flaky 5 s timeout in CI.
The deleted tests were verifying that clicking a `ContextMenuItem` fires its `onClick` — React/Radix wiring, not app logic. The remaining presence/absence tests already cover the conditional rendering (which items appear under which conditions), which is where the actual app logic lives.
## Test plan
- [ ] `npm run test:run -- MiniDraftGrid DraftGridSection` — all remaining tests pass, no timeouts
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #81
## Summary
- Removes the last in-process \`setInterval\` (\`server/snapshots.ts\` 24h loop) and replaces it with an external HTTP cron job via Forgejo Actions
- Adds automated standings sync + conditional simulation: syncs every 2h, only simulates when standings actually changed (detected by comparing \`gamesPlayed\`/\`leagueRank\` before upsert)
- Adds \`GET /healthz\` for Docker healthcheck (Phase B prerequisite)
## What's new
| Endpoint | Triggered by | What it does |
|---|---|---|
| \`POST /admin/jobs/run-daily-snapshots\` | Forgejo schedule \`5 0 * * *\` | Creates daily fantasy standings snapshots for all active/draft seasons |
| \`POST /admin/jobs/sync-and-simulate\` | Forgejo schedule \`0 */2 * * *\` | Syncs standings from external APIs; runs simulation only if standings changed |
| \`GET /healthz\` | Docker / Traefik | Returns 200 \`{ok:true}\` when DB reachable, 503 otherwise |
Both cron endpoints are protected by \`X-Cron-Secret\` header (set \`CRON_SECRET\` in Forgejo repo secrets + production env).
## Schema changes (migration 0118)
Two new nullable columns on \`sports_seasons\`:
- \`standings_last_changed_at\` — written by \`syncStandings()\` when data actually changes
- \`last_simulated_at\` — written by the cron job after a successful simulation run
## Deployment notes
1. Add \`CRON_SECRET\` to Forgejo repo secrets (generate with \`openssl rand -hex 32\`)
2. Add same value to production environment
3. Migration runs automatically via the \`migrate\` container on deploy
## Test plan
- [ ] \`curl -X POST https://brackt.com/admin/jobs/run-daily-snapshots -H "X-Cron-Secret: ..."\` → 200 \`{total, succeeded, errors}\`
- [ ] \`curl -X POST https://brackt.com/admin/jobs/sync-and-simulate -H "X-Cron-Secret: ..."\` → 200 with \`synced\`/\`unchanged\`/\`simulated\` breakdown
- [ ] \`curl https://brackt.com/healthz\` → 200 \`{ok:true}\`
- [ ] Verify Forgejo workflow runs appear in Actions tab after merge
- [ ] Kill web process mid-day; confirm external cron still fires (no in-process dependency)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #79
- Pause snapshot used Math.floor while the client display used Math.ceil,
causing the visible clock to round down by 1s on pause click
- draft-state-sync also used Math.floor for reconnecting clients
- Extract msToSeconds() to app/lib/draft-timer.ts as the single source of
truth for all ms→seconds conversions across server and client
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
SportIcon renders <img> elements whose onError handler calls setFailed(true),
scheduling state updates asynchronously outside React act() in jsdom. With
multiple icons on the Sports page this caused the synchronous render test to
hit the 5000ms Vitest timeout intermittently.
Mock SportIcon in the test using resolveSportIconUrl() so the mock stays in
sync with the real URL resolution logic if it ever changes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Filter the QP table to show only participants with QP > 0 or drafted by any team in the league (undrafted 0-QP participants hidden)
- Compute global ranks with tie handling across the full field before filtering so displayed rank numbers and the top-8 Points Line remain correct after rows are removed
- Fix flaky CI timeouts: world-cup simulator test (100 → 50 iterations), SportsSection userEvent test (explicit 15s timeout)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- pauseDraftOnError now calls onDraftPaused() before emitting so the
error-path pause carries the same snapshotted timer data as the
manual-pause route (fixes inconsistency between the two paths)
- Parallelize DB updates in onDraftPaused with Promise.all instead of
sequential awaits
- Extract clientExpiresAt() helper to draft-timer.ts and use it in all
three places that re-anchor timeRemaining to the client clock, replacing
duplicated Date.now() + timeRemaining * 1000 expressions
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary
- The countdown display used `data.expiresAt` (server-side Unix timestamp) subtracted from `client Date.now()`. When the server clock runs ~2-3s ahead of the client (observed in production), the display was inflated by that delta.
- Fixes three linked symptoms: timer starting at 2:02 instead of 2:00, chess-clock increment crediting 1:54 instead of 1:55, and the commissioner's adjust-time-bank dialog disagreeing with the visible countdown.
- Fix: replace all server `expiresAt` timestamps with a client-local expiry from the server-provided `timeRemaining` integer (`Date.now() + timeRemaining * 1000`). The skew then cancels algebraically when the server computes credit.
## Sites changed
- `handleTimerPickStarted` — fires after every pick (the main fix)
- `handleDraftStateSync` — reconnect path
- `useState` initializer in the draft room — initial page load seed from loader data (uses `loaderTimerNow` server timestamp to compute remaining server-side, then re-anchors to client clock)
## Test plan
- [ ] Start a chess-clock draft (2:00 bank, 15s increment) — timer should show exactly **2:00** when a team goes on the clock
- [ ] Pick at 1:40 — new bank should show **1:55** (100 + 15s)
- [ ] Commissioner adjust-time-bank dialog — displayed remaining should match the countdown
- [ ] Force autopick at any displayed time T — new bank should be T + increment
- [ ] Reconnect mid-pick — timer should resume at the correct remaining time
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #74
## Summary
- **Timer bank broadcasts**: emit `timer-bank-updated` after every pick so all clients immediately see the updated bank instead of waiting for the next `timer-pick-started`
- **Increment accuracy**: capture `pickMadeAt` at route entry (before auth/DB overhead) and use `Math.ceil` so credited seconds always match the client countdown display
- **Race condition fix**: hold `schedulingInProgress` lock for the full timer callback to prevent the recovery interval from scheduling a duplicate timeout mid-pick
- **force-autopick fix**: call `rescheduleTimer` so the next team's clock starts immediately instead of waiting for the old timeout to naturally expire
- **adjust-time-bank fix**: for on-clock teams, shift `picksExpiresAt` by the adjustment and reschedule so the client countdown updates; block adjustments that would reduce the bank to zero
- **New socket events**: `timer-pick-started`, `timer-overnight-paused`, `timer-bank-updated` with full type definitions; removed dead `timer-update` event
- **Reconnect sync**: `draft-state-sync` now includes `expiresAt` for the active timer and `isOvernightPause` state so reconnecting clients see accurate countdown and pause banner immediately without a page reload
- **Room closure countdown**: capture client-side timestamp when draft completes so the "Room closes in X" countdown actually ticks down before the loader revalidates with `draftCompletedAt`
- **Countdown interval**: run at 500ms with `Math.ceil` to prevent skipped seconds under event loop pressure
- **Overnight pause UX**: `canPick` only blocks on commissioner pause — overnight pause freezes the timer but the on-clock player can still pick early
- **Overnight pause refactor**: extract `checkOvernightPause` to `server/overnight-pause-check.ts`, breaking the `timer↔socket` circular import and sharing the timezone cache across both callers with correct eviction
- **PostgreSQL type fix**: cast `varchar` owner ID to `uuid` in `getTeamTimezone` join
## Test plan
- [ ] Manual pick: all clients see bank increment immediately after pick
- [ ] Timeout pick: all clients see bank update (0 → increment); next clock starts within ~1s
- [ ] Force-autopick: next team's clock starts immediately; no "Pick already made" log
- [ ] Force-manual-pick: all clients see bank increment
- [ ] Pause while clock running: countdown freezes on all clients
- [ ] Resume: clock continues from frozen value
- [ ] adjust-time-bank on on-clock team: countdown shifts immediately
- [ ] adjust-time-bank to zero: returns 400 error
- [ ] Reconnect (socket disconnect/connect): countdown resumes for correct team
- [ ] Hard refresh mid-draft: on-clock indicator and countdown correct immediately
- [ ] Draft complete: "Room closes in X" counts down
- [ ] Overnight pause: banner shows, pick buttons still enabled, timer frozen
- [ ] `npm run test:run` — all 158 files / 2351 tests pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #72
## Problem
Running a simulation on MLB (and any sport where the readiness check fails) showed a confusing React Router 400 error instead of the real failure reason. The cause: the simulate route had only an \`action\` export. When the action **threw** instead of redirecting, React Router tried to render the route via GET to display the error — hit the missing loader — and replaced the real error with its own internal 400.
A secondary issue: the interim fix used \`?simulationError=\` query params, which had three problems identified in code review:
- Stale errors re-appeared when pressing browser Back after fixing the issue
- The param reflected arbitrary text into the UI (social engineering surface)
- The styling didn't match the established \`bg-destructive/15\` error pattern
## Changes
**\`admin.sports-seasons.\$id.simulate.tsx\`** — strip the action; keep a loader-only redirect stub so bookmarked URLs degrade gracefully to the season page.
**\`admin.sports-seasons.\$id.tsx\`** — add \`intent="simulate"\` to the action dispatcher (matching \`delete\`, \`rescore\`, \`sync-standings\`, \`finalize-standings\`). On success: redirect to expected-values (unchanged). On failure: return \`{ simulateError: message }\` displayed inline with the correct \`bg-destructive/15\` styling.
## Test plan
- [ ] Click Run Simulation on a season with a missing readiness input → error message appears inline below the description text, styled consistently with other errors on the page
- [ ] Click Run Simulation on a fully-configured season → redirects to expected-values as before
- [ ] Navigate directly to \`/admin/sports-seasons/<id>/simulate\` in browser → redirects to season page (no 400)
- [ ] Run simulation, see error, fix the issue, run again successfully → no stale error message persists
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #64
## Summary
- **Per-league queue**: replaced the single global notification queue with a \`Map<leagueId, queue>\` so concurrent drafts in different leagues drain independently and don't block each other
- **Deadlock fix**: wrapped the drainer loop in \`try/finally\` so \`drainingLeagues\` is always cleaned up even if a task throws unexpectedly — previously a crash would leave the flag set permanently, silently dropping all future notifications for that league
- **Wait cap fix**: moved \`Math.min\` to wrap \`(retryAfter * (attempt+1))\` so the 10s ceiling applies to the final product, not just the base value — settings actions that directly await webhook calls were previously blockable for up to 30s on a rate-limited third attempt
## Root cause of the original problem
During an autodraft chain, \`notifyPickMadeOnDiscord\` was called fire-and-forget for each pick in the chain, causing all webhook requests to fly concurrently. Discord's per-webhook rate limit (~5 req/2s) rejected most of them; the single retry logic fired for all simultaneously, hit the limit again, and the \`.catch()\` swallowed the errors silently.
## Test plan
- [ ] Enable autodraft for 5+ consecutive teams; trigger the chain; confirm all picks announce in Discord in order
- [ ] Confirm a slow/rate-limited webhook in League A does not delay League B's announcements
- [ ] \`npm run test:run\` — 158 test files, 2336 tests, all pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #57
## Summary
- **Group stage match list**: Removed MD 1/2/3 headings; matches now listed chronologically under date separators (e.g. "Jun 14"). Kick-off time appears below the team names instead of between them.
- **Sort order**: \`findMatchesByGroupIds\` / \`findMatchesByEventId\` now order by \`scheduledAt ASC NULLS LAST\` so unscheduled matches always trail scheduled ones.
- **Groups/Bracket toggle**: When both group stage and knockout bracket exist, a toggle appears (mirroring the NBA/AFL standings toggle). Sports with both regular-season standings and a group stage get all views available.
- **Upcoming events**: \`getUpcomingEventsForDraftedParticipants\` now also queries \`groupStageMatches\`, so World Cup group fixtures appear on the home page calendar sorted by kick-off time with a label like "Group A — France vs Germany".
- **\`isAllCompete\` fix**: \`UpcomingEventsCard\` and \`UpcomingCalendarPanel\` now treat \`group_stage_match\` as a bracket-style event, showing team badges instead of "N of your picks".
Fixes#53
## Test plan
- [ ] Navigate to a World Cup sports season page — groups should be listed chronologically under date headers with no MD labels; kick-off time should appear below each match row
- [ ] Once the knockout bracket has matches, confirm the Groups/Bracket toggle appears and both views render correctly
- [ ] On the home page, a user with drafted World Cup participants should see upcoming group fixtures in the calendar panel with individual team badges (not a participant count)
- [ ] NBA/AFL/NHL pages unaffected — their standings/playoffs/finished toggle still works normally
- [ ] \`npm run typecheck\` and \`npm run test:run\` pass
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #55
## Summary
- Swap side-effect order so `updateProbabilitiesAfterResult` runs before `recalculateAffectedLeagues` in `processMatchResult`, `processPlayoffEvent`, and the `set-round-winners` route — projected points now reflect the new result immediately instead of waiting on the next simulation.
- Eliminate the N+1 EV lookup in `calculateTeamProjectedScore` by pre-fetching every EV the season needs in a single `inArray` query inside `recalculateStandings` and passing the map down.
- Add `skipProbabilities` option to `processPlayoffEvent`, used from `autoCompleteRoundIfDone` (callers have already refreshed EVs), avoiding a redundant pass on round-completing saves.
Fixes#31
## Test plan
- [x] `npm run typecheck`
- [x] `npx vitest run app/models/__tests__/team-projected-score.test.ts app/models/__tests__/process-match-result.test.ts app/services/__tests__/probability-updater.test.ts` — 57/57 passing
- [ ] Manual: save a round of bracket winners on a sports season with at least one fantasy league and confirm (a) the request returns faster and (b) the team standings show projected points updated to reflect the result without re-running the simulator
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #54
- Move notifyPickMadeOnDiscord() before checkAndTriggerNextAutodraft() in
both executeAutoPick() and the manual pick action. Previously the
triggering pick's announcement fired after all chained autodraft picks
had already announced, causing Discord to show e.g. pick #106 before
#105 before #104. Now each pick announces itself before the next pick
in the chain is triggered.
- Add a single retry with Retry-After delay in sendDiscordWebhook() on
HTTP 429. A burst of consecutive autodraft picks could hit Discord's
per-webhook rate limit and silently drop announcements. Use || 1
(not ?? 1) to handle non-numeric/NaN headers, and cap at 10 s so
that awaited callers such as the draft-order settings actions are
never hung for a full global rate-limit window.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When next_queue autodraft fires and turns itself off, two bugs prevented
the UI from behaving correctly:
1. After reconnect, useDraftAuthRecovery synced autodraftStatus (draft
grid) but not userAutodraft (settings panel), leaving the settings
badge stale until the next page load.
2. Toast notifications for autodraft auto-disable were unreliable: the
condition checked prev.mode rather than why the server disabled it,
causing the wrong toast for manual disables and queue-empty events.
Fix the reconnect sync by calling setUserAutodraft in the revalidation
effect alongside setAutodraftStatus. Fix the toast logic by adding a
reason field ("pick_complete" | "queue_empty") to the server's
autodraft-updated emit, so the client can show the right message without
guessing from local state. Also removes the now-unused userAutodraftRef.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add findTeamByNameInSeason (exact case-insensitive match via lower()) to the team model
- Validate uniqueness in the user-facing team settings rename action
- Validate uniqueness in admin assign-owner and remove-owner paths that auto-generate names
- Reject whitespace-only team names that would trim to an empty string
- Add DB-level unique index on (season_id, lower(name)) to close the TOCTOU race
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Use x-forwarded-proto header (allowlisted to http/https only) when
building the invite link origin so it shows https behind a TLS proxy
- Show the "View Draft Board" bare card in the right column while a
draft is running, matching the card already shown for active/completed
seasons
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When a manual pick triggered an immediate autodraft chain, both Discord
announcements re-read currentPickNumber from the DB, which had already
advanced past the chained pick. Both messages showed the same "On the
clock" person, pinging them twice.
Fix: pass nextPickNumber (the pick immediately following each specific
pick, before any chain) as an explicit param to notifyPickMadeOnDiscord
instead of re-reading from the DB. Also removes a now-unnecessary DB
round-trip on every pick announcement.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary
- **Discord snake draft fix**: pick notifications now show the sequential pick-in-round (e.g. "Round 2, Pick 9") rather than the snake-adjusted slot position ("Round 2, Pick 5"). Also removes the now-unused \`pickInRound\` param from \`notifyPickMadeOnDiscord\` and adds a regression test for the 13-team case.
- **League card**: league name in draft-in-progress cards is now a link to the league homepage (the Enter Draft button still goes to the draft room).
- **Overnight pause label**: shortened to "🌙 Pause" — the "Resumes 4:00 AM" line below already provides context, so "Overnight" was just causing wrapping.
- **Queue & Picks backgrounds**: items use \`bg-card\` instead of \`bg-muted\` for better visual separation from the panel background.
## Test plan
- [x] Discord: in a snake draft, verify pick #22 of 13 shows "Round 2, Pick 9" in Discord
- [x] League card: dashboard with a draft-in-progress league — click name → league homepage, click Enter Draft → draft room
- [x] Overnight pause: pause a draft overnight — cell shows "🌙 Pause" on one line, "Resumes X:XX" below
- [x] Queue/Picks: open draft room and confirm queue items and recent picks visually pop from the sidebar background
- [x] Unit tests: `npm run test:run` passes (13 discord tests)
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #2
* Add Discord draft pick announcements
Posts a message to the league Discord webhook each time a pick is made, announcing the picked participant and pinging the next team on the clock if their owner has opted into Discord notifications. Enabled via a separate toggle in league settings (independent from standings update notifications).
https://claude.ai/code/session_01Tvwsv3LfL9JUqxoLct8dTn
* Address code review feedback on Discord pick announcements
- Fix "on the clock" timing: read currentPickNumber fresh from DB post-autodraft-chain (matches sendOnTheClockEmail guarantee)
- Remove outer try/catch from notifyPickMadeOnDiscord so callers' .catch() is not dead code
- Add missing draft-discord.server.test.ts with 12 tests covering all early-exit and happy paths
- Fix silent empty-string fallback for missing pickedSlot: warn and skip instead
- Eliminate sequential season→league DB queries by accepting leagueId as a direct param
- Show "save webhook URL to configure options" hint when URL is typed but not yet saved
- Remove block-scope braces at both call sites (plain const declarations)
- Remove redundant "Round N, Pick M" description line (title already carries this info)
- Inline pickInRoundFor helper to avoid circular import with draft-utils
https://claude.ai/code/session_01Tvwsv3LfL9JUqxoLct8dTn
* Fix lint errors from review fixes
- Remove unused logger import (no longer needed after removing try/catch)
- Remove unused OWNER_ID constant in test fixture
- Use toSorted() instead of sort() in sendDraftOrderNotification
https://claude.ai/code/session_01Tvwsv3LfL9JUqxoLct8dTn
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add on-the-clock email notifications and fix push notification modal
- Add `draft_email_notifications_enabled` column to users table
- New `sendOnTheClockEmail` service sends an email when a user's turn arrives
in a draft; detects back-to-back picks and sends one combined email instead
of two; skips notification if the team has autodraft enabled
- Email is triggered after every manual pick (make-pick route) and every
timer-expiry pick (executeAutoPick) once the full autodraft chain settles,
so the notified user is always the first human on the clock
- Add email notification toggle to the user settings Notifications section
- Fix push notification dropdown in the draft room: the bare absolute div is
replaced with a Radix Popover so clicking outside dismisses it without
toggling notifications off
- Rename draft room label from "Pick Notifications" to "Push Notifications"
to distinguish from the new email notifications
https://claude.ai/code/session_01LMGxgYvtE3CF8Jf3u2pXgA
* Address code review feedback on email notification feature
- sendOnTheClockEmail now fetches season (and currentPickNumber) internally,
removing the blocking postChainSeason pre-fetch from both make-pick.ts and
executeAutoPick; callers are now true fire-and-forget with no IIFE needed
- Parallel Promise.all for team, autodraftSettings, and league queries reduces
sequential DB round-trips from 5 to 3
- Remove team.ownerId type cast; assign to local after the null guard
- Combine the two calculatePickInfo calls for the same pick into one
- Fix popoverOpen/enabled divergence: remove the {enabled && ...} guard on
PopoverContent so popoverOpen is the sole visibility control
- Unify NotificationsSection feedback pattern: both Discord and email sections
now read success/error directly from their respective fetcher data via a
shared feedbackFromFetcher helper; removes the success/error props and the
verbose cast that was used for email
- Add 13 unit tests for sendOnTheClockEmail covering: early-exit paths
(no season, past totalPicks, no owner, notifications disabled, autodraft
enabled, no league), single vs back-to-back subject selection, draft room
link presence, error logging without throwing, and parallel query execution
https://claude.ai/code/session_01LMGxgYvtE3CF8Jf3u2pXgA
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add Discord account linking from settings page
Adds a "Connect Discord" button in the Account settings section that
triggers BetterAuth's linkSocial flow to attach a Discord account to
an existing user without requiring a sign-out/sign-in. After the OAuth
callback, the ?section= URL param returns the user to the Account tab.
The Notifications toggle was already gated on Discord being linked.
https://claude.ai/code/session_01UerTpTuBWjreTNEns8srkp
* Fix Discord linking error handling and section routing issues
- Reset linkingDiscord state and show error message when linkSocial throws,
so users can retry if the OAuth flow fails
- Move VALID_SECTION_IDS to module level and derive it from SECTIONS to
avoid per-render allocation and prevent the two from drifting out of sync
- Remove premature SectionId cast before the allowlist validation in
the ?section= URL param handling
- Add tests for loading state and error recovery in AccountSection
Fixes#455https://claude.ai/code/session_01UerTpTuBWjreTNEns8srkp
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix draft order showing only new team when league size increased before order was set
When a commissioner increased the team count on a league that had teams
but no draft order set yet, the server created draft slots only for the
newly-added teams. This left the DB with N+K teams but only K slots,
causing the drag-and-drop list to display only the K new teams.
Two fixes:
1. Server: only append new draft slots when an order was already set
(existingSlots.length > 0). If no order exists yet, skip slot creation
so the page correctly treats the order as unset for all teams.
2. Frontend: buildDraftOrderTeams() appends any unslotted teams after the
slotted ones, so a partially-corrupt DB state still shows all teams.
https://claude.ai/code/session_01M3H55gnMxRztJK9KMXqqZo
* Address code review feedback on draft order bug fix
- Move buildDraftOrderTeams to app/lib/draft-order.ts so it is importable
and testable; remove the local copy from the settings component
- Add unit tests for buildDraftOrderTeams covering the empty, full, and
partial-slot cases
- Tighten the draft slot guard from existingSlots.length > 0 to
existingSlots.length === currentTeamCount so partial legacy states are
treated the same as "order not set"
- Condense the 3-line server comment to a single line per project style
- Rename getNumTeamsInSeason → getNumDraftSlotsBySeasonId to reflect what
the function actually counts, and update its one call site
- Add tests for the server-side slot-creation guard logic
https://claude.ai/code/session_01M3H55gnMxRztJK9KMXqqZo
* Fix lint: move shouldAppendDraftSlots to outer scope
oxlint (consistent-function-scoping) requires functions that don't close
over any variables to be defined at the outer scope rather than inside a
describe block.
https://claude.ai/code/session_01M3H55gnMxRztJK9KMXqqZo
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add notParticipating flag to allow excluding withdrawn participants from qualifying-points simulators
Adds a `not_participating` boolean column to `event_results` so admins can
mark a participant as not competing in a specific upcoming major (e.g. Alcaraz
withdrawing from Wimbledon due to injury). The golf, tennis, and CS2 major
simulators now query this flag for incomplete events and exclude those
participants from the event's draw/field, redistributing probability weight
to the remaining field. Admin UI for qualifying major_tournament events gains
a "Not Participating" card to mark/unmark withdrawals before the event runs.
https://claude.ai/code/session_01HxNPLEXzr5Km3suWrJe2F9
* Address code review feedback on not-participating flag
Security: unmark-not-participating now validates the result exists, belongs
to this event, and is actually a DNP row before deleting. mark-not-participating
now returns a user-friendly error on duplicate-key constraint violations.
Code quality: extract shared getExcludedByEventMap() utility to event-result
model, eliminating the duplicated 20-line exclusion-loading block that was
copy-pasted into all three simulators. Fix hasParticipantResult() to exclude
notParticipating rows so it correctly reflects actual competition participation.
Remove optional chaining on the non-optional notParticipatingIds field in the
admin UI. Fix misleading empty-state message.
Tests: replace the misleading first tennis DNP test (which never used the
activeIds variable it created) with a test that explicitly validates the
fallback behaviour when too few players remain after exclusion. Add three CS2
DNP tests covering the excluded-team-gets-zero-QP path, the redistribution
of wins, and per-event pool independence.
https://claude.ai/code/session_01HxNPLEXzr5Km3suWrJe2F9
* Fix lint errors: replace non-null assertions in CS2 DNP test
https://claude.ai/code/session_01HxNPLEXzr5Km3suWrJe2F9
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Show toast instead of redirecting after league settings save
Commishes now stay on the settings page when saving, with a Sonner
toast confirming the save rather than being navigated to the league
homepage.
https://claude.ai/code/session_01PewdKxVfAbqasJbmk2UGw4
* Fix toast firing for unrelated intents after settings save
Tag update responses with intent: "update" so the success useEffect
only fires for the main settings form, not for owner/commissioner/
reset-draft actions which also return { success: true }. Also replaces
the remaining ?updated=true redirect (no-season edge case) with the
same response shape for consistency.
https://claude.ai/code/session_01PewdKxVfAbqasJbmk2UGw4
---------
Co-authored-by: Claude <noreply@anthropic.com>
useBlocker was receiving a boolean, which caused it to block the settings
form's own POST submission before the onSubmit state-clear could propagate.
Switching to a BlockerFunction that checks nextLocation.pathname lets
same-URL form posts through, so the "leave without saving?" dialog only
fires on genuine navigation away from the settings page.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add Discord notification when draft order is set or randomized
Posts the full draft order to the league's Discord webhook after each
set-draft-order or randomize-draft-order action, with distinct titles
(📋 vs 🎲) so members can tell how it was determined.
https://claude.ai/code/session_01XrBxu358RK6q8iDgRQbMFx
* Refine Discord draft order notification: league name/link, usernames, polish
- Replace seasonName with leagueName + leagueUrl; title links to the league
- Distinguish manual vs randomized in title ("Manually Set" vs "Randomized")
- Show owner username next to each team name in the draft order list
- Remove footer in favour of the linked embed title
- Add 4096-char description clamp consistent with standings notification
- Use a teamMap in both intent branches to avoid O(n²) find-in-loop
- Add test for all-unowned-teams rendering no trailing parentheses
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Remove emoji from draft order notification titles
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
* fix: resolve all 48 WCAG 2.2 AA accessibility issues
Critical fixes:
- Add aria-label to all unlabeled inputs/selects in draft dialogs (ParticipantSelectionDialog, TimeBankAdjustmentDialog, AvailableParticipantsSection)
- Add role="dialog" + aria-modal + focus trap to ConnectionOverlay and AuthRecoveryOverlay
- Add aria-live region and connection status announcement to ConnectionOverlay
Serious fixes:
- Add skip-to-content link in root.tsx with id="main-content" on <main>
- Add aria-label to UserMenu trigger button
- Add aria-describedby + role="alert" to all auth form error messages (login, register, onboarding, forgot-password, reset-password)
- Replace emoji column headers in StandingsTable with aria-label + aria-hidden spans
- Add aria-live="assertive" to "It's your turn" desktop and mobile on-clock indicators
- Add aria-live="polite" to draft room countdown timer
- Add pause button to SportTicker (WCAG 2.2.2); add aria-hidden to ticker content
- Fix Footer text contrast (changed from 28% to text-muted-foreground)
- Fix OvernightPauseSettings: add htmlFor/id pairs and role="radiogroup"+aria-checked to mode buttons
- Fix DraftSetupSection: replace broken htmlFor with aria-label on date picker button
- Add aria-label to PeopleSection owner and commissioner selects
- Add labels to ScoringPresetPicker score inputs; add role="radiogroup"+aria-checked to preset buttons
- Add role="radiogroup"+aria-checked to AutodraftSettings option buttons
- Add accessible names, aria-current="step", and <ol> list semantics to WizardStepper
Moderate fixes:
- Add aria-controls to RecentPicksFeed toggle button; wrap picks list in aria-live region
- Add role="tab"+aria-selected+aria-controls to mobile board sub-tabs + role="tabpanel"
- Add role="radiogroup"+aria-checked to TimerModeSelector
- Add aria-current="page" + aria-label to SettingsDesktopNav
- Add aria-label="Admin navigation" to admin sidebar nav
- Add scope="col" + <caption> to StandingsTable and ScoringTables
- Add ARIA table roles (role="table/rowgroup/row/columnheader/rowheader/cell") to DraftSummaryView CSS grid
Minor fixes:
- Add aria-hidden="true" to decorative trend icons in StandingsTable
- Add aria-hidden="true" to desktop column header labels row in AvailableParticipantsSection
- Replace title with aria-label on all icon-only buttons (watchlist, queue) in AvailableParticipantsSection
- Add aria-label to NotificationSettings switchOnly Switch
- Add prefers-reduced-motion check to SlotMachineHeadline JS animation
- Bump --muted-foreground from 55% to 62% opacity for improved contrast margin
https://claude.ai/code/session_01JXajpFxhqLf8aPCncP81k3
* Fix code review findings from WCAG compliance pass
- Add Arrow key navigation + roving tabindex to all role=radiogroup
components (AutodraftSettings x2, TimerModeSelector,
OvernightPauseSettings, ScoringPresetPicker) per ARIA radio pattern
- Extract shared focus-trap logic into useFocusTrap hook; update
ConnectionOverlay and AuthRecoveryOverlay to use it
- Add tabIndex={-1} to ConnectionOverlay Card so focus can land in
spinner-only state (no interactive children)
- Replace aria-live on loading dots container with sr-only span so
status changes are announced by text content, not aria-label
- Remove contradictory aria-hidden+role=columnheader from
AvailableParticipantsSection visual-only header row
- Remove invalid scope="col" from div[role=columnheader] in
DraftSummaryView (scope is only valid on <th>)
- Remove redundant aria-label from ParticipantSelectionDialog sport
select (htmlFor label is sufficient)
- Change WizardStepper connector <li> to role=presentation
- Revert muted-foreground from 62% to 55% (original already passes
contrast; footer was fixed separately via text-muted-foreground)
https://claude.ai/code/session_01JXajpFxhqLf8aPCncP81k3
* Fix lint error and update tests for WCAG role changes
- Replace el! non-null assertion with optional chaining in useFocusTrap
- Update AutodraftSettings tests to query role="radio" instead of
role="button" (buttons have an explicit radio role since the WCAG pass)
- Update AvailableParticipantsSection watchlist tests to use
getByRole/getAllByRole instead of getByTitle/getAllByTitle (watchlist
buttons now use aria-label instead of title)
https://claude.ai/code/session_01JXajpFxhqLf8aPCncP81k3
---------
Co-authored-by: Claude <noreply@anthropic.com>
Commissioners can now opt in to having a draft start automatically at
its scheduled draftDateTime rather than requiring a manual "Start Draft"
click. The 1-second timer loop checks for eligible seasons each tick and
calls the new shared startDraft() service, which is also used by the
existing commissioner HTTP route.
- Add autoStartDraft boolean to seasons table (migration 0108)
- Extract core start logic into app/services/draft-autostart.ts so both
the API route and the timer can call it without AsyncLocalStorage
- Add checkAndAutoStartDrafts() to the timer tick; disables autoStartDraft
and stops retrying if no draft order is set at fire time
- Guard against null draftDateTime in both the timer query (isNotNull)
and server actions (autoStartDraft forced false when datetime is null)
- Add "Auto-start at scheduled time" checkbox to league creation wizard
(step 3) and league settings, gated on date+time being set
- Show countdown + "Start Now" button in draft room when auto-start is
scheduled; reuses the existing nowForPauseCheck 1-second ticker
- Show orange warning banner on league homepage to commissioners when
auto-start is within 1 hour and no draft order has been configured
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Rename queue page to Set Pre-Draft Queue, remove VORP, fix re-add race condition
- Rename page title, h1, button, error message, and tests from
"Pre-Draft Rankings" to "Set Pre-Draft Queue"
- Remove VORP values and "Sorted by VORP" labels from the all-players list
- Fix bug where removing a player then immediately re-adding would fail
with "already in queue": track in-flight removes in a ref and guard
handleAdd against firing while a remove is still in-flight
https://claude.ai/code/session_01TGAV9A2c72PNkL1ffY7Xeq
* Address code review findings on Set Pre-Draft Queue page
- Rename component function from PreDraftRankings to SetPreDraftQueue
- Guard handleRemove against temp IDs — items added optimistically but
not yet written to the DB have no server-side record to delete; skip
the API call and just drop them from local state
- Surface a toast when handleAdd is blocked by a pending remove instead
of silently no-oping
- Group both refs before their shared useEffect for readability
- Drop justify-between from the All Players desktop heading (sole child)
- Update test describe blocks to "Set Pre-Draft Queue Access"
https://claude.ai/code/session_01TGAV9A2c72PNkL1ffY7Xeq
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add pre-draft queue builder so users can rank players before draft order is set
Creates a new /leagues/:leagueId/draft-queue/:seasonId page that lets team
owners browse participants by VORP and build their autopick queue during the
pre_draft phase. The queue uses the existing draftQueue table so it carries
seamlessly into the live draft room.
Adds a "Build Your Queue" button to DraftInfoCard that shows only when draft
order has not been set yet (replaced by "Enter Draft Room" once it is).
https://claude.ai/code/session_01Gu2DkTWL3nv74EMuGPpxhG
* Improve pre-draft rankings UX: mobile tabs, add/remove toggle, rename
On mobile, show tabs ("All Players" / "My Rankings") instead of a stacked
layout that buries the queue below a long participant list. On the All Players
list, the button now toggles between Add and Remove so users never need to
switch tabs just to drop someone. Desktop keeps the side-by-side panel layout.
Also renames the feature throughout from "queue builder" to "pre-draft rankings"
and the DraftInfoCard button to "Set Pre-Draft Rankings".
https://claude.ai/code/session_01Gu2DkTWL3nv74EMuGPpxhG
* Fix all code review issues in pre-draft rankings feature
- Replace useFetcher with direct fetch() for add/remove/reorder so rapid
clicks no longer cancel in-flight requests
- Add toast.error() on all failure paths (matching live draft room pattern)
and revert optimistic state when operations fail
- Add useRef to give handleReorder a stable reference without a localQueue
closure dependency, preventing unnecessary QueueSection re-renders
- Convert allPlayersPanel and rankingsPanel to useMemo
- Remove leagueId from loader return; read from useParams() instead
- Extract queueBuilderHref to a variable in the league home component
- Add emptyMessage prop to QueueSection with a correct message for the
pre-draft context ("Add players from All Players...")
- Add draft-queue-access.test.ts covering all loader access control paths:
401/403 errors, status-based redirects, and redirect URL correctness
https://claude.ai/code/session_01Gu2DkTWL3nv74EMuGPpxhG
* Fix lint: use !== null check instead of != null
oxlint enforces eqeqeq; replace != null with !== null && !== undefined.
https://claude.ai/code/session_01Gu2DkTWL3nv74EMuGPpxhG
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Show season name instead of year/bracket format; add local timezone hint to draft time
Replace the raw year number and scoringType string in the league creation
sport picker, review step, and league settings sports section with the
human-readable season name (e.g. "2025 NBA Season"), matching how the
league homepage sports list already displays seasons.
Add a client-side local timezone label below the draft date & time fields
on both the league creation wizard and the league settings page, so users
know that draft times are in their local timezone.
https://claude.ai/code/session_01GtJowGruAc1A4jURkSDVjX
* Address code review: shared tz hook, short abbrev, sort fix, dead type cleanup, test update
- Extract timezone detection into useLocalTimezone hook to avoid duplication
across DraftSetupSection and Step3DraftSettings
- Use Intl short timezone abbreviation (e.g. "EST") instead of raw IANA name,
matching DraftInfoCard's existing pattern
- Sort review step sport list by season name instead of sport.name so the
visible order matches the displayed text
- Remove unused scoringType and year fields from SportsSection's local type
- Update SportsSection tests to use realistic season names and the new
display format
https://claude.ai/code/session_01GtJowGruAc1A4jURkSDVjX
---------
Co-authored-by: Claude <noreply@anthropic.com>