brackt/app/routes/admin.standings-snapshots.tsx
Chris Parsons 4bffa40606
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

312 lines
10 KiB
TypeScript

import { Form } from "react-router";
import type { Route } from "./+types/admin.standings-snapshots";
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,
},
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) {
console.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
? "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 ? (
<CheckCircle2 className="h-5 w-5 text-emerald-400" />
) : (
<AlertCircle className="h-5 w-5 text-destructive" />
)}
<p
className={
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"
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>
);
}