brackt/app/routes/admin.data-sync.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

407 lines
14 KiB
TypeScript

import { useState } from "react";
import { useFetcher } from "react-router";
import type { Route } from "./+types/admin.data-sync";
import { findAllSports } from "~/models/sport";
import { findAllSportsSeasons } from "~/models/sports-season";
import { findAllSeasonTemplates } from "~/models/season-template";
import { countAllParticipants } from "~/models/participant";
import { countAllParticipantEVs } from "~/models/participant-expected-value";
import { Button } from "~/components/ui/button";
import { Label } from "~/components/ui/label";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card";
import { Download, Upload, AlertTriangle, Database } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
export function meta(): Route.MetaDescriptors {
return [{ title: "Data Sync - Brackt Admin" }];
}
export async function loader() {
const [sports, sportsSeasons, templates, participantCount, evCount] =
await Promise.all([
findAllSports(),
findAllSportsSeasons(),
findAllSeasonTemplates(),
countAllParticipants(),
countAllParticipantEVs(),
]);
return {
stats: {
sportsCount: sports.length,
sportsSeasonsCount: sportsSeasons.length,
templatesCount: templates.length,
participantCount,
evCount,
},
};
}
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "import") {
const mode = formData.get("mode") as "merge" | "replace";
const fileData = formData.get("fileData") as string;
if (!fileData) {
return { success: false, error: "No file data provided" };
}
try {
const { importSportsDataFromJSON } = await import(
"~/utils/sports-data-sync.server"
);
const result = await importSportsDataFromJSON(fileData, mode);
return {
success: true,
error: null,
message: `Import complete! Created: ${result.created}, Updated: ${result.updated}, Skipped: ${result.skipped}`,
};
} catch (error) {
console.error("Import error:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Import failed",
message: null,
};
}
}
return { success: false, error: "Invalid intent", message: null };
}
export default function DataSync({ loaderData }: Route.ComponentProps) {
const { stats } = loaderData;
const [importMode, setImportMode] = useState<"merge" | "replace">("merge");
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [isExporting, setIsExporting] = useState(false);
const fetcher = useFetcher<typeof action>();
const isImporting = fetcher.state !== "idle";
const handleExport = async () => {
setIsExporting(true);
try {
const response = await fetch("/api/admin/export-sports-data");
const data = await response.json();
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `sports-data-export-${new Date().toISOString().split("T")[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error("Export failed:", error);
alert("Export failed. Please try again.");
} finally {
setIsExporting(false);
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setSelectedFile(file);
}
};
const handleImport = (e: React.FormEvent) => {
e.preventDefault();
if (!selectedFile) {
alert("Please select a file first");
return;
}
const reader = new FileReader();
reader.addEventListener("load", (event) => {
const fileData = event.target?.result as string;
const formData = new FormData();
formData.append("intent", "import");
formData.append("mode", importMode);
formData.append("fileData", fileData);
fetcher.submit(formData, { method: "POST" });
});
reader.readAsText(selectedFile);
};
return (
<div className="p-8">
<div className="max-w-4xl">
<div className="mb-6">
<h1 className="text-3xl font-bold">Data Sync</h1>
<p className="text-muted-foreground mt-1">
Import and export sports data between environments
</p>
</div>
{fetcher.data?.success && (
<div className="bg-emerald-500/15 text-emerald-400 px-4 py-3 rounded-md text-sm mb-6">
{fetcher.data.message || "Operation completed successfully!"}
</div>
)}
{fetcher.data?.error && (
<div className="bg-destructive/15 text-destructive px-4 py-3 rounded-md text-sm mb-6">
{fetcher.data.error}
</div>
)}
<div className="grid gap-6 md:grid-cols-5 mb-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Sports</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.sportsCount}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Sports Seasons
</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.sportsSeasonsCount}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Participants
</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.participantCount}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">EV Records</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.evCount}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Templates</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.templatesCount}</div>
</CardContent>
</Card>
</div>
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Export Data</CardTitle>
<CardDescription>
Download all sports data as a JSON file
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">
This will export all sports, sports seasons, participants,
participant EV/futures data, participant results, and season
templates.
</p>
<Button
onClick={handleExport}
disabled={isExporting}
className="w-full"
>
<Download className="mr-2 h-4 w-4" />
{isExporting ? "Exporting..." : "Export Data"}
</Button>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Import Data</CardTitle>
<CardDescription>
Upload a JSON file to import sports data
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="file">Select File</Label>
<input
id="file"
type="file"
accept=".json"
onChange={handleFileChange}
className="block w-full text-sm text-muted-foreground
file:mr-4 file:py-2 file:px-4
file:rounded-md file:border-0
file:text-sm file:font-semibold
file:bg-primary file:text-primary-foreground
hover:file:bg-primary/90"
/>
</div>
<div className="space-y-2">
<Label>Import Mode</Label>
<div className="flex gap-2">
<Button
type="button"
variant={importMode === "merge" ? "default" : "outline"}
size="sm"
onClick={() => setImportMode("merge")}
>
Merge
</Button>
<Button
type="button"
variant={importMode === "replace" ? "default" : "outline"}
size="sm"
onClick={() => setImportMode("replace")}
>
Replace
</Button>
</div>
<p className="text-xs text-muted-foreground">
{importMode === "merge"
? "Updates existing records and adds new ones (safe)"
: "Deletes all existing data and recreates from file (destructive)"}
</p>
</div>
{importMode === "replace" ? (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
disabled={!selectedFile || isImporting}
variant="destructive"
className="w-full"
>
<Upload className="mr-2 h-4 w-4" />
{isImporting
? "Importing..."
: "Import Data (Replace)"}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Are you absolutely sure?
</AlertDialogTitle>
<AlertDialogDescription>
This will{" "}
<strong>delete all existing sports data</strong> and
replace it with the data from the file. This action
cannot be undone.
<br />
<br />
This includes:
<ul className="list-disc list-inside mt-2">
<li>All sports</li>
<li>All sports seasons</li>
<li>All participants</li>
<li>All participant EV/futures data</li>
<li>All participant results</li>
<li>All season templates</li>
</ul>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleImport}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Yes, Replace All Data
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
) : (
<Button
onClick={handleImport}
disabled={!selectedFile || isImporting}
className="w-full"
>
<Upload className="mr-2 h-4 w-4" />
{isImporting ? "Importing..." : "Import Data (Merge)"}
</Button>
)}
</CardContent>
</Card>
</div>
<Card className="mt-6 border-electric/30 bg-electric/10">
<CardHeader>
<CardTitle className="text-electric">How It Works</CardTitle>
</CardHeader>
<CardContent className="text-sm text-foreground/80 space-y-3">
<div>
<strong>Export:</strong> Downloads all sports data as a JSON file
that you can save, version control, or transfer to another
environment.
</div>
<div>
<strong>Import (Merge):</strong> Updates existing records and adds
new ones. Safe to use won&apos;t delete anything.
</div>
<div>
<strong>Import (Replace):</strong> Deletes all existing sports
data and recreates it from the file. Use this for a clean slate.
</div>
<div className="pt-2 border-t border-electric/30">
<strong>Typical workflow:</strong>
<ol className="list-decimal list-inside mt-1 space-y-1">
<li>Export data from development</li>
<li>Download the JSON file</li>
<li>Upload it to production</li>
<li>Import using merge mode</li>
</ol>
</div>
</CardContent>
</Card>
</div>
</div>
);
}