Commit graph

495 commits

Author SHA1 Message Date
8a40953019 Fix unhandled rejection from session ping when network is unavailable (#56)
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m34s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m23s
🚀 Deploy / 🔍 Lint (push) Successful in 50s
🚀 Deploy / 🐳 Build (push) Successful in 14m52s
🚀 Deploy / 🚀 Deploy (push) Successful in 12s
## Summary

- The 15-minute session keep-alive interval in `useDraftAuthRecovery` had no `try-catch`. When `authClient.getSession()` is called while the network is down (e.g. a laptop waking from sleep), `better-fetch` throws a `TypeError: Failed to fetch` — producing an unhandled promise rejection that was reported in Sentry.
- Fixed by wrapping the interval callback in a `try-catch`. Network-level `TypeError`s are silently swallowed because real session expiry (HTTP 401) is returned in-band as `{ data: null }` by `better-fetch` and already caught by the `!session` check.
- Improved the comment to explain the mechanism rather than citing socket offline detection (which doesn't validate auth).
- Added 3 tests covering: network throw (no authDegraded), null session response (authDegraded set), valid session (no change).

## Root cause

User left the draft page open overnight. The 15-minute ping fired repeatedly. At some point the computer woke from sleep with the network not yet ready — `getSession()` threw, `setInterval` dropped the rejected promise, Sentry caught it as an unhandled rejection. Confirmed via Sentry breadcrumbs: last activity May 26 8:32 PM, error fired May 27 12:23 PM (~28 hours later).

## Test plan

- [x] 3 new tests pass
- [x] typecheck clean
- [ ] After deploy: monitor Sentry for recurrence

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #56
2026-05-27 16:14:14 +00:00
a9d4954242 Fix World Cup group stage display and upcoming events (#55)
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m28s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m17s
🚀 Deploy / 🔍 Lint (push) Successful in 49s
🚀 Deploy / 🐳 Build (push) Successful in 14m50s
🚀 Deploy / 🚀 Deploy (push) Successful in 10s
## 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
2026-05-27 05:43:08 +00:00
a02f603575 Fix slow bracket save and stale projected points (#54)
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m31s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m20s
🚀 Deploy / 🔍 Lint (push) Successful in 51s
🚀 Deploy / 🐳 Build (push) Successful in 15m9s
🚀 Deploy / 🚀 Deploy (push) Successful in 25s
## 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
2026-05-27 04:28:10 +00:00
b4c224b368 Merge pull request 'Add robots.txt and sitemap for SEO' (#52) from feat/sitemap-robots into main
Some checks failed
🚀 Deploy / 🧪 Test (push) Failing after 1m33s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m21s
🚀 Deploy / 🔍 Lint (push) Successful in 49s
🚀 Deploy / 🐳 Build (push) Has been skipped
🚀 Deploy / 🚀 Deploy (push) Has been skipped
Reviewed-on: #52
2026-05-25 05:21:25 +00:00
Chris Parsons
8e73296067 Fix robots.txt and sitemap issues from code review
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m32s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m23s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 49s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
- Point Sitemap directive at /sitemap.xml (not .gz) so crawlers receive
  plain XML without needing Content-Encoding headers
- Add Disallow: /leagues/ to block all auth-gated league routes
- Gitignore public/sitemap.xml* so they are always generated fresh at
  build time rather than serving a stale committed snapshot

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 22:16:49 -07:00
Chris Parsons
2978ba787d Add robots.txt and sitemap.xml.gz for SEO
Adds a static robots.txt blocking admin/API/auth routes, a sitemap
generation script (scripts/generate-sitemap.mjs) that writes both
sitemap.xml and sitemap.xml.gz to public/, and hooks it into the
build so the sitemap is always fresh on deploy.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 22:05:37 -07:00
874a2db853 Merge pull request 'Fix Discord pick announcements arriving out of order and add 429 retry' (#51) from fix/discord-pick-announcement-ordering into main
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m27s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m18s
🚀 Deploy / 🔍 Lint (push) Successful in 47s
🚀 Deploy / 🐳 Build (push) Successful in 14m54s
🚀 Deploy / 🚀 Deploy (push) Successful in 12s
Reviewed-on: #51
2026-05-25 04:34:47 +00:00
Chris Parsons
77f520823c Fix Discord pick announcements arriving out of order and add 429 retry
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m30s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m16s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 48s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
- 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>
2026-05-24 21:29:02 -07:00
425b4724d2 Fix autodraft settings panel not reflecting auto-disable after pick (#50)
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m21s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m13s
🚀 Deploy / 🔍 Lint (push) Successful in 46s
🚀 Deploy / 🐳 Build (push) Successful in 14m31s
🚀 Deploy / 🚀 Deploy (push) Successful in 9s
2026-05-24 01:35:13 +00:00
Chris Parsons
e3a7a1a9b1 Fix autodraft settings panel not reflecting auto-disable after pick
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m24s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m13s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 45s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
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>
2026-05-23 18:29:13 -07:00
3518bd77e8 Merge pull request 'Enforce unique team names within a season' (#49) from fix/team-name-uniqueness into main
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m26s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m16s
🚀 Deploy / 🔍 Lint (push) Successful in 48s
🚀 Deploy / 🐳 Build (push) Successful in 14m33s
🚀 Deploy / 🚀 Deploy (push) Successful in 10s
Reviewed-on: #49
2026-05-24 00:07:28 +00:00
Chris Parsons
c9fdb12a09 Enforce unique team names within a season
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m31s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m19s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 48s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
- 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>
2026-05-23 16:55:08 -07:00
79e7591dc7 Merge pull request 'Fix invite link showing http and add draft board link during live draft' (#48) from fix/invite-link-https-draft-board-link into main
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m23s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m15s
🚀 Deploy / 🔍 Lint (push) Successful in 46s
🚀 Deploy / 🐳 Build (push) Successful in 14m25s
🚀 Deploy / 🚀 Deploy (push) Successful in 10s
Reviewed-on: #48
2026-05-23 05:36:33 +00:00
Chris Parsons
3f9c1d99e2 Fix invite link showing http and show draft board card during live draft
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m25s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m14s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 48s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
- 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>
2026-05-22 22:31:52 -07:00
4fa927e66b Merge pull request 'Fix Discord double-ping when autodraft fires after manual pick' (#47) from fix/discord-autodraft-double-ping into main
All checks were successful
🚀 Deploy / ʦ TypeScript (push) Successful in 1m15s
🚀 Deploy / 🔍 Lint (push) Successful in 48s
🚀 Deploy / 🧪 Test (push) Successful in 1m24s
🚀 Deploy / 🐳 Build (push) Successful in 14m25s
🚀 Deploy / 🚀 Deploy (push) Successful in 15s
Reviewed-on: #47
2026-05-23 03:46:48 +00:00
Chris Parsons
1b51cb554b Fix Discord double-ping when autodraft fires immediately after manual pick
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m33s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m16s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 47s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
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>
2026-05-22 20:38:35 -07:00
841760541d Fix snake draft Discord pick numbering and small UX tweaks (#2)
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m27s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m16s
🚀 Deploy / 🔍 Lint (push) Successful in 1m55s
🚀 Deploy / 🐳 Build (push) Successful in 14m23s
🚀 Deploy / 🚀 Deploy (push) Successful in 10s
## 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
2026-05-22 04:18:11 +00:00
Chris Parsons
4f9f9b5c6f Install Docker CLI in build job
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 1m33s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m23s
🚀 Deploy / 🔍 Lint (push) Successful in 49s
🚀 Deploy / 🐳 Build (push) Successful in 15m5s
🚀 Deploy / 🚀 Deploy (push) Successful in 31s
node:20-bookworm doesn't include the Docker CLI; install docker.io via
apt before the buildx and registry steps.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 20:05:34 -07:00
85b3317f9a Merge pull request 'Migrate CI/CD from GitHub Actions to Forgejo Actions' (#1) from chore/forgejo-actions into main
Some checks failed
🚀 Deploy / 🧪 Test (push) Successful in 1m29s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m21s
🚀 Deploy / 🔍 Lint (push) Successful in 48s
🚀 Deploy / 🐳 Build (push) Has been cancelled
🚀 Deploy / 🚀 Deploy (push) Has been cancelled
Reviewed-on: #1
2026-05-22 01:39:03 +00:00
Chris Parsons
b9a1ea2cb4 Remove setup-node from CI jobs
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 1m26s
🚀 Deploy / ʦ TypeScript (pull_request) Successful in 1m17s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 48s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
Node 20 is already in the node:20-bookworm runner image; setup-node
was hanging ~5min trying to reach an unconfigured npm cache service.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 17:04:12 -07:00
Chris Parsons
2192f1790d Add oxlint config and fix unicorn/no-array-sort violation
Some checks failed
🚀 Deploy / ʦ TypeScript (pull_request) Has been cancelled
🚀 Deploy / 🔍 Lint (pull_request) Has been cancelled
🚀 Deploy / 🐳 Build (pull_request) Has been cancelled
🚀 Deploy / 🚀 Deploy (pull_request) Has been cancelled
🚀 Deploy / 🧪 Test (pull_request) Has been cancelled
Promote unicorn/no-array-sort to error in oxlint.json and replace
[...teams].sort() with teams.toSorted() in discord.ts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 17:01:02 -07:00
Chris Parsons
0b8f7edc08 Fix postgres service for Forgejo Docker runner
Some checks failed
🚀 Deploy / 🧪 Test (pull_request) Failing after 21m9s
🚀 Deploy / ʦ TypeScript (pull_request) Failing after 11m24s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 10m2s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
Remove host port binding (conflicts with local postgres on runner) and
use service name hostname instead of localhost for DATABASE_URL.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 16:14:27 -07:00
Chris Parsons
9ac7fb5b31 Migrate CI/CD from GitHub Actions to Forgejo Actions
Some checks failed
🚀 Deploy / 🧪 Test (pull_request) Failing after 2m57s
🚀 Deploy / ʦ TypeScript (pull_request) Failing after 10m55s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 10m36s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
- Move workflows from .github/ to .forgejo/ so they only run on Forgejo
- Replace styfle/cancel-workflow-action with native concurrency block
- Use full GitHub URLs for all third-party actions to bypass mirror
- Switch Docker layer cache from type=gha to type=registry
- Drop label-subissues workflow (relies on GitHub-specific GraphQL API)
- Add timeout-minutes to all jobs; cancel-in-progress only for non-main branches

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 15:52:00 -07:00
Chris Parsons
fbcecb490e
Add Discord draft pick announcements (#460)
* 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>
2026-05-20 19:55:48 -07:00
Chris Parsons
b8b58ec9f8
Add draft email notifications feature (#459)
* 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>
2026-05-20 15:35:43 -07:00
Chris Parsons
7809864674
Add Discord account linking from settings page (#457)
* 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 #455

https://claude.ai/code/session_01UerTpTuBWjreTNEns8srkp

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-20 13:38:44 -07:00
Chris Parsons
80973d3212
Fix draft Summary tab showing wrong avatar for teams without custom logos (#453)
DraftSummaryView was not declaring or forwarding ownerAvatarData, so
TeamAvatar fell back to a generated flag instead of the owner's avatar.
DraftGrid and DraftGridSection already threaded ownerAvatarData correctly;
this makes the Summary tab consistent. No route changes needed — the loader
already enriches draftSlots with ownerAvatarData.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 00:02:19 -07:00
Chris Parsons
ea125e0d5e
Fix draft room Summary tab layout and board scroll clipping (#452)
- Add display:contents to rowgroup divs in DraftSummaryView so cells
  flow correctly into the CSS grid (sports as rows, teams as columns)
- Use opaque bg-muted on team column headers to prevent content
  bleeding through during sticky scroll
- Remove whitespace-nowrap and add break-words on sport row headers
  so long names like "FIFA Men's World Cup" wrap within the column
- Add pb-4 to DraftGridSection scroll wrapper so the last pick row
  isn't flush against the scroll boundary

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 23:31:40 -07:00
Chris Parsons
461847c414
Add public sports overview page (#451) 2026-05-19 23:02:58 -07:00
Chris Parsons
0ba2b391f8
Fix draft order initialization for teams added mid-season (#449)
* 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>
2026-05-19 18:22:47 -07:00
Chris Parsons
06d415d95c
Change Socket.IO connection error logging from error to log level (#448)
* fix: stop reporting transient WebSocket connect_error to Sentry

connect_error fires on every retry attempt (e.g. iOS Safari dropping
WebSocket during network transitions). Using logger.error routed each
attempt to Sentry.captureException, generating noise for a self-healing
failure. Switch to logger.log (no-op in production); the real failure
path (reconnect_failed) still uses logger.error and surfaces in Sentry.

https://claude.ai/code/session_01TpZ9W111Trkv2g4CkCWFpB

* refactor(useDraftSocket): clean up reconnect event handling

- Remove redundant reconnect_attempt listener: connect_error already
  sets isReconnecting(true), and connectionError is never set before
  reconnect_attempt fires, making that handler a no-op
- Wrap reconnect_failed in an Error object so Sentry receives a proper
  exception with stack trace instead of a plain captureMessage string
- Store handleReconnectFailed as a named reference so socket.io.off()
  removes only this listener rather than all reconnect_failed listeners

https://claude.ai/code/session_01TpZ9W111Trkv2g4CkCWFpB

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-19 15:47:41 -07:00
Chris Parsons
43dbdf0040
Add not-participating exclusion support for event results (#446)
* 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>
2026-05-19 11:13:32 -07:00
Chris Parsons
3c757c1f73
Replace settings redirect with toast notification (#445)
* 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>
2026-05-18 16:08:10 -07:00
Chris Parsons
68193e31c5
Block bot probe requests before routing (#444)
Fixes #344

* Add bot probe filter middleware and Sentry noise suppression

Block common bot scanning paths (wp-admin, .env, .php, etc.) in Express
before React Router handles them, preventing spurious Sentry errors.
Also filter Sentry events for React Flight protocol probes ($1:aa:aa
multipart body pattern) and any remaining bot-path 404 noise.

https://claude.ai/code/session_01Y5Ca6oxd5zyyM89acmogf7

* Tighten bot probe regex and React Flight Sentry filter

- Remove .xml, .log, .git from bot probe blocklist to avoid false positives
  on legitimate routes (e.g. /sitemap.xml)
- Tighten React Flight error filter from broad string match to precise
  wire-format pattern (/\$\d+:[a-z]/) to avoid swallowing real errors
- Remove redundant URL check from beforeSend (ignoreErrors already covers it)
- Fix missing newline at end of instrument.server.mjs

https://claude.ai/code/session_01Y5Ca6oxd5zyyM89acmogf7

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-18 11:17:18 -07:00
Chris Parsons
f258d7a304
fix: prevent useBlocker from intercepting same-route form submissions (#443)
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>
2026-05-18 08:47:46 -07:00
Chris Parsons
c71eb69648
Add Discord notifications for draft order changes (#441)
* 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>
2026-05-17 23:20:51 -07:00
Chris Parsons
1f0fcf970b
Fix QP tie rounding and finalized scoring (#440) 2026-05-17 21:58:53 -07:00
Chris Parsons
4bbcac1949
fix: resolve all 48 WCAG 2.2 AA accessibility issues (#439)
* 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>
2026-05-17 20:11:38 -07:00
Chris Parsons
d468385d90
Add auto-start draft at scheduled time (#437) (#438)
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>
2026-05-16 23:37:29 -07:00
Chris Parsons
faecfd8ecc
Rename queue page to Set Pre-Draft Queue, remove VORP, fix re-add race condition (#436)
* 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>
2026-05-15 18:47:36 -07:00
Chris Parsons
973e56142f
Add pre-draft queue builder so users can rank players before draft order is set (#435)
* 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>
2026-05-15 17:26:36 -07:00
Chris Parsons
55828e9f42
Simplify sports season display and add local timezone hints (#434)
* 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>
2026-05-15 16:04:07 -07:00
Chris Parsons
d92f73e449
Extract chess clock presets to shared constant (#432)
* Fix custom chess-clock timer detection and save settings blocker

- Extract getInitialDraftSpeed() helper so both useState init and
  resetSettingsFormState use the same logic; unrecognized presets
  now produce a "custom:{bank}:{incr}" string instead of falling
  back to "standard", so the custom section auto-expands correctly
  (e.g. 8 hr bank + 30 min increment is no longer shown as Standard)
- resetSettingsFormState was not resetting draftSpeed at all; fixed
- Clear hasUnsavedSettingsChanges in the Form's onSubmit so the
  useBlocker check is false at the moment the save navigation starts,
  preventing the "Leave without saving?" dialog from firing on save
- Replace the cleared-on-success useEffect with one that re-marks
  dirty when the action returns an error, so the warning reappears
  after a failed save

https://claude.ai/code/session_01DgHNkvJXGizx41CE2tkVS1

* Address code review: single source of truth for presets, useEffect guard, tests

- Extract CHESS_CLOCK_PRESETS (pure data) into draft-timer.ts as the
  canonical source of truth; DraftSpeedPicker.tsx now spreads those
  values into CHESS_PRESETS rather than duplicating the numbers
- getInitialDraftSpeed moved to draft-timer.ts and rewritten to use
  CHESS_CLOCK_PRESETS.find() — no more hardcoded bankSec/incrSec values
  in three separate places
- parseDraftSpeed switch replaced with CHESS_CLOCK_PRESETS.find() and
  an explicit fallback comment; eliminates the silent default-handles-
  "standard" fragility called out in review
- useEffect that re-marks settings dirty now guards against non-settings
  errors (draft-order, commissioner actions) which carry a `section`
  field — previously any error actionData would spuriously set
  hasUnsavedSettingsChanges=true
- Add parseDraftSpeed and getInitialDraftSpeed test suites to
  draft-timer.test.ts, including parametrised preset coverage via
  it.each(CHESS_CLOCK_PRESETS)

https://claude.ai/code/session_01DgHNkvJXGizx41CE2tkVS1

* Fix lint: use !== null/undefined instead of != null

oxlint enforces eqeqeq; the null check in getInitialDraftSpeed used
!= which triggered two errors.

https://claude.ai/code/session_01DgHNkvJXGizx41CE2tkVS1

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-15 14:02:49 -07:00
Chris Parsons
6f70a19b73
Add admin user management interface with search and username editing (#431)
* Add admin users management page with pagination, search, and inline username editing

https://claude.ai/code/session_01E4UUQqQedhFP2F5YcBRArs

* Fix five issues from admin users page code review

- admin.users: use useEffect to close inline edit on success so validation
  errors are not silently discarded when the save button fires onClick
- root: add /admin to ONBOARDING_EXEMPT so admin users without a username
  are not redirect-looped away from admin pages
- settings: skip username validation when the username field is empty so
  updating timezone alone does not break for accounts without a username
- models/user: exclude soft-deleted users from findUsersPaginated
- admin.users: remove unused hasMore from loader return; simplify header div

https://claude.ai/code/session_01E4UUQqQedhFP2F5YcBRArs

* Fix lint: rename shadowed variables in user model

- findUserByUsername: use imported sql directly instead of destructuring
  it from the callback (shadowed the top-level import)
- findUsersPaginated: rename orderBy callback param from users to t
  (shadowed the outer users result variable)

https://claude.ai/code/session_01E4UUQqQedhFP2F5YcBRArs

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-15 12:07:51 -07:00
Chris Parsons
215b0cf6b5
Add user onboarding flow with username selection (#430)
* Add username onboarding prompt for new signups

New users (especially via OAuth/Google) are redirected to /onboarding
to choose a display username before accessing the app. Adds unique
constraint on users.username and case-insensitive uniqueness validation.

https://claude.ai/code/session_01UinBMAy9d6dQzzbcUAdq8J

* Address all code review issues on username onboarding

- Replace case-sensitive unique constraint with functional unique index on
  lower(username) so DB-level uniqueness is case-insensitive (fix #1)
- Share USERNAME_RE from models/user.ts; add same format + uniqueness
  validation to the settings update-profile action (fix #2)
- Wrap updateUser calls in try/catch to handle race-condition DB errors
  gracefully in both onboarding and settings (fix #3)
- Add unit tests for suggestUsername, safeRedirectTo, USERNAME_RE, and
  isOnboardingExempt (fix #4)
- Guard suggestUsername against returning strings shorter than 3 chars (fix #5)
- Preserve the user's intended destination via redirectTo query param
  through the onboarding flow (fix #6)
- Treat empty username in settings as a validation error instead of a
  silent no-op (fix #7)
- Use exact/sub-path matching in isOnboardingExempt to prevent
  false-positive prefix matches like /loginpage (fix #8)

https://claude.ai/code/session_01UinBMAy9d6dQzzbcUAdq8J

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-15 11:17:15 -07:00
Chris Parsons
469cc82e15
Add opt-in Discord pings to standings notifications (#429)
* Add opt-in Discord ping to standings notifications

Users who have linked their Discord account can enable a ping preference
in Settings > Notifications. When enabled, their bracket username is replaced
with a Discord @mention (<@userId>) in league standings update messages,
sending them a push notification and showing their Discord display name.

Adds discordPingEnabled column to users, a findDiscordIdsByUserIds model
helper, allowed_mentions support to the Discord webhook payload, and a
NotificationsSection settings component.

https://claude.ai/code/session_01NUv93WRrufHhpZSMyY4bjs

* Remove Display Name field from user profile settings

Username is the only user-facing name field. The display_name column
remains in the database since BetterAuth writes the OAuth provider name
there, and it serves as a programmatic fallback via getUserDisplayName.

https://claude.ai/code/session_01NUv93WRrufHhpZSMyY4bjs

* Address code review feedback on Discord ping feature

- Fix broken Account settings link in NotificationsSection: replace the
  non-functional ?section=account href with an onNavigateToAccount callback
  that drives the parent's useState-based section switcher
- Replace hand-rolled toggle button with the project's Switch component
  (Radix UI) for consistent sizing, accessibility, and dark-mode support
- Guard update-discord-ping action: return an error if the user attempts
  to enable pings without a Discord account linked
- Surface action error in NotificationsSection UI
- Cap allowed_mentions.users at 100 to avoid Discord rejecting the payload
  in large leagues
- Remove the showWinner alias in scoring-calculator; inline winnerScoreChanged
- Add comment to league settings test notification explaining why discordUserId
  is omitted
- Clarify database schema comment: displayName is write-only from BetterAuth

https://claude.ai/code/session_01NUv93WRrufHhpZSMyY4bjs

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-15 10:06:54 -07:00
Chris Parsons
d4a9fc8aaf
Improve draft info panel formatting (#428) 2026-05-14 23:42:04 -07:00
Chris Parsons
9e9a37d4d2
Improve unmatched team reconciliation UX (#425) 2026-05-14 16:45:02 -07:00
Chris Parsons
766ba948e1
Add MLS standings sync and fix simulator conference resolution (#423)
* Add MLS standings sync and fix simulator conference resolution

- New MlsStandingsAdapter using ESPN's free soccer API (no key required),
  returning Eastern/Western conference data, W/D/L/GF/GA/GD/PTS, conference
  rank, and home/away records; registered under mls_bracket
- Display route now shows soccer table columns and a 9-team playoff cutoff
  line for mls_bracket (top 9 per conference qualify for MLS Cup Playoffs)
- MLS simulator gains a third conference fallback: reads externalId="Eastern"
  or "Western" on the participant, mirroring the LLWS pool-assignment pattern
  so admins can bootstrap conference data before the first standings sync
- 9 unit tests covering stat mapping, conference normalization, rank ordering,
  and error paths

https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u

* Address code review feedback on MLS standings + simulator

1. Update mls-simulator.ts module comment to document the new step-3
   externalId fallback in the conference resolution order
2. Tighten normalizeConference to exact-match "Eastern"/"Western
   Conference" instead of broad substring, preventing false matches
   on names like "Northeast"
3. Pre-parse statsMap for each entry before the sort so it isn't
   rebuilt O(n log n) times during comparison
4. Document the externalId name-matching tradeoff on
   parseConferenceFromExternalId
5. Try ESPN's gamesPlayed stat before falling back to wins+losses+ties
   sum; export parseConferenceFromExternalId for direct testing
6. Add tests: normalizeConference passthrough, winPct=0 at preseason,
   and parseConferenceFromExternalId (case-insensitivity, null/undefined,
   numeric ESPN IDs, unrecognized strings)

https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u

* Fix lint: replace != null with !== null && !== undefined

oxlint enforces eqeqeq; the five != null checks in mls.ts were flagged.

https://claude.ai/code/session_01WhzXHpv6taXdHzhgvnv83u

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 15:39:40 -07:00
Chris Parsons
c097e4827c
Add MLS sport simulator (mls_bracket) (#422)
* Add MLS sport simulator (mls_bracket)

Adds Major League Soccer as a draftable sport with a full-season Monte Carlo
simulator. Models both preseason regular-season projection (34 games across
Eastern and Western conferences) and the MLS Cup Playoffs bracket, including
the Wild Card (single game + PKs), Round 1 best-of-3 series, Conference
Semis/Finals (single game), and MLS Cup.

P1–P8 mapping: MLS Cup winner, finalist, Conference Finals losers, Conference
Semifinals losers. Conference assignment reads from regularSeasonStandings.conference
or falls back to the region simulator input ("Eastern"/"Western").

Admin inputs: projectedTablePoints (primary, max 102 for 34×3), with derivation
chain to sourceElo via existing input-policy; sourceOdds as alternative.
No hardcoded team data — all inputs are admin-managed per season.

- database/schema.ts: add mls_bracket to simulatorTypeEnum
- drizzle/0104_chief_boom_boom.sql: migration for the new enum value
- mls-simulator.ts: MLSSimulator + exported pure helpers for testability
- registry.ts / manifest.ts / simulator-config.ts: register mls_bracket
- mls-simulator.test.ts: 38 unit tests covering all helpers and sync checks

https://claude.ai/code/session_015wkBJ3SYGcMGjsddKKGkwa

* Fix MLS simulator: config loading, sourceOdds fallback, normalization

Three issues found in code review comparing against EPL and NFL simulators:

1. Load simulator config from DB via getSportsSeasonSimulatorConfig so
   admins can override iterations, seasonGames, parityFactor, drawRates
   per season without code changes. Previously all constants were hardcoded.

2. Add sourceOdds → convertFuturesToElo fallback when no sourceElo is
   present. EPL and NFL both do this; MLS was throwing immediately instead
   of attempting the odds conversion that the manifest declares as optional.

3. Call normalizeSimulationResultColumns before returning results, matching
   EPL's local normalization pattern for consistency (runner also normalizes
   globally, but EPL calls it locally too).

https://claude.ai/code/session_015wkBJ3SYGcMGjsddKKGkwa

* Polish MLS simulator: configNumber zero, logger warning, Map lookup

Three small fixes from secondary code review:

1. configNumber: allow value >= 0 (not just > 0) so admins can
   legitimately set baseDrawRate or drawDecay to 0 without the value
   being silently discarded and replaced with the default.

2. Add logger.warn when a participant is excluded from simulation due
   to a missing Elo rating, matching the NLL bracket-aware pattern.
   Gives admins a visible signal instead of a silent exclusion.

3. getBySeeds: build a Map once instead of calling Array.find() per
   seed. Eliminates 4M linear scans across 50k iterations for a 9-
   element array — trivially fast either way, but Map is the right tool.

https://claude.ai/code/session_015wkBJ3SYGcMGjsddKKGkwa

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-14 12:45:53 -07:00