working leantime widget 32

This commit is contained in:
Alma 2025-04-12 14:20:58 +02:00
parent 870c5c06f2
commit f0b718442c

View File

@ -1,4 +1,3 @@
import { NextRequest } from "next/server";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
@ -6,12 +5,14 @@ import { NextResponse } from "next/server";
interface StatusLabel { interface StatusLabel {
id: string; id: string;
name: string; name: string;
statusType: string;
class: string; class: string;
statusType: string;
kanbanCol: boolean | string;
sortKey: number | string;
} }
interface Project { interface Project {
id: string; id: number;
name: string; name: string;
labels: StatusLabel[]; labels: StatusLabel[];
} }
@ -19,93 +20,52 @@ interface Project {
// Cache for user IDs to avoid repeated lookups // Cache for user IDs to avoid repeated lookups
const userCache = new Map<string, number>(); const userCache = new Map<string, number>();
async function getLeantimeUserId(email: string): Promise<number | null> { export async function GET() {
// 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(request: NextRequest) {
try { try {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!session || !session.user?.email) { if (!session?.user?.email) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
// Get Leantime user ID // Check cache first
const leantimeUserId = await getLeantimeUserId(session.user.email); let leantimeUserId = userCache.get(session.user.email);
// If not in cache, fetch from API
if (!leantimeUserId) { if (!leantimeUserId) {
return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 }); 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);
} }
// Get all tasks assigned to the user // Get projects
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({ projects: [] });
}
// Get project details to include project names
const projectsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { const projectsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
method: 'POST', method: 'POST',
headers: { headers: {
@ -125,60 +85,47 @@ export async function GET(request: NextRequest) {
const projectsData = await projectsResponse.json(); const projectsData = await projectsResponse.json();
// Create a map of projects with their tasks grouped by status // Get status labels
const projectMap = new Map<string, Project>(); const labelsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
method: 'POST',
data.result.forEach((task: any) => { headers: {
const project = projectsData.result.find((p: any) => p.id === task.projectId); 'Content-Type': 'application/json',
const projectName = project ? project.name : `Project ${task.projectId}`; 'X-API-Key': process.env.LEANTIME_TOKEN || '',
const projectId = task.projectId.toString(); },
body: JSON.stringify({
if (!projectMap.has(projectId)) { jsonrpc: '2.0',
projectMap.set(projectId, { method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId',
id: projectId, id: 1,
name: projectName, params: {
labels: [] userId: leantimeUserId
});
}
const currentProject = projectMap.get(projectId)!;
// Check if this status label already exists for this project
const existingLabel = currentProject.labels.find(label => label.name === task.status);
if (!existingLabel) {
let statusType;
let statusClass;
switch (task.status.toLowerCase()) {
case 'new':
statusType = 'NEW';
statusClass = 'bg-blue-100 text-blue-800';
break;
case 'in_progress':
statusType = 'INPROGRESS';
statusClass = 'bg-yellow-100 text-yellow-800';
break;
case 'done':
statusType = 'DONE';
statusClass = 'bg-green-100 text-green-800';
break;
default:
statusType = 'NONE';
statusClass = 'bg-gray-100 text-gray-800';
} }
})
currentProject.labels.push({
id: `${projectId}-${task.status}`,
name: task.status,
statusType: statusType,
class: statusClass
});
}
}); });
// Convert the map to an array and sort projects by name if (!labelsResponse.ok) {
const projects = Array.from(projectMap.values()).sort((a, b) => a.name.localeCompare(b.name)); throw new Error('Failed to fetch status labels from Leantime');
}
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({ projects });
} catch (error) { } catch (error) {