brackt/app/routes/api/draft.rollback.ts
Chris Parsons a3ec556ecc
Refactor autodraft chain logic and improve timer handling (#25)
* Fix draft timer missing after rollback causing draft to freeze

The rollback endpoint was deleting all timers but only recreating one
for the team currently on the clock. After that team made their pick,
the next team had no timer row, causing the timer system to log
"No timer found" and skip indefinitely, freezing the draft.

Fix: recreate timers for ALL teams after a rollback, each starting at
draftInitialTime.

Also add a defensive fallback in the timer system: if a timer row is
missing for the current team during an active draft, create it at
draftInitialTime instead of skipping, so the draft can never get
permanently stuck due to a missing timer.

https://claude.ai/code/session_01YPxgcQywG57KiXj7m46gLV

* Fix rollback to not touch timers at all

Timers are each team's time bank and should not be affected by rolling
back a pick. The previous code (both original and the first fix) was
deleting all timer rows during rollback, which was the actual root cause
of the missing timer bug.

Rollback now only does what it should: delete picks from the rollback
point onwards and reset currentPickNumber. The timer system will
naturally resume for the correct team on its next tick.

Also removes the incorrect timer-update socket emit that was sending
initialTime instead of the team's actual remaining bank.

https://claude.ai/code/session_01YPxgcQywG57KiXj7m46gLV

* Fix all code review issues across timer, rollback, start, and draft-utils

server/timer.ts:
- Remove noisy per-tick console.log that fired every second per active draft
- Remove slot:any type cast (Drizzle query results are already typed)
- Fix inconsistent autodraftSettings argument in the === 0 trigger path
  to match the <= 0 path (pass null when autodraft is disabled)
- Fix infinite auto-pick loop: triggerAutoPick now returns boolean;
  on failure the draft is paused and a draft-paused socket event is
  emitted so clients and commissioners are notified. "Pick already made"
  (race condition) is treated as success, not failure.

draft.start.ts:
- Validate that draft slots exist before updating season status to draft.
  Previously a missing-slots error left the season stuck in draft status
  with no timer rows.

draft.rollback.ts:
- Guard against empty draftSlots before performing snake draft math,
  which would produce Infinity/NaN with zero teams.

draft-utils.ts:
- Convert checkAndTriggerNextAutodraft from recursive to iterative.
  The mutual recursion (executeAutoPick → checkAndTriggerNextAutodraft
  → executeAutoPick) is now a while loop, preventing unbounded call
  stack growth in all-autodraft leagues. Add chainEnabled param to
  executeAutoPick so chain calls skip spawning a second chain.
- Restructure getTopAvailableParticipant so the single-sport query is
  only built when actually needed (not thrown away in the multi-sport
  branch).
- Update misleading timeUsed comment to accurately describe that the
  stored value is the team's bank balance at pick time, not time spent.

https://claude.ai/code/session_01YPxgcQywG57KiXj7m46gLV

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-22 17:02:35 -08:00

105 lines
2.9 KiB
TypeScript

import { getAuth } from "@clerk/react-router/server";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq, and, gte } from "drizzle-orm";
import { getSocketIO } from "../../../server/socket";
export async function action(args: any) {
const { request } = args;
const auth = await getAuth(args);
const userId = (auth as any).userId as string | null;
if (!userId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const formData = await request.formData();
const seasonId = formData.get("seasonId") as string;
const pickNumber = parseInt(formData.get("pickNumber") as string);
if (!seasonId || isNaN(pickNumber) || pickNumber < 1) {
return Response.json({ error: "Missing required fields" }, { 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 });
}
const isCommissioner = await db.query.commissioners.findFirst({
where: and(
eq(schema.commissioners.leagueId, season.leagueId),
eq(schema.commissioners.userId, userId)
),
});
if (!isCommissioner) {
return Response.json({ error: "Only commissioners can roll back the draft" }, { status: 403 });
}
if (season.status !== "draft") {
return Response.json(
{ error: "Cannot roll back a draft that is not in progress" },
{ status: 400 }
);
}
const draftSlots = await db.query.draftSlots.findMany({
where: eq(schema.draftSlots.seasonId, seasonId),
orderBy: schema.draftSlots.draftOrder,
});
const totalTeams = draftSlots.length;
if (totalTeams === 0) {
return Response.json({ error: "No draft slots found for this season" }, { status: 400 });
}
// Calculate which team is on the clock at the rollback pick (snake draft)
const round = Math.ceil(pickNumber / totalTeams);
const isEvenRound = round % 2 === 0;
let pickInRound = ((pickNumber - 1) % totalTeams) + 1;
if (isEvenRound) {
pickInRound = totalTeams - pickInRound + 1;
}
const rollbackSlot = draftSlots.find((slot) => slot.draftOrder === pickInRound);
// Delete picks from pickNumber onwards
await db
.delete(schema.draftPicks)
.where(
and(
eq(schema.draftPicks.seasonId, seasonId),
gte(schema.draftPicks.pickNumber, pickNumber)
)
);
// Update season: reset pick number and unpause
await db
.update(schema.seasons)
.set({
currentPickNumber: pickNumber,
draftPaused: false,
})
.where(eq(schema.seasons.id, seasonId));
// Emit socket events
try {
const io = getSocketIO();
io.to(`draft-${seasonId}`).emit("draft-rolled-back", {
seasonId,
pickNumber,
teamId: rollbackSlot?.teamId,
});
} catch (error) {
console.error("Socket.IO error:", error);
}
return Response.json({ success: true, pickNumber });
}