working leantime widget 21
This commit is contained in:
parent
c90b1949e0
commit
56a37c68e3
@ -2,41 +2,30 @@ 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() {
|
||||||
|
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 });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// Get user ID from Leantime
|
||||||
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', {
|
const userResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@ -44,79 +33,24 @@ export async function GET() {
|
|||||||
'X-API-Key': process.env.LEANTIME_TOKEN || '',
|
'X-API-Key': process.env.LEANTIME_TOKEN || '',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
method: 'leantime.rpc.Users.Users.getUserByEmail',
|
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
|
method: 'leantime.rpc.users.getAll',
|
||||||
id: 1,
|
id: 1,
|
||||||
params: {
|
}),
|
||||||
email: session.user.email
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!userResponse.ok) {
|
if (!userResponse.ok) {
|
||||||
const errorData = await userResponse.json();
|
throw new Error('Failed to fetch user from Leantime');
|
||||||
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();
|
const userData = await userResponse.json();
|
||||||
console.log('User lookup response:', userData);
|
const user = userData.result.find((u: any) => u.email === session.user.email);
|
||||||
|
|
||||||
if (!userData.result || !userData.result.id) {
|
if (!user) {
|
||||||
throw new Error('Could not find Leantime user ID');
|
return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
leantimeUserId = userData.result.id as number;
|
// Get projects
|
||||||
// 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', {
|
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: {
|
||||||
|
'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: user.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
// Transform the nested structure into a flat array of tasks
|
if (!labelsResponse.ok) {
|
||||||
const tasks: Task[] = [];
|
throw new Error('Failed to fetch status labels from Leantime');
|
||||||
Object.entries(data.result).forEach(([projectId, statusGroups]) => {
|
}
|
||||||
const project = projectsData.result.find((p: Project) => p.id === Number(projectId));
|
|
||||||
const projectName = project ? project.name : `Project ${projectId}`;
|
|
||||||
|
|
||||||
if (typeof statusGroups === 'object' && statusGroups !== null) {
|
const labelsData = await labelsResponse.json();
|
||||||
// Iterate through each status group
|
|
||||||
Object.entries(statusGroups).forEach(([_, label]) => {
|
// Transform the data into the required format
|
||||||
if (typeof label === 'object' && label !== null && 'name' in label) {
|
const projects: Project[] = projectsData.result.map((project: any) => {
|
||||||
const statusLabel = label as {
|
const projectLabels = labelsData.result[project.id];
|
||||||
name: string;
|
const labels: StatusLabel[] = projectLabels ? Object.entries(projectLabels).map(([key, value]: [string, any]) => ({
|
||||||
class: string;
|
id: key,
|
||||||
statusType: string;
|
name: value.name,
|
||||||
kanbanCol: string;
|
class: value.class,
|
||||||
sortKey: string;
|
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);
|
||||||
|
|
||||||
tasks.push({
|
return NextResponse.json({ projects });
|
||||||
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
|
|
||||||
tasks.sort((a, b) => {
|
|
||||||
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 uniqueTasks = tasks.reduce((acc: Task[], task) => {
|
|
||||||
const existingTask = acc.find(t =>
|
|
||||||
t.headline === task.headline &&
|
|
||||||
t.status === task.status
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!existingTask) {
|
|
||||||
acc.push(task);
|
|
||||||
}
|
|
||||||
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return NextResponse.json({ tasks: uniqueTasks });
|
|
||||||
} 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 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user