diff --git a/src/app/api/assignment/auto/route.ts b/src/app/api/assignment/auto/route.ts index 7445979..42cedf3 100644 --- a/src/app/api/assignment/auto/route.ts +++ b/src/app/api/assignment/auto/route.ts @@ -52,6 +52,7 @@ export async function GET(request: NextRequest) { const yearMonth = searchParams.get('yearMonth'); const validateRules = searchParams.get('validateRules') === 'true'; const validateHardRule2 = searchParams.get('validateHardRule2') === 'true'; + const autoAssign = searchParams.get('autoAssign') === 'true'; if (!yearMonth) { return NextResponse.json({ error: 'yearMonth is required' }, { status: 400 }); @@ -79,6 +80,54 @@ export async function GET(request: NextRequest) { return NextResponse.json({ error: 'No roster found' }, { status: 404 }); } + // Handle auto-assignment via GET request (for Cron jobs) + if (autoAssign) { + try { + // If no yearMonth provided, generate for next month + let targetYearMonth = yearMonth; + if (!targetYearMonth) { + const now = new Date(); + const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1); + targetYearMonth = `${nextMonth.getFullYear()}-${String(nextMonth.getMonth() + 1).padStart(2, '0')}`; + } + + console.log(`🚀 Starting auto-assignment for ${targetYearMonth} via Cron`); + + // Create or get roster for the target month + const { data: targetRoster, error: targetRosterError } = await supabase + .from('crew_roster') + .upsert( + { year_month: targetYearMonth, status: 'generated' }, + { onConflict: 'year_month' } + ) + .select() + .single(); + + if (targetRosterError) { + console.error('Failed to create/get target roster:', targetRosterError); + return NextResponse.json({ error: 'Failed to create target roster' }, { status: 500 }); + } + + const result = await autoAssignCrew(targetYearMonth, false, targetRoster.id); + console.log(`✅ Auto-assignment completed for ${targetYearMonth}:`, result); + return NextResponse.json({ + success: true, + message: `Auto-assignment completed for ${targetYearMonth}`, + result, + }); + } catch (error) { + console.error(`❌ Auto-assignment failed:`, error); + return NextResponse.json( + { + success: false, + error: `Auto-assignment failed`, + details: error instanceof Error ? error.message : 'Unknown error', + }, + { status: 500 } + ); + } + } + // Get assignments with all related data for validation (with pagination) const allAssignments: any[] = []; let from = 0; diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..b857156 --- /dev/null +++ b/vercel.json @@ -0,0 +1,8 @@ +{ + "crons": [ + { + "path": "/api/assignment/auto?autoAssign=true", + "schedule": "15 1 * * *" + } + ] +}