brackt/app/routes/leagues/$leagueId.server.ts

180 lines
5.9 KiB
TypeScript
Raw Normal View History

import { getAuth } from "@clerk/react-router/server";
import { addDays, subDays } from "date-fns";
import { toEventSortKey } from "~/lib/date-utils";
import {
findLeagueById,
findTeamsBySeasonId,
findCommissionersByLeagueId,
isUserLeagueMember,
isCommissioner,
Optimize user data fetching with batch queries and centralize display name logic (#176) * Fall back to displayName when username is null for Discord webhook Users who sign up via OAuth (Google, GitHub, etc.) without setting a Clerk username have a null `username` field but always have a `displayName` (computed from firstName+lastName or email). Previously, `usernameByClerkId` was filtered to only include users with a non-null username, causing those owners to appear without any identifier in Discord standings messages (e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)"). https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Extract getUserDisplayName helper and use consistently throughout Add a single getUserDisplayName(user) function to app/models/user.ts that encapsulates the username → displayName fallback logic. Replace 9 scattered inline expressions across the codebase (owner-map, scoring-calculator, league routes, settings, invite flow, draft API, Clerk webhook) with calls to the shared helper. No behaviour change — all existing logic preserved, just centralised. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in league loader and settings loader Add findUsersByClerkIds() batch function to the user model and replace two separate Promise.all+findUserByClerkId loops (one for owners, one for commissioners) with a single inArray query in both $leagueId.server.ts and $leagueId.settings.tsx. The merged query covers both owner and commissioner IDs in one round-trip. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in buildOwnerMap Replace the Promise.all+findUserByClerkId loop with a single findUsersByClerkIds batch query, consistent with the league loader and settings loader fixes. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
findUsersByClerkIds,
getUserDisplayName,
findDraftSlotsBySeasonId,
} from "~/models";
import { findCurrentSeasonWithSports } from "~/models/season";
2026-03-05 10:07:15 -08:00
import { getSeasonStandings } from "~/models/standings";
2026-03-12 10:12:38 -07:00
import { getUpcomingEventsForDraftedParticipants } from "~/models/scoring-event";
import { getDraftedParticipantsBySportsSeason } from "~/models/draft-pick";
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 { Route } from "./+types/$leagueId";
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
export async function loader(args: Route.LoaderArgs) {
const { userId } = await getAuth(args);
const { params } = args;
const { leagueId } = params;
// Fetch league
const league = await findLeagueById(leagueId);
if (!league) {
throw new Response("League not found", { status: 404 });
}
// Fetch current season with sports
const seasonWithSports = await findCurrentSeasonWithSports(leagueId);
const season = seasonWithSports || null;
// Fetch commissioners
const commissioners = await findCommissionersByLeagueId(leagueId);
// Check if current user is a commissioner
const isUserCommissioner = userId
? await isCommissioner(leagueId, userId)
: false;
// Check if user is a member (has a team in current season)
const isUserMember = userId
? await isUserLeagueMember(leagueId, userId)
: false;
// Check access: user must be a commissioner, a member, or an admin
// If not logged in or not authorized, throw 403
if (!userId) {
throw new Response("You must be logged in to view this league", {
status: 401,
});
}
if (!isUserCommissioner && !isUserMember) {
throw new Response("You do not have access to this league", {
status: 403,
});
}
// Fetch teams for current season
const teams = season ? await findTeamsBySeasonId(season.id) : [];
// Fetch draft slots if season is in pre_draft or draft status
const draftSlots =
season && (season.status === "pre_draft" || season.status === "draft")
? await findDraftSlotsBySeasonId(season.id)
: [];
2026-03-05 10:07:15 -08:00
// Fetch standings for active/completed seasons
const standings =
season && (season.status === "active" || season.status === "completed")
? await getSeasonStandings(season.id)
: [];
Optimize user data fetching with batch queries and centralize display name logic (#176) * Fall back to displayName when username is null for Discord webhook Users who sign up via OAuth (Google, GitHub, etc.) without setting a Clerk username have a null `username` field but always have a `displayName` (computed from firstName+lastName or email). Previously, `usernameByClerkId` was filtered to only include users with a non-null username, causing those owners to appear without any identifier in Discord standings messages (e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)"). https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Extract getUserDisplayName helper and use consistently throughout Add a single getUserDisplayName(user) function to app/models/user.ts that encapsulates the username → displayName fallback logic. Replace 9 scattered inline expressions across the codebase (owner-map, scoring-calculator, league routes, settings, invite flow, draft API, Clerk webhook) with calls to the shared helper. No behaviour change — all existing logic preserved, just centralised. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in league loader and settings loader Add findUsersByClerkIds() batch function to the user model and replace two separate Promise.all+findUserByClerkId loops (one for owners, one for commissioners) with a single inArray query in both $leagueId.server.ts and $leagueId.settings.tsx. The merged query covers both owner and commissioner IDs in one round-trip. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in buildOwnerMap Replace the Promise.all+findUserByClerkId loop with a single findUsersByClerkIds batch query, consistent with the league loader and settings loader fixes. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
// Batch-fetch all users needed for owner and commissioner maps in one query
const ownerIds = [...new Set(teams.map((t) => t.ownerId).filter((id): id is string => id !== null))];
const commissionerIds = commissioners.map((c) => c.userId);
const allUserIds = [...new Set([...ownerIds, ...commissionerIds])];
const userRows = await findUsersByClerkIds(allUserIds);
const userByClerkId = new Map(userRows.map((u) => [u.clerkId, u]));
const ownerMap = new Map(
Optimize user data fetching with batch queries and centralize display name logic (#176) * Fall back to displayName when username is null for Discord webhook Users who sign up via OAuth (Google, GitHub, etc.) without setting a Clerk username have a null `username` field but always have a `displayName` (computed from firstName+lastName or email). Previously, `usernameByClerkId` was filtered to only include users with a non-null username, causing those owners to appear without any identifier in Discord standings messages (e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)"). https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Extract getUserDisplayName helper and use consistently throughout Add a single getUserDisplayName(user) function to app/models/user.ts that encapsulates the username → displayName fallback logic. Replace 9 scattered inline expressions across the codebase (owner-map, scoring-calculator, league routes, settings, invite flow, draft API, Clerk webhook) with calls to the shared helper. No behaviour change — all existing logic preserved, just centralised. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in league loader and settings loader Add findUsersByClerkIds() batch function to the user model and replace two separate Promise.all+findUserByClerkId loops (one for owners, one for commissioners) with a single inArray query in both $leagueId.server.ts and $leagueId.settings.tsx. The merged query covers both owner and commissioner IDs in one round-trip. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in buildOwnerMap Replace the Promise.all+findUserByClerkId loop with a single findUsersByClerkIds batch query, consistent with the league loader and settings loader fixes. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
ownerIds
.map((id) => [id, userByClerkId.get(id)] as const)
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
.filter((entry): entry is [string, NonNullable<typeof entry[1]>] => entry[1] !== undefined)
Optimize user data fetching with batch queries and centralize display name logic (#176) * Fall back to displayName when username is null for Discord webhook Users who sign up via OAuth (Google, GitHub, etc.) without setting a Clerk username have a null `username` field but always have a `displayName` (computed from firstName+lastName or email). Previously, `usernameByClerkId` was filtered to only include users with a non-null username, causing those owners to appear without any identifier in Discord standings messages (e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)"). https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Extract getUserDisplayName helper and use consistently throughout Add a single getUserDisplayName(user) function to app/models/user.ts that encapsulates the username → displayName fallback logic. Replace 9 scattered inline expressions across the codebase (owner-map, scoring-calculator, league routes, settings, invite flow, draft API, Clerk webhook) with calls to the shared helper. No behaviour change — all existing logic preserved, just centralised. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in league loader and settings loader Add findUsersByClerkIds() batch function to the user model and replace two separate Promise.all+findUserByClerkId loops (one for owners, one for commissioners) with a single inArray query in both $leagueId.server.ts and $leagueId.settings.tsx. The merged query covers both owner and commissioner IDs in one round-trip. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in buildOwnerMap Replace the Promise.all+findUserByClerkId loop with a single findUsersByClerkIds batch query, consistent with the league loader and settings loader fixes. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
.map(([id, user]) => [id, getUserDisplayName(user)])
);
const commissionerMap = new Map(
Optimize user data fetching with batch queries and centralize display name logic (#176) * Fall back to displayName when username is null for Discord webhook Users who sign up via OAuth (Google, GitHub, etc.) without setting a Clerk username have a null `username` field but always have a `displayName` (computed from firstName+lastName or email). Previously, `usernameByClerkId` was filtered to only include users with a non-null username, causing those owners to appear without any identifier in Discord standings messages (e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)"). https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Extract getUserDisplayName helper and use consistently throughout Add a single getUserDisplayName(user) function to app/models/user.ts that encapsulates the username → displayName fallback logic. Replace 9 scattered inline expressions across the codebase (owner-map, scoring-calculator, league routes, settings, invite flow, draft API, Clerk webhook) with calls to the shared helper. No behaviour change — all existing logic preserved, just centralised. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in league loader and settings loader Add findUsersByClerkIds() batch function to the user model and replace two separate Promise.all+findUserByClerkId loops (one for owners, one for commissioners) with a single inArray query in both $leagueId.server.ts and $leagueId.settings.tsx. The merged query covers both owner and commissioner IDs in one round-trip. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in buildOwnerMap Replace the Promise.all+findUserByClerkId loop with a single findUsersByClerkIds batch query, consistent with the league loader and settings loader fixes. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
commissionerIds
.map((id) => [id, userByClerkId.get(id)] as const)
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
.filter((entry): entry is [string, NonNullable<typeof entry[1]>] => entry[1] !== undefined)
Optimize user data fetching with batch queries and centralize display name logic (#176) * Fall back to displayName when username is null for Discord webhook Users who sign up via OAuth (Google, GitHub, etc.) without setting a Clerk username have a null `username` field but always have a `displayName` (computed from firstName+lastName or email). Previously, `usernameByClerkId` was filtered to only include users with a non-null username, causing those owners to appear without any identifier in Discord standings messages (e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)"). https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Extract getUserDisplayName helper and use consistently throughout Add a single getUserDisplayName(user) function to app/models/user.ts that encapsulates the username → displayName fallback logic. Replace 9 scattered inline expressions across the codebase (owner-map, scoring-calculator, league routes, settings, invite flow, draft API, Clerk webhook) with calls to the shared helper. No behaviour change — all existing logic preserved, just centralised. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in league loader and settings loader Add findUsersByClerkIds() batch function to the user model and replace two separate Promise.all+findUserByClerkId loops (one for owners, one for commissioners) with a single inArray query in both $leagueId.server.ts and $leagueId.settings.tsx. The merged query covers both owner and commissioner IDs in one round-trip. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH * Fix N+1 user queries in buildOwnerMap Replace the Promise.all+findUserByClerkId loop with a single findUsersByClerkIds batch query, consistent with the league loader and settings loader fixes. https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00
.map(([id, user]) => [id, getUserDisplayName(user)])
);
// Count available teams
const availableTeamCount = teams.filter((t) => !t.ownerId).length;
// Count teams with owners
const teamsWithOwners = teams.filter((t) => t.ownerId !== null).length;
2026-03-12 10:12:38 -07:00
// Get sports seasons data with upcoming participant events for the current user
const rawSportsSeasons = seasonWithSports?.seasonSports?.map((ss) => ss.sportsSeason) || [];
2026-03-12 10:12:38 -07:00
const myTeam = teams.find((t) => t.ownerId === userId) ?? null;
const today = new Date();
const dateFromStr = subDays(today, 1).toISOString().split("T")[0];
const dateToStr = addDays(today, 30).toISOString().split("T")[0];
2026-03-12 10:12:38 -07:00
Fix oxlint warnings: no-shadow, consistent-function-scoping, no-non-null-assertion, and others (#196) * Fix no-shadow and consistent-function-scoping lint violations Resolves all 11 no-shadow and 16 consistent-function-scoping oxlint warnings and promotes both rules to errors in .oxlintrc.json. no-shadow: renamed Drizzle callback params (sports→s, matches→m, seasons→s) to avoid shadowing outer imports; removed shadowed destructures (eq, inArray) from where callbacks; renamed inner template→bracketTemplate, prev→currentTimers, season→ss, name→teamName (with name: teamName fix to preserve semantics). consistent-function-scoping: moved formatDate, getRankBadge, getMovementIndicator, getPositionBadge, getStatusBadge, toDateStr, elo (×2), weightedPick, sortByMatchNumber (×2) to module scope; moved formatTime (×2), isValidLeagueName, getDraftTimes, makeSeasonQueues to file scope in test files. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-non-null-assertion lint violations and promote to error Eliminates all 208 no-non-null-assertion warnings across 38 files. Promotes typescript/no-non-null-assertion from warn to error in .oxlintrc.json. Fix patterns applied: - Map.get(key)! after .has() check → extract with get() + null guard - Map.get(key)! on pre-populated count maps → ?? 0 default - .set(id, map.get(id)! + 1) increment → ?? 0 before adding - participant1Id!/participant2Id! on DB matches → ?? "" fallback - array.find()! in tests → guard + throw or expect().toBeDefined() - bracketTemplateCache.get(id)! → null guard extract - Various nullable field accesses → optional chain or ?? default Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix prefer-add-event-listener, no-unassigned-import, require-module-specifiers Resolves all 9 remaining non-console lint warnings and promotes all three rules to errors in .oxlintrc.json. - prefer-add-event-listener: converted onchange/onclick/onload assignments to addEventListener in useDraftNotifications.ts and admin.data-sync.tsx; stored changeHandler ref for proper cleanup with removeEventListener - no-unassigned-import: configured rule with allow list for legitimate side-effect imports (*.css, @testing-library/jest-dom, @testing-library/cypress/add-commands) - require-module-specifiers: removed redundant `export {}` from cypress/support/e2e.ts (file already has an import) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix TypeScript errors from no-non-null-assertion fixes Two fixes introduced by the non-null assertion cleanup produced type errors: - scoring-event.ts: `?? ""` was wrong type for a participant object map; restructured to explicit null guards so TypeScript can narrow correctly - standings-sync/index.ts: `?? null` after name-match lookup lost the truthy guarantee, causing TS18047 on the write-back block; added `participant &&` guard before accessing its properties Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Add npm run typecheck as Stop hook in Claude settings Runs a full project typecheck at the end of each Claude turn so type errors surface as feedback before the next message. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 10:59:51 -07:00
const participantsBySportsSeason = myTeam && season
? await getDraftedParticipantsBySportsSeason(myTeam.id, season.id)
2026-03-12 10:12:38 -07:00
: new Map<string, Array<{ id: string; name: string }>>();
const sportsSeasons = await Promise.all(
rawSportsSeasons.map(async (ss) => {
2026-03-12 10:12:38 -07:00
const draftedParticipants = participantsBySportsSeason.get(ss.id) ?? [];
const upcomingParticipantEvents =
draftedParticipants.length > 0
? await getUpcomingEventsForDraftedParticipants(
ss.id,
ss.scoringPattern ?? "",
draftedParticipants,
dateFromStr,
dateToStr
2026-03-12 10:12:38 -07:00
)
: [];
return {
id: ss.id,
name: ss.name,
status: ss.status as "upcoming" | "active" | "completed",
scoringPattern: ss.scoringPattern,
sport: ss.sport,
2026-03-12 10:12:38 -07:00
upcomingParticipantEvents,
};
})
);
const sportsCount = sportsSeasons.length;
2026-03-12 10:12:38 -07:00
// Flatten all events into a panel-ready list, sorted by date
const upcomingCalendarEvents = sportsSeasons
.flatMap((ss) =>
ss.upcomingParticipantEvents.map((e) => ({
...e,
sportName: ss.sport.name,
sportSeasonName: ss.name,
sportsSeasonPageUrl: `/leagues/${leagueId}/sports-seasons/${ss.id}`,
}))
)
Add oxlint linting setup with zero errors (#194) * Add oxlint and fix all lint errors - Install oxlint, add .oxlintrc.json with rules for TypeScript/React - Add npm run lint / lint:fix scripts - Add Claude PostToolUse hook to run oxlint on every edited file - Fix 101 errors: unused vars/imports, eqeqeq, prefer-const, no-new-array - Fix no-array-index-key (use stable keys or suppress positional cases) - Fix exhaustive-deps missing dependency in useEffect - Promote exhaustive-deps and no-array-index-key to errors - Fix Map.get() !== null bug in $leagueId.server.ts (should be !== undefined) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix no-explicit-any warnings and upgrade tsconfig to ES2023 - Replace all `any` types with proper types or `unknown` across ~20 files - Add typed socket payload interfaces in draft route and useDraftSocket - Use any[] with eslint-disable for socket.io callbacks (legitimate escape hatch) - Bump all tsconfigs from ES2022 → ES2023 to support toSorted/toReversed - Fix cascading type errors uncovered by removing any: Map.get narrowing, participant relation types, ChartDataPoint, Partial<NewSeason> indexing - Add ParticipantResultWithParticipant type to participant-result model - Fix test fixtures to match updated interfaces (DraftCell, ParticipantResult) - Fix duplicate getQPStandings import in sportsSeasonId.server.ts Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Promote no-explicit-any to error Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 09:44:05 -07:00
.toSorted((a, b) => toEventSortKey(a).localeCompare(toEventSortKey(b)));
2026-03-12 10:12:38 -07:00
// Check if draft order is set
const isDraftOrderSet = draftSlots.length > 0;
// Extract origin for client use (avoids SSR/client mismatch on invite URLs)
const origin = new URL(args.request.url).origin;
return {
league,
season,
teams,
commissioners,
currentUserId: userId,
isUserCommissioner,
ownerMap: Object.fromEntries(ownerMap),
commissionerMap: Object.fromEntries(commissionerMap),
availableTeamCount,
sportsCount,
teamsWithOwners,
isDraftOrderSet,
User/chris/bracket UI redesign (#95) * feat: redesign playoff bracket UI with compact layout and owner display - Replace per-match Card wrappers with compact left-vs-right rows (stacks on mobile) - Add TeamOwnerBadge component (colored avatar + team name + username), matching the standings "Drafted By" style - Show owner info below each participant name in bracket matches - Add TBD forward-reference labels ("Winner of Quarterfinals M1") computed via buildFeederMap - Add Final Rankings table below bracket showing all participants ranked by elimination round - Fix round ordering in loader: sort by match count descending (more matches = earlier round) - Add loser relation to playoff matches query for elimination tracking - Extract getAvatarColor to app/lib/color-hash.ts (shared across GroupStageDisplay, SeasonStandings, TeamOwnerBadge) - Extract groupMatchesByRound helper; share grouped map between feeder computation and render - Remove dead getTeamAvatar from SeasonStandings after TeamOwnerBadge adoption - Add tests for groupMatchesByRound and buildFeederMap (7 tests) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: add draft order card to league home page Show draft order on the league home page when order is set and season is in pre_draft or draft status. Includes team name, owner name, and a link to the draft room. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: enhance playoff bracket with eliminated teams, points, and ownership highlights - Show eliminated teams (including group-stage losers) in Final Rankings card - Display computed fantasy points per participant in rankings table - Card title switches between "Eliminated Teams" and "Final Rankings" based on bracket completion - Highlight owned participants with electric blue name, dot indicator, and card border in bracket matches - Highlight owned rows with electric border/background in rankings table - Suppress EventSchedule for playoff_bracket sports seasons - Fix title redundancy: bracket section title no longer repeats sport name - Two-column match grid on desktop (md:grid-cols-2) - Code review fixes: parallel DB fetches, targeted query for pre-eliminated, single-pass parseFloat, remove IIFE Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 22:44:33 -07:00
draftSlots,
sportsSeasons,
2026-03-05 10:07:15 -08:00
standings,
origin,
2026-03-12 10:12:38 -07:00
upcomingCalendarEvents,
};
}