145 lines
4.7 KiB
TypeScript
145 lines
4.7 KiB
TypeScript
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
|
import { NextResponse } from "next/server";
|
|
|
|
// Simple in-memory 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 status labels 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
|
|
}
|
|
})
|
|
});
|
|
|
|
const userData = await userResponse.json();
|
|
console.log('User lookup response:', userData);
|
|
|
|
if (userData.error === 'Too many requests per minute.') {
|
|
return NextResponse.json(
|
|
{ error: "Rate limit exceeded. Please try again in a minute." },
|
|
{ status: 429 }
|
|
);
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
// Now fetch the status labels
|
|
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({
|
|
method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId',
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
params: {
|
|
userId: leantimeUserId
|
|
}
|
|
})
|
|
});
|
|
|
|
const responseText = await response.text();
|
|
console.log('Leantime API Response Status:', response.status);
|
|
console.log('Leantime API Response Headers:', response.headers);
|
|
console.log('Leantime API Response Body:', responseText);
|
|
|
|
if (!response.ok) {
|
|
if (response.status === 401) {
|
|
return NextResponse.json({ error: "Unauthorized access to Leantime API" }, { status: 401 });
|
|
}
|
|
if (response.status === 403) {
|
|
return NextResponse.json({ error: "Forbidden access to Leantime API" }, { status: 403 });
|
|
}
|
|
if (response.status === 429) {
|
|
return NextResponse.json(
|
|
{ error: "Rate limit exceeded. Please try again in a minute." },
|
|
{ status: 429 }
|
|
);
|
|
}
|
|
throw new Error(`Leantime API returned ${response.status}: ${responseText}`);
|
|
}
|
|
|
|
let data;
|
|
try {
|
|
data = JSON.parse(responseText);
|
|
} catch (e) {
|
|
console.error('Failed to parse Leantime response:', e);
|
|
throw new Error('Invalid JSON response from Leantime');
|
|
}
|
|
|
|
if (!data.result) {
|
|
console.log('No result in Leantime response');
|
|
return NextResponse.json({ projects: [] });
|
|
}
|
|
|
|
// Transform the response into a more structured format while maintaining project grouping
|
|
const transformedProjects = Object.entries(data.result as Record<string, Record<string, any>>).map(([projectId, labels]) => {
|
|
// Convert the labels object to an array and sort by sortKey
|
|
const sortedLabels = Object.entries(labels).map(([id, label]) => ({
|
|
id,
|
|
name: label.name,
|
|
statusType: label.statusType,
|
|
class: label.class,
|
|
sortKey: Number(label.sortKey) || 0,
|
|
kanbanCol: label.kanbanCol
|
|
})).sort((a, b) => a.sortKey - b.sortKey);
|
|
|
|
return {
|
|
projectId,
|
|
labels: sortedLabels
|
|
};
|
|
});
|
|
|
|
// Sort projects by ID for consistency
|
|
transformedProjects.sort((a, b) => a.projectId.localeCompare(b.projectId));
|
|
|
|
return NextResponse.json({ projects: transformedProjects });
|
|
} catch (error) {
|
|
console.error('Detailed error in status labels fetch:', error);
|
|
return NextResponse.json(
|
|
{
|
|
error: "Failed to fetch status labels",
|
|
details: error instanceof Error ? error.message : 'Unknown error'
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|