feat: Implement internationalization for task management components
- Added translation support for task-related strings in ProjectTaskForm and ProjectTasksSection components. - Integrated translation for navigation items in the Navigation component. - Created ProjectCalendarWidget component with Polish translations for project statuses and deadlines. - Developed Tooltip component for enhanced user experience with tooltips. - Established a field change history logging system in the database with associated queries. - Enhanced task update logging to include translated status and priority changes. - Introduced server-side translations for system messages to improve localization.
This commit is contained in:
46
src/app/api/field-history/route.js
Normal file
46
src/app/api/field-history/route.js
Normal file
@@ -0,0 +1,46 @@
|
||||
// Force this API route to use Node.js runtime for database access
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import { getFieldHistory, hasFieldHistory } from "@/lib/queries/fieldHistory";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withReadAuth } from "@/lib/middleware/auth";
|
||||
import initializeDatabase from "@/lib/init-db";
|
||||
|
||||
// Make sure the DB is initialized before queries run
|
||||
initializeDatabase();
|
||||
|
||||
async function getFieldHistoryHandler(req) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const tableName = searchParams.get("table_name");
|
||||
const recordId = searchParams.get("record_id");
|
||||
const fieldName = searchParams.get("field_name");
|
||||
const checkOnly = searchParams.get("check_only") === "true";
|
||||
|
||||
if (!tableName || !recordId || !fieldName) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing required parameters: table_name, record_id, field_name" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
if (checkOnly) {
|
||||
// Just check if history exists
|
||||
const exists = hasFieldHistory(tableName, parseInt(recordId), fieldName);
|
||||
return NextResponse.json({ hasHistory: exists });
|
||||
} else {
|
||||
// Get full history
|
||||
const history = getFieldHistory(tableName, parseInt(recordId), fieldName);
|
||||
return NextResponse.json(history);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching field history:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch field history" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Protected route - require read authentication
|
||||
export const GET = withReadAuth(getFieldHistoryHandler);
|
||||
72
src/app/api/notes/[id]/route.js
Normal file
72
src/app/api/notes/[id]/route.js
Normal file
@@ -0,0 +1,72 @@
|
||||
// Force this API route to use Node.js runtime for database access
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import db from "@/lib/db";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withUserAuth } from "@/lib/middleware/auth";
|
||||
import {
|
||||
logApiActionSafe,
|
||||
AUDIT_ACTIONS,
|
||||
RESOURCE_TYPES,
|
||||
} from "@/lib/auditLogSafe.js";
|
||||
import initializeDatabase from "@/lib/init-db";
|
||||
|
||||
// Make sure the DB is initialized before queries run
|
||||
initializeDatabase();
|
||||
|
||||
async function deleteNoteHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "Note ID is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
// Get note data before deletion for audit log
|
||||
const note = db.prepare("SELECT * FROM notes WHERE note_id = ?").get(id);
|
||||
|
||||
if (!note) {
|
||||
return NextResponse.json({ error: "Note not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Check if user has permission to delete this note
|
||||
// Users can delete their own notes, or admins can delete any note
|
||||
const userRole = req.user?.role;
|
||||
const userId = req.user?.id;
|
||||
|
||||
if (userRole !== 'admin' && note.created_by !== userId) {
|
||||
return NextResponse.json({ error: "Unauthorized to delete this note" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Delete the note
|
||||
db.prepare("DELETE FROM notes WHERE note_id = ?").run(id);
|
||||
|
||||
// Log note deletion
|
||||
await logApiActionSafe(
|
||||
req,
|
||||
AUDIT_ACTIONS.NOTE_DELETE,
|
||||
RESOURCE_TYPES.NOTE,
|
||||
id,
|
||||
req.auth,
|
||||
{
|
||||
deletedNote: {
|
||||
project_id: note?.project_id,
|
||||
task_id: note?.task_id,
|
||||
note_length: note?.note?.length || 0,
|
||||
created_by: note?.created_by,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Error deleting note:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to delete note", details: error.message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Protected route - require user authentication
|
||||
export const DELETE = withUserAuth(deleteNoteHandler);
|
||||
@@ -3,13 +3,59 @@ export const runtime = "nodejs";
|
||||
|
||||
import db from "@/lib/db";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withUserAuth } from "@/lib/middleware/auth";
|
||||
import { withUserAuth, withReadAuth } from "@/lib/middleware/auth";
|
||||
import {
|
||||
logApiActionSafe,
|
||||
AUDIT_ACTIONS,
|
||||
RESOURCE_TYPES,
|
||||
} from "@/lib/auditLogSafe.js";
|
||||
|
||||
async function getNotesHandler(req) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const projectId = searchParams.get("project_id");
|
||||
const taskId = searchParams.get("task_id");
|
||||
|
||||
let query;
|
||||
let params;
|
||||
|
||||
if (projectId) {
|
||||
query = `
|
||||
SELECT n.*,
|
||||
u.name as created_by_name,
|
||||
u.username as created_by_username
|
||||
FROM notes n
|
||||
LEFT JOIN users u ON n.created_by = u.id
|
||||
WHERE n.project_id = ?
|
||||
ORDER BY n.note_date DESC
|
||||
`;
|
||||
params = [projectId];
|
||||
} else if (taskId) {
|
||||
query = `
|
||||
SELECT n.*,
|
||||
u.name as created_by_name,
|
||||
u.username as created_by_username
|
||||
FROM notes n
|
||||
LEFT JOIN users u ON n.created_by = u.id
|
||||
WHERE n.task_id = ?
|
||||
ORDER BY n.note_date DESC
|
||||
`;
|
||||
params = [taskId];
|
||||
} else {
|
||||
return NextResponse.json({ error: "project_id or task_id is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const notes = db.prepare(query).all(...params);
|
||||
return NextResponse.json(notes);
|
||||
} catch (error) {
|
||||
console.error("Error fetching notes:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch notes" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function createNoteHandler(req) {
|
||||
const { project_id, task_id, note } = await req.json();
|
||||
|
||||
@@ -118,6 +164,7 @@ async function updateNoteHandler(req, { params }) {
|
||||
}
|
||||
|
||||
// Protected routes - require authentication
|
||||
export const GET = withReadAuth(getNotesHandler);
|
||||
export const POST = withUserAuth(createNoteHandler);
|
||||
export const DELETE = withUserAuth(deleteNoteHandler);
|
||||
export const PUT = withUserAuth(updateNoteHandler);
|
||||
|
||||
24
src/app/api/projects/[id]/finish-date-updates/route.js
Normal file
24
src/app/api/projects/[id]/finish-date-updates/route.js
Normal file
@@ -0,0 +1,24 @@
|
||||
// Force this API route to use Node.js runtime for database access
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import { getFinishDateUpdates } from "@/lib/queries/projects";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withReadAuth } from "@/lib/middleware/auth";
|
||||
|
||||
async function getFinishDateUpdatesHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const updates = getFinishDateUpdates(parseInt(id));
|
||||
return NextResponse.json(updates);
|
||||
} catch (error) {
|
||||
console.error("Error fetching finish date updates:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch finish date updates" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Protected route - require authentication
|
||||
export const GET = withReadAuth(getFinishDateUpdatesHandler);
|
||||
@@ -3,9 +3,11 @@ export const runtime = "nodejs";
|
||||
|
||||
import {
|
||||
getProjectById,
|
||||
getProjectWithContract,
|
||||
updateProject,
|
||||
deleteProject,
|
||||
} from "@/lib/queries/projects";
|
||||
import { logFieldChange } from "@/lib/queries/fieldHistory";
|
||||
import initializeDatabase from "@/lib/init-db";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withReadAuth, withUserAuth } from "@/lib/middleware/auth";
|
||||
@@ -20,7 +22,7 @@ initializeDatabase();
|
||||
|
||||
async function getProjectHandler(req, { params }) {
|
||||
const { id } = await params;
|
||||
const project = getProjectById(parseInt(id));
|
||||
const project = getProjectWithContract(parseInt(id));
|
||||
|
||||
if (!project) {
|
||||
return NextResponse.json({ error: "Project not found" }, { status: 404 });
|
||||
@@ -46,9 +48,31 @@ async function updateProjectHandler(req, { params }) {
|
||||
// Get user ID from authenticated request
|
||||
const userId = req.user?.id;
|
||||
|
||||
// Get original project data for audit log
|
||||
// Get original project data for audit log and field tracking
|
||||
const originalProject = getProjectById(parseInt(id));
|
||||
|
||||
if (!originalProject) {
|
||||
return NextResponse.json({ error: "Project not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Track field changes for specific fields we want to monitor
|
||||
const fieldsToTrack = ['finish_date', 'project_status', 'assigned_to', 'contract_id'];
|
||||
|
||||
for (const fieldName of fieldsToTrack) {
|
||||
if (data.hasOwnProperty(fieldName)) {
|
||||
const oldValue = originalProject[fieldName];
|
||||
const newValue = data[fieldName];
|
||||
|
||||
if (oldValue !== newValue) {
|
||||
try {
|
||||
logFieldChange('projects', parseInt(id), fieldName, oldValue, newValue, userId);
|
||||
} catch (error) {
|
||||
console.error(`Failed to log field change for ${fieldName}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateProject(parseInt(id), data, userId);
|
||||
|
||||
// Get updated project
|
||||
|
||||
48
src/app/api/task-notes/[id]/route.js
Normal file
48
src/app/api/task-notes/[id]/route.js
Normal file
@@ -0,0 +1,48 @@
|
||||
import { deleteNote } from "@/lib/queries/notes";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withUserAuth } from "@/lib/middleware/auth";
|
||||
import db from "@/lib/db";
|
||||
|
||||
// DELETE: Delete a specific task note
|
||||
async function deleteTaskNoteHandler(req, { params }) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "Note ID is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Get note data before deletion for permission checking
|
||||
const note = db.prepare("SELECT * FROM notes WHERE note_id = ?").get(id);
|
||||
|
||||
if (!note) {
|
||||
return NextResponse.json({ error: "Note not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Check if user has permission to delete this note
|
||||
// Users can delete their own notes, or admins can delete any note
|
||||
const userRole = req.user?.role;
|
||||
const userId = req.user?.id;
|
||||
|
||||
if (userRole !== 'admin' && note.created_by !== userId) {
|
||||
return NextResponse.json({ error: "Unauthorized to delete this note" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Don't allow deletion of system notes by regular users
|
||||
if (note.is_system && userRole !== 'admin') {
|
||||
return NextResponse.json({ error: "Cannot delete system notes" }, { status: 403 });
|
||||
}
|
||||
|
||||
deleteNote(id);
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Error deleting task note:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to delete task note" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Protected route - require user authentication
|
||||
export const DELETE = withUserAuth(deleteTaskNoteHandler);
|
||||
361
src/app/calendar/page.js
Normal file
361
src/app/calendar/page.js
Normal file
@@ -0,0 +1,361 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/Card";
|
||||
import Button from "@/components/ui/Button";
|
||||
import Badge from "@/components/ui/Badge";
|
||||
import PageContainer from "@/components/ui/PageContainer";
|
||||
import PageHeader from "@/components/ui/PageHeader";
|
||||
import { LoadingState } from "@/components/ui/States";
|
||||
import { formatDate } from "@/lib/utils";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import {
|
||||
format,
|
||||
startOfMonth,
|
||||
endOfMonth,
|
||||
startOfWeek,
|
||||
endOfWeek,
|
||||
addDays,
|
||||
isSameMonth,
|
||||
isSameDay,
|
||||
addMonths,
|
||||
subMonths,
|
||||
parseISO,
|
||||
isAfter,
|
||||
isBefore,
|
||||
startOfDay,
|
||||
addWeeks
|
||||
} from "date-fns";
|
||||
import { pl } from "date-fns/locale";
|
||||
|
||||
const statusColors = {
|
||||
registered: "bg-blue-100 text-blue-800",
|
||||
approved: "bg-green-100 text-green-800",
|
||||
pending: "bg-yellow-100 text-yellow-800",
|
||||
in_progress: "bg-orange-100 text-orange-800",
|
||||
fulfilled: "bg-gray-100 text-gray-800",
|
||||
};
|
||||
|
||||
const statusTranslations = {
|
||||
registered: "Zarejestrowany",
|
||||
approved: "Zatwierdzony",
|
||||
pending: "Oczekujący",
|
||||
in_progress: "W trakcie",
|
||||
fulfilled: "Zakończony",
|
||||
};
|
||||
|
||||
export default function ProjectCalendarPage() {
|
||||
const { t } = useTranslation();
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [currentDate, setCurrentDate] = useState(new Date());
|
||||
const [viewMode, setViewMode] = useState('month'); // 'month' or 'upcoming'
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/projects")
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
// Filter projects that have finish dates and are not fulfilled
|
||||
const projectsWithDates = data.filter(p =>
|
||||
p.finish_date && p.project_status !== 'fulfilled'
|
||||
);
|
||||
setProjects(projectsWithDates);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error fetching projects:", error);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const getProjectsForDate = (date) => {
|
||||
return projects.filter(project => {
|
||||
if (!project.finish_date) return false;
|
||||
try {
|
||||
const projectDate = parseISO(project.finish_date);
|
||||
return isSameDay(projectDate, date);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const getUpcomingProjects = () => {
|
||||
const today = startOfDay(new Date());
|
||||
const nextMonth = addWeeks(today, 4);
|
||||
|
||||
return projects
|
||||
.filter(project => {
|
||||
if (!project.finish_date) return false;
|
||||
try {
|
||||
const projectDate = parseISO(project.finish_date);
|
||||
return isAfter(projectDate, today) && isBefore(projectDate, nextMonth);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.sort((a, b) => {
|
||||
const dateA = parseISO(a.finish_date);
|
||||
const dateB = parseISO(b.finish_date);
|
||||
return dateA - dateB;
|
||||
});
|
||||
};
|
||||
|
||||
const getOverdueProjects = () => {
|
||||
const today = startOfDay(new Date());
|
||||
|
||||
return projects
|
||||
.filter(project => {
|
||||
if (!project.finish_date) return false;
|
||||
try {
|
||||
const projectDate = parseISO(project.finish_date);
|
||||
return isBefore(projectDate, today);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.sort((a, b) => {
|
||||
const dateA = parseISO(a.finish_date);
|
||||
const dateB = parseISO(b.finish_date);
|
||||
return dateB - dateA; // Most recently overdue first
|
||||
});
|
||||
};
|
||||
|
||||
const renderCalendarGrid = () => {
|
||||
const monthStart = startOfMonth(currentDate);
|
||||
const monthEnd = endOfMonth(currentDate);
|
||||
const calendarStart = startOfWeek(monthStart, { weekStartsOn: 1 });
|
||||
const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 1 });
|
||||
|
||||
const days = [];
|
||||
let day = calendarStart;
|
||||
|
||||
while (day <= calendarEnd) {
|
||||
days.push(day);
|
||||
day = addDays(day, 1);
|
||||
}
|
||||
|
||||
const weekdays = ['Pon', 'Wt', 'Śr', 'Czw', 'Pt', 'Sob', 'Nie'];
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow">
|
||||
{/* Calendar Header */}
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-gray-900">
|
||||
{format(currentDate, 'LLLL yyyy', { locale: pl })}
|
||||
</h2>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentDate(subMonths(currentDate, 1))}
|
||||
>
|
||||
←
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentDate(new Date())}
|
||||
>
|
||||
Dziś
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentDate(addMonths(currentDate, 1))}
|
||||
>
|
||||
→
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Weekday Headers */}
|
||||
<div className="grid grid-cols-7 border-b border-gray-200">
|
||||
{weekdays.map(weekday => (
|
||||
<div key={weekday} className="p-2 text-sm font-medium text-gray-500 text-center">
|
||||
{weekday}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Calendar Grid */}
|
||||
<div className="grid grid-cols-7">
|
||||
{days.map((day, index) => {
|
||||
const dayProjects = getProjectsForDate(day);
|
||||
const isCurrentMonth = isSameMonth(day, currentDate);
|
||||
const isToday = isSameDay(day, new Date());
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`min-h-[120px] p-2 border-r border-b border-gray-100 ${
|
||||
!isCurrentMonth ? 'bg-gray-50' : 'bg-white'
|
||||
} ${isToday ? 'bg-blue-50' : ''}`}
|
||||
>
|
||||
<div className={`text-sm font-medium mb-2 ${
|
||||
!isCurrentMonth ? 'text-gray-400' : isToday ? 'text-blue-600' : 'text-gray-900'
|
||||
}`}>
|
||||
{format(day, 'd')}
|
||||
</div>
|
||||
|
||||
{dayProjects.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
{dayProjects.slice(0, 3).map(project => (
|
||||
<Link
|
||||
key={project.project_id}
|
||||
href={`/projects/${project.project_id}`}
|
||||
className="block"
|
||||
>
|
||||
<div className={`text-xs p-1 rounded truncate ${
|
||||
statusColors[project.project_status] || statusColors.registered
|
||||
} hover:opacity-80 transition-opacity`}>
|
||||
{project.project_name}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
{dayProjects.length > 3 && (
|
||||
<div className="text-xs text-gray-500 p-1">
|
||||
+{dayProjects.length - 3} więcej
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderUpcomingView = () => {
|
||||
const upcomingProjects = getUpcomingProjects();
|
||||
const overdueProjects = getOverdueProjects();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Overdue Projects */}
|
||||
{overdueProjects.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="text-lg font-semibold text-red-600">
|
||||
Projekty przeterminowane ({overdueProjects.length})
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{overdueProjects.map(project => (
|
||||
<div key={project.project_id} className="flex items-center justify-between p-3 bg-red-50 rounded-lg border border-red-200">
|
||||
<div className="flex-1">
|
||||
<Link
|
||||
href={`/projects/${project.project_id}`}
|
||||
className="font-medium text-gray-900 hover:text-blue-600"
|
||||
>
|
||||
{project.project_name}
|
||||
</Link>
|
||||
<div className="text-sm text-gray-600 mt-1">
|
||||
{project.customer && `${project.customer} • `}
|
||||
{project.address}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm font-medium text-red-600">
|
||||
{formatDate(project.finish_date)}
|
||||
</div>
|
||||
<Badge className={statusColors[project.project_status] || statusColors.registered}>
|
||||
{statusTranslations[project.project_status] || project.project_status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Upcoming Projects */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="text-lg font-semibold text-gray-900">
|
||||
Nadchodzące terminy ({upcomingProjects.length})
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{upcomingProjects.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{upcomingProjects.map(project => {
|
||||
const daysUntilDeadline = Math.ceil((parseISO(project.finish_date) - new Date()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
return (
|
||||
<div key={project.project_id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
|
||||
<div className="flex-1">
|
||||
<Link
|
||||
href={`/projects/${project.project_id}`}
|
||||
className="font-medium text-gray-900 hover:text-blue-600"
|
||||
>
|
||||
{project.project_name}
|
||||
</Link>
|
||||
<div className="text-sm text-gray-600 mt-1">
|
||||
{project.customer && `${project.customer} • `}
|
||||
{project.address}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm font-medium text-gray-900">
|
||||
{formatDate(project.finish_date)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
za {daysUntilDeadline} dni
|
||||
</div>
|
||||
<Badge className={statusColors[project.project_status] || statusColors.registered}>
|
||||
{statusTranslations[project.project_status] || project.project_status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500 text-center py-8">
|
||||
Brak nadchodzących projektów w następnych 4 tygodniach
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <LoadingState />;
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="Kalendarz projektów"
|
||||
subtitle={`${projects.length} aktywnych projektów z terminami`}
|
||||
>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
variant={viewMode === 'month' ? 'primary' : 'outline'}
|
||||
onClick={() => setViewMode('month')}
|
||||
>
|
||||
Kalendarz
|
||||
</Button>
|
||||
<Button
|
||||
variant={viewMode === 'upcoming' ? 'primary' : 'outline'}
|
||||
onClick={() => setViewMode('upcoming')}
|
||||
>
|
||||
Lista terminów
|
||||
</Button>
|
||||
</div>
|
||||
</PageHeader>
|
||||
|
||||
{viewMode === 'month' ? renderCalendarGrid() : renderUpcomingView()}
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import {
|
||||
getProjectWithContract,
|
||||
getNotesForProject,
|
||||
} from "@/lib/queries/projects";
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useSession } from "next-auth/react";
|
||||
import NoteForm from "@/components/NoteForm";
|
||||
import ProjectTasksSection from "@/components/ProjectTasksSection";
|
||||
import FieldWithHistory from "@/components/FieldWithHistory";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/Card";
|
||||
import Button from "@/components/ui/Button";
|
||||
import Badge from "@/components/ui/Badge";
|
||||
@@ -15,10 +17,63 @@ import PageHeader from "@/components/ui/PageHeader";
|
||||
import ProjectStatusDropdown from "@/components/ProjectStatusDropdown";
|
||||
import ClientProjectMap from "@/components/ui/ClientProjectMap";
|
||||
|
||||
export default async function ProjectViewPage({ params }) {
|
||||
const { id } = await params;
|
||||
const project = await getProjectWithContract(id);
|
||||
const notes = await getNotesForProject(id);
|
||||
export default function ProjectViewPage() {
|
||||
const params = useParams();
|
||||
const { data: session } = useSession();
|
||||
const [project, setProject] = useState(null);
|
||||
const [notes, setNotes] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Helper function to check if user can delete a note
|
||||
const canDeleteNote = (note) => {
|
||||
if (!session?.user) return false;
|
||||
|
||||
// Admins can delete any note
|
||||
if (session.user.role === 'admin') return true;
|
||||
|
||||
// Users can delete their own notes
|
||||
return note.created_by === session.user.id;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!params.id) return;
|
||||
|
||||
try {
|
||||
// Fetch project data
|
||||
const projectRes = await fetch(`/api/projects/${params.id}`);
|
||||
if (!projectRes.ok) {
|
||||
throw new Error('Project not found');
|
||||
}
|
||||
const projectData = await projectRes.json();
|
||||
|
||||
// Fetch notes data
|
||||
const notesRes = await fetch(`/api/notes?project_id=${params.id}`);
|
||||
const notesData = notesRes.ok ? await notesRes.json() : [];
|
||||
|
||||
setProject(projectData);
|
||||
setNotes(notesData);
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
setProject(null);
|
||||
setNotes([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, [params.id]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<PageContainer>
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-gray-500">Loading...</div>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (!project) {
|
||||
return (
|
||||
@@ -79,7 +134,7 @@ export default async function ProjectViewPage({ params }) {
|
||||
Powrót do projektów
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href={`/projects/${id}/edit`}>
|
||||
<Link href={`/projects/${params.id}/edit`}>
|
||||
<Button variant="primary">
|
||||
<svg
|
||||
className="w-4 h-4 mr-2"
|
||||
@@ -174,16 +229,13 @@ export default async function ProjectViewPage({ params }) {
|
||||
{project.unit || "N/A"}
|
||||
</p>
|
||||
</div>{" "}
|
||||
<div>
|
||||
<span className="text-sm font-medium text-gray-500 block mb-1">
|
||||
Termin zakończenia
|
||||
</span>
|
||||
<p className="text-gray-900 font-medium">
|
||||
{project.finish_date
|
||||
? formatDate(project.finish_date)
|
||||
: "N/A"}
|
||||
</p>
|
||||
</div>
|
||||
<FieldWithHistory
|
||||
tableName="projects"
|
||||
recordId={project.project_id}
|
||||
fieldName="finish_date"
|
||||
currentValue={project.finish_date}
|
||||
label="Termin zakończenia"
|
||||
/>
|
||||
<div>
|
||||
<span className="text-sm font-medium text-gray-500 block mb-1">
|
||||
WP
|
||||
@@ -325,7 +377,7 @@ export default async function ProjectViewPage({ params }) {
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<Link href={`/projects/${id}/edit`} className="block">
|
||||
<Link href={`/projects/${params.id}/edit`} className="block">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -449,7 +501,7 @@ export default async function ProjectViewPage({ params }) {
|
||||
)}
|
||||
{/* Project Tasks Section */}
|
||||
<div className="mb-8">
|
||||
<ProjectTasksSection projectId={id} />
|
||||
<ProjectTasksSection projectId={params.id} />
|
||||
</div>
|
||||
{/* Notes Section */}
|
||||
<Card>
|
||||
@@ -458,7 +510,7 @@ export default async function ProjectViewPage({ params }) {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="mb-6">
|
||||
<NoteForm projectId={id} />
|
||||
<NoteForm projectId={params.id} />
|
||||
</div>
|
||||
{notes.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
@@ -486,7 +538,7 @@ export default async function ProjectViewPage({ params }) {
|
||||
{notes.map((n) => (
|
||||
<div
|
||||
key={n.note_id}
|
||||
className="border border-gray-200 p-4 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors"
|
||||
className="border border-gray-200 p-4 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors group"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -499,6 +551,44 @@ export default async function ProjectViewPage({ params }) {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{canDeleteNote(n) && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (confirm('Czy na pewno chcesz usunąć tę notatkę?')) {
|
||||
try {
|
||||
const res = await fetch(`/api/notes/${n.note_id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (res.ok) {
|
||||
// Remove the note from local state instead of full page reload
|
||||
setNotes(prevNotes => prevNotes.filter(note => note.note_id !== n.note_id));
|
||||
} else {
|
||||
alert('Błąd podczas usuwania notatki');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting note:', error);
|
||||
alert('Błąd podczas usuwania notatki');
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="opacity-0 group-hover:opacity-100 transition-opacity p-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded"
|
||||
title="Usuń notatkę"
|
||||
>
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-gray-900 leading-relaxed">{n.note}</p>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import ProjectForm from "@/components/ProjectForm";
|
||||
import PageContainer from "@/components/ui/PageContainer";
|
||||
import PageHeader from "@/components/ui/PageHeader";
|
||||
@@ -5,11 +8,13 @@ import Button from "@/components/ui/Button";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function NewProjectPage() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="Create New Project"
|
||||
description="Add a new project to your portfolio"
|
||||
title={t("projects.newProject")}
|
||||
// description={t("projects.noProjectsMessage")}
|
||||
action={
|
||||
<Link href="/projects">
|
||||
<Button variant="outline" size="sm">
|
||||
@@ -26,7 +31,7 @@ export default function NewProjectPage() {
|
||||
d="M15 19l-7-7 7-7"
|
||||
/>
|
||||
</svg>
|
||||
Back to Projects
|
||||
{t("common.back")}
|
||||
</Button>
|
||||
</Link>
|
||||
}
|
||||
|
||||
@@ -18,33 +18,68 @@ export default function ProjectListPage() {
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [filteredProjects, setFilteredProjects] = useState([]);
|
||||
const [filters, setFilters] = useState({
|
||||
status: 'all',
|
||||
type: 'all',
|
||||
customer: 'all'
|
||||
});
|
||||
|
||||
const [customers, setCustomers] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/projects")
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
setProjects(data);
|
||||
setFilteredProjects(data);
|
||||
|
||||
// Extract unique customers for filter
|
||||
const uniqueCustomers = [...new Set(data.map(p => p.customer).filter(Boolean))];
|
||||
setCustomers(uniqueCustomers);
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Filter projects based on search term
|
||||
// Filter projects based on search term and filters
|
||||
useEffect(() => {
|
||||
if (!searchTerm.trim()) {
|
||||
setFilteredProjects(projects);
|
||||
} else {
|
||||
const filtered = projects.filter((project) => {
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
let filtered = projects;
|
||||
|
||||
// Apply status filter
|
||||
if (filters.status !== 'all') {
|
||||
if (filters.status === 'not_finished') {
|
||||
filtered = filtered.filter(project => project.project_status !== 'fulfilled');
|
||||
} else {
|
||||
filtered = filtered.filter(project => project.project_status === filters.status);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply type filter
|
||||
if (filters.type !== 'all') {
|
||||
filtered = filtered.filter(project => project.project_type === filters.type);
|
||||
}
|
||||
|
||||
// Apply customer filter
|
||||
if (filters.customer !== 'all') {
|
||||
filtered = filtered.filter(project => project.customer === filters.customer);
|
||||
}
|
||||
|
||||
// Apply search term
|
||||
if (searchTerm.trim()) {
|
||||
const searchLower = searchTerm.toLowerCase();
|
||||
filtered = filtered.filter((project) => {
|
||||
return (
|
||||
project.project_name?.toLowerCase().includes(searchLower) ||
|
||||
project.wp?.toLowerCase().includes(searchLower) ||
|
||||
project.plot?.toLowerCase().includes(searchLower) ||
|
||||
project.investment_number?.toLowerCase().includes(searchLower) ||
|
||||
project.address?.toLowerCase().includes(searchLower)
|
||||
project.address?.toLowerCase().includes(searchLower) ||
|
||||
project.customer?.toLowerCase().includes(searchLower) ||
|
||||
project.investor?.toLowerCase().includes(searchLower)
|
||||
);
|
||||
});
|
||||
setFilteredProjects(filtered);
|
||||
}
|
||||
}, [searchTerm, projects]);
|
||||
|
||||
setFilteredProjects(filtered);
|
||||
}, [searchTerm, projects, filters]);
|
||||
|
||||
async function handleDelete(id) {
|
||||
const confirmed = confirm(t('projects.deleteConfirm'));
|
||||
@@ -61,6 +96,41 @@ export default function ProjectListPage() {
|
||||
const handleSearchChange = (e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
};
|
||||
|
||||
const handleFilterChange = (filterType, value) => {
|
||||
setFilters(prev => ({
|
||||
...prev,
|
||||
[filterType]: value
|
||||
}));
|
||||
};
|
||||
|
||||
const clearAllFilters = () => {
|
||||
setFilters({
|
||||
status: 'all',
|
||||
type: 'all',
|
||||
customer: 'all'
|
||||
});
|
||||
setSearchTerm('');
|
||||
};
|
||||
|
||||
const getStatusLabel = (status) => {
|
||||
switch(status) {
|
||||
case "registered": return t('projectStatus.registered');
|
||||
case "in_progress_design": return t('projectStatus.in_progress_design');
|
||||
case "in_progress_construction": return t('projectStatus.in_progress_construction');
|
||||
case "fulfilled": return t('projectStatus.fulfilled');
|
||||
default: return "-";
|
||||
}
|
||||
};
|
||||
|
||||
const getTypeLabel = (type) => {
|
||||
switch(type) {
|
||||
case "design": return t('projectType.design');
|
||||
case "construction": return t('projectType.construction');
|
||||
case "design+construction": return t('projectType.design+construction');
|
||||
default: return "-";
|
||||
}
|
||||
};
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader title={t('projects.title')} description={t('projects.subtitle')}>
|
||||
@@ -80,7 +150,7 @@ export default function ProjectListPage() {
|
||||
d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7"
|
||||
/>
|
||||
</svg>
|
||||
Widok mapy
|
||||
{t('projects.mapView') || 'Widok mapy'}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/projects/new">
|
||||
@@ -109,8 +179,76 @@ export default function ProjectListPage() {
|
||||
onSearchChange={handleSearchChange}
|
||||
placeholder={t('projects.searchPlaceholder')}
|
||||
resultsCount={filteredProjects.length}
|
||||
resultsText="projektów"
|
||||
resultsText={t('projects.projects') || 'projektów'}
|
||||
/>
|
||||
|
||||
{/* Filters */}
|
||||
<Card className="mb-6">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex flex-wrap gap-4 items-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-sm font-medium text-gray-700">{t('common.status') || 'Status'}:</label>
|
||||
<select
|
||||
value={filters.status}
|
||||
onChange={(e) => handleFilterChange('status', e.target.value)}
|
||||
className="px-3 py-1 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="all">{t('common.all')}</option>
|
||||
<option value="not_finished">{t('projects.notFinished') || 'Nie zakończone'}</option>
|
||||
<option value="registered">{t('projectStatus.registered')}</option>
|
||||
<option value="in_progress_design">{t('projectStatus.in_progress_design')}</option>
|
||||
<option value="in_progress_construction">{t('projectStatus.in_progress_construction')}</option>
|
||||
<option value="fulfilled">{t('projectStatus.fulfilled')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-sm font-medium text-gray-700">{t('common.type') || 'Typ'}:</label>
|
||||
<select
|
||||
value={filters.type}
|
||||
onChange={(e) => handleFilterChange('type', e.target.value)}
|
||||
className="px-3 py-1 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="all">{t('common.all')}</option>
|
||||
<option value="design">{t('projectType.design')}</option>
|
||||
<option value="construction">{t('projectType.construction')}</option>
|
||||
<option value="design+construction">{t('projectType.design+construction')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-sm font-medium text-gray-700">{t('contracts.customer') || 'Klient'}:</label>
|
||||
<select
|
||||
value={filters.customer}
|
||||
onChange={(e) => handleFilterChange('customer', e.target.value)}
|
||||
className="px-3 py-1 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="all">{t('common.all')}</option>
|
||||
{customers.map((customer) => (
|
||||
<option key={customer} value={customer}>
|
||||
{customer}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{(filters.status !== 'all' || filters.type !== 'all' || filters.customer !== 'all' || searchTerm) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={clearAllFilters}
|
||||
className="text-xs"
|
||||
>
|
||||
{t('common.clearAllFilters') || 'Wyczyść wszystkie filtry'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="text-sm text-gray-500 ml-auto">
|
||||
{t('projects.showingResults', { shown: filteredProjects.length, total: projects.length }) || `Wyświetlono ${filteredProjects.length} z ${projects.length} projektów`}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{filteredProjects.length === 0 && searchTerm ? (
|
||||
<Card>
|
||||
<CardContent className="text-center py-12">
|
||||
@@ -131,10 +269,10 @@ export default function ProjectListPage() {
|
||||
{t('common.noResults')}
|
||||
</h3>
|
||||
<p className="text-gray-500 mb-6">
|
||||
Brak projektów pasujących do kryteriów wyszukiwania. Spróbuj zmienić wyszukiwane frazy.
|
||||
{t('projects.noMatchingResults') || 'Brak projektów pasujących do kryteriów wyszukiwania. Spróbuj zmienić wyszukiwane frazy.'}
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => setSearchTerm("")}>
|
||||
Wyczyść wyszukiwanie
|
||||
{t('common.clearSearch') || 'Wyczyść wyszukiwanie'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -161,7 +299,7 @@ export default function ProjectListPage() {
|
||||
{t('projects.noProjectsMessage')}
|
||||
</p>
|
||||
<Link href="/projects/new">
|
||||
<Button variant="primary">Utwórz pierwszy projekt</Button>
|
||||
<Button variant="primary">{t('projects.createFirstProject') || 'Utwórz pierwszy projekt'}</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -192,13 +330,13 @@ export default function ProjectListPage() {
|
||||
{t('projects.finishDate')}
|
||||
</th>
|
||||
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-12">
|
||||
Typ
|
||||
{t('common.type') || 'Typ'}
|
||||
</th>
|
||||
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-24">
|
||||
Status
|
||||
{t('common.status') || 'Status'}
|
||||
</th>
|
||||
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-20">
|
||||
Akcje
|
||||
{t('common.actions') || 'Akcje'}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -266,15 +404,7 @@ export default function ProjectListPage() {
|
||||
: "-"}
|
||||
</td>
|
||||
<td className="px-2 py-3 text-xs text-gray-600 truncate">
|
||||
{project.project_status === "registered"
|
||||
? "Zarejestr."
|
||||
: project.project_status === "in_progress_design"
|
||||
? "W real. (P)"
|
||||
: project.project_status === "in_progress_construction"
|
||||
? "W real. (R)"
|
||||
: project.project_status === "fulfilled"
|
||||
? "Zakończony"
|
||||
: "-"}
|
||||
{getStatusLabel(project.project_status)}
|
||||
</td>
|
||||
<td className="px-2 py-3">
|
||||
<Link href={`/projects/${project.project_id}`}>
|
||||
@@ -283,7 +413,7 @@ export default function ProjectListPage() {
|
||||
size="sm"
|
||||
className="text-xs px-2 py-1"
|
||||
>
|
||||
Wyświetl
|
||||
{t('common.view') || 'Wyświetl'}
|
||||
</Button>
|
||||
</Link>
|
||||
</td>
|
||||
|
||||
Reference in New Issue
Block a user