234 lines
6.9 KiB
TypeScript
234 lines
6.9 KiB
TypeScript
import { NextRequest } from "next/server";
|
|
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
|
import { NextResponse } from "next/server";
|
|
|
|
interface StatusLabel {
|
|
id: string;
|
|
name: string;
|
|
statusType: string;
|
|
class: string;
|
|
}
|
|
|
|
interface Project {
|
|
id: string;
|
|
name: string;
|
|
labels: StatusLabel[];
|
|
}
|
|
|
|
// 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 {
|
|
console.log('Fetching Leantime user with token:', process.env.LEANTIME_TOKEN ? 'Token present' : 'Token missing');
|
|
|
|
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.Users.getUserByEmail',
|
|
id: 1,
|
|
params: {
|
|
email: email
|
|
}
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error('Failed to fetch user from Leantime:', {
|
|
status: response.status,
|
|
statusText: response.statusText
|
|
});
|
|
throw new Error(`Failed to fetch user from Leantime: ${response.status} ${response.statusText}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
console.log('Leantime user response:', data);
|
|
|
|
if (!data.result || data.result === false) {
|
|
console.log('User not found in Leantime');
|
|
return null;
|
|
}
|
|
|
|
// Cache the user ID
|
|
userCache.set(email, data.result.id);
|
|
// Clear cache after 5 minutes
|
|
setTimeout(() => userCache.delete(email), 5 * 60 * 1000);
|
|
return data.result.id;
|
|
} catch (error) {
|
|
console.error('Error getting Leantime user ID:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
console.log('Session:', session ? 'Present' : 'Missing');
|
|
|
|
if (!session) {
|
|
return NextResponse.json(
|
|
{ error: "Unauthorized", message: "No session found. Please sign in." },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
if (!session.user?.email) {
|
|
return NextResponse.json(
|
|
{ error: "Unauthorized", message: "No email found in session. Please sign in again." },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
console.log('User email:', session.user.email);
|
|
|
|
// Get Leantime user ID
|
|
const leantimeUserId = await getLeantimeUserId(session.user.email);
|
|
console.log('Leantime user ID:', leantimeUserId);
|
|
|
|
if (!leantimeUserId) {
|
|
return NextResponse.json(
|
|
{ error: "User not found", message: "Could not find user in Leantime. Please check your email." },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Get all tasks assigned to the user
|
|
console.log('Fetching tasks for user:', 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.getAll',
|
|
id: 1,
|
|
params: {
|
|
projectId: 0, // 0 means all projects
|
|
userId: leantimeUserId,
|
|
status: "all",
|
|
limit: 100
|
|
}
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error('Failed to fetch tasks:', {
|
|
status: response.status,
|
|
statusText: response.statusText
|
|
});
|
|
throw new Error(`Failed to fetch tasks: ${response.status} ${response.statusText}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
console.log('Tasks response:', data);
|
|
|
|
if (!data.result) {
|
|
return NextResponse.json({ projects: [] });
|
|
}
|
|
|
|
// Get project details to include project names
|
|
console.log('Fetching projects');
|
|
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) {
|
|
console.error('Failed to fetch projects:', {
|
|
status: projectsResponse.status,
|
|
statusText: projectsResponse.statusText
|
|
});
|
|
throw new Error(`Failed to fetch projects: ${projectsResponse.status} ${projectsResponse.statusText}`);
|
|
}
|
|
|
|
const projectsData = await projectsResponse.json();
|
|
console.log('Projects response:', projectsData);
|
|
|
|
// Create a map of projects with their tasks grouped by status
|
|
const projectMap = new Map<string, Project>();
|
|
|
|
data.result.forEach((task: any) => {
|
|
const project = projectsData.result.find((p: any) => p.id === task.projectId);
|
|
const projectName = project ? project.name : `Project ${task.projectId}`;
|
|
const projectId = task.projectId.toString();
|
|
|
|
if (!projectMap.has(projectId)) {
|
|
projectMap.set(projectId, {
|
|
id: projectId,
|
|
name: projectName,
|
|
labels: []
|
|
});
|
|
}
|
|
|
|
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;
|
|
|
|
// Convert numeric status to string and handle accordingly
|
|
const statusStr = task.status.toString();
|
|
switch (statusStr) {
|
|
case '1':
|
|
statusType = 'NEW';
|
|
statusClass = 'bg-blue-100 text-blue-800';
|
|
break;
|
|
case '2':
|
|
statusType = 'INPROGRESS';
|
|
statusClass = 'bg-yellow-100 text-yellow-800';
|
|
break;
|
|
case '3':
|
|
statusType = 'DONE';
|
|
statusClass = 'bg-green-100 text-green-800';
|
|
break;
|
|
default:
|
|
statusType = 'UNKNOWN';
|
|
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
|
|
const projects = Array.from(projectMap.values()).sort((a, b) => a.name.localeCompare(b.name));
|
|
console.log('Final projects:', projects);
|
|
|
|
return NextResponse.json({ projects });
|
|
} catch (error) {
|
|
console.error('Error fetching status labels:', error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to fetch status labels", message: error instanceof Error ? error.message : "Unknown error occurred" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|