working leantime widget 12

This commit is contained in:
Alma 2025-04-12 13:14:24 +02:00
parent 75915ce4ce
commit 6e64455ef2
2 changed files with 115 additions and 215 deletions

View File

@ -2,6 +2,19 @@ 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 StatusLabel {
name: string;
class: string;
statusType: string;
kanbanCol: boolean | string;
sortKey: number;
}
interface Project {
projectId: string;
labels: StatusLabel[];
}
// Simple in-memory cache for user IDs and status labels // Simple in-memory cache for user IDs and status labels
const userCache = new Map<string, number>(); const userCache = new Map<string, number>();
const statusLabelsCache = new Map<number, { data: any; timestamp: number }>(); const statusLabelsCache = new Map<number, { data: any; timestamp: number }>();
@ -81,90 +94,55 @@ 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.Tickets.Tickets.getAllStatusLabelsByUserId',
jsonrpc: '2.0', jsonrpc: '2.0',
method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId',
id: 1, id: 1,
params: { params: {
userId: leantimeUserId userId: session.user.id
} }
}) })
}); });
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.ok) {
if (response.status === 429) { throw new Error('Failed to fetch status labels from Leantime');
const retryAfter = response.headers.get('retry-after') || '60';
return NextResponse.json(
{ error: "Rate limit exceeded. Please try again later." },
{
status: 429,
headers: {
'Retry-After': retryAfter
}
}
);
}
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 });
}
throw new Error(`Leantime API returned ${response.status}: ${responseText}`);
} }
let data; const data = await response.json();
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) { if (!data.result) {
console.log('No result in Leantime response');
return NextResponse.json({ projects: [] }); return NextResponse.json({ projects: [] });
} }
// Transform the response into a more structured format while maintaining project grouping // Transform the response into our desired format
const transformedProjects = Object.entries(data.result as Record<string, Record<string, any>>).map(([projectId, labels]) => { const projects: Project[] = Object.entries(data.result).map(([projectId, statusLabels]: [string, any]) => {
// Convert the labels object to an array and sort by sortKey const labels = Object.entries(statusLabels).map(([_, label]: [string, any]) => ({
const sortedLabels = Object.entries(labels).map(([id, label]) => ({
id,
name: label.name, name: label.name,
statusType: label.statusType,
class: label.class, class: label.class,
sortKey: Number(label.sortKey) || 0, statusType: label.statusType,
kanbanCol: label.kanbanCol kanbanCol: label.kanbanCol,
})).sort((a, b) => a.sortKey - b.sortKey); sortKey: parseInt(label.sortKey)
}));
// Sort labels by sortKey
labels.sort((a, b) => a.sortKey - b.sortKey);
return { return {
projectId, projectId,
labels: sortedLabels labels
}; };
}); });
// Sort projects by ID for consistency
transformedProjects.sort((a, b) => a.projectId.localeCompare(b.projectId));
// Cache the transformed data // Cache the transformed data
statusLabelsCache.set(leantimeUserId, { statusLabelsCache.set(leantimeUserId, {
data: transformedProjects, data: projects,
timestamp: Date.now() timestamp: Date.now()
}); });
return NextResponse.json({ projects: transformedProjects }); return NextResponse.json({ projects });
} catch (error) { } catch (error) {
console.error('Detailed error in status labels fetch:', error); console.error('Error fetching status labels:', error);
return NextResponse.json( return NextResponse.json(
{ { error: "Failed to fetch status labels" },
error: "Failed to fetch status labels",
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 } { status: 500 }
); );
} }

View File

@ -1,208 +1,130 @@
"use client"; "use client";
import { useEffect, useState, useCallback } from "react"; import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { RefreshCw, ChevronDown, Filter } from "lucide-react"; import { RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
interface Task { interface StatusLabel {
id: string; name: string;
headline: string; class: string;
projectName: string; statusType: string;
dueDate: string; kanbanCol: boolean | string;
status: string; sortKey: number;
details?: string;
} }
interface TaskGroup { interface Project {
name: string; projectId: string;
count: number; labels: StatusLabel[];
tasks: Task[];
} }
export function Flow() { export function Flow() {
const [taskGroups, setTaskGroups] = useState<TaskGroup[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false); const [refreshing, setRefreshing] = useState(false);
const [retryTimeout, setRetryTimeout] = useState<NodeJS.Timeout | null>(null); const [retryTimeout, setRetryTimeout] = useState<NodeJS.Timeout | null>(null);
const router = useRouter();
const { data: session } = useSession();
const fetchTasks = useCallback(async (isRefresh = false, retryCount = 0) => { const fetchStatusLabels = async (isRefresh = false) => {
try { try {
if (isRefresh) { if (isRefresh) {
setRefreshing(true); setRefreshing(true);
} }
const response = await fetch('/api/leantime/status-labels');
if (retryTimeout) {
clearTimeout(retryTimeout);
setRetryTimeout(null);
}
const response = await fetch('/api/leantime/tasks', {
cache: 'no-store',
next: { revalidate: 0 },
});
if (response.status === 401) {
setError('Session expired. Please sign in again.');
return;
}
if (response.status === 429) { if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After'); const retryAfter = parseInt(response.headers.get('retry-after') || '60');
const waitTime = retryAfter ? parseInt(retryAfter, 10) * 1000 : Math.min(1000 * Math.pow(2, retryCount), 60000); const timeout = setTimeout(() => fetchStatusLabels(), retryAfter * 1000);
setError(`Rate limit exceeded. Retrying in ${Math.round(waitTime / 1000)} seconds...`);
const timeout = setTimeout(() => {
fetchTasks(isRefresh, retryCount + 1);
}, waitTime);
setRetryTimeout(timeout); setRetryTimeout(timeout);
setError(`Rate limit exceeded. Retrying in ${retryAfter} seconds...`);
return; return;
} }
if (!response.ok) { if (!response.ok) {
throw new Error('Failed to fetch tasks'); throw new Error('Failed to fetch status labels');
} }
const data = await response.json(); const data = await response.json();
setProjects(data.projects || []);
// Group tasks by status
const groups: { [key: string]: Task[] } = {};
data.tasks.forEach((task: Task) => {
const status = task.status || 'No Status';
if (!groups[status]) {
groups[status] = [];
}
groups[status].push(task);
});
// Convert to array format with counts
const formattedGroups = Object.entries(groups).map(([name, tasks]) => ({
name,
count: tasks.length,
tasks
}));
setTaskGroups(formattedGroups);
setError(null); setError(null);
} catch (err) { } catch (err) {
console.error('Error fetching tasks:', err); console.error('Error fetching status labels:', err);
setError(err instanceof Error ? err.message : 'Failed to fetch tasks'); setError('Failed to fetch status labels');
} finally { } finally {
setLoading(false); setLoading(false);
setRefreshing(false); setRefreshing(false);
} }
}, [retryTimeout]); };
useEffect(() => { useEffect(() => {
if (session) { fetchStatusLabels();
fetchTasks(); return () => {
const interval = setInterval(() => fetchTasks(), 300000); if (retryTimeout) {
return () => { clearTimeout(retryTimeout);
clearInterval(interval); }
if (retryTimeout) { };
clearTimeout(retryTimeout); }, []);
}
}; const getStatusClass = (className: string) => {
switch (className) {
case 'label-info':
case 'label-blue':
return 'text-blue-600';
case 'label-warning':
return 'text-yellow-600';
case 'label-success':
return 'text-green-600';
case 'label-dark-green':
return 'text-emerald-600';
case 'label-important':
return 'text-red-600';
case 'label-default':
return 'text-gray-600';
default:
return 'text-gray-600';
} }
}, [session, fetchTasks, retryTimeout]); };
return ( return (
<Card <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
className="transition-transform duration-500 ease-in-out transform hover:scale-105 cursor-pointer bg-white/50 backdrop-blur-sm h-full"
onClick={() => router.push('/flow')}
>
<CardHeader className="flex flex-row items-center justify-between pb-2"> <CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-lg font-semibold flex items-center gap-2"> <CardTitle className="text-lg font-medium">Flow</CardTitle>
📋 My ToDos <Button
</CardTitle> variant="ghost"
<div className="flex items-center gap-2"> size="icon"
<Button onClick={() => fetchStatusLabels(true)}
variant="ghost" disabled={refreshing || !!retryTimeout}
size="icon" className={refreshing ? 'animate-spin' : ''}
onClick={(e) => { >
e.stopPropagation(); <RefreshCw className="h-4 w-4" />
fetchTasks(true); </Button>
}}
disabled={refreshing || !!retryTimeout}
className={refreshing ? 'animate-spin' : ''}
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
</CardHeader> </CardHeader>
<CardContent className="p-4"> <CardContent>
{loading && <p className="text-center text-muted-foreground">Loading tasks...</p>} {loading ? (
{error && ( <div className="flex items-center justify-center py-4">
<div className="text-center"> <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
<p className="text-red-500">Error: {error}</p>
{!retryTimeout && (
<Button
variant="outline"
onClick={(e) => {
e.stopPropagation();
fetchTasks(true);
}}
className="mt-2"
>
Try Again
</Button>
)}
</div> </div>
)} ) : error ? (
{!loading && !error && ( <div className="text-center text-sm text-red-500">{error}</div>
) : projects.length === 0 ? (
<div className="text-center text-sm text-gray-500">No status labels found</div>
) : (
<div className="space-y-4"> <div className="space-y-4">
<div className="flex items-center justify-between text-sm text-gray-500"> {projects.map((project) => (
<Button variant="ghost" size="sm" className="text-gray-500"> <div key={project.projectId} className="space-y-2">
<Filter className="h-4 w-4 mr-2" /> <h3 className="font-medium text-sm">Project {project.projectId}</h3>
Group By: Due Date <div className="space-y-1">
</Button> {project.labels.map((label, index) => (
<Button variant="ghost" size="sm" className="text-gray-500"> <div key={index} className="flex justify-between items-center text-sm">
Filters <span>{label.name}</span>
</Button> <span className={getStatusClass(label.class)}>
</div> {label.statusType}
{taskGroups.length === 0 ? ( </span>
<p className="text-center text-muted-foreground">No tasks found</p> </div>
) : ( ))}
taskGroups.map((group) => (
<div key={group.name} className="space-y-2">
<div className="flex items-center gap-2 text-gray-700">
<ChevronDown className="h-4 w-4" />
{group.name === 'overdue' && <span className="text-red-500">🔥</span>}
<h3 className="font-medium">
{group.name.charAt(0).toUpperCase() + group.name.slice(1)} ({group.count})
</h3>
</div>
<div className="space-y-2 pl-6">
{group.tasks.map((task) => (
<div
key={task.id}
className="relative pl-4 py-2 hover:bg-gray-50 rounded-lg transition-colors"
>
{group.name === 'overdue' && (
<div className="absolute left-0 top-0 bottom-0 w-1 bg-red-500 rounded-full" />
)}
<div className="space-y-1">
<div className="font-medium text-gray-700">{task.projectName}</div>
<div className="text-sm">
{task.headline}
{task.details && (
<span className="text-gray-500"> // {task.details}</span>
)}
</div>
<div className="flex items-center text-sm text-gray-500">
<span>🗓 {new Date(task.dueDate).toLocaleDateString()}</span>
</div>
</div>
</div>
))}
</div>
</div> </div>
)) </div>
)} ))}
</div> </div>
)} )}
</CardContent> </CardContent>