brackt/app/routes/admin.standings-snapshots.tsx

314 lines
10 KiB
TypeScript
Raw Normal View History

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
import { Form } from "react-router";
import type { Route } from "./+types/admin.standings-snapshots";
import { logger } from "~/lib/logger";
import { database } from "~/database/context";
import { eq, or } from "drizzle-orm";
import * as schema from "~/database/schema";
import { createDailySnapshot } from "~/models/standings";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card";
import { Button } from "~/components/ui/button";
import { Badge } from "~/components/ui/badge";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";
import { Calendar, RefreshCw, CheckCircle2, AlertCircle } from "lucide-react";
export function meta(): Route.MetaDescriptors {
return [{ title: "Standings Snapshots - Brackt Admin" }];
}
export async function loader() {
const db = database();
// Get all active and draft seasons
const seasons = await db.query.seasons.findMany({
where: or(
eq(schema.seasons.status, "active"),
eq(schema.seasons.status, "draft")
),
with: {
league: true,
},
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
orderBy: (s, { desc }) => [desc(s.createdAt)],
});
// For each season, get the most recent snapshot
const seasonsWithSnapshots = await Promise.all(
seasons.map(async (season) => {
const mostRecentSnapshot = await db.query.teamStandingsSnapshots.findFirst({
where: eq(schema.teamStandingsSnapshots.seasonId, season.id),
orderBy: (snapshots, { desc }) => [desc(snapshots.snapshotDate)],
});
return {
...season,
lastSnapshotDate: mostRecentSnapshot?.snapshotDate || null,
lastSnapshotTime: mostRecentSnapshot?.createdAt || null,
};
})
);
return {
seasons: seasonsWithSnapshots,
};
}
export async function action({ request }: Route.ActionArgs) {
const db = database();
const formData = await request.formData();
const intent = formData.get("intent");
const seasonId = formData.get("seasonId") as string;
try {
if (intent === "create-snapshot") {
if (seasonId === "all") {
// Create snapshots for all active seasons
const seasons = await db.query.seasons.findMany({
where: or(
eq(schema.seasons.status, "active"),
eq(schema.seasons.status, "draft")
),
});
for (const season of seasons) {
await createDailySnapshot(season.id, db);
}
return {
success: true,
message: `Created snapshots for ${seasons.length} season(s)`,
};
} else {
// Create snapshot for specific season
await createDailySnapshot(seasonId, db);
return {
success: true,
message: "Snapshot created successfully",
};
}
}
return {
success: false,
message: "Invalid intent",
};
} catch (error) {
logger.error("Error creating snapshot:", error);
return {
success: false,
message: error instanceof Error ? error.message : "Unknown error",
};
}
}
export default function AdminStandingsSnapshots({
loaderData,
actionData,
}: Route.ComponentProps) {
const { seasons } = loaderData;
const today = new Date().toISOString().split("T")[0];
return (
<div className="p-8">
{/* Header */}
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2">Standings Snapshots</h1>
<p className="text-muted-foreground">
Manage daily standings snapshots for historical tracking and 7-day
comparison
</p>
</div>
{/* Action Result */}
{actionData && (
<Card
className={`mb-6 ${
actionData.success
Redesign to dark-mode-only with navy palette and accent colors (#13) Removes light mode entirely in favour of a permanent dark theme with a navy-tinted background and three signature accents (electric blue, amber/gold, coral) exposed as CSS custom properties and Tailwind utilities (bg-electric, text-amber-accent, text-coral-accent). - Set class="dark" on <html> and apply Clerk dark base theme - Rewrite app.css: single :root palette (oklch navy values), custom --electric / --amber-accent / --coral-accent variables, remove duplicate .dark block and light-mode bg-white/bg-gray-950 rule - Install @clerk/themes for Clerk dark modal support - Replace hardcoded Tailwind colors across 30+ files: - Draft grid cells: blue-50/blue-950 → electric/15, green-50/950 → emerald/10 - Timer: green-600/yellow-600/red-600 → emerald-400/amber-accent/coral-accent - Status badges: blue-50/green-50/gray-50 → electric/emerald/muted variants - Success messages: green-500/15 text-green-700 dark:text-green-400 → emerald-500/15 text-emerald-400 - Info cards: blue-50 dark:bg-blue-950 → electric/10 - Warning cards: yellow-500 → amber-accent variants - Medal/placement badges: yellow-500/orange-600 → amber-accent/coral-accent - Movement indicators: green-600/red-600 → emerald-400/coral-accent - Connection dots: green-500/red-500 → emerald-500/coral-accent - Remove dark:hidden/dark:block logo toggle in welcome.tsx (always dark) - Update DraftGrid test assertions to match new class names Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 19:26:11 -08:00
? "border-emerald-500/30 bg-emerald-500/10"
: "border-destructive/30 bg-destructive/10"
}`}
>
<CardContent className="flex items-center gap-3 pt-6">
{actionData.success ? (
Redesign to dark-mode-only with navy palette and accent colors (#13) Removes light mode entirely in favour of a permanent dark theme with a navy-tinted background and three signature accents (electric blue, amber/gold, coral) exposed as CSS custom properties and Tailwind utilities (bg-electric, text-amber-accent, text-coral-accent). - Set class="dark" on <html> and apply Clerk dark base theme - Rewrite app.css: single :root palette (oklch navy values), custom --electric / --amber-accent / --coral-accent variables, remove duplicate .dark block and light-mode bg-white/bg-gray-950 rule - Install @clerk/themes for Clerk dark modal support - Replace hardcoded Tailwind colors across 30+ files: - Draft grid cells: blue-50/blue-950 → electric/15, green-50/950 → emerald/10 - Timer: green-600/yellow-600/red-600 → emerald-400/amber-accent/coral-accent - Status badges: blue-50/green-50/gray-50 → electric/emerald/muted variants - Success messages: green-500/15 text-green-700 dark:text-green-400 → emerald-500/15 text-emerald-400 - Info cards: blue-50 dark:bg-blue-950 → electric/10 - Warning cards: yellow-500 → amber-accent variants - Medal/placement badges: yellow-500/orange-600 → amber-accent/coral-accent - Movement indicators: green-600/red-600 → emerald-400/coral-accent - Connection dots: green-500/red-500 → emerald-500/coral-accent - Remove dark:hidden/dark:block logo toggle in welcome.tsx (always dark) - Update DraftGrid test assertions to match new class names Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 19:26:11 -08:00
<CheckCircle2 className="h-5 w-5 text-emerald-400" />
) : (
Redesign to dark-mode-only with navy palette and accent colors (#13) Removes light mode entirely in favour of a permanent dark theme with a navy-tinted background and three signature accents (electric blue, amber/gold, coral) exposed as CSS custom properties and Tailwind utilities (bg-electric, text-amber-accent, text-coral-accent). - Set class="dark" on <html> and apply Clerk dark base theme - Rewrite app.css: single :root palette (oklch navy values), custom --electric / --amber-accent / --coral-accent variables, remove duplicate .dark block and light-mode bg-white/bg-gray-950 rule - Install @clerk/themes for Clerk dark modal support - Replace hardcoded Tailwind colors across 30+ files: - Draft grid cells: blue-50/blue-950 → electric/15, green-50/950 → emerald/10 - Timer: green-600/yellow-600/red-600 → emerald-400/amber-accent/coral-accent - Status badges: blue-50/green-50/gray-50 → electric/emerald/muted variants - Success messages: green-500/15 text-green-700 dark:text-green-400 → emerald-500/15 text-emerald-400 - Info cards: blue-50 dark:bg-blue-950 → electric/10 - Warning cards: yellow-500 → amber-accent variants - Medal/placement badges: yellow-500/orange-600 → amber-accent/coral-accent - Movement indicators: green-600/red-600 → emerald-400/coral-accent - Connection dots: green-500/red-500 → emerald-500/coral-accent - Remove dark:hidden/dark:block logo toggle in welcome.tsx (always dark) - Update DraftGrid test assertions to match new class names Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 19:26:11 -08:00
<AlertCircle className="h-5 w-5 text-destructive" />
)}
<p
className={
Redesign to dark-mode-only with navy palette and accent colors (#13) Removes light mode entirely in favour of a permanent dark theme with a navy-tinted background and three signature accents (electric blue, amber/gold, coral) exposed as CSS custom properties and Tailwind utilities (bg-electric, text-amber-accent, text-coral-accent). - Set class="dark" on <html> and apply Clerk dark base theme - Rewrite app.css: single :root palette (oklch navy values), custom --electric / --amber-accent / --coral-accent variables, remove duplicate .dark block and light-mode bg-white/bg-gray-950 rule - Install @clerk/themes for Clerk dark modal support - Replace hardcoded Tailwind colors across 30+ files: - Draft grid cells: blue-50/blue-950 → electric/15, green-50/950 → emerald/10 - Timer: green-600/yellow-600/red-600 → emerald-400/amber-accent/coral-accent - Status badges: blue-50/green-50/gray-50 → electric/emerald/muted variants - Success messages: green-500/15 text-green-700 dark:text-green-400 → emerald-500/15 text-emerald-400 - Info cards: blue-50 dark:bg-blue-950 → electric/10 - Warning cards: yellow-500 → amber-accent variants - Medal/placement badges: yellow-500/orange-600 → amber-accent/coral-accent - Movement indicators: green-600/red-600 → emerald-400/coral-accent - Connection dots: green-500/red-500 → emerald-500/coral-accent - Remove dark:hidden/dark:block logo toggle in welcome.tsx (always dark) - Update DraftGrid test assertions to match new class names Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 19:26:11 -08:00
actionData.success ? "text-emerald-400" : "text-destructive"
}
>
{actionData.message}
</p>
</CardContent>
</Card>
)}
{/* Info Card */}
<Card className="mb-6">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Calendar className="h-5 w-5" />
Snapshot System
</CardTitle>
<CardDescription>
Snapshots are automatically created daily for all active seasons.
Use the buttons below to manually trigger snapshot creation if
needed.
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3 text-sm">
<p>
<strong>Automatic Snapshots:</strong> The system creates snapshots
once per day for all active seasons that don't already have a snapshot for today.
</p>
<p>
<strong>Manual Snapshots:</strong> Use the "Create Snapshot"
buttons below to manually trigger snapshot creation for specific
seasons or all active seasons.
</p>
<p>
<strong>7-Day Comparison:</strong> Standings pages show movement
indicators comparing current rank to the snapshot from 7 days ago.
</p>
</div>
</CardContent>
</Card>
{/* Bulk Actions */}
<Card className="mb-6">
<CardHeader>
<CardTitle>Bulk Actions</CardTitle>
<CardDescription>
Create snapshots for all active seasons at once
</CardDescription>
</CardHeader>
<CardContent>
<Form method="post">
<input type="hidden" name="intent" value="create-snapshot" />
<input type="hidden" name="seasonId" value="all" />
<Button type="submit" className="w-full sm:w-auto">
<RefreshCw className="h-4 w-4 mr-2" />
Create Snapshots for All Active Seasons
</Button>
</Form>
</CardContent>
</Card>
{/* Seasons Table */}
<Card>
<CardHeader>
<CardTitle>Active Seasons</CardTitle>
<CardDescription>
{seasons.length} season(s) eligible for snapshots
</CardDescription>
</CardHeader>
<CardContent>
{seasons.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<p>No active or draft seasons found</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>League</TableHead>
<TableHead>Season</TableHead>
<TableHead>Status</TableHead>
<TableHead>Last Snapshot</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{seasons.map((season) => {
const hasSnapshotToday =
season.lastSnapshotDate === today;
return (
<TableRow key={season.id}>
<TableCell className="font-medium">
{season.league.name}
</TableCell>
<TableCell>{season.year}</TableCell>
<TableCell>
<Badge
variant={
season.status === "active"
? "default"
: "secondary"
}
>
{season.status}
</Badge>
</TableCell>
<TableCell>
{season.lastSnapshotDate ? (
<div className="flex items-center gap-2">
<span className="text-sm">
{season.lastSnapshotDate}
</span>
{hasSnapshotToday && (
<Badge
variant="outline"
Redesign to dark-mode-only with navy palette and accent colors (#13) Removes light mode entirely in favour of a permanent dark theme with a navy-tinted background and three signature accents (electric blue, amber/gold, coral) exposed as CSS custom properties and Tailwind utilities (bg-electric, text-amber-accent, text-coral-accent). - Set class="dark" on <html> and apply Clerk dark base theme - Rewrite app.css: single :root palette (oklch navy values), custom --electric / --amber-accent / --coral-accent variables, remove duplicate .dark block and light-mode bg-white/bg-gray-950 rule - Install @clerk/themes for Clerk dark modal support - Replace hardcoded Tailwind colors across 30+ files: - Draft grid cells: blue-50/blue-950 → electric/15, green-50/950 → emerald/10 - Timer: green-600/yellow-600/red-600 → emerald-400/amber-accent/coral-accent - Status badges: blue-50/green-50/gray-50 → electric/emerald/muted variants - Success messages: green-500/15 text-green-700 dark:text-green-400 → emerald-500/15 text-emerald-400 - Info cards: blue-50 dark:bg-blue-950 → electric/10 - Warning cards: yellow-500 → amber-accent variants - Medal/placement badges: yellow-500/orange-600 → amber-accent/coral-accent - Movement indicators: green-600/red-600 → emerald-400/coral-accent - Connection dots: green-500/red-500 → emerald-500/coral-accent - Remove dark:hidden/dark:block logo toggle in welcome.tsx (always dark) - Update DraftGrid test assertions to match new class names Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 19:26:11 -08:00
className="text-xs bg-emerald-500/15 text-emerald-400 border-emerald-500/30"
>
Today
</Badge>
)}
</div>
) : (
<span className="text-muted-foreground text-sm">
No snapshots yet
</span>
)}
</TableCell>
<TableCell className="text-right">
<Form method="post" className="inline">
<input
type="hidden"
name="intent"
value="create-snapshot"
/>
<input
type="hidden"
name="seasonId"
value={season.id}
/>
<Button
type="submit"
variant="outline"
size="sm"
disabled={hasSnapshotToday}
>
<RefreshCw className="h-3 w-3 mr-1" />
{hasSnapshotToday
? "Already Created"
: "Create Snapshot"}
</Button>
</Form>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}