brackt/app/routes/leagues/$leagueId.standings.$seasonId.tsx
Chris Parsons e2b178221a
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

232 lines
8.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useLoaderData, Link } from "react-router";
import { getAuth } from "@clerk/react-router/server";
import { database } from "~/database/context";
import { eq, and } from "drizzle-orm";
import * as schema from "~/database/schema";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
import { StandingsTable } from "~/components/standings/StandingsTable";
import { getSevenDayStandingsChange, getSeasonPointProgression } from "~/models/standings";
import { isSeasonComplete, getSeasonCompletionPercentage } from "~/lib/season-helpers.server";
import { PointProgressionChart } from "~/components/standings/PointProgressionChart";
import { findUsersByClerkIds, getUserDisplayName } from "~/models/user";
import type { Route } from "./+types/$leagueId.standings.$seasonId";
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
return [{ title: `Standings — ${data?.league?.name ?? "League"} - Brackt` }];
}
export async function loader(args: Route.LoaderArgs) {
try {
const { userId } = await getAuth(args);
const { params } = args;
const { leagueId, seasonId } = params;
const db = database();
// Fetch league
const league = await db.query.leagues.findFirst({
where: eq(schema.leagues.id, leagueId),
});
if (!league) {
throw new Response("League not found", { status: 404 });
}
// Fetch season
const season = await db.query.seasons.findFirst({
where: eq(schema.seasons.id, seasonId),
});
if (!season || season.leagueId !== leagueId) {
throw new Response("Season not found", { status: 404 });
}
// Check access
if (!userId) {
throw new Response("You must be logged in to view standings", {
status: 401,
});
}
// Check if user is a commissioner
const isUserCommissioner = await db.query.commissioners.findFirst({
where: and(
eq(schema.commissioners.leagueId, leagueId),
eq(schema.commissioners.userId, userId)
),
});
// Check if user has a team in this season
const hasTeam = await db.query.teams.findFirst({
where: and(
eq(schema.teams.seasonId, seasonId),
eq(schema.teams.ownerId, userId)
),
});
if (!isUserCommissioner && !hasTeam) {
throw new Response("You do not have access to this league", {
status: 403,
});
}
// Fetch standings, teams (for owner lookup), and independent data in parallel
const [standingsWithComparison, teams, progressionData, seasonComplete, completionPercentage] =
await Promise.all([
getSevenDayStandingsChange(seasonId, db),
db.query.teams.findMany({
where: eq(schema.teams.seasonId, seasonId),
columns: { id: true, ownerId: true },
}),
getSeasonPointProgression(seasonId, db),
isSeasonComplete(seasonId, db),
getSeasonCompletionPercentage(seasonId, db),
]);
// Build teamId -> ownerName map
const ownerIds = [...new Set(teams.map((t) => t.ownerId).filter((id): id is string => id !== null))];
const userRows = await findUsersByClerkIds(ownerIds);
const userByClerkId = new Map(userRows.map((u) => [u.clerkId, u]));
const ownerNameByTeamId = new Map(
teams
.filter((t): t is typeof t & { ownerId: string } => t.ownerId !== null)
.map((t) => {
const user = userByClerkId.get(t.ownerId);
return [t.id, user ? getUserDisplayName(user) : null] as const;
})
);
// Map to format expected by component (use sevenDayRankChange instead of previousRank)
const formattedStandings = standingsWithComparison.map((standing) => ({
...standing,
rankChange: standing.sevenDayRankChange,
ownerName: ownerNameByTeamId.get(standing.teamId) ?? null,
}));
return {
league,
season,
standings: formattedStandings,
progressionData,
seasonComplete,
completionPercentage,
};
} catch (error) {
console.error("Error loading standings:", error);
console.error("Error details:", {
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
}
export default function LeagueStandings() {
const { league, season, standings, progressionData, seasonComplete, completionPercentage } = useLoaderData<typeof loader>();
return (
<div className="container mx-auto py-8 px-4">
{/* Header */}
<div className="mb-8">
<Button variant="ghost" className="mb-4" asChild>
<Link to={`/leagues/${league.id}`}>
Back to League
</Link>
</Button>
<div className="flex items-center justify-between">
<div>
<h1 className="text-4xl font-bold mb-2">{league.name}</h1>
<p className="text-muted-foreground text-lg">
{season.year} Season Standings
</p>
</div>
<div className="text-right">
{seasonComplete ? (
<div className="inline-flex items-center px-3 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100 text-sm font-medium">
Season Complete
</div>
) : (
<div className="text-sm text-muted-foreground">
{completionPercentage}% Complete
</div>
)}
</div>
</div>
</div>
{/* Point Progression Chart */}
{progressionData.chartData.length > 0 && (
<div className="mb-6">
<PointProgressionChart
chartData={progressionData.chartData}
teams={progressionData.teams}
/>
</div>
)}
{/* Standings Card */}
<Card>
<CardHeader>
<CardTitle>
{seasonComplete ? "Final Standings" : "Current Standings"}
</CardTitle>
</CardHeader>
<CardContent>
{standings.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<p className="text-lg">No standings data yet.</p>
<p className="text-sm mt-2">
Standings will appear once participants have results.
</p>
</div>
) : (
<StandingsTable
standings={standings}
leagueId={league.id}
seasonId={season.id}
showPlacementBreakdown={true}
/>
)}
</CardContent>
</Card>
{/* Info Card */}
<Card className="mt-6">
<CardContent className="pt-6">
<div className="text-sm text-muted-foreground space-y-2">
<p>
<strong>Projected Points:</strong> Shows actual points from finished
participants plus expected value (EV) from remaining participants based
on their probability distributions. The "+X.X EV" indicates how many
additional points are expected from unfinished participants.
</p>
<p>
<strong>Tiebreaker Rules:</strong> Teams are ranked by total
points. If tied, the team with more 1st place finishes ranks
higher. If still tied, 2nd place finishes are compared, then 3rd,
and so on through 8th place.
</p>
<p>
<strong>Movement Indicators:</strong> Arrows show rank changes
compared to 7 days ago. Green arrows () indicate improvement in rank,
red arrows () indicate decline.
</p>
<p>
<strong>Placement Breakdown:</strong> Shows how many times each
team's participants finished in each position (1st×2 means 2 first-place finishes).
</p>
{progressionData.chartData.length > 0 && (
<p>
<strong>Point Progression Chart:</strong> Visualizes how each team's
total points evolved over time based on {progressionData.chartData.length} day{progressionData.chartData.length !== 1 ? 's' : ''} of snapshot data.
{seasonComplete && " Use this to see how the final standings developed throughout the season."}
</p>
)}
</div>
</CardContent>
</Card>
</div>
);
}