working leantime widget 21

This commit is contained in:
Alma 2025-04-12 13:52:10 +02:00
parent c90b1949e0
commit 56a37c68e3
2 changed files with 64 additions and 147 deletions

View File

@ -2,92 +2,31 @@ 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";
interface Task { interface StatusLabel {
id: string; id: string;
headline: string; name: string;
projectName: string;
status: string;
dueDate: string | null;
details?: string | null;
milestone?: string | null;
class: string; class: string;
statusType: string;
kanbanCol: boolean | string;
sortKey: number | string;
} }
interface Project { interface Project {
id: number; id: number;
name: string; name: string;
labels: StatusLabel[];
} }
// Cache for user IDs
const userCache = new Map<string, number>();
export async function GET() { export async function GET() {
const session = await getServerSession(authOptions);
if (!session || !session.user?.email) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try { try {
console.log('Fetching tasks for user:', session.user.id); const session = await getServerSession(authOptions);
console.log('Using LEANTIME_TOKEN:', process.env.LEANTIME_TOKEN ? 'Present' : 'Missing');
// Check cache first if (!session?.user?.email) {
let leantimeUserId = userCache.get(session.user.email); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// 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 // Get user ID from Leantime
const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { const userResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -95,28 +34,23 @@ export async function GET() {
}, },
body: JSON.stringify({ body: JSON.stringify({
jsonrpc: '2.0', jsonrpc: '2.0',
method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId', method: 'leantime.rpc.users.getAll',
id: 1, id: 1,
params: { }),
userId: leantimeUserId
}
})
}); });
if (!response.ok) { if (!userResponse.ok) {
const errorData = await response.json(); throw new Error('Failed to fetch user from Leantime');
console.error('Tasks fetch failed:', errorData);
throw new Error(`Failed to fetch tasks: ${errorData.error || 'Unknown error'}`);
} }
const data = await response.json(); const userData = await userResponse.json();
console.log('Tasks response:', JSON.stringify(data, null, 2)); const user = userData.result.find((u: any) => u.email === session.user.email);
if (!data.result) { if (!user) {
return NextResponse.json({ tasks: [] }); return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 });
} }
// Get project details to include project names // Get projects
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: {
@ -131,75 +65,58 @@ export async function GET() {
}); });
if (!projectsResponse.ok) { if (!projectsResponse.ok) {
throw new Error('Failed to fetch projects'); throw new Error('Failed to fetch projects from Leantime');
} }
const projectsData = await projectsResponse.json(); const projectsData = await projectsResponse.json();
console.log('Projects response:', JSON.stringify(projectsData, null, 2));
const projectsMap = new Map( // Get status labels
projectsData.result.map((project: Project) => [project.id, project.name]) const labelsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
); method: 'POST',
headers: {
// Transform the nested structure into a flat array of tasks 'Content-Type': 'application/json',
const tasks: Task[] = []; 'X-API-Key': process.env.LEANTIME_TOKEN || '',
Object.entries(data.result).forEach(([projectId, statusGroups]) => { },
const project = projectsData.result.find((p: Project) => p.id === Number(projectId)); body: JSON.stringify({
const projectName = project ? project.name : `Project ${projectId}`; jsonrpc: '2.0',
method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId',
if (typeof statusGroups === 'object' && statusGroups !== null) { id: 1,
// Iterate through each status group params: {
Object.entries(statusGroups).forEach(([_, label]) => { userId: user.id
if (typeof label === 'object' && label !== null && 'name' in label) { }
const statusLabel = label as { })
name: string;
class: string;
statusType: string;
kanbanCol: string;
sortKey: string;
};
tasks.push({
id: `${projectId}-${statusLabel.sortKey}`,
headline: statusLabel.name,
projectName,
status: statusLabel.statusType.toLowerCase(),
dueDate: null,
details: undefined,
milestone: undefined,
class: statusLabel.class
});
}
});
}
}); });
// Sort tasks by their sortKey if (!labelsResponse.ok) {
tasks.sort((a, b) => { throw new Error('Failed to fetch status labels from Leantime');
const sortKeyA = Number(a.id.split('-')[1]) || 99; }
const sortKeyB = Number(b.id.split('-')[1]) || 99;
return sortKeyA - sortKeyB;
});
// Deduplicate tasks based on headline and status const labelsData = await labelsResponse.json();
const uniqueTasks = tasks.reduce((acc: Task[], task) => {
const existingTask = acc.find(t =>
t.headline === task.headline &&
t.status === task.status
);
if (!existingTask) { // Transform the data into the required format
acc.push(task); 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 acc; return {
}, []); id: project.id,
name: project.name,
labels
};
}).filter((project: Project) => project.labels.length > 0);
return NextResponse.json({ tasks: uniqueTasks }); return NextResponse.json({ projects });
} catch (error) { } catch (error) {
console.error('Error fetching tasks:', error); console.error('Error fetching status labels:', error);
return NextResponse.json( return NextResponse.json(
{ error: error instanceof Error ? error.message : "Failed to fetch tasks" }, { error: "Failed to fetch status labels" },
{ status: 500 } { status: 500 }
); );
} }

View File

@ -101,7 +101,7 @@ export function Flow() {
<h3 className="font-medium text-sm">{project.name}</h3> <h3 className="font-medium text-sm">{project.name}</h3>
<div className="space-y-2"> <div className="space-y-2">
{project.labels.map((label) => ( {project.labels.map((label) => (
<div key={label.id} className="flex justify-between items-start text-sm border-b border-gray-100 pb-2"> <div key={`${project.id}-${label.id}`} className="flex justify-between items-start text-sm border-b border-gray-100 pb-2">
<div className="flex-1"> <div className="flex-1">
<div className="font-medium">{label.name}</div> <div className="font-medium">{label.name}</div>
</div> </div>