working leantime widget 31
This commit is contained in:
parent
fcfac2c56f
commit
870c5c06f2
@ -1,3 +1,4 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
import { getServerSession } from "next-auth/next";
|
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";
|
||||||
@ -5,14 +6,12 @@ import { NextResponse } from "next/server";
|
|||||||
interface StatusLabel {
|
interface StatusLabel {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
class: string;
|
|
||||||
statusType: string;
|
statusType: string;
|
||||||
kanbanCol: boolean | string;
|
class: string;
|
||||||
sortKey: number | string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Project {
|
interface Project {
|
||||||
id: number;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
labels: StatusLabel[];
|
labels: StatusLabel[];
|
||||||
}
|
}
|
||||||
@ -20,52 +19,93 @@ interface Project {
|
|||||||
// Cache for user IDs to avoid repeated lookups
|
// Cache for user IDs to avoid repeated lookups
|
||||||
const userCache = new Map<string, number>();
|
const userCache = new Map<string, number>();
|
||||||
|
|
||||||
export async function GET() {
|
async function getLeantimeUserId(email: string): Promise<number | null> {
|
||||||
|
// Check cache first
|
||||||
|
if (userCache.has(email)) {
|
||||||
|
return userCache.get(email)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
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({
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
method: 'leantime.rpc.users.getAll',
|
||||||
|
id: 1,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch users from Leantime');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
const user = data.result.find((u: any) => u.email === email);
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
// Cache the user ID
|
||||||
|
userCache.set(email, user.id);
|
||||||
|
// Clear cache after 5 minutes
|
||||||
|
setTimeout(() => userCache.delete(email), 5 * 60 * 1000);
|
||||||
|
return user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting Leantime user ID:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
if (!session?.user?.email) {
|
if (!session || !session.user?.email) {
|
||||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check cache first
|
// Get Leantime user ID
|
||||||
let leantimeUserId = userCache.get(session.user.email);
|
const leantimeUserId = await getLeantimeUserId(session.user.email);
|
||||||
|
|
||||||
// If not in cache, fetch from API
|
|
||||||
if (!leantimeUserId) {
|
if (!leantimeUserId) {
|
||||||
const userResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
|
return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 });
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-API-Key': process.env.LEANTIME_TOKEN || '',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
jsonrpc: '2.0',
|
|
||||||
method: 'leantime.rpc.Users.Users.getUserByEmail',
|
|
||||||
id: 1,
|
|
||||||
params: {
|
|
||||||
email: session.user.email
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!userResponse.ok) {
|
|
||||||
throw new Error('Failed to fetch user from Leantime');
|
|
||||||
}
|
|
||||||
|
|
||||||
const userData = await userResponse.json();
|
|
||||||
|
|
||||||
if (!userData.result || !userData.result.id) {
|
|
||||||
return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 });
|
|
||||||
}
|
|
||||||
|
|
||||||
leantimeUserId = userData.result.id;
|
|
||||||
// Cache the user ID for 5 minutes
|
|
||||||
userCache.set(session.user.email, leantimeUserId);
|
|
||||||
setTimeout(() => userCache.delete(session.user.email!), 5 * 60 * 1000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get projects
|
// Get 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.getAllByUserId',
|
||||||
|
id: 1,
|
||||||
|
params: {
|
||||||
|
userId: leantimeUserId,
|
||||||
|
status: "all",
|
||||||
|
limit: 100
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch tasks from Leantime');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!data.result) {
|
||||||
|
return NextResponse.json({ projects: [] });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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: {
|
||||||
@ -85,47 +125,60 @@ export async function GET() {
|
|||||||
|
|
||||||
const projectsData = await projectsResponse.json();
|
const projectsData = await projectsResponse.json();
|
||||||
|
|
||||||
// Get status labels
|
// Create a map of projects with their tasks grouped by status
|
||||||
const labelsResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', {
|
const projectMap = new Map<string, Project>();
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
data.result.forEach((task: any) => {
|
||||||
'Content-Type': 'application/json',
|
const project = projectsData.result.find((p: any) => p.id === task.projectId);
|
||||||
'X-API-Key': process.env.LEANTIME_TOKEN || '',
|
const projectName = project ? project.name : `Project ${task.projectId}`;
|
||||||
},
|
const projectId = task.projectId.toString();
|
||||||
body: JSON.stringify({
|
|
||||||
jsonrpc: '2.0',
|
if (!projectMap.has(projectId)) {
|
||||||
method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId',
|
projectMap.set(projectId, {
|
||||||
id: 1,
|
id: projectId,
|
||||||
params: {
|
name: projectName,
|
||||||
userId: leantimeUserId
|
labels: []
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentProject = projectMap.get(projectId)!;
|
||||||
|
|
||||||
|
// Check if this status label already exists for this project
|
||||||
|
const existingLabel = currentProject.labels.find(label => label.name === task.status);
|
||||||
|
|
||||||
|
if (!existingLabel) {
|
||||||
|
let statusType;
|
||||||
|
let statusClass;
|
||||||
|
|
||||||
|
switch (task.status.toLowerCase()) {
|
||||||
|
case 'new':
|
||||||
|
statusType = 'NEW';
|
||||||
|
statusClass = 'bg-blue-100 text-blue-800';
|
||||||
|
break;
|
||||||
|
case 'in_progress':
|
||||||
|
statusType = 'INPROGRESS';
|
||||||
|
statusClass = 'bg-yellow-100 text-yellow-800';
|
||||||
|
break;
|
||||||
|
case 'done':
|
||||||
|
statusType = 'DONE';
|
||||||
|
statusClass = 'bg-green-100 text-green-800';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
statusType = 'NONE';
|
||||||
|
statusClass = 'bg-gray-100 text-gray-800';
|
||||||
}
|
}
|
||||||
})
|
|
||||||
|
currentProject.labels.push({
|
||||||
|
id: `${projectId}-${task.status}`,
|
||||||
|
name: task.status,
|
||||||
|
statusType: statusType,
|
||||||
|
class: statusClass
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!labelsResponse.ok) {
|
// Convert the map to an array and sort projects by name
|
||||||
throw new Error('Failed to fetch status labels from Leantime');
|
const projects = Array.from(projectMap.values()).sort((a, b) => a.name.localeCompare(b.name));
|
||||||
}
|
|
||||||
|
|
||||||
const labelsData = await labelsResponse.json();
|
|
||||||
|
|
||||||
// Transform the data into the required format
|
|
||||||
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 {
|
|
||||||
id: project.id,
|
|
||||||
name: project.name,
|
|
||||||
labels
|
|
||||||
};
|
|
||||||
}).filter((project: Project) => project.labels.length > 0);
|
|
||||||
|
|
||||||
return NextResponse.json({ projects });
|
return NextResponse.json({ projects });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@ -5,51 +5,55 @@ 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";
|
||||||
|
|
||||||
interface Task {
|
interface StatusLabel {
|
||||||
id: string;
|
id: string;
|
||||||
headline: string;
|
name: string;
|
||||||
projectName: string;
|
statusType: string;
|
||||||
status: string;
|
class: string;
|
||||||
dueDate: string | null;
|
}
|
||||||
milestone: string | null;
|
|
||||||
|
interface Project {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
labels: StatusLabel[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Flow() {
|
export function Flow() {
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
const [projects, setProjects] = useState<Project[]>([]);
|
||||||
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 fetchTasks = async (isRefresh = false) => {
|
const fetchProjects = 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');
|
||||||
|
|
||||||
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(() => fetchTasks(), retryAfter * 1000);
|
const timeout = setTimeout(() => fetchProjects(), 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 tasks');
|
throw new Error('Failed to fetch projects');
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (data.tasks && Array.isArray(data.tasks)) {
|
if (data.projects && Array.isArray(data.projects)) {
|
||||||
setTasks(data.tasks);
|
setProjects(data.projects);
|
||||||
} else {
|
} else {
|
||||||
setTasks([]);
|
setProjects([]);
|
||||||
}
|
}
|
||||||
setError(null);
|
setError(null);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching tasks:', err);
|
console.error('Error fetching projects:', err);
|
||||||
setError('Failed to fetch tasks');
|
setError('Failed to fetch projects');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setRefreshing(false);
|
setRefreshing(false);
|
||||||
@ -57,7 +61,7 @@ export function Flow() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchTasks();
|
fetchProjects();
|
||||||
return () => {
|
return () => {
|
||||||
if (retryTimeout) {
|
if (retryTimeout) {
|
||||||
clearTimeout(retryTimeout);
|
clearTimeout(retryTimeout);
|
||||||
@ -65,29 +69,6 @@ export function Flow() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const getStatusClass = (status: string): string => {
|
|
||||||
switch (status.toLowerCase()) {
|
|
||||||
case 'new':
|
|
||||||
return 'bg-blue-100 text-blue-800';
|
|
||||||
case 'in_progress':
|
|
||||||
return 'bg-yellow-100 text-yellow-800';
|
|
||||||
case 'done':
|
|
||||||
return 'bg-green-100 text-green-800';
|
|
||||||
default:
|
|
||||||
return 'bg-gray-100 text-gray-800';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDate = (dateString: string | null): string => {
|
|
||||||
if (!dateString) return 'No due date';
|
|
||||||
const date = new Date(dateString);
|
|
||||||
return date.toLocaleDateString('en-US', {
|
|
||||||
month: '2-digit',
|
|
||||||
day: '2-digit',
|
|
||||||
year: 'numeric'
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
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">
|
||||||
@ -95,7 +76,7 @@ export function Flow() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => fetchTasks(true)}
|
onClick={() => fetchProjects(true)}
|
||||||
disabled={refreshing || !!retryTimeout}
|
disabled={refreshing || !!retryTimeout}
|
||||||
className={refreshing ? 'animate-spin' : ''}
|
className={refreshing ? 'animate-spin' : ''}
|
||||||
>
|
>
|
||||||
@ -109,35 +90,27 @@ 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>
|
||||||
) : tasks.length === 0 ? (
|
) : projects.length === 0 ? (
|
||||||
<div className="text-center text-sm text-gray-500">No tasks found</div>
|
<div className="text-center text-sm text-gray-500">No projects found</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{tasks.map((task) => (
|
{projects.map((project) => (
|
||||||
<div key={task.id} className="border rounded-lg p-4 bg-white shadow-sm">
|
<div key={project.id} className="space-y-2">
|
||||||
<div className="flex items-start justify-between">
|
<h3 className="font-medium text-gray-900">{project.name}</h3>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<div className="text-sm font-medium text-gray-600">{task.projectName}</div>
|
{project.labels.map((label) => (
|
||||||
<div className="text-base font-medium text-blue-600 hover:text-blue-800">
|
<div
|
||||||
{task.headline}
|
key={label.id}
|
||||||
|
className="flex items-center justify-between p-2 rounded-lg bg-white shadow-sm"
|
||||||
|
>
|
||||||
|
<span className="text-sm font-medium text-gray-700">
|
||||||
|
{label.name}
|
||||||
|
</span>
|
||||||
|
<span className={`px-2 py-1 rounded-full text-xs font-medium ${label.class}`}>
|
||||||
|
{label.statusType}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center space-x-3 text-sm text-gray-500">
|
))}
|
||||||
<div className="flex items-center space-x-1">
|
|
||||||
<span className="w-4 h-4">🗓️</span>
|
|
||||||
<span>{formatDate(task.dueDate)}</span>
|
|
||||||
</div>
|
|
||||||
{task.milestone && (
|
|
||||||
<div className="flex items-center space-x-1">
|
|
||||||
<span className="px-2 py-1 rounded-full bg-gray-100">
|
|
||||||
{task.milestone}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusClass(task.status)}`}>
|
|
||||||
{task.status.toUpperCase()}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user