brackt/app/routes/api/draft.make-pick.ts
chrisp f96c8f5244
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 2m40s
🚀 Deploy / ʦ🔍 Typecheck & Lint (push) Successful in 1m26s
🚀 Deploy / 🐳 Build (push) Successful in 1m14s
🚀 Deploy / 🚀 Deploy (push) Successful in 12s
Fix draft timer: broadcasts, increments, reconnect sync, overnight pause (#72)
## Summary

- **Timer bank broadcasts**: emit `timer-bank-updated` after every pick so all clients immediately see the updated bank instead of waiting for the next `timer-pick-started`
- **Increment accuracy**: capture `pickMadeAt` at route entry (before auth/DB overhead) and use `Math.ceil` so credited seconds always match the client countdown display
- **Race condition fix**: hold `schedulingInProgress` lock for the full timer callback to prevent the recovery interval from scheduling a duplicate timeout mid-pick
- **force-autopick fix**: call `rescheduleTimer` so the next team's clock starts immediately instead of waiting for the old timeout to naturally expire
- **adjust-time-bank fix**: for on-clock teams, shift `picksExpiresAt` by the adjustment and reschedule so the client countdown updates; block adjustments that would reduce the bank to zero
- **New socket events**: `timer-pick-started`, `timer-overnight-paused`, `timer-bank-updated` with full type definitions; removed dead `timer-update` event
- **Reconnect sync**: `draft-state-sync` now includes `expiresAt` for the active timer and `isOvernightPause` state so reconnecting clients see accurate countdown and pause banner immediately without a page reload
- **Room closure countdown**: capture client-side timestamp when draft completes so the "Room closes in X" countdown actually ticks down before the loader revalidates with `draftCompletedAt`
- **Countdown interval**: run at 500ms with `Math.ceil` to prevent skipped seconds under event loop pressure
- **Overnight pause UX**: `canPick` only blocks on commissioner pause — overnight pause freezes the timer but the on-clock player can still pick early
- **Overnight pause refactor**: extract `checkOvernightPause` to `server/overnight-pause-check.ts`, breaking the `timer↔socket` circular import and sharing the timezone cache across both callers with correct eviction
- **PostgreSQL type fix**: cast `varchar` owner ID to `uuid` in `getTeamTimezone` join

## Test plan

- [ ] Manual pick: all clients see bank increment immediately after pick
- [ ] Timeout pick: all clients see bank update (0 → increment); next clock starts within ~1s
- [ ] Force-autopick: next team's clock starts immediately; no "Pick already made" log
- [ ] Force-manual-pick: all clients see bank increment
- [ ] Pause while clock running: countdown freezes on all clients
- [ ] Resume: clock continues from frozen value
- [ ] adjust-time-bank on on-clock team: countdown shifts immediately
- [ ] adjust-time-bank to zero: returns 400 error
- [ ] Reconnect (socket disconnect/connect): countdown resumes for correct team
- [ ] Hard refresh mid-draft: on-clock indicator and countdown correct immediately
- [ ] Draft complete: "Room closes in X" counts down
- [ ] Overnight pause: banner shows, pick buttons still enabled, timer frozen
- [ ] `npm run test:run` — all 158 files / 2351 tests pass

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

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #72
2026-06-06 05:57:46 +00:00

358 lines
12 KiB
TypeScript

import { auth } from "~/lib/auth.server";
import { getTeamForPick } from "~/lib/draft-order";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq, and } from "drizzle-orm";
import { isUserAdmin } from "~/models/user";
import { calculateDraftEligibility } from "~/lib/draft-eligibility";
import { getDraftPicksWithSports, getTeamDraftPicksWithSports } from "~/models/draft-pick";
import { getParticipantsForSeasonWithSports } from "~/models/season-participant";
import { getSeasonSportsSimple } from "~/models/season-sport";
import { calculatePickInfo, checkAndTriggerNextAutodraft, pruneIneligibleQueueItems } from "~/models/draft-utils";
import { getSocketIO, scheduleDraftRoomClosure } from "../../../server/socket";
import { rescheduleTimer } from "../../../server/timer";
import { logger } from "~/lib/logger";
import { runBracktHarvilleForFantasySeason } from "~/services/brackt.server";
import { sendOnTheClockEmail } from "~/services/draft-email.server";
import { notifyPickMadeOnDiscord } from "~/services/draft-discord.server";
import { enqueuePickNotification } from "~/services/discord";
import type { ActionFunctionArgs } from "react-router";
export async function action(args: ActionFunctionArgs) {
const pickMadeAt = Date.now(); // capture before any async work for accurate timer credit
const { request } = args;
const session = await auth.api.getSession({ headers: args.request.headers });
const userId = session?.user.id ?? null;
if (!userId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const formData = await request.formData();
const seasonId = formData.get("seasonId") as string;
const participantId = formData.get("participantId") as string;
if (!seasonId || !participantId) {
return Response.json({ error: "Missing required fields" }, { status: 400 });
}
const db = database();
// Get season details
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: 400 });
}
if (season.draftPaused) {
return Response.json({ error: "Draft is currently paused" }, { status: 400 });
}
// Get current draft slot (who should be picking now)
const currentPickNumber = season.currentPickNumber || 1;
const draftSlots = await db.query.draftSlots.findMany({
where: eq(schema.draftSlots.seasonId, seasonId),
orderBy: schema.draftSlots.draftOrder,
with: {
team: true,
},
});
const totalTeams = draftSlots.length;
const { round: currentRound, pickInRound, rawPickInRound } = calculatePickInfo(currentPickNumber, totalTeams);
const currentDraftSlot = draftSlots.find((slot) => slot.draftOrder === pickInRound);
if (!currentDraftSlot) {
return Response.json({ error: "Invalid draft state" }, { status: 500 });
}
// Check permissions: must be team owner or commissioner/admin
// Capture both results to set pickedByType accurately in the audit record
const isTeamOwner = currentDraftSlot.team.ownerId === userId;
const [isAdmin, commissionerRecord] = await Promise.all([
isUserAdmin(userId),
db.query.commissioners.findFirst({
where: and(
eq(schema.commissioners.leagueId, season.leagueId),
eq(schema.commissioners.userId, userId)
),
}),
]);
if (!isTeamOwner && !isAdmin && !commissionerRecord) {
return Response.json({ error: "You do not have permission to pick for this team" }, { status: 403 });
}
// Check if participant is already drafted
const existingPick = await db.query.draftPicks.findFirst({
where: and(
eq(schema.draftPicks.seasonId, seasonId),
eq(schema.draftPicks.participantId, participantId)
),
});
if (existingPick) {
return Response.json({ error: "Participant already drafted" }, { status: 400 });
}
// Get participant details
const participant = await db.query.seasonParticipants.findFirst({
where: eq(schema.seasonParticipants.id, participantId),
with: {
sportsSeason: {
with: {
sport: true,
},
},
},
});
if (!participant) {
return Response.json({ error: "Participant not found" }, { status: 404 });
}
// ELIGIBILITY VALIDATION: Check if team can draft from this sport
const allPicks = await getDraftPicksWithSports(seasonId);
const teamPicks = await getTeamDraftPicksWithSports(currentDraftSlot.teamId, seasonId);
const allParticipants = await getParticipantsForSeasonWithSports(seasonId);
const seasonSports = await getSeasonSportsSimple(seasonId);
// Get all teams for the season
const allTeams = draftSlots.map((slot) => ({ id: slot.teamId }));
const eligibility = calculateDraftEligibility(
currentDraftSlot.teamId,
teamPicks,
allPicks,
allParticipants,
seasonSports,
season.draftRounds,
allTeams
);
const sportId = participant.sportsSeason.sport.id;
if (!eligibility.eligibleSportIds.has(sportId)) {
const reason = eligibility.ineligibleReasons[sportId]?.message || "Cannot draft from this sport";
return Response.json({ error: reason }, { status: 400 });
}
// Snapshot the team's time bank before the pick (used for audit / pick history).
// Use picksExpiresAt to compute actual remaining time rather than the stale timeRemaining.
const timerSnapshot = await db.query.draftTimers.findFirst({
where: and(
eq(schema.draftTimers.seasonId, seasonId),
eq(schema.draftTimers.teamId, currentDraftSlot.teamId)
),
});
const timeRemainingAtPick = (() => {
if (!timerSnapshot?.picksExpiresAt) return timerSnapshot?.timeRemaining ?? 0;
const msRemaining = timerSnapshot.picksExpiresAt.getTime() - pickMadeAt;
return msRemaining > 0 ? Math.ceil(msRemaining / 1000) : 0;
})();
// Create the draft pick
const [draftPick] = await db
.insert(schema.draftPicks)
.values({
seasonId,
teamId: currentDraftSlot.teamId,
participantId,
pickNumber: currentPickNumber,
round: currentRound,
pickInRound,
pickedByUserId: userId,
pickedByType: isTeamOwner ? "owner" : commissionerRecord ? "commissioner" : "admin",
timeUsed: timeRemainingAtPick,
})
.returning();
// Remove from ALL team queues in this season (participant is now drafted)
await db
.delete(schema.draftQueue)
.where(
and(
eq(schema.draftQueue.seasonId, seasonId),
eq(schema.draftQueue.participantId, participantId)
)
);
// Notify all clients that this participant was removed from queues
try {
getSocketIO().to(`draft-${seasonId}`).emit("participant-removed-from-queues", {
participantId,
});
} catch (error) {
logger.error("Socket.IO participant-removed-from-queues error:", error);
}
// Proactively prune queue items that are now ineligible due to this pick
// (e.g. a team queued a snooker player but just filled their last flex slot)
try {
const allTeamIds = draftSlots.map((slot) => slot.teamId);
const prunedQueues = await pruneIneligibleQueueItems({
seasonId,
draftRounds: season.draftRounds,
allTeamIds,
db,
});
for (const { teamId: prunedTeamId, removedParticipantIds } of prunedQueues) {
getSocketIO().to(`draft-${seasonId}`).emit("queue-eligibility-pruned", {
teamId: prunedTeamId,
removedParticipantIds,
});
}
} catch (error) {
logger.error("Queue pruning error after pick:", error);
}
// Calculate next pick info (before updating season)
const nextPickNumber = currentPickNumber + 1;
const totalPicks = totalTeams * season.draftRounds;
const isDraftComplete = nextPickNumber > totalPicks;
// Update the picking team's timer after their pick.
// Standard mode: always reset to the per-pick time.
// Chess clock: add the increment to the actual remaining time (computed from picksExpiresAt).
// Also clear picksExpiresAt so the timer system knows this team's turn is over.
const incrementTime = season.draftIncrementTime || 30;
const newTimeRemaining =
season.draftTimerMode === "standard"
? incrementTime
: timeRemainingAtPick + incrementTime;
const timerUpdateSet = {
timeRemaining: newTimeRemaining,
picksExpiresAt: null as Date | null,
picksStartedAt: null as Date | null,
updatedAt: new Date(),
};
const [updatedTimer] = await db
.update(schema.draftTimers)
.set(timerUpdateSet)
.where(
and(
eq(schema.draftTimers.seasonId, seasonId),
eq(schema.draftTimers.teamId, currentDraftSlot.teamId)
)
)
.returning();
if (!updatedTimer) {
await db.insert(schema.draftTimers).values({
seasonId,
teamId: currentDraftSlot.teamId,
timeRemaining: newTimeRemaining,
});
}
// Update season's current pick number (AFTER initializing next timer to prevent race condition)
await db
.update(schema.seasons)
.set({
currentPickNumber: isDraftComplete ? currentPickNumber : nextPickNumber,
status: isDraftComplete ? "active" : season.status,
draftCompletedAt: isDraftComplete ? new Date() : undefined,
})
.where(eq(schema.seasons.id, seasonId));
// Emit socket event
try {
getSocketIO().to(`draft-${seasonId}`).emit("pick-made", {
pick: {
...draftPick,
team: currentDraftSlot.team,
participant: {
...participant,
sport: participant.sportsSeason.sport,
},
sport: participant.sportsSeason.sport,
},
nextPickNumber: isDraftComplete ? currentPickNumber : nextPickNumber,
isDraftComplete,
});
// Emit timer bank update AFTER pick-made so handlePickMade stops the countdown
// interval first — otherwise the interval could tick 0 and overwrite the new bank.
getSocketIO().to(`draft-${seasonId}`).emit("timer-bank-updated", {
teamId: currentDraftSlot.teamId,
timeRemaining: newTimeRemaining,
});
if (isDraftComplete) {
getSocketIO().to(`draft-${seasonId}`).emit("draft-completed");
scheduleDraftRoomClosure(seasonId);
}
} catch (error) {
logger.error("Socket.IO error:", error);
}
// Announce before triggering the chain so Discord messages arrive in pick-number
// order. If the chain ran first, chained picks would announce before this one.
const nextSlot = !isDraftComplete ? getTeamForPick(nextPickNumber, draftSlots) : undefined;
enqueuePickNotification(season.leagueId, () =>
notifyPickMadeOnDiscord({
seasonId,
leagueId: season.leagueId,
pickedTeamName: currentDraftSlot.team.name,
participantName: participant.name,
sportName: participant.sportsSeason.sport.name,
pickNumber: currentPickNumber,
round: currentRound,
pickInRound: rawPickInRound,
isDraftComplete,
nextTeamName: nextSlot?.team.name,
nextTeamOwnerId: nextSlot?.team.ownerId,
db,
}).catch((err) => logger.error("Discord pick announcement failed:", err))
);
// Check if next team has autodraft enabled and trigger immediately
if (!isDraftComplete) {
// Fire-and-forget so it doesn't delay rescheduleTimer (and timer-pick-started) for the next team.
runBracktHarvilleForFantasySeason(seasonId, db)
.then((updates) => {
if (updates.length > 0) {
getSocketIO().to(`draft-${seasonId}`).emit("brackt-evs-updated", { updates });
}
})
.catch((error) => logger.error("Brackt EV update after pick failed:", error));
const freshSeason = await db.query.seasons.findFirst({ where: eq(schema.seasons.id, seasonId) });
if (!freshSeason?.draftPaused) {
await checkAndTriggerNextAutodraft({
seasonId,
nextPickNumber,
totalTeams,
draftSlots,
db,
});
}
// Fire-and-forget: sendOnTheClockEmail fetches the current pick number from
// the DB itself, so it always sees the post-chain state without blocking here.
sendOnTheClockEmail({ seasonId, totalTeams, draftSlots, db })
.catch((err) => logger.error("On-the-clock email failed:", err));
}
// Reschedule the timer for the next team on the clock (runs after the full autodraft chain).
try {
await rescheduleTimer(seasonId);
} catch (err) {
logger.error("[Pick] rescheduleTimer failed:", err);
}
return Response.json({
success: true,
pick: draftPick,
nextPickNumber: isDraftComplete ? currentPickNumber : nextPickNumber,
isDraftComplete,
});
}