* Migrate authentication from Clerk to BetterAuth (#322)
Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.
**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field
**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict
better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add opencode oxlint plugin and UI refinements
- Add .opencode/plugins/oxlint.ts to run oxlint automatically on file edits
- Refactor RankingDisplay into shared StatHelpers component
- Add tied rank display support in home loader
- Update navbar with NavLink for active state styling
- Replace .reverse() with .toReversed() in RecentPicksFeed
* Remove unused RankChangeIndicator import in LeagueRow
Show visual dividers in the available participants list indicating where
your future draft picks fall relative to the current pick position.
Dividers are suppressed when any filter is active (search, sport filter,
hide drafted, etc.) since positional references are meaningless in a
filtered view.
- Add getProjectedPicks() to draft-order.ts for computing future pick
positions in a snake draft
- Interleave divider items into the virtualized list in
AvailableParticipantsSection
- Extract ListItem type to module scope
- Add tests for getProjectedPicks, divider rendering, and filter
suppression
Logo SVGs referenced by string path (/logo.svg) were cached by CDNs and
browsers after deployments. Import them with Vite's ?url suffix so the
build emits content-hashed filenames that force a refresh on change.
LeagueRow and StandingsPreview had duplicated StatColumn, StatDivider,
and rank-change indicator helpers. Extract them into a shared
StatHelpers module so both pages render rank and points identically
(#3 style with consistent rank-change arrows).
* Redesign home page with new layout and component system
- Two-column layout (My Leagues 2/3, Upcoming Events 1/3) with mobile stack
- LeagueRow: square avatar, gradient draft highlight, rank/points display, progress bar
- MyLeaguesCard, CreateLeagueCard with shared SectionCardHeader
- UpcomingEventsCard: vertical timeline with grouped multi-league events
- Shared gradient system: BracktGradients SVG defs, GradientIcon wrapper, brand.ts constants
- Button default variant updated to green→cyan gradient
- Navbar: plain nav links with gradient hover, support/admin icon buttons
- Accessibility fixes: semantic h2 headings, aria-label on LeagueAvatar and nav elements
- Storybook stories for all new components
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Responsive league row layout and mobile polish
- League rows stack avatar+name on top, stats full-width below on mobile
- Stats spread to right side on sm+ screens with border separator on mobile
- Tighter padding on mobile (px-3/py-3), full padding on sm+
- Card headers and content use px-3 sm:px-6 to reduce mobile gutters
- Two-column home layout deferred to lg breakpoint (tablet gets stacked)
- Active leagues sorted by completion percentage descending
- Default rank 1 / 0 points for active leagues with no scoring events yet
- Fix ordinal bug for 11th/12th/13th; add aria-labels to rank change indicators
- Remove dead StatDivider className prop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Improve claude file.
* Add StandingsPreview card component with podium row styling
- New StandingsPreview component with gold/silver/bronze row tints for
top 3, team avatar, and LeagueRow-style stat columns (Ranking + Points)
with rank and 7-day point change indicators
- Fix GradientIcon in Storybook by adding BracktGradients decorator to
preview.tsx (renamed from .ts to support JSX)
- Fix degenerate SVG gradient on horizontal strokes by switching
BracktGradients to gradientUnits="userSpaceOnUse" with Lucide-space
coordinates (0→24)
- Revert erroneous fill: url(#gradient) from GradientIcon; stroke-only
fix was sufficient once gradientUnits was corrected
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Update components on league homepage.
* Finish up league page styling.
* Work on standings page.
* Add story for RecentScoresCard
* Update Point Progression Chart.
* Sort point progression legend by ranking and add team links to standings rows
* Fix standings discrepancy on change.
* Create draft cell component.
* Update draft board page
* Draft room improvements.
* Update some draft room styling.
* Fix context menu missing.
* Move tab navigation and autodraft to header row, narrow sidebar
* Virtualize available participants list, memoize draft room props
Adds @tanstack/react-virtual to replace separate mobile/desktop lists
with a single unified virtual scroll loop. Also memoizes miniDraftGrid
and availableParticipantsSectionProps, and switches pick lookup from
Array.find to a Map for O(1) access.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Update draft room UI.
* More draft room fixes.
* Draft room tweaks.
* Fix Rosters page.
* Queue Section fixes.
* Mobile Draft fixes.
* Fix draft board page.
* Create bracket look.
* Bracket work.
* Finish bracket page.
* Homepage initial styling
* homepage copy
* Add privacy policy. Fixes#88.
* how to play copy
* rules copy
* Fix brackets on homepage.
* Add footer to website.
* Glow on dots.
* Landing page copy.
* Fix sidebar.
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add projected-wins input mode to admin Elo Ratings page
Admins can now enter projected season win totals instead of raw Elo
numbers on the Elo Ratings page. Wins are auto-converted to Elo using
the inverse formula and stored as sourceElo, keeping the rest of the
simulation pipeline unchanged.
- Add `projectedWinsToElo` / `eloToProjectedWins` to probability-engine
- Add `simulator-config.ts` centralising per-sport season length, parity
factor, and average opponent Elo (AFL, NFL, NBA, NHL, MLB, WNBA)
- Admin Elo Ratings page: toggle between Elo and Projected Wins input
modes; bulk import parses wins format; existing sourceElo back-fills
the wins field on load
- AFL simulator now reads sourceElo from participantExpectedValues first,
falling back to hardcoded TEAMS_DATA then 1400
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix lint errors in simulator-config tests and probability-engine
- Replace non-null assertions (`!`) with optional chaining (`?.`) in simulator-config tests
- Remove redundant type annotations on default parameters in probability-engine
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Include playoffMatchId in the grouping key so that each match within a
scoring event (e.g. different Round of 32 matchups in snooker) appears
as its own calendar entry instead of being merged together.
- Fix computeEliminatedByRound() to track participant1Id/participant2Id
in addition to winnerId/loserId, so a 7v8 play-in loser placed in a
PIR2 slot (incomplete match) is not shown as eliminated on the league page
- Replace separate Recalculate Floors and Reprocess Eliminations buttons
with a single Reprocess Bracket action that replays all matches and
re-marks non-bracket participants as eliminated
- Add NBA play-in test cases for the elimination computation logic
* Emit standings-updated socket event after recalculate-floors so league pages refresh automatically
When the admin runs "Recalculate Floors" on the bracket page, the league
sports-season homepage was showing stale elimination data because there was
no mechanism to notify it of the change.
Fix: after recalculate-floors updates participant_results, emit a
standings-updated socket event to all fantasy-season draft rooms linked to
the sports season. The sports-season page now joins its draft room and
revalidates its loader whenever it receives that event for the matching
sports season.
https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB
* Fix recalculate-floors incorrectly eliminating play-in losers who still advance
The playoff_matches.isScoring column defaults to true in the database. Brackets
created before this column was added (or before the migration set correct values)
have isScoring=true on play-in rounds that should be false. When recalculate-floors
replayed those matches, it took the "scoring round" path; since "Play-In Round 1"
isn't in ROUND_CONFIG, config===null, and the loser was assigned finalPosition=0
regardless of loserAdvances — permanently eliminating teams like the Suns who had
a second play-in game remaining.
Fix: build a round→isScoring lookup from the bracket template before replaying
matches and use it as the source of truth, falling back to the DB field only when
the template doesn't define the round. This ensures non-scoring play-in rounds
are always processed with isScoring=false so the loserAdvances guard fires
correctly.
Also revert unrelated socket changes from the previous (wrong) commit.
https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB
* Fix isScoring fallback and loserAdvances gaps across all match-processing paths
Three issues found in code review around the recalculate-floors fix:
1. set-winner and set-round-winners (bracket.server.ts) used `match.isScoring ?? true`
just like recalculate-floors did. Both now derive isScoring from the bracket
template as the source of truth, falling back to the DB field only when the round
isn't defined in the template.
2. processPlayoffEvent (scoring-calculator.ts) used `matches[0]?.isScoring ?? true`
with the same DB-default problem. Now uses BRACKET_TEMPLATES[bracketTemplateId]
to look up the round's isScoring before falling back to the DB field.
3. doesLoserAdvance (playoff-match.ts) was missing the AFL afl_10 Qualifying Finals
case: both losers advance to Semi-Finals. Without this, AFL QF losers would
incorrectly receive finalPosition=0 when processed through the non-scoring path.
https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB
* Fix no-non-null-assertion lint errors in isScoring Map lookups
Replace Map.has(key) ? Map.get(key)! : fallback pattern with
Map.get(key) ?? fallback to satisfy oxlint no-non-null-assertion rule.
https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix NBA Play-In 7/8 loser incorrectly marked as eliminated
processPlayoffEvent (called by autoCompleteRoundIfDone when all round matches
finish) was marking every non-scoring round loser as eliminated without
checking doesLoserAdvance. This caused the 7v8 loser, who should advance to
Play-In Round 2, to get finalPosition=0 as soon as the full round completed.
Fixes:
- processPlayoffEvent now calls doesLoserAdvance per match before writing a
0-pt elimination result, matching the guard already in processMatchResult
- recalculate-floors handler now passes loserAdvances to processMatchResult
so a full reprocess also respects the loser-advances rule
- recalculateAffectedLeagues gains a skipDiscord option; recalculate-floors
uses it so clicking the admin "Recalculate Floors" button corrects the bad
data without re-announcing results on Discord
- Add two tests confirming 7v8 loser is not eliminated and 9v10 loser is
https://claude.ai/code/session_01QmvezscLYY38gN4GbvXZbA
* Address code review feedback on Play-In loserAdvances fix
- Use outer `round` variable instead of match.round in processPlayoffEvent
(they're identical, but consistent with surrounding code)
- Add comment at recalculate-floors call site explaining skipDiscord intent
- Combine two redundant test cases into one covering all four assertions
- Add West conference matches (M3/M4) to test fixture — East-only was
insufficient given doesLoserAdvance checks matchNumber 1 & 3
- Add guard test: when bracketTemplateId is null all losers are eliminated,
catching any future refactor that drops the field from the DB query
https://claude.ai/code/session_01QmvezscLYY38gN4GbvXZbA
---------
Co-authored-by: Claude <noreply@anthropic.com>
The loser of NBA Play-In Round 1 matches 1 and 3 (East/West 7v8 games)
advances to Play-In Round 2 rather than being eliminated, but was being
assigned finalPosition=0 and appearing in Discord as knocked out.
- Add `loserAdvances` param to `processMatchResult` to skip recording an
elimination result when the loser continues to another match
- Extract `doesLoserAdvance()` to `playoff-match.ts` as the single source
of truth for which play-in matches have advancing losers (replaces
duplicated hardcoded checks at both call sites in bracket.server.ts)
- Extract `isLoserNotifiable()` as a pure exported helper so Discord
notification eligibility is testable; losers only appear when their
team's score changed OR they have a finalized (non-partial) result,
correctly suppressing advancing losers while still surfacing 0-pt
eliminations that produce no score delta
- Add 14 new unit tests covering `doesLoserAdvance`, `isLoserNotifiable`,
and the advancing-loser/eliminated-loser `processMatchResult` branches
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
- Fix sports seasons not updating when saving league settings. The form
submits intent="update" but sports were only handled under the dead
intent="update-sports" branch, which nothing called.
- Fix spurious audit log entries (scoring rules, draft settings) firing
on every settings save. Change detection now compares submitted values
against current DB values before adding to seasonUpdates.
- Add previousValues to scoring_rules_changed and draft_settings_changed
audit log entries so the detail formatter can show old → new diffs
(e.g. "Scoring updated: 1st: 100 → 105").
- Add sports_changed audit action (migration 0076) with sport names
resolved at log time. Batch-fetch added sports in one query instead
of N individual queries.
- Improve audit log display for all action types: field-level old→new
diffs, readable labels, truncated sport lists (+N more).
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Closes#144
* feat: add commissioner audit log for league transparency (issue #144)
Adds a complete audit log system so league members can verify that
settings, draft order, picks, and time banks have not been quietly
changed without their awareness.
Changes:
- database/schema.ts: new `audit_action` enum + `commissioner_audit_log`
table (seasonId, leagueId, actorClerkId, actorDisplayName, action,
affectedTeamIds[], details jsonb, createdAt)
- drizzle/0075: generated migration for the new table
- app/models/audit-log.ts: createAuditLogEntry, getAuditLogForSeason
(paginated), logCommissionerAction (resolves display name automatically)
- app/lib/audit-log-display.ts: shared formatAuditDetail() helper used by
both the league home widget and the full audit log page
- app/routes/leagues/$leagueId.audit-log.tsx: new read-only route at
/leagues/:id/audit-log, accessible to all league members, with
action-type filter and pagination
- app/routes.ts: registers the new route
- League home page ($leagueId.server.ts / $leagueId.tsx): "Recent Activity"
summary card showing the last 5 entries with "View all" link
- Settings page ($leagueId.settings.tsx): "View Full Audit Log" link card;
audit log calls added for league/draft settings changes, draft order
set/randomized, and draft reset
- API routes: audit log calls added to draft.start, draft.pause,
draft.resume, draft.rollback, draft.adjust-time-bank, draft.force-autopick,
draft.force-manual-pick, draft.replace-pick
- Tests: 11 new unit tests for the audit-log model; mocks added to 3
existing route test files to account for the new logCommissionerAction call
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* fix: validate action filter URL param against known enum values
The action filter on the audit log route was cast directly from the URL
search param to AuditAction without validation. An invalid value would
be passed into the Drizzle inArray() call, potentially throwing a
PostgreSQL enum type error. Now validates against the actual enum values
before using the filter.
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
* Fix lint errors: use !== instead of != and toSorted instead of sort
https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm
---------
Co-authored-by: Claude <noreply@anthropic.com>
* fix: NBA play-in advancement writes E7/W7 to wrong participant slot
advanceNBAPlayInWinner was writing the PIR1 7v8 winner to participant1Id
of First Round M3/M7, but those slots already hold E2/W2 (seeded at
generation time). The "already filled" guard fired, silently swallowing
both the winner advancement and the loser's placement into Play-In
Round 2 — so the 7/8 loser never appeared in the second play-in game.
Fix: write the 7v8 winner to participant2Id (the correct null slot) and
update the guard, doc comment, and load-bearing comment accordingly.
Also swap the p2Override arguments in the simulator and test fixture to
match the corrected slot layout (FR M3: E2=p1, E7=p2).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: hasGroupStage check for templates without groupStage property
undefined !== null is true, so templates that omit groupStage (like
nba_20) were incorrectly treated as group-stage templates, triggering
the generate-groups action and the "Invalid template or template has
no group stage" error.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds the NBA_20 bracket template (20-team structure with play-in
tournament) and rewrites the NBA simulator to be bracket-aware like UCL.
- Add NBA_20 bracket template: PIR1 (4) → PIR2 (2) → First Round (8)
→ Conference Semifinals → Conference Finals → NBA Finals
- Add participantLabels (East/West 1–10) for admin bracket UI slot labels
- Add generateNBA20Bracket and advanceNBAPlayInWinner in playoff-match.ts
with custom play-in advancement logic (PIR1 winners go to two different
destinations)
- Rewrite NBASimulator with two auto-detected modes:
- Bracket-aware (preferred): reads actual bracket state, simulates only
remaining rounds forward using 50k Monte Carlo iterations
- Season-projection (fallback): existing logic for pre-playoff use
- Guard resolveGame/resolveSeries against null participants (throws with
match ID and slot info instead of silently using empty string)
- Document load-bearing First Round match ordering in generateNBA20Bracket
- Add 25 unit tests covering Elo math, team data, template structure,
and all simulator integration paths
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Fixes#289
* docs: add batch qualifying results entry design spec
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs: add batch qualifying results entry implementation plan
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: ignore .worktrees directory
* feat: add qualifying results text parser with tests
* fix: handle no-space after dot separator, tighten T-prefix to uppercase only
* feat: add batch-add-results server intent with duplicate filtering
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: add create-participant intent for inline participant creation
* fix: trim sportsSeasonId validation in create-participant intent
* feat: fill 0-QP rows for unplaced participants on qualifying event finalize
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* perf: use bulk insert for 0-QP rows on qualifying event finalize
* feat: add BatchResultEntry component for paste-and-parse batch result import
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: disable add participant button while create request is in flight
* feat: render BatchResultEntry on qualifying event pages
Add BatchResultEntry component import and render it on event pages when
the event is a qualifying event, not a final_standings/playoff_game type,
and not yet complete.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: address final review issues (sportsSeasonId authority, participant validation, CRLF, unused prop)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds a Clone Season button on the admin sports season detail page. The
clone form pre-fills all settings with the source season's data, bumping
the year by one and shifting all dates accordingly. On submit, the new
season is created in a single transaction that copies participants,
scoring events (with dates shifted), futures odds/Elo rating stubs
(zeroed-out probabilities so the simulator can re-run), and QP config
for qualifying_points seasons.
Fixes#282
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Active seasons sort first, then upcoming, then completed. Within each
status group, seasons sort by sport name alphabetically then year
ascending. Fixes return type of findAllSportsSeasons to reflect the
included sport/participants relations, removing the cast in the loader.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Participants are created with externalId=null by default, causing the
LLWS simulator to crash at runtime. Fix in two parts:
1. Name-prefix inference: if externalId is null, participants whose
name starts with "US " or equals "US" are assigned to the US side;
all others are assigned to Intl. Pools are always randomized when
inferred (no pool suffix).
2. Admin UI: add an inline-editable "Group" column to the Manage
Participants page so admins can explicitly set externalId for any
simulator that uses it (LLWS, and future cases like NHL conferences).
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: lower darts ELO_DIVISOR to 400 and fallback Elo to 1400
ELO_DIVISOR 500 → 400: elite darts is more skill-dominated than the
previous setting implied. A 400-point gap now gives ~78% per-set win
probability (vs ~73% before).
fallbackElo 1600 → 1400: unseeded PDC World Championship entrants
(regional qualifiers, Q-School players) are materially weaker than
seeded tour professionals. 1400 better reflects that gap.
Combined effect: a dominant player (e.g. 2000 Elo vs 1400-1600 field)
now produces EV ≈ 65 instead of ≈ 30, which better matches expectations
for a top-ranked player in a 128-player bracket.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: lower darts ELO_DIVISOR to 200 for realistic EV distribution
With the actual PDC field (top players clustered 1800–1970 Elo, Littler at
~2080), ELO_DIVISOR=400 made the gap between world #1 and the top 8 too
soft — EV for Littler came out ~37 instead of the expected 65–70.
ELO_DIVISOR=200 calibrates correctly for this field: a 100-pt gap now
gives ~62% per-set win probability (vs ~56% at 400), sharply rewarding
the best players while still allowing upsets. Littler at 2084 produces
EV ≈ 65–70 against the real PDC tour roster.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: seed darts bracket by Elo instead of world ranking
World ranking (PDC Order of Merit) is prize-money-based and can diverge
from current skill — e.g. Kevin Doets (1818 Elo) was ranked 35th while
Joe Cullen (1667 Elo) held the 32nd seed. Seeding the weaker player and
leaving the stronger one unseeded contradicts the Elo-based match model.
Seeding by Elo descending ensures the 32 strongest players (by the same
metric used to compute match probabilities) get protected bracket positions.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* revert: restore world-ranking-based seeding for darts bracket
Seeding should follow the PDC Order of Merit (world ranking), not Elo.
Reverts the previous Elo-seeding commit.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: interleave seeded and unseeded R1 pairs in darts bracket
Previously, all 32 seeded-vs-unseeded matches were added to r1Pairs
first (indices 0–31) and all 32 unseeded-vs-unseeded matches last
(indices 32–63). Since R2 pairs adjacent R1 winners, this created two
completely separate sub-brackets that only converged at the Final:
- Seeded sub-bracket: top players eliminating each other early
- Unseeded sub-bracket: high-Elo unseeded players (e.g. Doets 1818,
Zonneveld 1806) steamrolling weak opponents and making the Final
~20% of the time
Fix: interleave each seeded match with its adjacent unseeded-vs-unseeded
match. Seeded pair i is at r1Pairs[2i], unseeded pair i is at r1Pairs[2i+1].
From R2 onwards, winners from seeded and unseeded regions now merge
correctly as in a real single-elimination bracket.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: address VORP code review issues
- Switch admin EV form to batchUpsertParticipantEVs to avoid N×N
concurrent UPDATE storm (was calling upsertParticipantEV per
participant, each triggering a full syncVorpForSeason)
- deleteParticipantEV now resets vorpValue to "0" and calls
syncVorpForSeason so remaining participants' ranks stay correct
- syncVorpForSeason issues a single bulk CASE UPDATE instead of
N individual UPDATE statements
- Add doc warning on recalculateEV that callers must sync VORP manually
- Extract REPLACEMENT_LEVEL_START/END_IDX constants; clarify comment
that 12-14 is a fixed product decision, not derived from league size
- Include vorpValue in draft room participant select projection
- Update drizzle-orm mock to support sql.join; update test assertions
to reflect single bulk-update call
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: resolve lint errors (toSorted, unused var)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Update draft participant sorting to use vorpValue column instead of expectedValue
in draft room initialization and auto-pick selection for both single-sport and
multi-sport seasons.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds syncVorpForSeason to recalculate and persist VORP for all participants
in a season after any EV change. Wires it into upsertParticipantEV,
batchUpsertParticipantEVs, and recalculateAllEVsForSeason so VORP stays
current whenever EVs are updated.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix NHL simulator dynamic seeding and code quality issues
- Replace hardcoded seeding probabilities with standings-based Monte Carlo
projection: simulates remaining regular season games per team using Elo
win probability vs. a league-average opponent, so mathematically eliminated
teams naturally fall out of playoff contention
- Fix double-simulation bug in wildcard pool: all 16 conference teams are now
projected exactly once via sortProjected([...divA, ...divB].map(projectTeam)),
then filtered — wildcard pool no longer re-runs simulateProjectedPoints with
fresh randomness independent of the division seeding
- Move ProjectedTeam interface, projectTeam(), and sortProjected() to module
scope (defined once, not recreated on every buildConferenceBracket call)
- Replace conference-level participant count check (east < 8 || west < 8) with
per-division checks (each division < 3) for a more actionable error message
- Add logger.warn when standings.length === 0 so admins know the sim is running
without synced data
- Remove unused easternTeams/westernTeams variables
- Simplify test: replace Object.fromEntries pattern with a plain for..of loop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix oxlint errors in NHL simulator and tests
- Replace non-null assertions (data!) with optional chaining (data?.x ?? "")
- Move makeEntry helper to module scope to avoid recreating on every call
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add LLWS bracket Monte Carlo simulator
Simulates the 20-team Little League World Series: pool play round-robin
(5 teams/pool, top 2 advance) → 4-team double-elimination per side
(US and International) → consolation game → World Series final.
Uses championship futures odds as the sole win-probability signal.
Pool assignments are auto-detected from externalId: bare "US"/"Intl"
randomizes pools each simulation (pre-draw mode); "US:A"/"Intl:B" etc.
uses fixed assignments (post-draw mode). Sides can differ.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix oxlint violations in LLWS simulator
- Replace non-null assertions with null-safe access (! → ?? / optional chaining)
- Replace .sort() with .toSorted() per linting rules
- Promote bump() to simulate() scope and pass it into simulateSideBracket,
removing the need to pass counts into that function
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Fixes#124
* Add NCAA Football CFP simulator (12-team bracket)
Implements a Monte Carlo simulator for the College Football Playoff using
the 2024-present 12-team format. Elo/FPI ratings are entered manually via
the existing admin Elo Ratings page; championship futures odds can
optionally be blended in (60% Elo / 40% odds).
- Add CFP_12 bracket template (First Round not scoring, QFs onward score)
- Add generateCFP12Bracket() with correct seeding: 5v12, 6v11, 7v10, 8v9
in First Round; seeds 1–4 receive QF byes
- Add NCAAFootballSimulator: 50k Monte Carlo sims, seeds teams by blended
Elo+odds strength, tracks champion/finalist/SF/QF placement tiers
- Register ncaa_football_bracket simulator type in registry and schema enum
- Add migration 0071: ALTER TYPE simulator_type ADD VALUE 'ncaa_football_bracket'
- Add tests: 30 tests covering bracket template structure and simulator
probability distributions, seeding, edge cases, futures blending
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix lint errors in NCAA Football CFP simulator
Replace non-null assertions with optional chaining, change let to const,
use toSorted() instead of sort(), and add a bump() helper to avoid
repeated map lookups with non-null assertions in simulateBracket.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TS2345 in NCAA football simulator test
Add ?? 0 fallback so optional-chained probFirst is number, not number | undefined.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix CS Major simulator bugs and accuracy issues (fixes#275)
- Fix crash when pool teams are missing Elo ratings by including all
participants with FALLBACK_ELO, ensuring Champions Stage always gets
exactly 8 teams
- Add AdvancedTeam type tracking losses-at-advancement; seed Champions
Stage by stage performance (fewer losses = higher seed) instead of
world rank alone
- Promote decisive Stage 2 matches (either team at ≥2W or ≥2L) to Bo3,
matching the real Challengers Stage format
- Tie-split QP for QF losers (slots 5–8) and SF losers (slots 3–4)
instead of assigning arbitrary individual placements
- Change stage-complete threshold from === 8 to >= 8 for robustness
- Validate even team count in simulateSwiss to prevent silent infinite loops
- Short-circuit Monte Carlo loop when all events are complete, returning
deterministic 0/1 probabilities
- Parallelize stage results DB fetches with Promise.all
- Export calcStage3ExitQP and simulateOneMajor; add test coverage for
both, plus new simulateSwiss and simulateChampionsStage edge cases
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix oxlint violations in CS Major simulator
- Replace non-null assertion (!) with null-safe guard in simulateOneMajor
- Replace non-null assertions in test expectations with nullish coalescing
- Move makeStage3QPConfig out of describe block (no captured variables)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Implements a new `nfl_bracket` simulator that projects the NFL regular
season and full playoff bracket using nfelo Elo ratings.
- Simulates remaining regular season games (17 total) per team using
Elo win probability vs an average opponent, then seeds both conferences
(division winners = seeds 1–4, wildcards = 5–7) per simulation
- Simulates Wild Card, Divisional, Conference Championship, and Super
Bowl rounds with correct NFL bracket structure (seed 1 bye)
- Applies +48 Elo home-field advantage (~57% win rate) for all rounds
except the neutral-site Super Bowl
- Pre-season mode (no standings in DB): simulates all 17 games from
scratch; falls back to futures odds → Elo conversion if no sourceElo
- Validates all 8 NFL divisions have Elo-rated teams before simulating,
with a clear error listing missing divisions
- Registers as `nfl_bracket` simulator type in the registry and schema
- Adds migration to extend the `simulator_type` enum
- Also updates drizzle.config.ts to prefer DIRECT_DATABASE_URL when set
Fixes#129
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Fixes#262
* Replace isDraftable boolean with draftOn/draftOff date fields on sport seasons
Admins can now schedule when a sport season becomes available for drafting
by setting explicit open and close dates instead of a manual toggle.
https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc
* Address code review feedback on draft window implementation
- sports-data-sync: use unambiguous past placeholder dates for synced seasons,
with a comment explaining the intent
- sports-season model: remove redundant top-level lte/gte imports (callback
form already supplies them)
- _journal.json: add missing trailing newline
- sports-season test: mock ~/database/schema instead of stubbing all drizzle
builder functions, matching the established pattern in the codebase
- admin list: compute today once in component body instead of per-row
https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc
* Fix: restore lte/gte imports removed in review cleanup
The relational query where-callback in this version of Drizzle does not
expose lte/gte as helper args, so they must be imported from drizzle-orm.
Removing them broke CI TypeScript.
https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Remove redundant processPlayoffEvent loop from finalize-bracket action
All bracket rounds are already processed (with scoring and Discord
notifications) as each match winner is set via set-winner/set-round-winners.
By the time the Finalize button is clicked, placements are current and
standings are up to date. The re-processing loop was firing recalculations
and Discord notifications once per round needlessly.
The finalize action now only assigns 0 points to non-bracket participants,
marks the event complete, and runs one final standings recalculation.
https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5
* Fix stale comment in finalize-bracket action
The template is now fetched only as a validity guard, not for round
order iteration (which was removed in the previous commit).
https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5
* Fix complete-round redundant Discord/recalculation and stale comment
complete-round was calling processPlayoffEvent without skipRecalculate,
firing recalculateAffectedLeagues and Discord even though each match
winner had already triggered those side effects via set-winner. Add
skipRecalculate: true to match the autoCompleteRoundIfDone pattern.
Also fix autoCompleteRoundIfDone comment which incorrectly said
"non-bracket eliminations are recorded" — that's a separate step in
finalize-bracket; processPlayoffEvent records bracket round placements.
https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add CS2 Major qualifying points simulator
Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
+ Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate Elo + ranking input into generic elo-ratings page
The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Consolidate server postgres connections into one shared pool
Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).
Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix and() bug and add Swiss loop safety guard
- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
were using JS && instead of Drizzle and(), causing WHERE to filter only
by participantId (not scoringEventId), which would update rows across
all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
prevent infinite loop if pairGroups returns no pairs
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix all remaining code review issues
- cs2-major-stage.ts: use schema column reference for stageEliminated
in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
results when a stage is complete (8 recorded eliminations), only
simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
React state (eliminatedChecked map) for checkbox show/hide logic;
remove unused stageMap and unassignedParticipants variables
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars
- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
* Fix flaky Champions Stage stochastic test
The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.
Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.
https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR
---------
Co-authored-by: Claude <noreply@anthropic.com>
Fixes#224
* Add inline edit for participant names on admin sports season page
Adds a pencil icon button next to each participant's delete button. Clicking
it switches the row into edit mode with an input field, a save (checkmark) and
cancel (X) button. Escape also cancels. Submits via intent="update-name" and
validates uniqueness within the season before persisting.
https://claude.ai/code/session_01Q94DWQ1HZEB9PJhGMArU8D
* Simplify edit state and surface edit errors to user
- Combine editingId + editingName into single editing: { id, name } | null state object
- Extract cancelEdit() helper called in 3 places instead of repeating setEditing(null)
- Tag all update-name action responses with intent: "update-name" so errors can be
identified and routed correctly
- Show update-name errors inline below the edit input
- Guard single-add and bulk-add error displays against showing update-name errors
https://claude.ai/code/session_01Q94DWQ1HZEB9PJhGMArU8D
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix admin Games to Score panel missing bracket events
The panel was silently dropping bracket events in two cases:
1. When a bracket event had `scoringEvents.eventDate` set to a future
round date (e.g. "April 5") but an individual game's `scheduledAt`
was today, the old dedup code picked `eventDate` first and the
component filter `displayDate === today` never matched.
2. When an event had games on both today and tomorrow, whichever row
the unordered step-1 query returned first "won" — potentially hiding
a today game from the today tab entirely.
Fix: replace the `Map<id, firstDate>` deduplication with
`Map<id, Set<date>>` that collects every requested date an event
qualifies for (via either `eventDate` or `gameDate`). The return uses
`flatMap` to emit one entry per (event, date) pair, so events with
games on multiple days now appear correctly in both tabs.
https://claude.ai/code/session_01QkFxCF4xmKjdVCNPysWDML
* Fix lint errors: replace .sort() with .toSorted() and remove non-null assertion
- Replace Array#sort() with Array#toSorted() in two places (unicorn rule)
- Remove non-null assertion on Map#get(); use early continue instead
https://claude.ai/code/session_01QkFxCF4xmKjdVCNPysWDML
---------
Co-authored-by: Claude <noreply@anthropic.com>
When generating groups for a tournament (e.g. FIFA World Cup), any
participants in the sport season who were not assigned to a group are
now automatically marked as eliminated (finalPosition = 0) — the same
result as running "Reprocess Eliminations" manually.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Fixes#123
* Add PDC World Darts Championship simulator (128-player bracket)
- New DartsSimulator: 128-player single-elimination, 7 rounds with
PDC-accurate best-of-sets formats (bo3/bo5/bo5/bo7/bo7/bo11/bo13).
ELO_DIVISOR=500 via set-level Bernoulli model. Two simulation paths:
Path A (bracket drawn) simulates from actual DB matches; Path B
(pre-bracket) seeds top 32 by world ranking in fixed positions and
randomly draws the remaining 96 per simulation run (50,000 iterations).
- darts_bracket added to simulatorTypeEnum and simulator registry.
- world_ranking nullable integer column added to participant_expected_values
(migration 0067); batchSaveSourceElos now accepts and persists it.
- Admin route /admin/sports-seasons/:id/darts-elo: bulk import with format
"Player Name, 2099, 1" (name, Elo, optional world ranking), fuzzy name
matching, auto-runs simulation and updates EV/snapshots on save.
- DARTS_128 bracket template added (scoring starts at Quarterfinals).
- 30 unit tests: math helpers, bracket seeding structure, Path A/B integration.
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Review fixes: pre-compute hot-loop invariants, import normalizeName
- Pre-compute seededSlots and getSeededMatchOrder(32) before the 50k
simulation loop — was being recomputed every iteration
- Pad unseeded pool to 96 once before the loop instead of inside it
- Inline bracket-building in the hot loop using pre-computed seededSlots;
removes the per-iteration call to buildR1Bracket/getSeededMatchOrder
- Remove dead SEEDED_R1_PAIRS constant (was never referenced)
- Import normalizeName from ~/lib/fuzzy-match instead of redefining it locally
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Fix lint failures: unused vars, eqeqeq, toSorted
- Remove unused seededSet/unseededSet variables in test
- Replace != null with !== null && !== undefined (eqeqeq rule)
- Replace .sort() with .toSorted() in simulator and route (unicorn/no-array-sort)
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
* Fix TS2552: restore seededSet declaration removed during lint fix
https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Exclude scored bracket matches from upcoming events calendar
Add `eq(schema.playoffMatches.isComplete, false)` to the bracket-sports
query in `getUpcomingEventsForDraftedParticipants` so that individual
playoff matches already scored (isComplete = true) no longer appear on
the upcoming events calendar, even when the parent scoring event is still
open.
Also update the schema mock in upcoming-calendar.test.ts to include
`playoffMatches.isComplete` and add a test covering this behaviour.
https://claude.ai/code/session_01GMLmjN9mwoANfpgSciD7Bi
* Fix leaked mockReturnValueOnce in scored-match test
The new test only triggers one selectDistinct call (rows is empty so the
max-game-number lookup is skipped). The second mockReturnValueOnce was
never consumed, leaving a makeMaxGameChain value in the queue that was
then picked up by the subsequent "uses leftJoin" test, causing it to fail
with "leftJoin is not a function".
https://claude.ai/code/session_01GMLmjN9mwoANfpgSciD7Bi
---------
Co-authored-by: Claude <noreply@anthropic.com>
Placement counts (used to break points ties) previously only included
fully-finalized participants. A team whose events all resolved first would
accumulate real placement counts while tied teams with pending events had
zeros, causing the tie to be broken in favour of whichever team finished
scoring first rather than on merit.
Fix: count a participant's current position toward the tiebreaker regardless
of isPartialScore. Their position is the best available signal; if it changes,
recalculateStandings reruns and ranks update naturally.
Also removes a redundant bounds check (finalPosition > 0 was already
asserted by the outer if-condition).
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes#127
- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
- Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
- Partial group completion: completed matches replayed with real scores, remaining matches simulated
- Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Increase Node heap to 4GB for unit tests in CI to prevent OOM
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests
Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Show tied ranks with T prefix across standings and Discord notifications, fixes#197
- Add buildTiedRankChecker() utility to standings-display.ts; replaces
four copies of inline rank-count logic spread across components,
the league home route, and the Discord service
- Prefix shared ranks with "T" (e.g. "T3") in StandingsTable (league
panel), StandingsTable (full standings), the league home preview, and
Discord webhook notifications
- Add useMemo wrapping in StandingsTable components so tie detection
does not recompute on every render
- Fix compareTeamsForRanking to round total points to hundredths before
comparing, preventing floating-point noise from producing spurious
non-ties in the standings
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix discord test to expect escaped period in rank display
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add unique index on (sports_season_id, name) in participants table
- findParticipantByName uses case-insensitive lower() comparison
- Single add: check for existing name before insert, return clear error
- Bulk add: load existing names once upfront (1 query vs N), dedup
input case-insensitively, report skipped names in UI
- Fix golf-skills and surface-elo routes which called createParticipant
without any duplicate guard (would have thrown DB constraint errors)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
- Fix UTC midnight rollover bug: server now queries from yesterday UTC
as a buffer; UpcomingCalendarPanel filters to local-today client-side
via useEffect + Intl.DateTimeFormat, removing the need for any
cookie or server-side timezone detection
- Cap homepage and league page panels at 6 events with a "View all" link
- Add /upcoming-events page (60-day view across all leagues)
- Add /leagues/:leagueId/upcoming-events page (60-day per-league view)
- Add emptyMessage prop to UpcomingCalendarPanel for context-specific copy
- Change getUpcomingEventsForDraftedParticipants to accept pre-computed
date strings instead of Date objects
fixes#213
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
- New /support route with Discord join button and contact form
- Contact form sends via Resend to support@brackt.com (email stays hidden from users)
- Spam protection: honeypot field + Cloudflare Turnstile verification
- Server-side input length limits (subject: 200, message: 5000 chars)
- Added Support nav link to navbar (desktop + mobile)
Fixes#233
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add WNBA playoff simulator with SRS-based Elo ratings, fixes#125
- New WNBASimulator: Monte Carlo (50k sims) projecting remaining regular
season games → seeding → R1 Bo3 / Semis Bo5 / Finals Bo7 bracket
- Hybrid Elo sourcing: pre-season uses futures odds (ICM); once avg
gamesPlayed ≥ 5, switches automatically to SRS-derived Elo
(elo = 1500 + srs × 20)
- New WnbaStandingsAdapter: fetches ESPN standings + teams endpoints in
parallel; includes zero-records for 2026 expansion teams (Portland
Fire, Toronto Tempo) not yet in standings
- Added srs column to regular_season_standings (migration 0063);
stored as net rating proxy (avgPointsFor − avgPointsAgainst)
- Added wnba_bracket to simulatorTypeEnum
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix missing afterEach import in wnba standings test
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>