working leantime widget 14
This commit is contained in:
parent
cbc14d1477
commit
c5045905c4
@ -2,23 +2,18 @@ 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 {
|
interface Task {
|
||||||
name: string;
|
id: string;
|
||||||
class: string;
|
headline: string;
|
||||||
statusType: string;
|
projectName: string;
|
||||||
kanbanCol: boolean | string;
|
status: string;
|
||||||
sortKey: number;
|
dueDate: string | null;
|
||||||
|
details?: string;
|
||||||
|
milestone?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Project {
|
// Cache for user IDs
|
||||||
projectId: string;
|
|
||||||
labels: StatusLabel[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 CACHE_TTL = 60000; // 1 minute cache TTL
|
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
@ -28,7 +23,7 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('Fetching status labels for user:', session.user.id);
|
console.log('Fetching tasks for user:', session.user.id);
|
||||||
console.log('Using LEANTIME_TOKEN:', process.env.LEANTIME_TOKEN ? 'Present' : 'Missing');
|
console.log('Using LEANTIME_TOKEN:', process.env.LEANTIME_TOKEN ? 'Present' : 'Missing');
|
||||||
|
|
||||||
// Check cache first
|
// Check cache first
|
||||||
@ -85,13 +80,7 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check status labels cache
|
// Fetch all tasks assigned to the user
|
||||||
const cachedLabels = statusLabelsCache.get(leantimeUserId);
|
|
||||||
if (cachedLabels && (Date.now() - cachedLabels.timestamp) < CACHE_TTL) {
|
|
||||||
return NextResponse.json({ projects: cachedLabels.data });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now fetch the status labels using leantimeUserId
|
|
||||||
const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
|
const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@ -100,57 +89,80 @@ 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.Tickets.Tickets.getAllByUserId',
|
||||||
id: 1,
|
id: 1,
|
||||||
params: {
|
params: {
|
||||||
userId: leantimeUserId // Use the Leantime user ID here
|
userId: leantimeUserId,
|
||||||
|
status: "all",
|
||||||
|
limit: 100
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorData = await response.json();
|
const errorData = await response.json();
|
||||||
console.error('Status labels fetch failed:', errorData);
|
console.error('Tasks fetch failed:', errorData);
|
||||||
throw new Error(`Failed to fetch status labels: ${errorData.error || 'Unknown error'}`);
|
throw new Error(`Failed to fetch tasks: ${errorData.error || 'Unknown error'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
console.log('Status labels response:', data);
|
console.log('Tasks response:', data);
|
||||||
|
|
||||||
if (!data.result) {
|
if (!data.result) {
|
||||||
return NextResponse.json({ projects: [] });
|
return NextResponse.json({ tasks: [] });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform the response into our desired format
|
// Get project details to include project names
|
||||||
const projects: Project[] = Object.entries(data.result).map(([projectId, statusLabels]: [string, any]) => {
|
const projectsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
|
||||||
const labels = Object.entries(statusLabels).map(([_, label]: [string, any]) => ({
|
method: 'POST',
|
||||||
name: label.name,
|
headers: {
|
||||||
class: label.class,
|
'Content-Type': 'application/json',
|
||||||
statusType: label.statusType,
|
'X-API-Key': process.env.LEANTIME_TOKEN || '',
|
||||||
kanbanCol: label.kanbanCol,
|
},
|
||||||
sortKey: Number(label.sortKey) || 0
|
body: JSON.stringify({
|
||||||
}));
|
jsonrpc: '2.0',
|
||||||
|
method: 'leantime.rpc.Projects.getAll',
|
||||||
|
id: 1
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
// Sort labels by sortKey
|
if (!projectsResponse.ok) {
|
||||||
labels.sort((a, b) => a.sortKey - b.sortKey);
|
throw new Error('Failed to fetch projects');
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectsData = await projectsResponse.json();
|
||||||
|
const projectsMap = new Map(
|
||||||
|
projectsData.result.map((project: any) => [project.id, project.name])
|
||||||
|
);
|
||||||
|
|
||||||
|
// Transform and categorize the tasks
|
||||||
|
const tasks = data.result.map((task: any) => {
|
||||||
|
const dueDate = task.dateToFinish ? new Date(task.dateToFinish * 1000) : null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
projectId,
|
id: task.id,
|
||||||
labels
|
headline: task.headline,
|
||||||
|
projectName: projectsMap.get(task.projectId) || `Project ${task.projectId}`,
|
||||||
|
status: task.status,
|
||||||
|
dueDate: dueDate ? dueDate.toISOString() : null,
|
||||||
|
details: task.description,
|
||||||
|
milestone: task.milestoneName
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cache the transformed data
|
// Sort tasks by due date
|
||||||
statusLabelsCache.set(leantimeUserId, {
|
tasks.sort((a: Task, b: Task) => {
|
||||||
data: projects,
|
if (!a.dueDate && !b.dueDate) return 0;
|
||||||
timestamp: Date.now()
|
if (!a.dueDate) return 1;
|
||||||
|
if (!b.dueDate) return -1;
|
||||||
|
return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ projects });
|
return NextResponse.json({ tasks });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching status labels:', error);
|
console.error('Error fetching tasks:', error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: error instanceof Error ? error.message : "Failed to fetch status labels" },
|
{ error: error instanceof Error ? error.message : "Failed to fetch tasks" },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,28 +4,26 @@ 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 } from "lucide-react";
|
import { RefreshCw } from "lucide-react";
|
||||||
|
import { formatDate } from "@/lib/utils";
|
||||||
|
|
||||||
interface StatusLabel {
|
interface Task {
|
||||||
name: string;
|
id: string;
|
||||||
class: string;
|
headline: string;
|
||||||
statusType: string;
|
projectName: string;
|
||||||
kanbanCol: boolean | string;
|
status: string;
|
||||||
sortKey: number;
|
dueDate: string | null;
|
||||||
}
|
details?: string;
|
||||||
|
milestone?: string;
|
||||||
interface Project {
|
|
||||||
projectId: string;
|
|
||||||
labels: StatusLabel[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Flow() {
|
export function Flow() {
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const [tasks, setTasks] = useState<Task[]>([]);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
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 fetchStatusLabels = async (isRefresh = false) => {
|
const fetchTasks = async (isRefresh = false) => {
|
||||||
try {
|
try {
|
||||||
if (isRefresh) {
|
if (isRefresh) {
|
||||||
setRefreshing(true);
|
setRefreshing(true);
|
||||||
@ -34,22 +32,22 @@ export function Flow() {
|
|||||||
|
|
||||||
if (response.status === 429) {
|
if (response.status === 429) {
|
||||||
const retryAfter = parseInt(response.headers.get('retry-after') || '60');
|
const retryAfter = parseInt(response.headers.get('retry-after') || '60');
|
||||||
const timeout = setTimeout(() => fetchStatusLabels(), retryAfter * 1000);
|
const timeout = setTimeout(() => fetchTasks(), retryAfter * 1000);
|
||||||
setRetryTimeout(timeout);
|
setRetryTimeout(timeout);
|
||||||
setError(`Rate limit exceeded. Retrying in ${retryAfter} seconds...`);
|
setError(`Rate limit exceeded. Retrying in ${retryAfter} seconds...`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to fetch status labels');
|
throw new Error('Failed to fetch tasks');
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setProjects(data.projects || []);
|
setTasks(data.tasks || []);
|
||||||
setError(null);
|
setError(null);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching status labels:', err);
|
console.error('Error fetching tasks:', err);
|
||||||
setError('Failed to fetch status labels');
|
setError('Failed to fetch tasks');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setRefreshing(false);
|
setRefreshing(false);
|
||||||
@ -57,7 +55,7 @@ export function Flow() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchStatusLabels();
|
fetchTasks();
|
||||||
return () => {
|
return () => {
|
||||||
if (retryTimeout) {
|
if (retryTimeout) {
|
||||||
clearTimeout(retryTimeout);
|
clearTimeout(retryTimeout);
|
||||||
@ -65,26 +63,34 @@ export function Flow() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const getStatusClass = (className: string) => {
|
const getStatusColor = (status: string) => {
|
||||||
switch (className) {
|
switch (status.toLowerCase()) {
|
||||||
case 'label-info':
|
case 'new':
|
||||||
case 'label-blue':
|
|
||||||
return 'text-blue-600';
|
return 'text-blue-600';
|
||||||
case 'label-warning':
|
case 'blocked':
|
||||||
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';
|
return 'text-red-600';
|
||||||
case 'label-default':
|
case 'in progress':
|
||||||
return 'text-gray-600';
|
case 'inprogress':
|
||||||
|
return 'text-orange-600';
|
||||||
|
case 'done':
|
||||||
|
case 'archived':
|
||||||
|
return 'text-green-600';
|
||||||
|
case 'waiting for approval':
|
||||||
|
return 'text-yellow-600';
|
||||||
default:
|
default:
|
||||||
return 'text-gray-600';
|
return 'text-gray-600';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Group tasks by project
|
||||||
|
const groupedTasks = tasks.reduce((acc, task) => {
|
||||||
|
if (!acc[task.projectName]) {
|
||||||
|
acc[task.projectName] = [];
|
||||||
|
}
|
||||||
|
acc[task.projectName].push(task);
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, Task[]>);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
|
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
|
||||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||||
@ -92,7 +98,7 @@ export function Flow() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => fetchStatusLabels(true)}
|
onClick={() => fetchTasks(true)}
|
||||||
disabled={refreshing || !!retryTimeout}
|
disabled={refreshing || !!retryTimeout}
|
||||||
className={refreshing ? 'animate-spin' : ''}
|
className={refreshing ? 'animate-spin' : ''}
|
||||||
>
|
>
|
||||||
@ -106,20 +112,32 @@ export function Flow() {
|
|||||||
</div>
|
</div>
|
||||||
) : error ? (
|
) : error ? (
|
||||||
<div className="text-center text-sm text-red-500">{error}</div>
|
<div className="text-center text-sm text-red-500">{error}</div>
|
||||||
) : projects.length === 0 ? (
|
) : Object.keys(groupedTasks).length === 0 ? (
|
||||||
<div className="text-center text-sm text-gray-500">No status labels found</div>
|
<div className="text-center text-sm text-gray-500">No tasks found</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-6">
|
||||||
{projects.map((project) => (
|
{Object.entries(groupedTasks).map(([projectName, projectTasks]) => (
|
||||||
<div key={project.projectId} className="space-y-2">
|
<div key={projectName} className="space-y-2">
|
||||||
<h3 className="font-medium text-sm">Project {project.projectId}</h3>
|
<h3 className="font-medium text-sm">{projectName}</h3>
|
||||||
<div className="space-y-1">
|
<div className="space-y-2">
|
||||||
{project.labels.map((label, index) => (
|
{projectTasks.map((task) => (
|
||||||
<div key={index} className="flex justify-between items-center text-sm">
|
<div key={task.id} className="flex justify-between items-start text-sm border-b border-gray-100 pb-2">
|
||||||
<span>{label.name}</span>
|
<div className="flex-1">
|
||||||
<span className={getStatusClass(label.class)}>
|
<div className="font-medium">{task.headline}</div>
|
||||||
{label.statusType}
|
{task.milestone && (
|
||||||
</span>
|
<div className="text-xs text-gray-500 mt-1">
|
||||||
|
{task.milestone}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{task.dueDate && (
|
||||||
|
<div className="text-xs text-gray-500 mt-1">
|
||||||
|
{formatDate(task.dueDate)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className={`ml-4 ${getStatusColor(task.status)}`}>
|
||||||
|
{task.status.toUpperCase()}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@ -130,4 +148,4 @@ export function Flow() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
19
lib/utils.ts
19
lib/utils.ts
@ -1,7 +1,20 @@
|
|||||||
import { type ClassValue, clsx } from "clsx"
|
import { type ClassValue, clsx } from "clsx";
|
||||||
import { twMerge } from "tailwind-merge"
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs))
|
return twMerge(clsx(inputs));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDate(dateString: string): string {
|
||||||
|
try {
|
||||||
|
const date = new Date(dateString);
|
||||||
|
return new Intl.DateTimeFormat('en-US', {
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
year: 'numeric'
|
||||||
|
}).format(date);
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user