import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; interface Task { id: string; headline: string; projectName: string; status: string; dueDate: string | null; details?: string; milestone?: string; } // Cache for user IDs const userCache = new Map(); export async function GET() { const session = await getServerSession(authOptions); if (!session || !session.user?.email) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } try { console.log('Fetching tasks for user:', session.user.id); console.log('Using LEANTIME_TOKEN:', process.env.LEANTIME_TOKEN ? 'Present' : 'Missing'); // Check cache first let leantimeUserId = userCache.get(session.user.email); // If not in cache, fetch from API if (!leantimeUserId) { const userResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.LEANTIME_TOKEN || '', }, body: JSON.stringify({ method: 'leantime.rpc.Users.Users.getUserByEmail', jsonrpc: '2.0', id: 1, params: { email: session.user.email } }) }); if (!userResponse.ok) { const errorData = await userResponse.json(); console.error('User lookup failed:', errorData); if (userResponse.status === 429) { const retryAfter = userResponse.headers.get('retry-after') || '60'; return NextResponse.json( { error: "Rate limit exceeded. Please try again later." }, { status: 429, headers: { 'Retry-After': retryAfter } } ); } throw new Error('Failed to fetch user data from Leantime'); } const userData = await userResponse.json(); console.log('User lookup response:', userData); if (!userData.result || !userData.result.id) { throw new Error('Could not find Leantime user ID'); } leantimeUserId = userData.result.id as number; // Cache the user ID for 5 minutes if (session.user.email) { userCache.set(session.user.email, leantimeUserId); setTimeout(() => userCache.delete(session.user.email!), 5 * 60 * 1000); } } // Fetch all tasks assigned to the user const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.LEANTIME_TOKEN || '', }, body: JSON.stringify({ jsonrpc: '2.0', method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId', id: 1, params: { userId: leantimeUserId } }) }); if (!response.ok) { const errorData = await response.json(); console.error('Tasks fetch failed:', errorData); throw new Error(`Failed to fetch tasks: ${errorData.error || 'Unknown error'}`); } const data = await response.json(); console.log('Tasks response:', data); if (!data.result) { return NextResponse.json({ tasks: [] }); } // Get project details to include project names const projectsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.LEANTIME_TOKEN || '', }, body: JSON.stringify({ jsonrpc: '2.0', method: 'leantime.rpc.Projects.getAll', id: 1 }) }); if (!projectsResponse.ok) { throw new Error('Failed to fetch projects'); } const projectsData = await projectsResponse.json(); const projectsMap = new Map( projectsData.result.map((project: any) => [project.id, project.name]) ); // Transform and categorize the tasks const tasks = data.result.map((task: any) => { const dueDate = task.dateToFinish ? new Date(task.dateToFinish * 1000) : null; return { id: task.id, headline: task.headline, projectName: projectsMap.get(task.projectId) || `Project ${task.projectId}`, status: task.status, dueDate: dueDate ? dueDate.toISOString() : null, details: task.description, milestone: task.milestoneName }; }); // Sort tasks by due date tasks.sort((a: Task, b: Task) => { if (!a.dueDate && !b.dueDate) return 0; 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 fetching tasks:', error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to fetch tasks" }, { status: 500 } ); } }