feat: implement team lead dashboard with data fetching and chart display

This commit is contained in:
2025-11-14 11:05:36 +01:00
parent 9b1f42c4ec
commit 38b9401b04
4 changed files with 241 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
// Force this API route to use Node.js runtime
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAllProjects } from "@/lib/queries/projects";
export async function GET(request) {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Only team leads can access dashboard data
if (session.user.role !== 'team_lead') {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
// Get all projects
const projects = getAllProjects();
// Filter completed projects (those with completion_date and fulfilled status)
const completedProjects = projects.filter(project =>
project.completion_date &&
project.wartosc_zlecenia &&
project.project_status === 'fulfilled'
);
// If no data, return sample data for demonstration
let chartData;
if (completedProjects.length === 0) {
chartData = [
{ month: 'Jan 2024', value: 50000, cumulative: 50000 },
{ month: 'Feb 2024', value: 75000, cumulative: 125000 },
{ month: 'Mar 2024', value: 60000, cumulative: 185000 },
{ month: 'Apr 2024', value: 80000, cumulative: 265000 },
{ month: 'May 2024', value: 95000, cumulative: 360000 },
{ month: 'Jun 2024', value: 70000, cumulative: 430000 },
{ month: 'Jul 2024', value: 85000, cumulative: 515000 },
{ month: 'Aug 2024', value: 90000, cumulative: 605000 },
{ month: 'Sep 2024', value: 78000, cumulative: 683000 },
{ month: 'Oct 2024', value: 92000, cumulative: 775000 },
{ month: 'Nov 2024', value: 88000, cumulative: 863000 },
{ month: 'Dec 2024', value: 95000, cumulative: 958000 }
];
} else {
// Group by month and calculate monthly totals first
const monthlyData = {};
// Sort projects by completion date
completedProjects.sort((a, b) => new Date(a.completion_date) - new Date(b.completion_date));
// First pass: calculate monthly totals
completedProjects.forEach(project => {
const date = new Date(project.completion_date);
const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
const monthName = date.toLocaleDateString('en-US', { year: 'numeric', month: 'short' });
if (!monthlyData[monthKey]) {
monthlyData[monthKey] = {
month: monthName,
value: 0
};
}
const projectValue = parseFloat(project.wartosc_zlecenia) || 0;
monthlyData[monthKey].value += projectValue;
});
// Second pass: calculate cumulative values
let cumulativeValue = 0;
const sortedMonths = Object.keys(monthlyData).sort((a, b) => a.localeCompare(b));
sortedMonths.forEach(monthKey => {
cumulativeValue += monthlyData[monthKey].value;
monthlyData[monthKey].cumulative = cumulativeValue;
});
// Convert to array
chartData = sortedMonths.map(monthKey => ({
month: monthlyData[monthKey].month,
value: Math.round(monthlyData[monthKey].value),
cumulative: Math.round(monthlyData[monthKey].cumulative)
}));
}
return NextResponse.json(chartData);
} catch (error) {
console.error('Dashboard API error:', error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}

134
src/app/dashboard/page.js Normal file
View File

@@ -0,0 +1,134 @@
"use client";
import { useState, useEffect } from "react";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
export default function TeamLeadsDashboard() {
const [chartData, setChartData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchDashboardData();
}, []);
const fetchDashboardData = async () => {
try {
const response = await fetch('/api/dashboard');
if (!response.ok) {
throw new Error('Failed to fetch dashboard data');
}
const data = await response.json();
setChartData(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const formatCurrency = (value) => {
return new Intl.NumberFormat('pl-PL', {
style: 'currency',
currency: 'PLN',
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(value);
};
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div className="bg-white dark:bg-gray-800 p-3 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg">
<p className="font-medium text-gray-900 dark:text-white">{`Month: ${label}`}</p>
<p className="text-blue-600 dark:text-blue-400">
{`Monthly Value: ${formatCurrency(payload[0].value)}`}
</p>
<p className="text-green-600 dark:text-green-400">
{`Cumulative: ${formatCurrency(payload[1].value)}`}
</p>
</div>
);
}
return null;
};
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-8">
Dashboard
</h1>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-6">
Project Completion Value Over Time
</h2>
{loading ? (
<div className="flex items-center justify-center h-64">
<div className="text-gray-500 dark:text-gray-400">Loading chart data...</div>
</div>
) : error ? (
<div className="flex items-center justify-center h-64">
<div className="text-red-500 dark:text-red-400">Error: {error}</div>
</div>
) : chartData.length === 0 ? (
<div className="flex items-center justify-center h-64">
<div className="text-gray-500 dark:text-gray-400">No completed projects data available</div>
</div>
) : (
<div className="h-96">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={chartData}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" className="opacity-30" />
<XAxis
dataKey="month"
className="text-gray-600 dark:text-gray-400"
fontSize={12}
/>
<YAxis
className="text-gray-600 dark:text-gray-400"
fontSize={12}
tickFormatter={(value) => `${(value / 1000).toFixed(0)}k`}
/>
<Tooltip content={<CustomTooltip />} />
<Legend />
<Line
type="monotone"
dataKey="cumulative"
stroke="#10b981"
strokeWidth={3}
name="Cumulative Value"
dot={{ fill: '#10b981', strokeWidth: 2, r: 4 }}
activeDot={{ r: 6, stroke: '#10b981', strokeWidth: 2 }}
/>
<Line
type="monotone"
dataKey="value"
stroke="#3b82f6"
strokeWidth={2}
name="Monthly Value"
dot={{ fill: '#3b82f6', strokeWidth: 2, r: 3 }}
activeDot={{ r: 5, stroke: '#3b82f6', strokeWidth: 2 }}
strokeDasharray="5 5"
/>
</LineChart>
</ResponsiveContainer>
</div>
)}
<div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
<p>This chart shows the cumulative value of completed projects over time, with monthly additions.</p>
</div>
</div>
</div>
);
}

View File

@@ -42,6 +42,11 @@ const Navigation = () => {
{ href: "/contracts", label: t('navigation.contracts') }, { href: "/contracts", label: t('navigation.contracts') },
]; ];
// Add team lead dashboard
// if (session?.user?.role === 'team_lead') {
// navItems.push({ href: "/dashboard", label: 'Dashboard' });
// }
// Add admin-only items // Add admin-only items
if (session?.user?.role === 'admin') { if (session?.user?.role === 'admin') {
navItems.push({ href: "/admin/users", label: t('navigation.userManagement') }); navItems.push({ href: "/admin/users", label: t('navigation.userManagement') });

View File

@@ -26,6 +26,13 @@ export default auth((req) => {
return Response.redirect(new URL("/", req.url)); return Response.redirect(new URL("/", req.url));
} }
} }
// Check team leads routes
if (pathname.startsWith("/dashboard/")) {
if (req.auth.user.role !== 'team_lead') {
return Response.redirect(new URL("/", req.url));
}
}
}); });
export const config = { export const config = {