diff --git a/scripts/reset-scored.ts b/scripts/reset-scored.ts new file mode 100644 index 0000000..c867a80 --- /dev/null +++ b/scripts/reset-scored.ts @@ -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 = { + 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); diff --git a/src/handlers/index.ts b/src/handlers/index.ts index ebf0fed..5555c58 100644 --- a/src/handlers/index.ts +++ b/src/handlers/index.ts @@ -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"; \ No newline at end of file diff --git a/src/handlers/reset_scored.ts b/src/handlers/reset_scored.ts new file mode 100644 index 0000000..fa7d7f6 --- /dev/null +++ b/src/handlers/reset_scored.ts @@ -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 { + 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", + }, + } + ); + } +} diff --git a/src/router.ts b/src/router.ts index 430c9d5..401eec3 100644 --- a/src/router.ts +++ b/src/router.ts @@ -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"; @@ -100,6 +100,16 @@ export async function route(req: Request, env?: Env): Promise { 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", { diff --git a/src/tests/reset_scored.test.ts b/src/tests/reset_scored.test.ts new file mode 100644 index 0000000..d3f7675 --- /dev/null +++ b/src/tests/reset_scored.test.ts @@ -0,0 +1,183 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { resetScoredHandler } from '../handlers/reset_scored'; +import type { Env } from '../env'; +import * as mongodb from '../shared/mongodb'; + +// Mock the MongoDB utilities +vi.mock('../shared/mongodb', () => ({ + withMongoClient: vi.fn(), + getPlayersCollection: vi.fn(), +})); + +const getCorsHeaders = (origin: string | null) => ({ + 'Access-Control-Allow-Origin': origin || '*', + 'Access-Control-Allow-Methods': 'GET,POST,DELETE,OPTIONS', +}); + +const mockEnv: Env = { + API_AUTH_TOKEN: 'test-token', + SHARED_SECRET: 'test-secret', + MONGODB_URI: 'mongodb://localhost:27017', + MONGODB_DATABASE: 'test-db', +}; + +interface ErrorResponse { + error: string; + details?: string; +} + +interface SuccessResponse { + date: string; + matchedCount: number; + modifiedCount: number; + message: string; +} + +describe('resetScoredHandler', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('Request body validation', () => { + it('should return 400 when request body is not valid JSON', async () => { + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: 'invalid json', + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(400); + const body = await response.json() as ErrorResponse; + expect(body.error).toBe('Invalid JSON in request body'); + }); + + it('should return 400 when date field is missing', async () => { + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({}), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(400); + const body = await response.json() as ErrorResponse; + expect(body.error).toBe('Date field is required'); + }); + + it('should return 400 when date format is invalid', async () => { + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-1-5' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(400); + const body = await response.json() as ErrorResponse; + expect(body.error).toBe('Invalid date format. Expected YYYY-MM-DD'); + }); + }); + + describe('Successful requests', () => { + it('should reset scored status for valid request', async () => { + vi.mocked(mongodb.withMongoClient).mockResolvedValue({ matchedCount: 25, modifiedCount: 20 }); + + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-01-15' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(200); + + const body = await response.json() as SuccessResponse; + expect(body.date).toBe('2026-01-15'); + expect(body.matchedCount).toBe(25); + expect(body.modifiedCount).toBe(20); + expect(body.message).toContain('2026-01-15'); + }); + + it('should handle zero matches', async () => { + vi.mocked(mongodb.withMongoClient).mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }); + + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-12-31' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(200); + + const body = await response.json() as SuccessResponse; + expect(body.matchedCount).toBe(0); + expect(body.modifiedCount).toBe(0); + }); + + it('should include correct Content-Type header', async () => { + vi.mocked(mongodb.withMongoClient).mockResolvedValue({ matchedCount: 5, modifiedCount: 5 }); + + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-01-05' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.headers.get('Content-Type')).toBe('application/json'); + }); + }); + + describe('CORS headers', () => { + it('should include CORS headers in response', async () => { + vi.mocked(mongodb.withMongoClient).mockResolvedValue({ matchedCount: 10, modifiedCount: 8 }); + + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-01-20' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*'); + expect(response.headers.get('Access-Control-Allow-Methods')).toBe('GET,POST,DELETE,OPTIONS'); + }); + + it('should include CORS headers in error response', async () => { + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-1-5' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*'); + }); + }); + + describe('Error handling', () => { + it('should handle MongoDB errors', async () => { + vi.mocked(mongodb.withMongoClient).mockRejectedValue(new Error('Connection failed')); + + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-01-05' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(500); + const body = await response.json() as ErrorResponse; + expect(body.error).toBe('Failed to reset scored status'); + expect(body.details).toBe('Connection failed'); + }); + + it('should handle unknown errors', async () => { + vi.mocked(mongodb.withMongoClient).mockRejectedValue('Unknown error'); + + const request = new Request('https://api.example.com/reset-scored', { + method: 'POST', + body: JSON.stringify({ date: '2026-01-05' }), + }); + const response = await resetScoredHandler(request, mockEnv, null, getCorsHeaders); + + expect(response.status).toBe(500); + const body = await response.json() as ErrorResponse; + expect(body.error).toBe('Failed to reset scored status'); + expect(body.details).toBe('Unknown error'); + }); + }); +});