import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; interface Task { id: string; headline: string; projectName: string; projectId: number; status: number; dueDate: string | null; milestone: string | null; details: string | null; } async function getLeantimeUserId(email: string): Promise { try { if (!process.env.LEANTIME_TOKEN) { console.error('LEANTIME_TOKEN is not set in environment variables'); return null; } console.log('Fetching Leantime users for email:', email); const response = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'apiKey': process.env.LEANTIME_TOKEN }, body: JSON.stringify({ jsonrpc: '2.0', method: 'leantime.rpc.users.getAll', id: 1 }), }); const responseText = await response.text(); console.log('Raw Leantime response:', responseText); if (!response.ok) { console.error('Failed to fetch Leantime users:', { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers.entries()) }); return null; } let data; try { data = JSON.parse(responseText); } catch (e) { console.error('Failed to parse Leantime response:', e); return null; } console.log('Leantime users response:', data); if (!data.result || !Array.isArray(data.result)) { console.error('Invalid response format from Leantime users API'); return null; } const users = data.result; const user = users.find((u: any) => u.email === email); if (user) { console.log('Found Leantime user:', { id: user.id, email: user.email }); } else { console.log('No Leantime user found for email:', email); } return user ? user.id : null; } catch (error) { console.error('Error fetching Leantime user ID:', error); return null; } } export async function GET(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } console.log('Fetching tasks for user:', session.user.email); const userId = await getLeantimeUserId(session.user.email); if (!userId) { console.error('User not found in Leantime:', session.user.email); return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 }); } console.log('Fetching tasks for Leantime user ID:', userId); const response = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'apiKey': process.env.LEANTIME_TOKEN }, body: JSON.stringify({ jsonrpc: '2.0', method: 'leantime.rpc.tickets.getAll', params: { userId: userId, status: "all" }, id: 1 }), }); const responseText = await response.text(); console.log('Raw tasks response:', responseText); if (!response.ok) { console.error('Failed to fetch tasks from Leantime:', { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers.entries()) }); throw new Error('Failed to fetch tasks from Leantime'); } let data; try { data = JSON.parse(responseText); } catch (e) { console.error('Failed to parse tasks response:', e); throw new Error('Invalid response format from Leantime'); } console.log('Leantime tasks response:', { success: true, taskCount: data.result?.length || 0 }); if (!data.result || !Array.isArray(data.result)) { console.error('Invalid response format from Leantime tasks API'); throw new Error('Invalid response format from Leantime'); } const tasks = data.result.map((task: any) => ({ id: task.id.toString(), headline: task.headline, projectName: task.projectName, projectId: task.projectId, status: task.status, dueDate: task.dateToFinish || null, milestone: task.type || null, details: task.description || null, editTo: task.editTo || null, dependingTicketId: task.dependingTicketId || null })); // Sort tasks by due date tasks.sort((a: any, b: any) => { if (!a.dueDate) return 1; if (!b.dueDate) return -1; return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime(); }); return NextResponse.json({ tasks }); } catch (error) { console.error('Error in tasks route:', error); return NextResponse.json( { error: "Failed to fetch tasks" }, { status: 500 } ); } }