NeahFront7/app/api/leantime/tasks/route.ts
2025-04-12 13:10:19 +02:00

172 lines
4.8 KiB
TypeScript

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;
priority: number;
details: string | null;
}
// Cache for user IDs to avoid repeated lookups
const userCache = new Map<string, number>();
async function getLeantimeUserId(email: string): Promise<number | null> {
// 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 || !session.user?.email) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Get Leantime user ID
const leantimeUserId = await getLeantimeUserId(session.user.email);
if (!leantimeUserId) {
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) {
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: {
'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 from Leantime');
}
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;
const now = new Date();
let status = 'upcoming';
if (dueDate && dueDate < now) {
status = 'overdue';
} else if (task.status === 'done' || task.status === 'closed') {
status = 'completed';
} else if (task.status === 'inprogress') {
status = 'in_progress';
}
return {
id: task.id,
headline: task.headline,
projectName: projectsMap.get(task.projectId) || `Project ${task.projectId}`,
projectId: task.projectId,
status: status,
dueDate: dueDate ? dueDate.toISOString() : null,
priority: task.priority,
details: task.description ? task.description.substring(0, 100) : null
};
});
// Sort tasks by due date and status
tasks.sort((a: Task, b: Task) => {
if (a.status === 'overdue' && b.status !== 'overdue') return -1;
if (a.status !== 'overdue' && b.status === 'overdue') return 1;
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: "Failed to fetch tasks" },
{ status: 500 }
);
}
}