working leantime widget

This commit is contained in:
Alma 2025-04-12 12:29:34 +02:00
parent 51686c1790
commit 7c8f64a716
2 changed files with 72 additions and 60 deletions

View File

@ -0,0 +1,47 @@
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { NextResponse } from "next/server";
export async function GET() {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
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: session.user.id,
}
})
});
if (!response.ok) {
throw new Error('Failed to fetch status labels from Leantime');
}
const data = await response.json();
if (!data.result) {
return NextResponse.json({ statusLabels: [] });
}
return NextResponse.json({ statusLabels: data.result });
} catch (error) {
console.error('Error fetching status labels:', error);
return NextResponse.json(
{ error: "Failed to fetch status labels" },
{ status: 500 }
);
}
}

View File

@ -3,33 +3,31 @@
import { useEffect, useState } 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, Calendar, CheckCircle2, Clock } from "lucide-react"; import { RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
interface Task { interface StatusLabel {
id: string; id: string;
headline: string; name: string;
description: string; projectId: string;
status: string; projectName: string;
dueDate: string;
priority: number;
} }
export function Flow() { export function Flow() {
const [tasks, setTasks] = useState<Task[]>([]); const [statusLabels, setStatusLabels] = useState<StatusLabel[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false); const [refreshing, setRefreshing] = useState(false);
const router = useRouter(); const router = useRouter();
const { data: session } = useSession(); const { data: session } = useSession();
const fetchTasks = async (isRefresh = false) => { const fetchStatusLabels = async (isRefresh = false) => {
try { try {
if (isRefresh) { if (isRefresh) {
setRefreshing(true); setRefreshing(true);
} }
const response = await fetch('/api/leantime/tasks', { const response = await fetch('/api/leantime/status-labels', {
cache: 'no-store', cache: 'no-store',
next: { revalidate: 0 }, next: { revalidate: 0 },
}); });
@ -41,15 +39,15 @@ export function Flow() {
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch tasks'); throw new Error(errorData.error || 'Failed to fetch status labels');
} }
const data = await response.json(); const data = await response.json();
setTasks(data.tasks); setStatusLabels(data.statusLabels);
setError(null); setError(null);
} catch (err) { } catch (err) {
console.error('Error fetching tasks:', err); console.error('Error fetching status labels:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch tasks'; const errorMessage = err instanceof Error ? err.message : 'Failed to fetch status labels';
setError(errorMessage); setError(errorMessage);
} finally { } finally {
setLoading(false); setLoading(false);
@ -59,50 +57,26 @@ export function Flow() {
useEffect(() => { useEffect(() => {
if (session) { if (session) {
fetchTasks(); fetchStatusLabels();
// Set up polling every 5 minutes // Set up polling every 5 minutes
const interval = setInterval(() => fetchTasks(), 300000); const interval = setInterval(() => fetchStatusLabels(), 300000);
return () => clearInterval(interval); return () => clearInterval(interval);
} }
}, [session]); }, [session]);
const getPriorityColor = (priority: number) => {
switch (priority) {
case 1:
return 'text-red-500';
case 2:
return 'text-yellow-500';
case 3:
return 'text-green-500';
default:
return 'text-gray-500';
}
};
const getStatusIcon = (status: string) => {
switch (status.toLowerCase()) {
case 'done':
return <CheckCircle2 className="h-4 w-4 text-green-500" />;
case 'in progress':
return <Clock className="h-4 w-4 text-yellow-500" />;
default:
return <Calendar className="h-4 w-4 text-blue-500" />;
}
};
return ( return (
<Card <Card
className="transition-transform duration-500 ease-in-out transform hover:scale-105 cursor-pointer bg-white/50 backdrop-blur-sm h-full" 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')} 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">My Tasks</CardTitle> <CardTitle className="text-lg font-semibold">Flow</CardTitle>
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
fetchTasks(true); fetchStatusLabels(true);
}} }}
disabled={refreshing} disabled={refreshing}
className={refreshing ? 'animate-spin' : ''} className={refreshing ? 'animate-spin' : ''}
@ -111,7 +85,7 @@ export function Flow() {
</Button> </Button>
</CardHeader> </CardHeader>
<CardContent className="p-4"> <CardContent className="p-4">
{loading && <p className="text-center text-muted-foreground">Loading tasks...</p>} {loading && <p className="text-center text-muted-foreground">Loading status labels...</p>}
{error && ( {error && (
<div className="text-center"> <div className="text-center">
<p className="text-red-500">Error: {error}</p> <p className="text-red-500">Error: {error}</p>
@ -119,7 +93,7 @@ export function Flow() {
variant="outline" variant="outline"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
fetchTasks(true); fetchStatusLabels(true);
}} }}
className="mt-2" className="mt-2"
> >
@ -129,30 +103,21 @@ export function Flow() {
)} )}
{!loading && !error && ( {!loading && !error && (
<div className="space-y-2 max-h-[300px] overflow-y-auto"> <div className="space-y-2 max-h-[300px] overflow-y-auto">
{tasks.length === 0 ? ( {statusLabels.length === 0 ? (
<p className="text-center text-muted-foreground">No tasks found</p> <p className="text-center text-muted-foreground">No status labels found</p>
) : ( ) : (
tasks.map((task) => ( statusLabels.map((label) => (
<div <div
key={task.id} key={`${label.projectId}-${label.id}`}
className="flex items-start space-x-2 hover:bg-gray-50 p-2 rounded-lg transition-colors" className="flex items-start space-x-2 hover:bg-gray-50 p-2 rounded-lg transition-colors"
> >
<div className="flex-shrink-0">
{getStatusIcon(task.status)}
</div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-baseline justify-between"> <div className="flex items-baseline justify-between">
<p className="text-sm font-medium truncate">{task.headline}</p> <p className="text-sm font-medium truncate">{label.name}</p>
<span className={`text-xs ${getPriorityColor(task.priority)}`}> <span className="text-xs text-gray-500">
{task.priority === 1 ? 'High' : task.priority === 2 ? 'Medium' : 'Low'} {label.projectName}
</span> </span>
</div> </div>
<p className="text-xs text-gray-600 line-clamp-2">{task.description}</p>
{task.dueDate && (
<p className="text-xs text-gray-500 mt-1">
Due: {new Date(task.dueDate).toLocaleDateString()}
</p>
)}
</div> </div>
</div> </div>
)) ))