2026-02-22 16:16:51 -08:00
|
|
|
import { getAuth } from "@clerk/react-router/server";
|
|
|
|
|
import { eq, and } from "drizzle-orm";
|
|
|
|
|
import { database } from "~/database/context";
|
|
|
|
|
import * as schema from "~/database/schema";
|
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
|
|
|
import { isCommissioner } from "~/models/commissioner";
|
2026-02-22 16:16:51 -08:00
|
|
|
import { getSocketIO } from "../../../server/socket";
|
2026-03-21 13:41:39 -07:00
|
|
|
import { logger } from "~/lib/logger";
|
2026-02-22 16:16:51 -08:00
|
|
|
|
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
|
|
|
import type { ActionFunctionArgs } from "react-router";
|
|
|
|
|
export async function action(args: ActionFunctionArgs) {
|
2026-02-22 16:16:51 -08:00
|
|
|
const { request } = args;
|
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
|
|
|
const { userId } = await getAuth(args);
|
2026-02-22 16:16:51 -08:00
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const formData = await request.formData();
|
|
|
|
|
const seasonId = formData.get("seasonId") as string;
|
|
|
|
|
const teamId = formData.get("teamId") as string;
|
|
|
|
|
const adjustmentRaw = formData.get("adjustment");
|
|
|
|
|
const adjustment = adjustmentRaw !== null ? parseInt(adjustmentRaw as string, 10) : NaN;
|
|
|
|
|
|
|
|
|
|
if (!seasonId || !teamId || isNaN(adjustment)) {
|
|
|
|
|
return Response.json({ error: "seasonId, teamId, and adjustment are required" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const db = database();
|
|
|
|
|
|
|
|
|
|
const season = await db.query.seasons.findFirst({
|
|
|
|
|
where: eq(schema.seasons.id, seasonId),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!season) {
|
|
|
|
|
return Response.json({ error: "Season not found" }, { status: 404 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (season.status !== "draft") {
|
|
|
|
|
return Response.json({ error: "Draft is not currently active" }, { status: 409 });
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
if (!(await isCommissioner(season.leagueId, userId))) {
|
2026-02-22 16:16:51 -08:00
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Only commissioners can adjust time banks" },
|
|
|
|
|
{ status: 403 }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const [currentTimer] = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(schema.draftTimers)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(schema.draftTimers.seasonId, seasonId),
|
|
|
|
|
eq(schema.draftTimers.teamId, teamId)
|
|
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
|
2026-02-22 17:27:16 -08:00
|
|
|
let newTime: number;
|
|
|
|
|
|
2026-02-22 16:16:51 -08:00
|
|
|
if (!currentTimer) {
|
2026-02-22 17:27:16 -08:00
|
|
|
if (adjustment <= 0) {
|
|
|
|
|
return Response.json({ error: "Timer not found for this team" }, { status: 404 });
|
|
|
|
|
}
|
|
|
|
|
newTime = adjustment;
|
|
|
|
|
await db.insert(schema.draftTimers).values({
|
|
|
|
|
seasonId,
|
|
|
|
|
teamId,
|
|
|
|
|
timeRemaining: newTime,
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
newTime = Math.max(0, currentTimer.timeRemaining + adjustment);
|
|
|
|
|
await db
|
|
|
|
|
.update(schema.draftTimers)
|
|
|
|
|
.set({ timeRemaining: newTime, updatedAt: new Date() })
|
|
|
|
|
.where(eq(schema.draftTimers.id, currentTimer.id));
|
2026-02-22 16:16:51 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
getSocketIO()
|
|
|
|
|
.to(`draft-${seasonId}`)
|
|
|
|
|
.emit("timer-update", {
|
|
|
|
|
seasonId,
|
|
|
|
|
teamId,
|
|
|
|
|
timeRemaining: newTime,
|
|
|
|
|
currentPickNumber: season.currentPickNumber ?? 1,
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
2026-03-21 13:41:39 -07:00
|
|
|
logger.error("Socket.IO error:", error);
|
2026-02-22 16:16:51 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Response.json({ success: true, timeRemaining: newTime });
|
|
|
|
|
}
|