Commit graph

13 commits

Author SHA1 Message Date
Chris Parsons
2949ca733a
Add standard draft clock mode (#67) (#189)
Implements a new "standard" timer mode alongside the existing chess clock
mode. In standard mode the per-pick timer resets to a fixed value after
every pick (no carry-over), and the speed selector shows plain time values
instead of named chess-clock presets.

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

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-20 21:36:39 -07:00
Chris Parsons
41384f08fb
Grant sitewide admins commissioner-level access in leagues (#162)
* Grant sitewide admins commissioner-level access in leagues

- `isCommissioner()` now returns true for site admins, covering all
  commissioner-gated loaders (league home, settings, sport season detail)
  and draft API routes (start, pause, resume, rollback, replace-pick,
  force-autopick, force-manual-pick, adjust-time-bank, make-pick)
- Added `hasCommissionerRecord()` (DB-only, no admin bypass) for the
  "already a commissioner" duplicate-entry check in the settings action,
  preventing a false positive when adding a site admin as commissioner
- `isCommissioner()` now runs the admin check and DB query in parallel
  via Promise.all to avoid a serial roundtrip on every check
- Added "admin" to the `picked_by_type` enum (migration 0049) so picks
  forced by a site admin are recorded accurately in the audit log rather
  than as "commissioner"
- 8 unit tests covering both isCommissioner and hasCommissionerRecord

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

* Fix draft.force-manual-pick tests broken by isUserAdminByClerkId

The route now calls isUserAdminByClerkId which hits database().query.users,
but the test's mock DB had no query.users entry. Add a vi.mock for
~/models/user and default isUserAdminByClerkId to false in beforeEach.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 00:41:56 -07:00
Chris Parsons
16aa450d63
feat: proactively prune ineligible queue items after each pick (#59)
After every pick, recalculate draft eligibility for all teams and
remove any queued participants whose sport is no longer eligible
(e.g. a team queued a snooker player but just filled their last flex
slot). Previously this was only caught lazily when autodraft fired,
which could pause the draft or pick an unwanted player.

- Add getAllQueuesForSeason to draft-queue.ts — fetches all queue rows
  for a season in one query (Map<teamId, QueueItem[]>) instead of N+1
  per-team queries
- Add pruneIneligibleQueueItems to draft-utils.ts — uses Promise.all
  for the four required data fetches, collects ineligible items in a
  single loop pass, warns on orphaned participant references
- Call from both pick paths: executeAutoPick and draft.make-pick.ts
- Emit queue-eligibility-pruned socket event per affected team so the
  client updates the queue UI in real time
- Add 5 tests covering: single ineligible removal, all eligible (no-op),
  empty queues (no delete called, getTeamQueue never called), mixed
  queue (only ineligible item removed), and unknown participant (warn)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 22:07:22 -08:00
Chris Parsons
f33e39264d
fix: harden draft timer system with race-condition safety and DRY refactor (#34)
- Fix settings action silently resetting timer values when draft speed
  select is disabled (add null guard before overwriting draftInitialTime/
  draftIncrementTime)
- Make timer decrement and pick increment atomic using SQL expressions to
  prevent read-modify-write races between the timer loop and HTTP handlers
- Add UNIQUE INDEX on (season_id, pick_number) in draft_picks to prevent
  duplicate picks from concurrent requests (TOCTOU guard)
- Add socket join-draft team ownership validation via DB query
- Add iteration cap to autodraft chain while loop (max = totalTeams)
- Add draftPaused re-check before firing autodraft chain in make-pick
  and force-manual-pick
- Consolidate all snake draft calculations into calculatePickInfo (DRY);
  remove duplicated logic from timer.ts, make-pick, force-manual-pick,
  executeAutoPick, and checkAndTriggerNextAutodraft
- Fix calculatePickInfo to return snake-adjusted pickInRound matching
  draftOrder values instead of raw pre-snake value
- Fix timer-update socket events to emit nextPickNumber after a pick
  instead of the already-completed currentPickNumber
- Fix force-manual-pick to validate submitted teamId matches the team
  whose turn it actually is at the given pick number
- Replace inline timer init in draft.start with deleteSeasonTimers +
  initializeDraftTimers model functions (dead code fix)
- Fix draft loader to not crash when getTeamQueue fails (returns [])
- Fix misleading 403 message for commissioner picks
- Remove dead hidden inputs from league settings form
- Document connectedTeams single-instance limitation in socket.ts

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-23 23:23:24 -08:00
Chris Parsons
01f1480159
Claude/fix pick timer ghll n (#29)
* Fix force-manual-pick resetting next team's timer to initial time

When a commissioner forced a manual pick, the next team's timer was
being reset to the initial time (2 minutes) instead of carrying
forward their existing time bank balance.

This aligns force-manual-pick with the behavior of regular user picks
and force-autopick: the picking team gets their increment added, and
the next team's timer is left untouched so their bank carries forward.

https://claude.ai/code/session_01X7gwWmafUSEvVHcV7Raz5p

* Add regression tests for draft.force-manual-pick timer behavior

18 tests across 5 describe blocks covering:
- Authorization (401/403)
- Input validation (missing fields, bad participant, ineligible sport)
- Successful pick (response shape, draft-complete detection, socket events)
- Timer behavior (increment added to picking team, new timer creation, additive not reset)
- Two regression tests confirming the next team's timer is never touched:
  draftTimers.findFirst called exactly once, no timer-update emitted for
  next team, db.update called exactly twice (not three times)

https://claude.ai/code/session_01X7gwWmafUSEvVHcV7Raz5p

* Add TypeScript types and improve draft validation (#28)

* Code review fixes: type safety, security hardening, and dead code removal

- Fix Socket.IO event types: draft-paused and draft-resumed were typed as
  () => void but are emitted with { seasonId, paused } data payloads

- Fix draft.force-manual-pick: add missing season.status === "draft" guard
  so commissioners cannot force picks outside an active draft; add duplicate
  pick-number check so a slot cannot be assigned two picks (the previous
  code only checked participant uniqueness, not slot uniqueness)

- Replace args: any with ActionFunctionArgs / Route.LoaderArgs across all
  API routes and league loaders; replace (auth as any).userId casts with
  proper const { userId } = await getAuth(args) destructuring

- Remove unused isSnakeDraft = true dead variable from draft.make-pick

- Replace autodraftSettings: any and draftSlots: any[] in draft-utils with
  properly typed InferSelectModel / DraftSlot types

- Update force-manual-pick tests: sequence draftPicks.findFirst mock for
  the two-call flow; add new tests for status-check and slot-uniqueness

https://claude.ai/code/session_01FKq2gPFYpgdfxr8cw4Z2AZ

* Fix RouterContextProvider type errors in action test files

Cast context argument to RouterContextProvider in test helpers so
ActionFunctionArgs strict typing is satisfied without weakening the
production action signatures back to any.

https://claude.ai/code/session_01FKq2gPFYpgdfxr8cw4Z2AZ

---------

Co-authored-by: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 19:29:29 -08:00
Chris Parsons
34da0594d1
Fix draft timer creation for teams without existing timers (#26)
* Create timer when adding time to a team with no existing timer

When a commissioner tries to add time to a team that has no draft timer,
instead of returning a 404 error, create a new timer record with the
specified amount of time. Removing time still returns a 404 if no timer
exists (nothing to remove from).

https://claude.ai/code/session_016VpJKZZFNQQqzfmLu8pHoc

* Fix silent timer failures and missing seasonId filter in timer model

- draft.make-pick.ts: create a timer with the increment amount instead of
  logging a warning and silently skipping when no timer exists for the
  picking team
- draft.force-manual-pick.ts: same fix for the commissioner force-pick path;
  also unconditionally emit the timer-update socket event so clients always
  see the updated time
- models/draft-timer.ts: add seasonId parameter to getTeamTimer and
  updateTeamTimer so they cannot match the wrong season's timer when a team
  participates in multiple seasons

https://claude.ai/code/session_016VpJKZZFNQQqzfmLu8pHoc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 17:27:16 -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
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
918e9ff04a feat: Implement autodraft chain logic and timer initialization for next team picks 2025-10-25 22:11:10 -07:00
Chris Parsons
190dfb92ca feat: add socket event for participant removal from queues 2025-10-24 21:46:55 -07:00
Chris Parsons
decb28dc19 Implement Omni League Draft Eligibility Rules
- Created draft eligibility calculation logic in `app/lib/draft-eligibility.ts`
- Added interfaces for sport availability and draft eligibility
- Implemented `calculateDraftEligibility` function to determine eligible sports based on team picks and global availability
- Developed `getEligibilitySummary` function for human-readable eligibility status
- Updated API endpoints to validate eligibility before making picks
- Enhanced frontend draft room UI to reflect eligibility status and provide visual indicators for ineligible participants
- Comprehensive implementation summary and testing documentation added
- All changes type-checked and unit tests passed successfully
2025-10-24 21:12:07 -07:00
Chris Parsons
a7f5df923f feat: add draft increment time and show team-specific timers in draft UI 2025-10-18 23:13:04 -07:00
Chris Parsons
9d41508fd0 feat: add draft API routes and implement draft room pick controls 2025-10-18 14:55:26 -07:00