brackt/app/routes/leagues/$leagueId.sports-seasons.$sportsSeasonId.server.ts
Chris Parsons d88be08deb
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

237 lines
7.6 KiB
TypeScript

import { getAuth } from "@clerk/react-router/server";
import type { Route } from "./+types/$leagueId.sports-seasons.$sportsSeasonId";
import {
findLeagueById,
isUserLeagueMember,
isCommissioner,
findTeamsBySeasonId,
findUserByClerkId,
} from "~/models";
import { getDraftPicks } from "~/models/draft-pick";
import { getSeasonResults } from "~/models/participant-season-result";
import { getQPStandings } from "~/models/qualifying-points";
import {
getUpcomingScoringEvents,
getRecentCompletedEvents,
} from "~/models/scoring-event";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq, and } from "drizzle-orm";
export async function loader(args: Route.LoaderArgs) {
const { userId } = await getAuth(args);
const { params } = args;
const { leagueId, sportsSeasonId } = params;
// Check authentication
if (!userId) {
throw new Response("You must be logged in to view this page", {
status: 401,
});
}
// Fetch league
const league = await findLeagueById(leagueId);
if (!league) {
throw new Response("League not found", { status: 404 });
}
// Check access: user must be a commissioner or member
const isUserCommissioner = await isCommissioner(leagueId, userId);
const isUserMember = await isUserLeagueMember(leagueId, userId);
if (!isUserCommissioner && !isUserMember) {
throw new Response("You do not have access to this league", {
status: 403,
});
}
// Fetch sports season with relations
const db = database();
const sportsSeason = await db.query.sportsSeasons.findFirst({
where: eq(schema.sportsSeasons.id, sportsSeasonId),
with: {
sport: true,
seasonSports: {
with: {
season: true,
},
},
},
});
if (!sportsSeason) {
throw new Response("Sports season not found", { status: 404 });
}
// Get the fantasy season for this league (to get teams and draft picks)
// We need to find which season in this league includes this sports season
// Filter by leagueId since a sports season can be linked to multiple leagues
const seasonSport = sportsSeason.seasonSports?.find(
(ss) => ss.season.leagueId === leagueId
);
if (!seasonSport) {
throw new Response("This sports season is not linked to this league", {
status: 404,
});
}
const season = seasonSport.season;
// Fetch teams and draft picks to determine ownership
const teams = await findTeamsBySeasonId(season.id);
const draftPicks = await getDraftPicks(season.id);
// Build ownership map: participantId -> { teamName, teamId, ownerName }
const ownershipMap = new Map<
string,
{ teamName: string; teamId: string; ownerName?: string }
>();
// Get unique owner IDs for user lookups
const ownerIds = [...new Set(teams.map((t) => t.ownerId).filter(Boolean))];
const ownerUsers = await Promise.all(
ownerIds.map(async (ownerId) => {
const user = await findUserByClerkId(ownerId!);
return {
ownerId,
name: user?.username || user?.displayName || "Unknown",
};
})
);
const ownerMap = new Map(ownerUsers.map((o) => [o.ownerId, o.name]));
// Map draft picks to ownership
for (const pick of draftPicks) {
const team = teams.find((t) => t.id === pick.teamId);
if (team && pick.participantId) {
ownershipMap.set(pick.participantId, {
teamName: team.name,
teamId: team.id,
ownerName: team.ownerId ? ownerMap.get(team.ownerId) : undefined,
});
}
}
// Convert to array for serialization
const teamOwnerships = Array.from(ownershipMap.entries()).map(
([participantId, data]) => ({
participantId,
...data,
})
);
// Derive which participant IDs the current user has drafted
const userTeams = teams.filter((t) => t.ownerId === userId);
const userTeamIds = new Set(userTeams.map((t) => t.id));
const userParticipantIds = draftPicks
.filter((p) => p.teamId && userTeamIds.has(p.teamId) && p.participantId)
.map((p) => p.participantId as string);
// Fetch pattern-specific data based on scoring pattern
const scoringPattern = sportsSeason.scoringPattern;
type SeasonStanding = { id: string; position: number; championshipPoints: string; participant: { id: string; name: string } };
let playoffMatches: any[] = [];
let playoffRounds: string[] = [];
let preEliminatedParticipants: { id: string; name: string }[] = [];
let participantPoints: { participantId: string; points: number }[] = [];
let seasonStandings: SeasonStanding[] = [];
let qpStandings: any[] = [];
if (scoringPattern === "playoff_bracket") {
// Fetch playoff matches via scoring events
const events = await db.query.scoringEvents.findMany({
where: eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
});
if (events.length > 0) {
const eventIds = events.map((e) => e.id);
const matches = await db.query.playoffMatches.findMany({
where: (playoffMatches, { inArray }) =>
inArray(playoffMatches.scoringEventId, eventIds),
with: {
participant1: true,
participant2: true,
winner: true,
loser: true,
},
});
playoffMatches = matches;
const roundMatchCounts = new Map<string, number>();
for (const m of matches) {
roundMatchCounts.set(m.round, (roundMatchCounts.get(m.round) || 0) + 1);
}
playoffRounds = Array.from(roundMatchCounts.keys()).sort(
(a, b) => (roundMatchCounts.get(b) || 0) - (roundMatchCounts.get(a) || 0)
);
}
// Fetch group-stage losers and fantasy points in parallel
const [eliminatedResults, seasonResults] = await Promise.all([
db.query.participantResults.findMany({
where: and(
eq(schema.participantResults.sportsSeasonId, sportsSeasonId),
eq(schema.participantResults.finalPosition, 0)
),
with: { participant: true },
}),
getSeasonResults(sportsSeasonId),
]);
preEliminatedParticipants = eliminatedResults
.filter((r) => r.participant)
.map((r) => ({ id: (r as any).participant.id, name: (r as any).participant.name }));
participantPoints = seasonResults
.map((r) => ({ participantId: r.participantId, points: parseFloat(r.currentPoints || "0") }))
.filter((r) => r.points > 0);
} else if (scoringPattern === "season_standings") {
// Fetch F1-style championship standings and map to SeasonStanding shape
const results = await getSeasonResults(sportsSeasonId);
seasonStandings = results
.filter((r) => r.currentPosition !== null || (r.currentPoints && parseFloat(r.currentPoints) > 0))
.map((r) => ({
id: r.id,
position: r.currentPosition ?? 999,
championshipPoints: r.currentPoints ?? "0",
participant: {
id: r.participant.id,
name: r.participant.name,
},
}));
} else if (scoringPattern === "qualifying_points") {
// Fetch qualifying points standings
const standings = await getQPStandings(sportsSeasonId);
qpStandings = standings;
}
// Fetch event schedule for all patterns (upcoming + recent)
const [upcomingEvents, recentEvents] = await Promise.all([
getUpcomingScoringEvents(sportsSeasonId, 5),
getRecentCompletedEvents(sportsSeasonId, 3),
]);
// Derive seasonIsFinalized from status
const seasonIsFinalized = sportsSeason.status === "completed";
return {
league,
season,
sportsSeason,
scoringPattern,
playoffMatches,
playoffRounds,
preEliminatedParticipants,
participantPoints,
seasonStandings,
qpStandings,
teamOwnerships,
userParticipantIds,
upcomingEvents,
recentEvents,
seasonIsFinalized,
};
}