import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; // Simple in-memory 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 status labels 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 } }) }); const userData = await userResponse.json(); console.log('User lookup response:', userData); if (userData.error === 'Too many requests per minute.') { return NextResponse.json( { error: "Rate limit exceeded. Please try again in a minute." }, { status: 429 } ); } 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); } } // Now fetch the status labels 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({ method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId', jsonrpc: '2.0', id: 1, params: { userId: leantimeUserId } }) }); const responseText = await response.text(); console.log('Leantime API Response Status:', response.status); console.log('Leantime API Response Headers:', response.headers); console.log('Leantime API Response Body:', responseText); if (!response.ok) { if (response.status === 401) { return NextResponse.json({ error: "Unauthorized access to Leantime API" }, { status: 401 }); } if (response.status === 403) { return NextResponse.json({ error: "Forbidden access to Leantime API" }, { status: 403 }); } if (response.status === 429) { return NextResponse.json( { error: "Rate limit exceeded. Please try again in a minute." }, { status: 429 } ); } throw new Error(`Leantime API returned ${response.status}: ${responseText}`); } let data; try { data = JSON.parse(responseText); } catch (e) { console.error('Failed to parse Leantime response:', e); throw new Error('Invalid JSON response from Leantime'); } if (!data.result) { console.log('No result in Leantime response'); return NextResponse.json({ statusLabels: [] }); } // Create a map to store unique status labels const uniqueLabels = new Map(); // Transform and deduplicate status labels Object.entries(data.result as Record>).forEach(([projectId, labels]) => { Object.entries(labels).forEach(([id, label]) => { const key = label.name; if (!uniqueLabels.has(key)) { uniqueLabels.set(key, { id, name: label.name, statusType: label.statusType, class: label.class, sortKey: Number(label.sortKey) || 0, // Convert to number, default to 0 if invalid projects: [] }); } uniqueLabels.get(key).projects.push({ id: projectId, name: projectId // You might want to fetch project names separately }); }); }); // Convert the map to an array and sort by sortKey numerically const transformedLabels = Array.from(uniqueLabels.values()) .sort((a, b) => a.sortKey - b.sortKey); return NextResponse.json({ statusLabels: transformedLabels }); } catch (error) { console.error('Detailed error in status labels fetch:', error); return NextResponse.json( { error: "Failed to fetch status labels", details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } }