import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; interface StatusLabel { name: string; class: string; statusType: string; kanbanCol: boolean | string; sortKey: number; } interface Project { projectId: string; labels: StatusLabel[]; } // Simple in-memory cache for user IDs and status labels const userCache = new Map(); const statusLabelsCache = new Map(); const CACHE_TTL = 60000; // 1 minute cache TTL 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 } }) }); 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); } } // Check status labels cache const cachedLabels = statusLabelsCache.get(leantimeUserId); if (cachedLabels && (Date.now() - cachedLabels.timestamp) < CACHE_TTL) { return NextResponse.json({ projects: cachedLabels.data }); } // Now fetch the status labels using leantimeUserId 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 // Use the Leantime user ID here } }) }); if (!response.ok) { const errorData = await response.json(); console.error('Status labels fetch failed:', errorData); throw new Error(`Failed to fetch status labels: ${errorData.error || 'Unknown error'}`); } const data = await response.json(); console.log('Status labels response:', data); if (!data.result) { return NextResponse.json({ projects: [] }); } // Transform the response into our desired format const projects: Project[] = Object.entries(data.result).map(([projectId, statusLabels]: [string, any]) => { const labels = Object.entries(statusLabels).map(([_, label]: [string, any]) => ({ name: label.name, class: label.class, statusType: label.statusType, kanbanCol: label.kanbanCol, sortKey: Number(label.sortKey) || 0 })); // Sort labels by sortKey labels.sort((a, b) => a.sortKey - b.sortKey); return { projectId, labels }; }); // Cache the transformed data statusLabelsCache.set(leantimeUserId, { data: projects, timestamp: Date.now() }); return NextResponse.json({ projects }); } catch (error) { console.error('Error fetching status labels:', error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to fetch status labels" }, { status: 500 } ); } }