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; projectId: number; status: string; dueDate: string | null; milestone: string | null; details: string | null; } // Cache for user IDs to avoid repeated lookups const userCache = new Map(); async function getLeantimeUserId(email: string): Promise { // Check cache first if (userCache.has(email)) { return userCache.get(email)!; } try { 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.users.getAll', id: 1, }), }); if (!response.ok) { console.error('Failed to fetch users from Leantime:', response.status, response.statusText); throw new Error('Failed to fetch users from Leantime'); } const data = await response.json(); const user = data.result.find((u: any) => u.email === email); if (user) { // Cache the user ID userCache.set(email, user.id); // Clear cache after 5 minutes setTimeout(() => userCache.delete(email), 5 * 60 * 1000); return user.id; } console.error('User not found in Leantime:', email); return null; } catch (error) { console.error('Error getting Leantime user ID:', error); return null; } } export async function GET() { try { const session = await getServerSession(authOptions); console.log('Session in tasks route:', session); if (!session || !session.user?.email) { console.error('Unauthorized: No session or email found'); return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Get Leantime user ID const leantimeUserId = await getLeantimeUserId(session.user.email); console.log('Leantime user ID:', leantimeUserId); if (!leantimeUserId) { console.error('User not found in Leantime:', session.user.email); return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 }); } // Get 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.getAllByUserId', id: 1, params: { userId: leantimeUserId, status: "all", limit: 100 } }) }); if (!response.ok) { console.error('Failed to fetch tasks from Leantime:', response.status, response.statusText); throw new Error('Failed to fetch tasks from Leantime'); } 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) { console.error('Failed to fetch projects from Leantime:', projectsResponse.status, projectsResponse.statusText); throw new Error('Failed to fetch projects from Leantime'); } const projectsData = await projectsResponse.json(); const projectsMap = new Map( projectsData.result.map((project: any) => [project.id, project.name]) ); // Transform and sort the tasks const tasks = data.result.map((task: any) => { const dueDate = task.dateToFinish ? new Date(task.dateToFinish * 1000).toISOString() : null; return { id: task.id, headline: task.headline, projectName: projectsMap.get(task.projectId) || `Project ${task.projectId}`, projectId: task.projectId, status: task.status, dueDate: dueDate, milestone: task.milestoneid || null, details: task.description || null }; }); // Sort tasks by due date (overdue first) tasks.sort((a: Task, b: Task) => { 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 } ); } }