Commit graph

151 commits

Author SHA1 Message Date
Chris Parsons
ab3437cd73
Display team owner names instead of team names in draft UI (#24)
* Show manager username instead of team name on draft board

Both the read-only draft board and the active draft room now display
the manager's username (falling back to displayName if no username is
set, and to team name if the team is unassigned) in the column headers
of the draft grid.

https://claude.ai/code/session_01C97GauJaAB83NVWxdpNVh1

* Address code review: extract ownerMap helper, fix TeamsDraftedGrid

- Extract ownerMap building into app/lib/owner-map.ts to eliminate
  duplication across the two loaders
- Guard against null username AND displayName so the map only contains
  real string values
- Apply username display to TeamsDraftedGrid (the "Teams" tab in the
  active draft room), which was missed in the initial change

https://claude.ai/code/session_01C97GauJaAB83NVWxdpNVh1

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 16:56:07 -08:00
Chris Parsons
b35791e76a
Fix public draft board access not working when setting is enabled (#23)
* Fix public draft board access not working when setting is enabled

Two bugs were causing the isPublicDraftBoard setting to fail:

1. Draft board loader called getAuth() before checking isPublicDraftBoard.
   Restructured to skip auth entirely for public boards - only call getAuth
   when the board is private and we need to verify member/commissioner access.

2. Settings action saved the league (name + isPublicDraftBoard) AFTER fetching
   the current season. If the season fetch had any issue, updateLeague was never
   reached. Moved the league-level save to happen unconditionally before the
   season fetch, so isPublicDraftBoard is always persisted on form submit.

https://claude.ai/code/session_01Jp2tE3YXhx2jdb6CgCnvZy

* Fix bugs in draft board access and settings update action

- Wrap updateLeague call in try-catch so DB errors return a user-friendly
  message instead of an unhandled 500
- Fix season-update catch block to say "season settings" not "league" since
  the league was already saved successfully at that point
- Validate leagueId URL param against season.leagueId in draft board loader
  to prevent accessing a season via the wrong league's URL
- Change 403 message for authenticated non-members from "not public" to
  "you don't have access" to accurately reflect their logged-in state
- Add settings-update.test.ts covering name validation, league save,
  error handling, draft speed mapping, and season-specific validation
- Add draft-board-access.test.ts covering public/private access rules,
  leagueId mismatch detection, commissioner/owner/unauthenticated cases,
  and the new per-role 403 message distinction

https://claude.ai/code/session_01Jp2tE3YXhx2jdb6CgCnvZy

* Fix TypeScript errors in settings-update tests

TS was narrowing const draftSpeed = 'fast' to the literal type 'fast',
making comparisons with 'slow'/'very-slow' etc. flagged as impossible.
Widen all draftSpeed locals and the season status locals to string so the
if-chains compile cleanly under strict mode.

https://claude.ai/code/session_01Jp2tE3YXhx2jdb6CgCnvZy

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 16:31:24 -08:00
Chris Parsons
51cffe1762
Add commissioner time bank adjustment feature for draft (#22)
* Add commissioner time bank adjustment via right-click on draft board team headers

Commissioners can right-click any team header on the Draft Board tab to open
an "Adjust Time Bank..." dialog. The dialog supports adding or removing an
arbitrary amount of time in seconds, minutes, or hours. The change is applied
immediately to the database and broadcast to all clients via the existing
timer-update Socket.IO event so every participant sees the updated clock
in real time.

- New API route: POST /api/draft/adjust-time-bank (commissioner-only)
- DraftGridSection: wraps team headers in a ContextMenu for commissioners
- Draft room: dialog state, handler, and updated DraftGridSection props

https://claude.ai/code/session_013wxPKzLUCx3nC3LpxgjvQL

* Fix code review issues in commissioner time bank adjustment

- Wrap fetch in try/finally so isAdjustingTimeBank is always reset,
  even on network errors that cause fetch to throw
- Guard against totalSeconds rounding to 0 for tiny fractional inputs
- Reject API requests when the draft is not in 'draft' status (409)
- Set input min to 0.001 so the browser rejects zero in native validation

https://claude.ai/code/session_013wxPKzLUCx3nC3LpxgjvQL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 16:16:51 -08:00
Chris Parsons
8a444a51a1
Improve error boundary UI with status-specific error pages (#21)
* Improve error pages with styled, status-aware UI

Replace the bare-bones error boundary with a proper error page that:
- Renders a minimal Brackt header so users can navigate home
- Shows distinct messages and icons for 401, 403, 404, 500+ errors
- Displays a "Sign in from the home page" hint on 401 so logged-out
  users know how to recover
- Hides internal details in production (stack traces dev-only)
- Uses existing dark theme Tailwind classes for visual consistency

https://claude.ai/code/session_011jv8desa5vhSkjZHSjWZiV

* Address code review feedback on error pages

- Move statusIcon out of ErrorBoundary render as a plain module-level
  function to avoid React re-creating a component type on every render
- Collapse 401 action into a single descriptive button label
  ("Go to Home Page to Sign In") instead of a fragmented button + hint
- Fix details/summary border radius collision by using overflow-hidden
  on the container and removing rounded-md from the summary element;
  separate the pre block with a border-t instead

https://claude.ai/code/session_011jv8desa5vhSkjZHSjWZiV

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-21 23:47:42 -08:00
Chris Parsons
e9798263b5
Add rules page, rewrite how-to-play, and fix scoring display (#20)
- Add new /rules route with official league rules covering rosters,
  scoring, major-based QP scoring, tiebreakers, draft, and season rules
- Rewrite how-to-play page with a tutorial/marketing tone, highlighting
  the Fischer increment draft clock as a novel feature
- Add Rules link to navbar (desktop and mobile)
- Align QP values in both pages with DEFAULT_QP_VALUES in code
- Fix tiebreaker description to match placement-count logic in code
- Update all fantasy point displays from toFixed(1) to toFixed(2) across
  StandingsTable, TeamScoreBreakdown, and PointProgressionChart
- Update tests to match new two-decimal-place point display format

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-21 21:58:51 -08:00
Chris Parsons
7a8ea60e77
Add draft clock UI, Fischer increment timer logic, and security fixes (#19)
- Add prominent clock badge to tab bar (lights up on your turn) with
  correct Fischer increment chess-clock model: bank starts at initialTime,
  += incrementTime after each pick, other teams' banks untouched
- Extract pure timer helpers to app/lib/draft-timer.ts and add 29 unit
  tests covering formatClockTime, calculateTimeAfterPick, getTimerColorClass,
  and full snake-draft lifecycle regression scenarios
- Fix make-pick.ts: add status !== 'draft' and draftPaused server guards
- Fix draft-utils.ts: replace (global as any).__socketIO with getSocketIO(),
  fix timeUsed to store actual timeRemaining at pick moment (not always 120),
  add null timer warning, move timer fetch before pick insert
- Fix draft.start.ts: batch timer inserts, guard against empty draftSlots
- Fix DraftGridSection: memoize currentTeamId, widen teamTimers type to
  Record<string, number | undefined>
- Fix duplicate animate-pulse (getTimerColorClass already includes it)
- Clamp negative seconds in formatClockTime to guard against timer drift

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-21 16:51:12 -08:00
Chris Parsons
41f3654956
Add commissioner replace pick and draft rollback features (#18)
Commissioners can now right-click any picked cell in the draft grid to
replace the drafted participant (available during and after draft) or
roll back the draft to that pick number (available during draft only).

Replace pick enforces sport eligibility with the replaced slot treated
as free, updates the pick in-place, and broadcasts a pick-replaced
socket event so all clients update in real time. Rollback deletes all
picks from the selected pick onward, resets the season pick number,
clears all timers, and creates a fresh timer for the team now on the
clock.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 22:47:29 -08:00
Chris Parsons
285981ab9d
Improve draft room UX with better error handling and UI refinements (#17)
* Remove pause/resume controls when draft is complete, rename Live to Connected

- Hide Pause/Resume Draft buttons when isDraftComplete is true
- Change 'Live' status indicator to 'Connected' in both draft room and draft board views

https://claude.ai/code/session_01AUaKzx465NrY29Qv6MVwjC

* Fix code review issues in draft room: security, bugs, and quality

Security:
- Fix inconsistent commissioner check: draft.start, force-autopick, force-manual-pick,
  and make-pick all now query the commissioners table instead of league.createdBy,
  so co-commissioners have consistent access to all draft controls

Bugs:
- canPick now includes !isPaused so the UI correctly blocks picks during a pause
- isDraftComplete initial state now covers 'completed' season status, not just 'active'
- Guard JSON.parse in queue.reorder.ts with try/catch to return 400 instead of 500

Code quality:
- Add error handling (try/catch + toast) to handlePauseDraft, handleResumeDraft,
  handleRemoveFromQueue, and handleReorderQueue
- Replace alert() with toast.error() in handleMakePick, handleForceAutopick,
  handleForceManualPick for consistent UX
- Memoize filteredParticipants with useMemo to avoid recomputing on every render
- Replace custom force-pick dialog div with ShadCN Dialog component for proper
  keyboard support (Escape to close, focus trap, accessible markup); add dialog.tsx
- Remove console.log debug statements from socket event handlers and API routes
- Replace (global as any).__socketIO with getSocketIO() across all API routes
- Replace window.location.reload() in handleStartDraft with useRevalidator

https://claude.ai/code/session_01AUaKzx465NrY29Qv6MVwjC

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 21:50:27 -08:00
Chris Parsons
7294084c13
Refactor draft grid sports calculation and improve type safety (#16)
* Fix flex pick count using unique sports drafted, not total season sports

The flex count was calculated as `totalPicks - totalSportsInSeason`, which
always returned 0 when a team drafted multiple participants from the same
sport (e.g. 2 picks from UEFA Champions League with 2 sports in season =
2 - 2 = 0). Now uses the number of unique sports the team has actually
drafted from, so 2 picks in 1 sport correctly shows 1 flex used.

https://claude.ai/code/session_01DZ6jqgZTDEmJucanBtRCtM

* Code review fixes for TeamsDraftedGrid and draft route

- Fix misleading early-return message: "No picks have been made yet" only
  fires when there are no sports configured, so update to say "No sports
  have been configured for this season."
- Remove unused draftOrder and team.seasonId from TeamsDraftedGrid props
- Replace availableParticipants prop with sports prop to eliminate
  duplicate sports derivation; route already computes seasonSportsData
- Add alphabetical sort to seasonSportsData so ordering is consistent
- Fix availableParticipants: any[] in loader — restructure to ternary so
  TypeScript infers the Drizzle select type directly
- Remove any annotation from seasonSportsData forEach callback (now typed)
- Fix teamSportPicks.indexOf(pick) O(n) re-scan — use map callback index i

https://claude.ai/code/session_01DZ6jqgZTDEmJucanBtRCtM

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 21:26:27 -08:00
Chris Parsons
edc4eb75e8
Optimize draft room performance with memoization and refactoring (#15)
* Fix flex spot count in draft room Teams Drafted view

The flexSpots column in the database defaults to 0 and was never
populated, causing the Teams Drafted grid to always show "0 of 0 flex".
Calculate numFlexPicks dynamically in the loader as
max(0, draftRounds - seasonSports.length) so teams see the correct
flex count (e.g. 7 rounds - 5 sports = 2 flex).

https://claude.ai/code/session_01CSzF4aWuyppGBDqM4MJmhc

* Clean up draft room flex calculation area

- Fix bug: force pick dialog now uses its own isolated search/sport
  filter state so it no longer mutates the main participants tab filters
- TeamsDraftedGrid: remove dead first pass in flexPicksByTeam memo,
  trim season prop to numFlexPicks only, drop unused type field from
  picks sport shape
- Loader: derive userAutodraftSettings from already-loaded
  autodraftSettings list, eliminating a redundant DB query
- Extract shared transformedPicks, transformedParticipants, and
  seasonSportsData into their own useMemos so both eligibility memos
  reuse them instead of duplicating the work
- Memoize draftGrid, draftedParticipantIds, and uniqueSports which
  were being recomputed on every render

https://claude.ai/code/session_01CSzF4aWuyppGBDqM4MJmhc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 21:10:26 -08:00
Chris Parsons
9ae00a8385
Add Zod validation and expand export/import for EV and results data (#14)
* Include participant EV/futures data in data sync export/import

The export now includes the full participantExpectedValues records
(placement probabilities, source, sourceOdds) alongside participants.
On import, EV records are upserted in merge mode and created fresh in
replace mode (cascade handles cleanup). Backward-compatible with older
exports that lack the participantExpectedValues field.

https://claude.ai/code/session_01TVzuuDR7jPtmihaXTrsX7B

* Address all data-sync code review findings

- Wrap importSportsDataFromJSON in a db.transaction() so any mid-import
  failure rolls back cleanly instead of leaving partial data
- Add zod validation of imported JSON before any DB writes, giving a
  clear error on malformed/incompatible files
- Fix N+1 queries: build participantIdMap during participant import so
  the EV and results sections resolve IDs from memory, not extra queries
- Fix merge mode silently skipping existing participants — now updates
  shortName, externalId, and expectedValue
- Add participantResults to export/import (was deleted in replace mode
  but never exported, so results were permanently lost)
- Restore calculatedAt timestamp on EV import instead of defaulting to
  now(); stored as ISO string in the export for portability
- Document that onDelete:cascade covers participantExpectedValues and
  participantResults when participants is deleted; remove the now-
  redundant explicit participantResults delete from replace mode
- Bump export version to 1.1; old v1.0 files still import cleanly since
  participantExpectedValues, participantResults, and calculatedAt are
  all optional in the zod schema
- Collapse all six DB fetches in exportSportsDataToJSON into one
  Promise.all for parallel execution
- Add countAllParticipants() and countAllParticipantEVs() model funcs
- Show Participants and EV Records counts on the dashboard stat cards
- Replace raw DOM form creation/submit in handleImport with useFetcher,
  giving proper loading state, no full-page reload, and type-safe data
- Remove dead export intent handler from the action function

https://claude.ai/code/session_01TVzuuDR7jPtmihaXTrsX7B

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 20:25:25 -08:00
Chris Parsons
401efcd833
Add browser push notifications toggle to draft page (#11)
* Add push notifications implementation plan

Documents the approach for adding a browser Notification API toggle
to the draft page sidebar, including files to create/modify and
edge cases to handle.

https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69

* Add browser push notifications toggle to draft page

Adds a Notifications toggle in the draft sidebar (below Autodraft)
that uses the Browser Notification API to alert users when a pick is
made or when it's their turn, while the tab is not focused.

- New useDraftNotifications hook for state, permission, and localStorage
- New NotificationSettings component with Switch toggle
- Fires "It's your turn to pick!" when the next pick is the user's
- Fires "{Team} picked {Player}" for all other picks
- Gracefully hides toggle when Notification API is unavailable

https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69

* Fix all code review issues with push notifications

- Extract snake draft order calculation to shared getTeamForPick()
  helper in lib/draft-order.ts, removing the duplicated logic
- Fix notification firing on user's own picks (guard with team id check)
- Fix notification firing after draft is complete (early return)
- Use a ref for sendNotification to prevent full socket handler
  re-registration every time the toggle is changed
- Add permission drift listener via Permissions API so the UI reacts
  if the user revokes notification permission in browser settings
- Add SSR guard for document.hidden in sendNotification
- Remove redundant isSupported prop from NotificationSettings;
  derive unsupported state from permissionState === "unsupported"
- Move NotificationSettings out of QueueSection prop-drilling path;
  render it via a new settingsSection slot on DraftSidebar instead

https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69

* Fix second round of notification code review issues

- Add My Turn Only / All Picks mode granularity so users can choose
  to only be notified when it's their pick, or for every pick
- Remove double top-border by stripping leftover border-t/pt-4/mt-4
  wrapper from NotificationSettings (now provided by DraftSidebar)
- Remove unused isSupported from hook return value
- Add n.onclick = () => window.focus() so clicking a notification
  brings the draft tab back into focus
- Scope localStorage keys to userId to avoid shared-browser conflicts
  (keys now: draftNotifications-{userId}-{seasonId})
- Add notificationsModeRef alongside sendNotificationRef so mode
  changes don't trigger full socket handler re-registration

https://claude.ai/code/session_0149MvVUYDY6pFUAV1fL4K69

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 19:30:53 -08:00
Chris Parsons
1584d34b89
Redesign to dark-mode-only with navy palette and accent colors (#13)
Removes light mode entirely in favour of a permanent dark theme with a
navy-tinted background and three signature accents (electric blue,
amber/gold, coral) exposed as CSS custom properties and Tailwind
utilities (bg-electric, text-amber-accent, text-coral-accent).

- Set class="dark" on <html> and apply Clerk dark base theme
- Rewrite app.css: single :root palette (oklch navy values), custom
  --electric / --amber-accent / --coral-accent variables, remove
  duplicate .dark block and light-mode bg-white/bg-gray-950 rule
- Install @clerk/themes for Clerk dark modal support
- Replace hardcoded Tailwind colors across 30+ files:
  - Draft grid cells: blue-50/blue-950 → electric/15, green-50/950 → emerald/10
  - Timer: green-600/yellow-600/red-600 → emerald-400/amber-accent/coral-accent
  - Status badges: blue-50/green-50/gray-50 → electric/emerald/muted variants
  - Success messages: green-500/15 text-green-700 dark:text-green-400 → emerald-500/15 text-emerald-400
  - Info cards: blue-50 dark:bg-blue-950 → electric/10
  - Warning cards: yellow-500 → amber-accent variants
  - Medal/placement badges: yellow-500/orange-600 → amber-accent/coral-accent
  - Movement indicators: green-600/red-600 → emerald-400/coral-accent
  - Connection dots: green-500/red-500 → emerald-500/coral-accent
- Remove dark:hidden/dark:block logo toggle in welcome.tsx (always dark)
- Update DraftGrid test assertions to match new class names

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 19:26:11 -08:00
Chris Parsons
8b480a0b9a
Fix ~/database/context resolving to browser stub during dev SSR (#12)
`resolve.alias` with `isSsrBuild` only works at build time — during
`npm run dev`, `isSsrBuild` is always false, so `ssrLoadModule` was
loading the browser stub (DatabaseContext = null) instead of the real
AsyncLocalStorage implementation, causing a TypeError on every request.

Replace the alias with an `enforce: 'pre'` plugin that checks
`options.ssr` at resolve time, which Vite correctly sets for both dev
SSR module loading and production SSR builds.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 16:10:22 -08:00
Chris Parsons
3323522782
Fix sports season page 404 when sports season is linked to multiple leagues (#10)
The loader was grabbing seasonSports[0] blindly instead of filtering by
the current league, causing a 404 when the first linked fantasy season
belonged to a different league.

https://claude.ai/code/session_01Mq6BqFhiYFuJyDcc8ueVJc

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 11:35:35 -08:00
Chris Parsons
83994b7a74
Fix draft round showing Infinity before draft starts (#9)
When draftSlots is empty (pre-draft state), dividing by zero caused
Math.ceil to return Infinity. Guard the division to fall back to round 1.

https://claude.ai/code/session_017mLmGc5wTrESaDeRQHkSPy

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 11:16:34 -08:00
Chris Parsons
47b69ce9cf
Include commissioner leagues in user's active leagues (#8)
* Show leagues where user is a member regardless of team assignment

The homepage now uses a union query to show leagues where the user
either has a team in the current season OR is a commissioner. Previously,
commissioners without a team could not see their leagues on the homepage.

https://claude.ai/code/session_01E3ugKTfatkEc5TcDGXvHiW

* Fix stale empty state card title in home route

Update 'No Active Leagues' to 'No Leagues' to match the updated
description which is now about membership rather than active seasons.

https://claude.ai/code/session_01E3ugKTfatkEc5TcDGXvHiW

* Fix union import: use two queries with JS deduplication

drizzle-orm 0.36.x does not export a standalone union() function.
Replace with two awaited queries merged via a Map (dedup by id),
then sorted by createdAt descending in JS.

https://claude.ai/code/session_01E3ugKTfatkEc5TcDGXvHiW

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 10:28:37 -08:00
Chris Parsons
8c9b131c00
Update scoring system and add Counter-Strike to special scoring (#7)
* Update how-to-play scoring rules to match standard scoring

- Update placement points: 1st 100, 2nd 70, 3rd-4th 45, 5th-8th 20
- Add Counter-Strike to the special majors scoring section alongside Golf & Tennis
- Add qualifying points breakdown (8/5/3/2/1) per major tournament

https://claude.ai/code/session_01JUAqVZgo7M7XRBLzpeaWpH

* Fix scoring to show all 8 individual placements correctly

Display each placement (1st-8th) with its own point value rather than
grouping/averaging: 100, 70, 50, 40, 25, 25, 15, 15

https://claude.ai/code/session_01JUAqVZgo7M7XRBLzpeaWpH

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 10:00:35 -08:00
Chris Parsons
eb7aa42cef
Add implementation plan for commissioner-without-team feature (#6)
* Add implementation plan for commissioner-without-team feature

https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3

* Allow commissioners to exist without owning a team

- Add opt-out checkbox on league creation ("I want to play in this league")
  so the creator can be commissioner-only without claiming a team
- Add Commissioner Management card to league settings with add/remove
  commissioner UI; guards against removing the last commissioner
- Add countCommissionersByLeagueId model helper for the last-commissioner guard
- Show "No team" indicator on the league homepage next to commissioners
  who don't own a team in the current season

https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3

* Fix code review issues in commissioner management

- Add success/error feedback banners to commissioner add/remove actions
- Gate allUsers query to admin-only (prevents exposing all users to non-admin commissioners)
- Prevent commissioner self-removal in both action (server) and UI (client)
- Add "(you)" label next to current user in commissioner list
- Remove all unnecessary `any` type casts in favor of inferred types

https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3

* Allow commissioners to add league members as co-commissioners

Non-admin commissioners can now add users who already own a team in
the league as co-commissioners. Admins still see the full user list.
Previously the add-commissioner form was admin-only.

https://claude.ai/code/session_01NSRMSYtb7jSFbngDS8okn3

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 08:45:09 -08:00
Chris Parsons
03fdba3022
Remove EV column from available participants table (#5)
* Hide EV column from draft board available participants table

https://claude.ai/code/session_016oJK1gmWZ48YWEZmVqm6f9

* Clean up dead expectedValue references after hiding EV column

- Remove expectedValue from AvailableParticipantsSection interface
- Remove EV column from Force Manual Pick commissioner dialog
- Remove expectedValue from participants loader SELECT and parsing step
- Retain ORDER BY expectedValue for default sort order

https://claude.ai/code/session_016oJK1gmWZ48YWEZmVqm6f9

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 17:02:55 -08:00
Chris Parsons
2d6dd6ec9f
Refactor expected values form to batch save all participants (#4)
* fix: remove probability sum validation and add batch save with total EV

- Remove the requirement that manual probabilities sum to 1.0, allowing
  partial distributions (e.g. when a participant has <100% chance of top 8)
- Replace per-row save buttons with a single "Save All" button that submits
  all participants at once
- Add a Total EV row at the bottom of the table summing all participant EVs
- Update action to batch process all participants from a single form submission

https://claude.ai/code/session_01WHRynBCcugSK7HHEmN6Yuy

* fix: validate participantIds server-side instead of trusting form input

Fetch participants from the DB in the action using the season ID from
the URL params, eliminating the untrusted participantIds hidden field.
Remove the now-unused hidden input from the frontend form.

https://claude.ai/code/session_01WHRynBCcugSK7HHEmN6Yuy

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 15:57:05 -08:00
Chris Parsons
eb260649b1
Add bulk import feature for futures odds with fuzzy matching (#3)
* Add bulk import to futures odds page

Adds a textarea where admins can paste odds from FanDuel, DraftKings,
OddsChecker, or any site. A client-side parser extracts American odds
from each line and fuzzy-matches team names to participants (exact,
substring, and word-overlap matching). Shows matched/unmatched results
before applying to the individual input fields.

https://claude.ai/code/session_01JvgcqKSJZ36bEztfg6CkWP

* Code review fixes for futures-odds page

- Remove unused upsertParticipantEVWithNormalization import
- Remove debug console.log statements left in save action
- Move normalizeName to module level (pure function, no component deps)
- Pre-compute normalized participant names once in findParticipantMatch
  instead of re-normalizing across three separate passes
- Fix array index key on unmatched list to use composite string key
- Drop unused result variable from upsertParticipantEV call

https://claude.ai/code/session_01JvgcqKSJZ36bEztfg6CkWP

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 14:34:45 -08:00
Chris Parsons
740ffbb411
fix: exclude database/context from browser bundle to fix Docker build (#2)
database/context.ts uses AsyncLocalStorage from node:async_hooks which
is a Node.js-only API. Vite externalizes it for browser builds but the
resulting error "AsyncLocalStorage is not exported by __vite-browser-external"
caused npm run build to fail.

Fix: add a Vite resolve.alias for the browser (non-SSR) build that maps
~/database/context to a browser-safe stub. The stub is never called at
runtime since database() is only invoked in server-side loaders, but it
allows the client bundle to build without errors.

https://claude.ai/code/session_01Fjf9WFqNnuHmmC5yTedL7G

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 11:54:32 -08:00
Chris Parsons
3210ab265f
Change participant expectedValue from integer to decimal (#1)
* feat: sync odds-based EV to participants table for draft room ranking

When admin enters futures odds or manual probabilities, the calculated EV
is now synced from participantExpectedValues to participants.expectedValue.
This closes the gap where EVs were calculated but never reflected in the
draft room ranking. Also changes expectedValue from integer to decimal(10,2)
for better precision, and displays "—" for participants with no odds data.

https://claude.ai/code/session_01JWG2zg2EMzCn6RgEufPC1T

* fix: correct expectedValue type to string in participants route

Missed instance of `expectedValue: 0` (number) that failed typecheck
after schema change from integer to decimal.

https://claude.ai/code/session_01JWG2zg2EMzCn6RgEufPC1T

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 11:26:40 -08:00
Chris Parsons
9211cad7d1 fix: correct test expectations for ICM edge cases and duplicate text queries
- ICM tests: fix single participant, zero probabilities, and 2-participant
  tests to account for simulation only filling min(participants, 8) positions
- TeamScoreBreakdown tests: use getAllByText for "150.0" which now appears
  in both the header and the Actual Points summary card

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 14:24:07 -08:00
Chris Parsons
96b4c5a350 fix: align ev-calculator tests with decimal (0-1) probability format
The implementation and rest of the system (ICM calculator, probability
updater) use decimals (0-1) for probabilities, but the tests were using
percentages (0-100). Updated tests and docs to match.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 23:26:32 -08:00
Chris Parsons
24126fe389 fix: add missing projectedPoints and actualPoints to TeamScoreBreakdown test fixtures
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 23:08:06 -08:00
Chris Parsons
7970cb6a9c feat: add FIFA World Cup 48-team bracket template with group stage and projected scoring
- Add FIFA_48 bracket template with 12 groups of 4, knockout stage of 32
- Add tournament groups schema, model, and GroupStageDisplay component
- Add projected/expected value scoring to standings and team breakdowns
- Add docker-compose for local PostgreSQL development
- Move DRAFT_ORDER_IMPLEMENTATION.md to plans directory

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 22:30:12 -08:00
Chris Parsons
840212c4f8 feat: implement sports season expected value calculations and probability updates
- Added loader and action functions for managing expected values in sports seasons.
- Implemented UI for recalculating probabilities based on participant results.
- Created a service to update probabilities after results are finalized, including handling finished and unfinished participants.
- Developed tests for the probability updater service to ensure correct functionality.
- Introduced a preview feature to show potential changes before applying updates.
2025-11-21 22:05:50 -08:00
Chris Parsons
79ec477a98 feat: implement Expected Value System with ICM probability calculator
Implements Phase 5.2 of the EV system with Harville-Malmuth Independent Chip Model
for calculating participant placement probabilities from futures odds.

## Key Features

### ICM Probability Calculator
- Implements Harville-Malmuth method for distributing probabilities
- Converts American odds to championship probabilities
- Generates P(1st) through P(8th) for all participants
- Column-normalized: each placement sums to 100% across all teams
- Works with any number of participants (not limited to 8)

### Admin UI - Futures Odds Entry
- Enter American odds (e.g., +550, -200) for championship futures
- Live preview of ICM-calculated probability distributions
- Displays all 8 placement probabilities
- Persists odds for editing on subsequent visits
- Automatic probability normalization (removes bookmaker vig)

### Database Schema Updates
- Renamed participant_expected_values.season_id → sports_season_id
- Updated foreign key to reference sports_seasons instead of seasons
- Added source_odds field to store original futures odds
- Migration 0025: Column rename and FK update
- Migration 0026: Add source_odds field

### Model Layer
- participant-expected-value: CRUD operations for probability distributions
- Supports multiple probability sources (manual, futures_odds, elo_simulation)
- Automatic EV calculation based on league scoring rules
- Probability validation and normalization

### Service Layer
- icm-calculator: Harville-Malmuth probability distribution
- probability-engine: Odds conversion and Elo utilities (for future use)
- bracket-simulator: Monte Carlo simulation (for future hybrid approach)
- ev-calculator: Expected value computation from probabilities

## Technical Details

- Uses exponential decay favoring top positions for strong teams
- Preserves championship probability ordering in final distributions
- Row sums vary (strong teams ~100%, weak teams lower)
- All probabilities between 0-1, mathematically valid
- Comprehensive test suite: 97 tests passing

## Future Enhancements

- Hybrid approach: ICM pre-playoffs, bracket simulation during playoffs
- Integration with league-specific scoring rules
- Historical probability tracking for accuracy analysis

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 22:19:46 -08:00
Chris Parsons
41b81771d4 Implement detailed Phase 5 implementation plan for Expected Value System
- Added comprehensive implementation plan for Phase 5, including executive summary, clarifications, recommended architecture, task breakdown, and performance considerations.
- Defined database schema changes for participant probabilities and expected values.
- Outlined service layer architecture for probability generation, EV calculation, and probability updates.
- Included detailed task breakdown for each sub-phase, focusing on manual entry, futures odds integration, real results integration, projected totals display, draft integration, and daily update job.
- Incorporated validation data and calibration goals for NHL futures odds.
- Updated planning questions and answers based on previous discussions to refine the approach for EV calculations and autodraft integration.
2025-11-15 22:54:59 -08:00
Chris Parsons
6ef829f667 feat: add recharts library and implement PointProgressionChart component for historical views
- Added recharts dependency to package.json for data visualization.
- Implemented PointProgressionChart component to display team point progression over time.
- Updated scoring-system.md to reflect completion of historical views and added implementation notes.
- Created unit tests for PointProgressionChart to ensure correct rendering and data handling.
- Developed season completion detection and percentage calculation functions in season-helpers.server.ts.
- Added tests for season completion logic and point progression data formatting.
- Enhanced league loader to fetch necessary data for current season and teams.
2025-11-14 21:18:34 -08:00
Chris Parsons
0eeb1b6245 feat: Enhance league home page with sports seasons section and scoring pattern display 2025-11-14 20:39:51 -08:00
Chris Parsons
f17699e4c5 feat: Implement team breakdown pages with detailed score breakdown
- Created `TeamScoreBreakdown` component to display all drafted participants, their placements, and points.
- Added new route for team breakdown at `/leagues/:leagueId/standings/:seasonId/teams/:teamId`.
- Enhanced `getTeamScoreBreakdown` model to include `sportsSeasonId` for grouping.
- Updated `StandingsTable` to include clickable team name links.
- Added functionality to finalize brackets in playoff events, including error handling and recalculating standings.
- Implemented tests for `TeamScoreBreakdown` component to ensure proper rendering and functionality.
- Updated routing to support new team breakdown feature and ensure seamless navigation.
2025-11-14 20:01:21 -08:00
Chris Parsons
9d38bdf1ca feat: implement daily standings snapshot system with admin management interface 2025-11-14 09:15:58 -08:00
Chris Parsons
0385ca220c feat: add standings page and enhance standings functionality
- Added a new route for league standings: `/leagues/:leagueId/standings/:seasonId`
- Implemented the `StandingsTable` component to display team standings with ranking, points, and placement breakdown.
- Integrated tiebreaker logic for ranking teams based on total points and placements.
- Enhanced the league home page with a link to view standings.
- Updated scoring system documentation to reflect the new standings features.
- Added comprehensive tests for tiebreaker logic and `StandingsTable` component.
- Created shared types for standings to be used in both server and client code.
2025-11-13 13:24:03 -08:00
Chris Parsons
604eb6980c feat: Add routes and components for sports season display, including playoff brackets and standings 2025-11-12 23:44:33 -08:00
Chris Parsons
4d5b4efc23 feat: Implement AFL Finals bracket template and scoring logic with double-chance system 2025-11-12 23:21:22 -08:00
Chris Parsons
1089022c09 feat: Implement Qualifying Points Standings component and related logic
- Added `QualifyingPointsStandings` component to display standings based on qualifying points.
- Introduced scoring rules and projected points calculation for participants.
- Implemented tie handling for rankings and displayed appropriate UI elements based on finalization status.
- Created tests for qualifying points configuration, accumulation logic, ranking logic, and scoring workflow.
- Developed scoring calculator tests to validate fantasy points conversion from qualifying points.
- Established qualifying points management functions including initialization, retrieval, updating, and resetting of points.
2025-11-11 10:08:25 -08:00
Chris Parsons
d926486934 feat: Implement season standings processing and participant result management for final standings events 2025-11-08 22:35:07 -08:00
Chris Parsons
5d0e6b999c feat: Implement NFL 14 bracket template with bye week handling and comprehensive unit tests 2025-11-08 21:56:57 -08:00
Chris Parsons
4d305c4117 feat: Add ParticipantSelector component for improved participant selection in brackets 2025-11-08 21:36:29 -08:00
Chris Parsons
bbacb00d6c feat: Implement NCAA 68 tournament structure with First Four play-in games and Round of 64 seeding logic 2025-11-08 21:18:09 -08:00
Chris Parsons
dfe4b7b643 Add bracket seeding tests and implement tournament-style seeding for 16 and 32-team brackets
- Introduced `generateStandardSeeding()` function to create proper tournament matchups (e.g., 1v16, 8v9).
- Added comprehensive tests for 4, 8, 16, and 32-team brackets to ensure correct seeding and balance.
- Updated testing instructions to reflect new features and improvements in bracket generation.
- Fixed issues with sequential seeding and ensured all matchups sum to n+1 for balance.
- Implemented batch winner selection and duplicate participant prevention for improved user experience.
- Enhanced fantasy points display on event pages for better visibility of participant results.
2025-11-04 22:09:44 -08:00
Chris Parsons
da1a17f2d3 Refactor code structure for improved readability and maintainability 2025-11-03 13:16:37 -08:00
Chris Parsons
a3b8fa6309 feat: Implement bracket expansion plan to support various tournament structures
- Added a comprehensive plan for bracket expansion, including support for 4, 8, 16, 32, and 68 team formats.
- Introduced a template-based bracket system with predefined templates for NCAA March Madness, NFL Playoffs, NBA Playoffs, and simple brackets.
- Updated UI flow for bracket creation, allowing admins to select templates and assign participants flexibly.
- Enhanced database schema to accommodate new scoring rules and bracket templates.
- Proposed updates to scoring logic to handle non-scoring rounds and participant placements correctly.
- Documented implementation phases for gradual rollout of new features.
- Addressed critical bugs in the playoff event processing and scoring logic, ensuring proper advancement and scoring rules across multiple leagues.
2025-11-03 09:36:16 -08:00
Chris Parsons
60ba3d4a6e feat: Implement event management for sports seasons with CRUD operations and UI 2025-10-31 22:13:12 -07:00
Chris Parsons
7dddf2c9a7 feat: Add scoring rules editor to league settings and creation pages
- Created ScoringRulesEditor component with 8 placement point inputs
- Added scoring-types.ts for shared client/server types
- Integrated scoring rules into league settings page
- Integrated scoring rules into league creation form
- Added validation for point values (0-1000 range)
- Disabled editing in settings after draft starts
- Included helpful tips and preview display

Phase 1.3 complete

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 00:04:27 -07:00
Chris Parsons
e49bb3df8b feat: Add scoring event and results management with comprehensive scoring rules and standings tracking 2025-10-28 23:50:50 -07:00
Chris Parsons
8e422c6503 fix: Pass database instance to isParticipantDrafted in timer context
The timer system runs outside the request context and uses its own database
  connection. This fix allows isParticipantDrafted to accept an optional db
  parameter so it works in both request handlers and timer contexts.

  Fixes: DatabaseContext not set error during autopick
2025-10-28 23:40:29 -07:00