2025-11-12 23:44:33 -08:00
|
|
|
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";
|
2026-03-07 21:59:29 -08:00
|
|
|
import {
|
|
|
|
|
getUpcomingScoringEvents,
|
|
|
|
|
getRecentCompletedEvents,
|
|
|
|
|
} from "~/models/scoring-event";
|
2025-11-12 23:44:33 -08:00
|
|
|
import { database } from "~/database/context";
|
|
|
|
|
import * as schema from "~/database/schema";
|
|
|
|
|
import { eq } 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
|
2026-02-20 11:35:35 -08:00
|
|
|
// Filter by leagueId since a sports season can be linked to multiple leagues
|
|
|
|
|
const seasonSport = sportsSeason.seasonSports?.find(
|
|
|
|
|
(ss) => ss.season.leagueId === leagueId
|
|
|
|
|
);
|
2025-11-12 23:44:33 -08:00
|
|
|
if (!seasonSport) {
|
|
|
|
|
throw new Response("This sports season is not linked to this league", {
|
|
|
|
|
status: 404,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-20 11:35:35 -08:00
|
|
|
const season = seasonSport.season;
|
2025-11-12 23:44:33 -08:00
|
|
|
|
|
|
|
|
// 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,
|
|
|
|
|
})
|
|
|
|
|
);
|
|
|
|
|
|
2026-03-07 21:59:29 -08:00
|
|
|
// 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);
|
|
|
|
|
|
2025-11-12 23:44:33 -08:00
|
|
|
// Fetch pattern-specific data based on scoring pattern
|
|
|
|
|
const scoringPattern = sportsSeason.scoringPattern;
|
|
|
|
|
|
2026-03-07 21:59:29 -08:00
|
|
|
type SeasonStanding = { id: string; position: number; championshipPoints: string; participant: { id: string; name: string } };
|
|
|
|
|
|
2025-11-12 23:44:33 -08:00
|
|
|
let playoffMatches: any[] = [];
|
|
|
|
|
let playoffRounds: string[] = [];
|
2026-03-07 21:59:29 -08:00
|
|
|
let seasonStandings: SeasonStanding[] = [];
|
2025-11-12 23:44:33 -08:00
|
|
|
let qpStandings: any[] = [];
|
|
|
|
|
|
2026-03-07 21:59:29 -08:00
|
|
|
if (scoringPattern === "playoff_bracket") {
|
2025-11-12 23:44:33 -08:00
|
|
|
// 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,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
playoffMatches = matches;
|
|
|
|
|
|
|
|
|
|
const roundSet = new Set(matches.map((m: any) => m.round));
|
|
|
|
|
playoffRounds = Array.from(roundSet);
|
|
|
|
|
}
|
|
|
|
|
} else if (scoringPattern === "season_standings") {
|
2026-03-07 21:59:29 -08:00
|
|
|
// Fetch F1-style championship standings and map to SeasonStanding shape
|
2025-11-12 23:44:33 -08:00
|
|
|
const results = await getSeasonResults(sportsSeasonId);
|
2026-03-07 21:59:29 -08:00
|
|
|
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,
|
|
|
|
|
},
|
|
|
|
|
}));
|
2025-11-12 23:44:33 -08:00
|
|
|
} else if (scoringPattern === "qualifying_points") {
|
|
|
|
|
// Fetch qualifying points standings
|
|
|
|
|
const standings = await getQPStandings(sportsSeasonId);
|
|
|
|
|
qpStandings = standings;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-07 21:59:29 -08:00
|
|
|
// 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";
|
|
|
|
|
|
2025-11-12 23:44:33 -08:00
|
|
|
return {
|
|
|
|
|
league,
|
|
|
|
|
season,
|
|
|
|
|
sportsSeason,
|
|
|
|
|
scoringPattern,
|
|
|
|
|
playoffMatches,
|
|
|
|
|
playoffRounds,
|
|
|
|
|
seasonStandings,
|
|
|
|
|
qpStandings,
|
|
|
|
|
teamOwnerships,
|
2026-03-07 21:59:29 -08:00
|
|
|
userParticipantIds,
|
|
|
|
|
upcomingEvents,
|
|
|
|
|
recentEvents,
|
|
|
|
|
seasonIsFinalized,
|
2025-11-12 23:44:33 -08:00
|
|
|
};
|
|
|
|
|
}
|