Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions scripts/reset-scored.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* Script to reset scored status to null for a specific date (undo a bad backfill run)
* Usage: npx tsx scripts/reset-scored.ts --date=2026-09-30 --env=dev --confirm
*
* This will set scored=null for all players on that date, so the next backfill
* (GET /unscored-dates -> distinct("date", {scored: null})) picks it up again.
*/

import { CONFIG } from "./config.js";

export {};

interface Args {
date: string;
env: "dev" | "prod" | "local";
token?: string;
confirm?: boolean;
}

function parseArgs(): Args {
// Filter to only include arguments starting with --
const args = process.argv.slice(2).filter(arg => arg.startsWith("--"));
const parsed: Partial<Args> = {
env: (process.env.API_ENV as "dev" | "prod" | "local") || "local",
date: process.env.DATE || new Date().toISOString().split("T")[0],
confirm: false,
};

args.forEach((arg) => {
if (arg.startsWith("--date=")) {
parsed.date = arg.split("=")[1];
} else if (arg.startsWith("--env=")) {
parsed.env = arg.split("=")[1] as "dev" | "prod" | "local";
} else if (arg.startsWith("--token=")) {
parsed.token = arg.split("=")[1];
} else if (arg === "--confirm" || arg === "--yes" || arg === "-y") {
parsed.confirm = true;
}
});

// Also support environment variables
if (process.env.AUTH_TOKEN && !parsed.token) {
parsed.token = process.env.AUTH_TOKEN;
}

return parsed as Args;
}

async function resetScored(
date: string,
env: string,
token?: string,
confirm?: boolean
) {
if (!date) {
console.error("\n❌ Error: --date parameter is required\n");
console.log("Usage: npx tsx scripts/reset-scored.ts --date=YYYY-MM-DD --env=dev --confirm\n");
return;
}

const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(date)) {
console.error("\n❌ Error: Invalid date format. Expected YYYY-MM-DD\n");
return;
}

const baseUrl = CONFIG.urls[env as keyof typeof CONFIG.urls] || CONFIG.urls.local;
const url = `${baseUrl}/reset-scored`;

console.log(`\n⚠️ WARNING: This will reset scored to null for ALL players on:`);
console.log(` Date: ${date}`);
console.log(`📡 URL: ${url}`);
console.log(`🌍 Environment: ${env}\n`);

// Safety check - require confirmation flag (destructive, like delete-game.ts)
if (!confirm) {
console.log("❌ Operation cancelled!");
console.log("To confirm resetting scored status, add the --confirm flag:");
console.log(` npx tsx scripts/reset-scored.ts --date=${date} --env=${env} --confirm\n`);
return;
}

const headers: HeadersInit = {
"Content-Type": "application/json",
};

if (token) {
headers["Authorization"] = `Bearer ${token}`;
} else if (process.env.API_AUTH_TOKEN) {
headers["Authorization"] = `Bearer ${process.env.API_AUTH_TOKEN}`;
} else if (CONFIG.authToken) {
headers["Authorization"] = `Bearer ${CONFIG.authToken}`;
}

console.log("🔄 Resetting scored status...\n");

try {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify({
date: date,
}),
});

console.log(`Status: ${response.status} ${response.statusText}`);

// Get response body as text first, then parse
const responseText = await response.text();

if (response.ok) {
const data = JSON.parse(responseText);
console.log("\n✅ Success!\n");
console.log(`📅 Date: ${data.date}`);
console.log(`🔍 Matched: ${data.matchedCount} player(s)`);
console.log(`✏️ Modified: ${data.modifiedCount} player(s)`);
console.log(`📝 Message: ${data.message}\n`);
} else {
let errorData;
try {
errorData = JSON.parse(responseText);
} catch {
errorData = { error: responseText };
}
console.log("\n❌ Error:\n");
console.log(JSON.stringify(errorData, null, 2));
}
} catch (error) {
console.error("\n❌ Request failed:");
console.error(error);
}
}

// Run the script
const args = parseArgs();
resetScored(args.date, args.env, args.token, args.confirm);
1 change: 1 addition & 0 deletions src/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export { getAllPlayers } from "./get_all_players";
export { deleteGameHandler } from "./delete_game";
export { getUnscoredDates } from "./get_unscored_dates";
export { backfillScoredHandler } from "./backfill_scored";
export { resetScoredHandler } from "./reset_scored";
export { uploadPlayersHandler } from "./upload_players";
133 changes: 133 additions & 0 deletions src/handlers/reset_scored.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { StatusCodes } from "http-status-codes";
import type { MongoClient } from "mongodb";
import type { Env } from "../env";
import {
withMongoClient,
getPlayersCollection,
} from "../shared";

/**
* Request body for reset scored endpoint
*/
interface ResetScoredRequest {
date: string;
}

/**
* Resets scored status to null for all players on a specific date,
* so the next backfill (GET /unscored-dates -> distinct("date", {scored: null}))
* picks the date up again.
*/
async function resetScored(
client: MongoClient,
env: Env,
date: string
): Promise<{ matchedCount: number; modifiedCount: number }> {
const playersCollection = getPlayersCollection(client, env);

const result = await playersCollection.updateMany(
{ date: date },
{ $set: { scored: null } }
);

return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
};
}

/**
* Handler for POST /reset-scored endpoint
*/
export async function resetScoredHandler(
req: Request,
env: Env,
origin: string | null,
getCorsHeaders: (origin: string | null) => HeadersInit
): Promise<Response> {
const corsHeaders = getCorsHeaders(origin);

// Parse request body
let body: ResetScoredRequest;
try {
body = await req.json() as ResetScoredRequest;
} catch {
return new Response(
JSON.stringify({ error: "Invalid JSON in request body" }),
{
status: StatusCodes.BAD_REQUEST,
headers: {
...corsHeaders,
"Content-Type": "application/json",
},
}
);
}

// Validate required fields
if (!body.date) {
return new Response(
JSON.stringify({ error: "Date field is required" }),
{
status: StatusCodes.BAD_REQUEST,
headers: {
...corsHeaders,
"Content-Type": "application/json",
},
}
);
}

// Validate date format
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(body.date)) {
return new Response(
JSON.stringify({ error: "Invalid date format. Expected YYYY-MM-DD" }),
{
status: StatusCodes.BAD_REQUEST,
headers: {
...corsHeaders,
"Content-Type": "application/json",
},
}
);
}

try {
// Reset scored status using shared MongoDB utilities
const result = await withMongoClient(env, (client) =>
resetScored(client, env, body.date)
);

return new Response(
JSON.stringify({
date: body.date,
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
message: `Reset scored to null for ${result.modifiedCount} player(s) on date ${body.date} (matched ${result.matchedCount})`,
}),
{
status: StatusCodes.OK,
headers: {
...corsHeaders,
"Content-Type": "application/json",
},
}
);
} catch (error) {
console.error("MongoDB error:", error);
return new Response(
JSON.stringify({
error: "Failed to reset scored status",
details: error instanceof Error ? error.message : "Unknown error",
}),
{
status: StatusCodes.INTERNAL_SERVER_ERROR,
headers: {
...corsHeaders,
"Content-Type": "application/json",
},
}
);
}
}
12 changes: 11 additions & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

import { hello, health, notFound, getPlayersForDate, getAllPlayers, deleteGameHandler, getUnscoredDates, backfillScoredHandler, uploadPlayersHandler } from "./handlers";
import { hello, health, notFound, getPlayersForDate, getAllPlayers, deleteGameHandler, getUnscoredDates, backfillScoredHandler, resetScoredHandler, uploadPlayersHandler } from "./handlers";
import { requireAuth, unauthorized } from "./auth";
import { StatusCodes } from "http-status-codes";
import type { Env } from "./env";
Expand Down Expand Up @@ -100,6 +100,16 @@ export async function route(req: Request, env?: Env): Promise<Response> {
return backfillScoredHandler(req, env, origin, getCorsHeaders);
}

if (req.method === "POST" && url.pathname === "/reset-scored") {
if (!env) {
return new Response("Server configuration error", {
status: StatusCodes.INTERNAL_SERVER_ERROR,
headers: getCorsHeaders(origin),
});
}
return resetScoredHandler(req, env, origin, getCorsHeaders);
}

if (req.method === "POST" && url.pathname === "/players") {
if (!env) {
return new Response("Server configuration error", {
Expand Down
Loading
Loading