NeahFront7/app/api/leantime/status-labels/route.ts
2025-04-12 13:33:12 +02:00

215 lines
6.5 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;
status: string;
dueDate: string | null;
details?: string;
milestone?: string;
}
// Cache for user IDs
const userCache = new Map<string, number>();
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 tasks 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);
}
}
// Fetch 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.getAllStatusLabelsByUserId',
id: 1,
params: {
userId: leantimeUserId
}
})
});
if (!response.ok) {
const errorData = await response.json();
console.error('Tasks fetch failed:', errorData);
throw new Error(`Failed to fetch tasks: ${errorData.error || 'Unknown error'}`);
}
const data = await response.json();
console.log('Tasks response:', JSON.stringify(data, null, 2));
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');
}
const projectsData = await projectsResponse.json();
console.log('Projects response:', JSON.stringify(projectsData, null, 2));
const projectsMap = new Map(
projectsData.result.map((project: any) => [project.id, project.name])
);
// Define status code mapping
const statusMapping: Record<string, string> = {
'-1': 'archived',
'0': 'new',
'1': 'in progress',
'2': 'waiting',
'3': 'in review',
'4': 'done'
};
// Transform the nested structure into a flat array of tasks
const tasks: Task[] = [];
Object.entries(data.result).forEach(([projectId, statusGroups]) => {
const projectName = projectsMap.get(Number(projectId)) || `Project ${projectId}`;
if (typeof statusGroups === 'object' && statusGroups !== null) {
// Iterate through each status group
Object.entries(statusGroups).forEach(([statusType, statusLabels]) => {
if (typeof statusLabels === 'object' && statusLabels !== null) {
// Each status label in the group
Object.values(statusLabels).forEach((label: any) => {
const statusName = statusMapping[statusType] || `status-${statusType}`;
const headline = String(label.title || label.name || statusName);
tasks.push({
id: label.id?.toString() || `${projectId}-${statusType}`,
headline,
projectName,
status: statusName,
dueDate: null,
details: label.description || null,
milestone: label.milestone || null
});
});
}
});
}
});
// Sort tasks by status type
const statusOrder: Record<string, number> = {
'new': 1,
'in progress': 2,
'waiting': 3,
'in review': 4,
'done': 5,
'archived': 6
};
tasks.sort((a, b) => {
const statusA = statusOrder[a.status.toLowerCase()] || 99;
const statusB = statusOrder[b.status.toLowerCase()] || 99;
return statusA - statusB;
});
// Deduplicate tasks based on project and status
const uniqueTasks = tasks.reduce((acc: Task[], task) => {
const existingTask = acc.find(t =>
t.projectName === task.projectName &&
t.status === task.status
);
if (!existingTask) {
acc.push(task);
}
return acc;
}, []);
return NextResponse.json({ tasks: uniqueTasks });
} catch (error) {
console.error('Error fetching tasks:', error);
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Failed to fetch tasks" },
{ status: 500 }
);
}
}