diff --git a/app/api/leantime/status-labels/route.ts b/app/api/leantime/status-labels/route.ts index 729f3299..debba36a 100644 --- a/app/api/leantime/status-labels/route.ts +++ b/app/api/leantime/status-labels/route.ts @@ -2,70 +2,107 @@ import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; -interface StatusLabel { +interface Task { id: string; - name: string; - class: string; - statusType: string; - kanbanCol: boolean | string; - sortKey: number | string; -} - -interface Project { - id: number; - name: string; - labels: StatusLabel[]; + 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) { + 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; + } + + return null; + } catch (error) { + console.error('Error getting Leantime user ID:', error); + return null; + } +} + export async function GET() { try { const session = await getServerSession(authOptions); - if (!session?.user?.email) { + if (!session || !session.user?.email) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } - // Check cache first - let leantimeUserId = userCache.get(session.user.email); + // Get Leantime user ID + const leantimeUserId = await getLeantimeUserId(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({ - jsonrpc: '2.0', - method: 'leantime.rpc.Users.Users.getUserByEmail', - id: 1, - params: { - email: session.user.email - } - }) - }); - - if (!userResponse.ok) { - throw new Error('Failed to fetch user from Leantime'); - } - - const userData = await userResponse.json(); - - if (!userData.result || !userData.result.id) { - return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 }); - } - - leantimeUserId = userData.result.id; - // Cache the user ID for 5 minutes - userCache.set(session.user.email, leantimeUserId); - setTimeout(() => userCache.delete(session.user.email!), 5 * 60 * 1000); + return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 }); } - // Get projects + // 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) { + throw new Error('Failed to fetch tasks from Leantime'); + } + + const data = await response.json(); + + 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: { @@ -84,54 +121,38 @@ export async function GET() { } const projectsData = await projectsResponse.json(); + const projectsMap = new Map( + projectsData.result.map((project: any) => [project.id, project.name]) + ); - // Get status labels - const labelsResponse = 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 - } - }) + // 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 + }; }); - if (!labelsResponse.ok) { - throw new Error('Failed to fetch status labels from Leantime'); - } + // 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(); + }); - const labelsData = await labelsResponse.json(); - - // Transform the data into the required format - const projects: Project[] = projectsData.result.map((project: any) => { - const projectLabels = labelsData.result[project.id]; - const labels: StatusLabel[] = projectLabels ? Object.entries(projectLabels).map(([key, value]: [string, any]) => ({ - id: key, - name: value.name, - class: value.class, - statusType: value.statusType, - kanbanCol: value.kanbanCol, - sortKey: value.sortKey - })).sort((a: StatusLabel, b: StatusLabel) => Number(a.sortKey) - Number(b.sortKey)) : []; - - return { - id: project.id, - name: project.name, - labels - }; - }).filter((project: Project) => project.labels.length > 0); - - return NextResponse.json({ projects }); + return NextResponse.json({ tasks }); } catch (error) { - console.error('Error fetching status labels:', error); + console.error('Error fetching tasks:', error); return NextResponse.json( - { error: "Failed to fetch status labels" }, + { error: "Failed to fetch tasks" }, { status: 500 } ); }