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:
2025-09-11 15:49:07 +02:00
parent 50adc50a24
commit 0dd988730f
24 changed files with 1945 additions and 114 deletions

View 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);

View 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);

View File

@@ -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);

View 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);

View File

@@ -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

View 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
View 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>
);
}

View File

@@ -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>

View File

@@ -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>
}

View File

@@ -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);
let filtered = projects;
// Apply status filter
if (filters.status !== 'all') {
if (filters.status === 'not_finished') {
filtered = filtered.filter(project => project.project_status !== 'fulfilled');
} else {
const filtered = projects.filter((project) => {
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>

View File

@@ -0,0 +1,126 @@
"use client";
import { useState, useEffect } from "react";
import Tooltip from "@/components/ui/Tooltip";
import { formatDate } from "@/lib/utils";
export default function FieldWithHistory({
tableName,
recordId,
fieldName,
currentValue,
displayValue = null,
label = null,
className = "",
}) {
const [hasHistory, setHasHistory] = useState(false);
const [history, setHistory] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchHistory = async () => {
try {
const response = await fetch(
`/api/field-history?table_name=${tableName}&record_id=${recordId}&field_name=${fieldName}`
);
if (response.ok) {
const historyData = await response.json();
setHistory(historyData);
setHasHistory(historyData.length > 0);
}
} catch (error) {
console.error("Failed to fetch field history:", error);
} finally {
setLoading(false);
}
};
if (tableName && recordId && fieldName) {
fetchHistory();
} else {
setLoading(false);
}
}, [tableName, recordId, fieldName]);
// Format value for display
const getDisplayValue = (value) => {
if (displayValue !== null) return displayValue;
if (value && fieldName.includes("date")) {
try {
return formatDate(value);
} catch {
return value;
}
}
return value || "N/A";
};
// Create tooltip content
const tooltipContent = history.length > 0 && (
<div className="space-y-2">
<div className="font-medium text-white mb-2">Change History:</div>
{history.map((change, index) => (
<div key={change.id} className="text-xs border-b border-gray-600 pb-1 last:border-b-0">
<div className="flex justify-between items-start gap-2">
<div className="flex-1">
<div className="text-white font-medium">
Changed to: {getDisplayValue(change.new_value)}
</div>
{change.old_value && (
<div className="text-gray-400 text-xs">
From: {getDisplayValue(change.old_value)}
</div>
)}
{change.changed_by_name && (
<div className="text-gray-300">
by {change.changed_by_name}
</div>
)}
</div>
<div className="text-gray-400 text-right text-xs">
{formatDate(change.changed_at)}
</div>
</div>
{change.change_reason && (
<div className="text-gray-400 text-xs mt-1">
Reason: {change.change_reason}
</div>
)}
</div>
))}
</div>
);
if (loading) {
return (
<div className={className}>
{label && <span className="text-sm font-medium text-gray-500 block mb-1">{label}</span>}
<p className="text-gray-900 font-medium">{getDisplayValue(currentValue)}</p>
</div>
);
}
return (
<div className={className}>
{label && <span className="text-sm font-medium text-gray-500 block mb-1">{label}</span>}
<div className="flex items-center gap-2">
<p className="text-gray-900 font-medium">{getDisplayValue(currentValue)}</p>
{hasHistory && (
<Tooltip content={tooltipContent}>
<svg
className="w-4 h-4 text-blue-500 hover:text-blue-700 cursor-help"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
clipRule="evenodd"
/>
</svg>
</Tooltip>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,114 @@
"use client";
import { useState, useEffect } from "react";
import Tooltip from "@/components/ui/Tooltip";
import { formatDate } from "@/lib/utils";
export default function FinishDateWithHistory({ projectId, finishDate }) {
const [hasUpdates, setHasUpdates] = useState(false);
const [updates, setUpdates] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUpdates = async () => {
try {
const res = await fetch(`/api/projects/${projectId}/finish-date-updates`);
if (res.ok) {
const data = await res.json();
setUpdates(data);
setHasUpdates(data.length > 0);
}
} catch (error) {
console.error("Failed to fetch finish date updates:", error);
} finally {
setLoading(false);
}
};
if (projectId) {
fetchUpdates();
}
}, [projectId]);
const formatDateTime = (dateString) => {
const date = new Date(dateString);
return date.toLocaleDateString("pl-PL", {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
};
const tooltipContent = (
<div className="space-y-2">
<div className="font-medium text-xs text-gray-300 mb-2">
Historia zmian terminu:
</div>
{updates.map((update, index) => (
<div key={update.id} className="text-xs">
<div className="flex justify-between items-start gap-2">
<div>
<div className="font-medium">
{update.new_finish_date
? formatDate(update.new_finish_date)
: "Usunięto termin"}
</div>
{update.old_finish_date && (
<div className="text-gray-400 text-xs">
poprzednio: {formatDate(update.old_finish_date)}
</div>
)}
</div>
</div>
<div className="text-gray-400 text-xs mt-1">
{update.updated_by_name && (
<span>przez {update.updated_by_name} </span>
)}
<span>{formatDateTime(update.updated_at)}</span>
</div>
{update.reason && (
<div className="text-gray-300 text-xs mt-1 italic">
"{update.reason}"
</div>
)}
{index < updates.length - 1 && (
<div className="border-b border-gray-600 my-2"></div>
)}
</div>
))}
</div>
);
if (loading) {
return (
<p className="text-gray-900 font-medium">
{finishDate ? formatDate(finishDate) : "N/A"}
</p>
);
}
return (
<div className="flex items-center gap-1">
<p className="text-gray-900 font-medium">
{finishDate ? formatDate(finishDate) : "N/A"}
</p>
{hasUpdates && (
<Tooltip content={tooltipContent} position="top">
<svg
className="w-4 h-4 text-blue-500 cursor-help hover:text-blue-600 transition-colors"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
clipRule="evenodd"
/>
</svg>
</Tooltip>
)}
</div>
);
}

View File

@@ -103,11 +103,11 @@ export default function ProjectForm({ initialData = null }) {
router.push("/projects");
}
} else {
alert("Failed to save project.");
alert(t('projects.saveError'));
}
} catch (error) {
console.error("Error saving project:", error);
alert("Failed to save project.");
alert(t('projects.saveError'));
} finally {
setLoading(false);
}
@@ -116,7 +116,7 @@ export default function ProjectForm({ initialData = null }) {
<Card>
<CardHeader>
<h2 className="text-xl font-semibold text-gray-900">
{isEdit ? "Edit Project Details" : "Project Details"}
{isEdit ? t('projects.editProjectDetails') : t('projects.projectDetails')}
</h2>
</CardHeader>
<CardContent>
@@ -125,7 +125,7 @@ export default function ProjectForm({ initialData = null }) {
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Contract <span className="text-red-500">*</span>
{t('projects.contract')} <span className="text-red-500">*</span>
</label>
<select
name="contract_id"
@@ -134,7 +134,7 @@ export default function ProjectForm({ initialData = null }) {
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
required
>
<option value="">Select Contract</option>
<option value="">{t('projects.selectContract')}</option>
{contracts.map((contract) => (
<option
key={contract.contract_id}
@@ -148,7 +148,7 @@ export default function ProjectForm({ initialData = null }) {
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Typ projektu <span className="text-red-500">*</span>
{t('projects.type')} <span className="text-red-500">*</span>
</label>
<select
name="project_type"
@@ -287,19 +287,19 @@ export default function ProjectForm({ initialData = null }) {
{/* Additional Information Section */}
<div className="border-t pt-6">
<h3 className="text-lg font-medium text-gray-900 mb-4">
Additional Information
{t('projects.additionalInfo')}
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Investment Number
{t('projects.investmentNumber')}
</label>
<Input
type="text"
name="investment_number"
value={form.investment_number || ""}
onChange={handleChange}
placeholder="Enter investment number"
placeholder={t('projects.placeholders.investmentNumber')}
/>
</div>
@@ -312,7 +312,7 @@ export default function ProjectForm({ initialData = null }) {
name="wp"
value={form.wp || ""}
onChange={handleChange}
placeholder="Enter WP"
placeholder={t('projects.placeholders.wp')}
/>
</div>

View File

@@ -3,8 +3,10 @@
import { useState, useEffect } from "react";
import Button from "./ui/Button";
import Badge from "./ui/Badge";
import { useTranslation } from "@/lib/i18n";
export default function ProjectTaskForm({ projectId, onTaskAdded }) {
const { t } = useTranslation();
const [taskTemplates, setTaskTemplates] = useState([]);
const [users, setUsers] = useState([]);
const [taskType, setTaskType] = useState("template"); // "template" or "custom"
@@ -67,10 +69,10 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
setAssignedTo("");
if (onTaskAdded) onTaskAdded();
} else {
alert("Failed to add task to project.");
alert(t("tasks.addTaskError"));
}
} catch (error) {
alert("Error adding task to project.");
alert(t("tasks.addTaskError"));
} finally {
setIsSubmitting(false);
}
@@ -79,7 +81,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-3">
Task Type
{t("tasks.taskType")}
</label>
<div className="flex space-x-6">
<label className="flex items-center">
@@ -90,7 +92,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
onChange={(e) => setTaskType(e.target.value)}
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300"
/>
<span className="ml-2 text-sm text-gray-900">From Template</span>
<span className="ml-2 text-sm text-gray-900">{t("tasks.fromTemplate")}</span>
</label>
<label className="flex items-center">
<input
@@ -100,7 +102,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
onChange={(e) => setTaskType(e.target.value)}
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300"
/>
<span className="ml-2 text-sm text-gray-900">Custom Task</span>
<span className="ml-2 text-sm text-gray-900">{t("tasks.customTask")}</span>
</label>
</div>
</div>
@@ -108,7 +110,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
{taskType === "template" ? (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Select Task Template
{t("tasks.selectTemplate")}
</label>{" "}
<select
value={selectedTemplate}
@@ -116,10 +118,10 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
>
<option value="">Choose a task template...</option>
<option value="">{t("tasks.chooseTemplate")}</option>
{taskTemplates.map((template) => (
<option key={template.task_id} value={template.task_id}>
{template.name} ({template.max_wait_days} days)
{template.name} ({template.max_wait_days} {t("tasks.days")})
</option>
))}
</select>
@@ -128,20 +130,20 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Task Name
{t("tasks.taskName")}
</label>
<input
type="text"
value={customTaskName}
onChange={(e) => setCustomTaskName(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder="Enter custom task name..."
placeholder={t("tasks.enterTaskName")}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Max Wait Days
{t("tasks.maxWait")}
</label>
<input
type="number"
@@ -154,13 +156,13 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Description
{t("tasks.description")}
</label>
<textarea
value={customDescription}
onChange={(e) => setCustomDescription(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder="Enter task description (optional)..."
placeholder={t("tasks.enterDescription")}
rows={3}
/>
</div>
@@ -169,14 +171,14 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Assign To <span className="text-gray-500 text-xs">(optional)</span>
{t("tasks.assignedTo")} <span className="text-gray-500 text-xs">({t("common.optional")})</span>
</label>
<select
value={assignedTo}
onChange={(e) => setAssignedTo(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
>
<option value="">Unassigned</option>
<option value="">{t("projects.unassigned")}</option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.name} ({user.email})
@@ -187,17 +189,17 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Priority
{t("tasks.priority")}
</label>
<select
value={priority}
onChange={(e) => setPriority(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
>
<option value="low">Low</option>
<option value="normal">Normal</option>
<option value="high">High</option>
<option value="urgent">Urgent</option>
<option value="low">{t("tasks.low")}</option>
<option value="normal">{t("tasks.normal")}</option>
<option value="high">{t("tasks.high")}</option>
<option value="urgent">{t("tasks.urgent")}</option>
</select>
</div>
@@ -211,7 +213,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
(taskType === "custom" && !customTaskName.trim())
}
>
{isSubmitting ? "Adding..." : "Add Task"}
{isSubmitting ? t("tasks.adding") : t("tasks.addTask")}
</Button>
</div>
</form>

View File

@@ -202,7 +202,7 @@ export default function ProjectTasksSection({ projectId }) {
alert(t("errors.generic") + ": " + (errorData.error || t("errors.unknown")));
}
} catch (error) {
alert("Error deleting task: " + error.message);
alert(t("tasks.deleteError") + ": " + error.message);
}
};
@@ -238,6 +238,28 @@ export default function ProjectTasksSection({ projectId }) {
}
};
const handleDeleteNote = async (noteId, taskId) => {
if (!confirm(t("common.deleteConfirm"))) return;
try {
const res = await fetch(`/api/task-notes/${noteId}`, {
method: "DELETE",
});
if (res.ok) {
// Refresh notes for this task
const notesRes = await fetch(`/api/task-notes?task_id=${taskId}`);
const notes = await notesRes.json();
setTaskNotes((prev) => ({ ...prev, [taskId]: notes }));
} else {
alert(t("errors.generic"));
}
} catch (error) {
console.error("Error deleting task note:", error);
alert(t("errors.generic"));
}
};
const handleEditTask = (task) => {
setEditingTask(task);
@@ -373,7 +395,7 @@ export default function ProjectTasksSection({ projectId }) {
>
<div className="flex items-center justify-between p-6 border-b">
<h3 className="text-lg font-semibold text-gray-900">
Add New Task
{t("tasks.newTask")}
</h3>
<button
onClick={() => setShowAddTaskModal(false)}
@@ -530,7 +552,7 @@ export default function ProjectTasksSection({ projectId }) {
size="sm"
onClick={() => toggleNotes(task.id)}
className="text-xs px-2 py-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 border-0"
title={`${taskNotes[task.id]?.length || 0} notes`}
title={`${taskNotes[task.id]?.length || 0} ${t("tasks.notes")}`}
>
<svg
className="w-3 h-3 mr-1"
@@ -658,7 +680,7 @@ export default function ProjectTasksSection({ projectId }) {
)
}
className="ml-2 text-red-500 hover:text-red-700 text-xs font-bold"
title="Delete note"
title={t("tasks.deleteNote")}
>
×
</button>

View File

@@ -22,6 +22,7 @@ const Navigation = () => {
const navItems = [
{ href: "/projects", label: t('navigation.projects') },
{ href: "/calendar", label: t('navigation.calendar') || 'Kalendarz' },
{ href: "/tasks/templates", label: t('navigation.taskTemplates') },
{ href: "/project-tasks", label: t('navigation.projectTasks') },
{ href: "/contracts", label: t('navigation.contracts') },

View File

@@ -0,0 +1,329 @@
"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { Card, CardHeader, CardContent } from "./Card";
import Badge from "./Badge";
import Button from "./Button";
import { formatDate } from "@/lib/utils";
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 ProjectCalendarWidget({
projects = [],
compact = false,
showUpcoming = true,
maxUpcoming = 5
}) {
const [currentDate, setCurrentDate] = useState(new Date());
const [viewMode, setViewMode] = useState(compact ? 'upcoming' : 'mini-calendar');
// Filter projects that have finish dates and are not fulfilled
const activeProjects = projects.filter(p =>
p.finish_date && p.project_status !== 'fulfilled'
);
const getProjectsForDate = (date) => {
return activeProjects.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 activeProjects
.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;
})
.slice(0, maxUpcoming);
};
const getOverdueProjects = () => {
const today = startOfDay(new Date());
return activeProjects
.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
})
.slice(0, maxUpcoming);
};
const renderMiniCalendar = () => {
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 = ['P', 'W', 'Ś', 'C', 'P', 'S', 'N'];
return (
<div className="space-y-3">
{/* Calendar Header */}
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-gray-900">
{format(currentDate, 'LLLL yyyy', { locale: pl })}
</h3>
<div className="flex space-x-1">
<button
onClick={() => setCurrentDate(subMonths(currentDate, 1))}
className="p-1 hover:bg-gray-100 rounded"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<button
onClick={() => setCurrentDate(addMonths(currentDate, 1))}
className="p-1 hover:bg-gray-100 rounded"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
{/* Weekday Headers */}
<div className="grid grid-cols-7 gap-1">
{weekdays.map(weekday => (
<div key={weekday} className="text-xs font-medium text-gray-500 text-center p-1">
{weekday}
</div>
))}
</div>
{/* Calendar Grid */}
<div className="grid grid-cols-7 gap-1">
{days.map((day, index) => {
const dayProjects = getProjectsForDate(day);
const isCurrentMonth = isSameMonth(day, currentDate);
const isToday = isSameDay(day, new Date());
const hasProjects = dayProjects.length > 0;
return (
<div
key={index}
className={`text-xs p-1 text-center relative ${
!isCurrentMonth ? 'text-gray-300' :
isToday ? 'bg-blue-100 text-blue-700 font-semibold rounded' :
'text-gray-700'
} ${hasProjects && isCurrentMonth ? 'font-semibold' : ''}`}
title={hasProjects ? `${dayProjects.length} projekt(ów): ${dayProjects.map(p => p.project_name).join(', ')}` : ''}
>
{format(day, 'd')}
{hasProjects && isCurrentMonth && (
<div className="absolute bottom-0 left-1/2 transform -translate-x-1/2 w-1 h-1 bg-red-500 rounded-full"></div>
)}
</div>
);
})}
</div>
</div>
);
};
const renderUpcomingList = () => {
const upcomingProjects = getUpcomingProjects();
const overdueProjects = getOverdueProjects();
return (
<div className="space-y-4">
{/* Overdue Projects */}
{overdueProjects.length > 0 && (
<div>
<h4 className="text-sm font-medium text-red-600 mb-2">
Przeterminowane ({overdueProjects.length})
</h4>
<div className="space-y-2">
{overdueProjects.map(project => (
<Link
key={project.project_id}
href={`/projects/${project.project_id}`}
className="block p-2 bg-red-50 rounded border border-red-200 hover:bg-red-100 transition-colors"
>
<div className="text-sm font-medium text-gray-900 truncate">
{project.project_name}
</div>
<div className="text-xs text-red-600">
{formatDate(project.finish_date)}
</div>
</Link>
))}
</div>
</div>
)}
{/* Upcoming Projects */}
{upcomingProjects.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-900 mb-2">
Nadchodzące ({upcomingProjects.length})
</h4>
<div className="space-y-2">
{upcomingProjects.map(project => {
const daysUntilDeadline = Math.ceil((parseISO(project.finish_date) - new Date()) / (1000 * 60 * 60 * 24));
return (
<Link
key={project.project_id}
href={`/projects/${project.project_id}`}
className="block p-2 bg-gray-50 rounded hover:bg-gray-100 transition-colors"
>
<div className="text-sm font-medium text-gray-900 truncate">
{project.project_name}
</div>
<div className="text-xs text-gray-600">
{formatDate(project.finish_date)} za {daysUntilDeadline} dni
</div>
</Link>
);
})}
</div>
</div>
)}
{upcomingProjects.length === 0 && overdueProjects.length === 0 && (
<div className="text-sm text-gray-500 text-center py-4">
Brak nadchodzących terminów
</div>
)}
</div>
);
};
if (activeProjects.length === 0) {
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Kalendarz projektów</h3>
<Link href="/calendar">
<Button variant="outline" size="sm">
Zobacz pełny kalendarz
</Button>
</Link>
</div>
</CardHeader>
<CardContent>
<div className="text-center py-8 text-gray-500">
Brak aktywnych projektów z terminami
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Kalendarz projektów</h3>
<div className="flex items-center space-x-2">
{!compact && (
<div className="flex rounded-md bg-gray-100 p-1">
<button
onClick={() => setViewMode('mini-calendar')}
className={`px-2 py-1 text-xs rounded ${
viewMode === 'mini-calendar'
? 'bg-white text-gray-900 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
Kalendarz
</button>
<button
onClick={() => setViewMode('upcoming')}
className={`px-2 py-1 text-xs rounded ${
viewMode === 'upcoming'
? 'bg-white text-gray-900 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
Lista
</button>
</div>
)}
<Link href="/calendar">
<Button variant="outline" size="sm">
Pełny kalendarz
</Button>
</Link>
</div>
</div>
</CardHeader>
<CardContent>
{viewMode === 'mini-calendar' ? renderMiniCalendar() : renderUpcomingList()}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import { useState, useRef, useEffect } from "react";
import { createPortal } from "react-dom";
export default function Tooltip({ children, content, className = "" }) {
const [isVisible, setIsVisible] = useState(false);
const [position, setPosition] = useState({ top: 0, left: 0 });
const triggerRef = useRef(null);
const tooltipRef = useRef(null);
const updatePosition = () => {
if (triggerRef.current && tooltipRef.current) {
const triggerRect = triggerRef.current.getBoundingClientRect();
const tooltipRect = tooltipRef.current.getBoundingClientRect();
const scrollY = window.scrollY;
const scrollX = window.scrollX;
// Calculate position (above the trigger by default)
let top = triggerRect.top + scrollY - tooltipRect.height - 8;
let left = triggerRect.left + scrollX + (triggerRect.width / 2) - (tooltipRect.width / 2);
// Keep tooltip within viewport
if (left < 10) left = 10;
if (left + tooltipRect.width > window.innerWidth - 10) {
left = window.innerWidth - tooltipRect.width - 10;
}
// If tooltip would go above viewport, show below instead
if (top < scrollY + 10) {
top = triggerRect.bottom + scrollY + 8;
}
setPosition({ top, left });
}
};
const handleMouseEnter = () => {
setIsVisible(true);
};
const handleMouseLeave = () => {
setIsVisible(false);
};
useEffect(() => {
if (isVisible) {
// Small delay to ensure tooltip is rendered before positioning
const timer = setTimeout(() => {
updatePosition();
}, 10);
const handleScroll = () => updatePosition();
const handleResize = () => updatePosition();
window.addEventListener("scroll", handleScroll, true);
window.addEventListener("resize", handleResize);
return () => {
clearTimeout(timer);
window.removeEventListener("scroll", handleScroll, true);
window.removeEventListener("resize", handleResize);
};
}
}, [isVisible]);
const tooltip = isVisible && (
<div
ref={tooltipRef}
className={`fixed z-50 px-3 py-2 text-sm bg-gray-900 text-white rounded-lg shadow-lg border max-w-sm ${className}`}
style={{
top: position.top,
left: position.left,
}}
>
{content}
{/* Arrow pointing down */}
<div className="absolute top-full left-1/2 transform -translate-x-1/2 border-4 border-transparent border-t-gray-900"></div>
</div>
);
return (
<>
<span
ref={triggerRef}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
className="inline-block"
>
{children}
</span>
{typeof document !== "undefined" && createPortal(tooltip, document.body)}
</>
);
}

View File

@@ -12,6 +12,7 @@ const translations = {
navigation: {
dashboard: "Panel główny",
projects: "Projekty",
calendar: "Kalendarz",
taskTemplates: "Szablony zadań",
projectTasks: "Zadania projektów",
contracts: "Umowy",
@@ -62,7 +63,14 @@ const translations = {
addNote: "Dodaj notatkę",
addNoteSuccess: "Notatka została dodana",
addNoteError: "Nie udało się zapisać notatki",
addNotePlaceholder: "Dodaj nową notatkę..."
addNotePlaceholder: "Dodaj nową notatkę...",
status: "Status",
type: "Typ",
actions: "Akcje",
view: "Wyświetl",
clearSearch: "Wyczyść wyszukiwanie",
clearAllFilters: "Wyczyść wszystkie filtry",
sortBy: "Sortuj według"
},
// Dashboard
@@ -127,9 +135,10 @@ const translations = {
city: "Miasto",
address: "Adres",
plot: "Działka",
district: "Dzielnica",
unit: "Jednostka",
district: "Jednostka ewidencyjna",
unit: "Obręb",
finishDate: "Data zakończenia",
type: "Typ",
contact: "Kontakt",
coordinates: "Współrzędne",
notes: "Notatki",
@@ -144,19 +153,44 @@ const translations = {
searchPlaceholder: "Szukaj projektów po nazwie, mieście lub adresie...",
noProjects: "Brak projektów",
noProjectsMessage: "Rozpocznij od utworzenia swojego pierwszego projektu.",
notFinished: "Nie zakończone",
projects: "projektów",
mapView: "Widok mapy",
createFirstProject: "Utwórz pierwszy projekt",
noMatchingResults: "Brak projektów pasujących do kryteriów wyszukiwania. Spróbuj zmienić wyszukiwane frazy.",
showingResults: "Wyświetlono {shown} z {total} projektów",
deleteConfirm: "Czy na pewno chcesz usunąć ten projekt?",
deleteSuccess: "Projekt został pomyślnie usunięty",
createSuccess: "Projekt został pomyślnie utworzony",
updateSuccess: "Projekt został pomyślnie zaktualizowany",
saveError: "Nie udało się zapisać projektu",
enterProjectName: "Wprowadź nazwę projektu",
enterCity: "Wprowadź miasto",
enterAddress: "Wprowadź adres",
enterPlotNumber: "Wprowadź numer działki",
enterDistrict: "Wprowadź dzielnicę",
enterUnit: "Wprowadź jednostkę",
enterDistrict: "Wprowadź jednostkę ewidencyjną",
enterUnit: "Wprowadź obręb",
enterContactDetails: "Wprowadź dane kontaktowe",
coordinatesPlaceholder: "np. 49.622958,20.629562",
enterNotes: "Wprowadź notatki..."
enterNotes: "Wprowadź notatki...",
createProject: "Utwórz projekt",
updateProject: "Aktualizuj projekt",
creating: "Tworzenie...",
updating: "Aktualizowanie...",
projectDetails: "Szczegóły projektu",
editProjectDetails: "Edytuj szczegóły projektu",
contract: "Umowa",
selectContract: "Wybierz umowę",
investmentNumber: "Numer inwestycji",
enterInvestmentNumber: "Wprowadź numer inwestycji",
enterWP: "Wprowadź WP",
placeholders: {
contact: "Wprowadź dane kontaktowe",
coordinates: "np. 49.622958,20.629562",
notes: "Wprowadź notatki...",
investmentNumber: "Wprowadź numer inwestycji",
wp: "Wprowadź WP"
}
},
// Contracts
@@ -240,6 +274,19 @@ const translations = {
actions: "Działania",
urgent: "Pilne",
updateTask: "Aktualizuj zadanie",
taskType: "Typ zadania",
fromTemplate: "Z szablonu",
customTask: "Zadanie niestandardowe",
selectTemplate: "Wybierz szablon zadania",
chooseTemplate: "Wybierz szablon zadania...",
enterTaskName: "Wprowadź nazwę zadania...",
enterDescription: "Wprowadź opis zadania (opcjonalnie)...",
addTask: "Dodaj zadanie",
adding: "Dodawanie...",
addTaskError: "Nie udało się dodać zadania do projektu",
notes: "notatki",
deleteNote: "Usuń notatkę",
deleteError: "Błąd usuwania zadania",
notStarted: "Nie rozpoczęte",
days: "dni"
},
@@ -454,7 +501,14 @@ const translations = {
addNote: "Add Note",
addNoteSuccess: "Note added",
addNoteError: "Failed to save note",
addNotePlaceholder: "Add a new note..."
addNotePlaceholder: "Add a new note...",
status: "Status",
type: "Type",
actions: "Actions",
view: "View",
clearSearch: "Clear search",
clearAllFilters: "Clear all filters",
sortBy: "Sort by"
},
dashboard: {
@@ -517,6 +571,7 @@ const translations = {
district: "District",
unit: "Unit",
finishDate: "Finish Date",
type: "Type",
contact: "Contact",
coordinates: "Coordinates",
notes: "Notes",
@@ -531,10 +586,17 @@ const translations = {
searchPlaceholder: "Search projects by name, city or address...",
noProjects: "No projects",
noProjectsMessage: "Get started by creating your first project.",
notFinished: "Not finished",
projects: "projects",
mapView: "Map View",
createFirstProject: "Create first project",
noMatchingResults: "No projects match the search criteria. Try changing your search terms.",
showingResults: "Showing {shown} of {total} projects",
deleteConfirm: "Are you sure you want to delete this project?",
deleteSuccess: "Project deleted successfully",
createSuccess: "Project created successfully",
updateSuccess: "Project updated successfully",
saveError: "Failed to save project",
enterProjectName: "Enter project name",
enterCity: "Enter city",
enterAddress: "Enter address",
@@ -543,7 +605,25 @@ const translations = {
enterUnit: "Enter unit",
enterContactDetails: "Enter contact details",
coordinatesPlaceholder: "e.g., 49.622958,20.629562",
enterNotes: "Enter notes..."
enterNotes: "Enter notes...",
createProject: "Create Project",
updateProject: "Update Project",
creating: "Creating...",
updating: "Updating...",
projectDetails: "Project Details",
editProjectDetails: "Edit Project Details",
contract: "Contract",
selectContract: "Select Contract",
investmentNumber: "Investment Number",
enterInvestmentNumber: "Enter investment number",
enterWP: "Enter WP",
placeholders: {
contact: "Enter contact details",
coordinates: "e.g., 49.622958,20.629562",
notes: "Enter notes...",
investmentNumber: "Enter investment number",
wp: "Enter WP"
}
},
contracts: {
@@ -625,6 +705,19 @@ const translations = {
actions: "Actions",
urgent: "Urgent",
updateTask: "Update Task",
taskType: "Task Type",
fromTemplate: "From Template",
customTask: "Custom Task",
selectTemplate: "Select Task Template",
chooseTemplate: "Choose a task template...",
enterTaskName: "Enter custom task name...",
enterDescription: "Enter task description (optional)...",
addTask: "Add Task",
adding: "Adding...",
addTaskError: "Failed to add task to project",
notes: "notes",
deleteNote: "Delete note",
deleteError: "Error deleting task",
notStarted: "Not started",
days: "days"
},

View File

@@ -362,5 +362,24 @@ export default function initializeDatabase() {
-- Create indexes for file attachments
CREATE INDEX IF NOT EXISTS idx_file_attachments_entity ON file_attachments(entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_file_attachments_uploaded_by ON file_attachments(uploaded_by);
-- Generic field change history table
CREATE TABLE IF NOT EXISTS field_change_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
table_name TEXT NOT NULL,
record_id INTEGER NOT NULL,
field_name TEXT NOT NULL,
old_value TEXT,
new_value TEXT,
changed_by INTEGER,
changed_at TEXT DEFAULT CURRENT_TIMESTAMP,
change_reason TEXT,
FOREIGN KEY (changed_by) REFERENCES users(id)
);
-- Create indexes for field change history
CREATE INDEX IF NOT EXISTS idx_field_history_table_record ON field_change_history(table_name, record_id);
CREATE INDEX IF NOT EXISTS idx_field_history_field ON field_change_history(table_name, record_id, field_name);
CREATE INDEX IF NOT EXISTS idx_field_history_changed_by ON field_change_history(changed_by);
`);
}

View File

@@ -0,0 +1,94 @@
import db from "../db.js";
/**
* Log a field change to the history table
*/
export function logFieldChange(tableName, recordId, fieldName, oldValue, newValue, changedBy = null, reason = null) {
// Don't log if values are the same
if (oldValue === newValue) return null;
const stmt = db.prepare(`
INSERT INTO field_change_history
(table_name, record_id, field_name, old_value, new_value, changed_by, change_reason)
VALUES (?, ?, ?, ?, ?, ?, ?)
`);
return stmt.run(
tableName,
recordId,
fieldName,
oldValue || null,
newValue || null,
changedBy,
reason
);
}
/**
* Get field change history for a specific field
*/
export function getFieldHistory(tableName, recordId, fieldName) {
const stmt = db.prepare(`
SELECT
fch.*,
u.name as changed_by_name,
u.username as changed_by_username
FROM field_change_history fch
LEFT JOIN users u ON fch.changed_by = u.id
WHERE fch.table_name = ? AND fch.record_id = ? AND fch.field_name = ?
ORDER BY fch.changed_at DESC
`);
return stmt.all(tableName, recordId, fieldName);
}
/**
* Get all field changes for a specific record
*/
export function getAllFieldHistory(tableName, recordId) {
const stmt = db.prepare(`
SELECT
fch.*,
u.name as changed_by_name,
u.username as changed_by_username
FROM field_change_history fch
LEFT JOIN users u ON fch.changed_by = u.id
WHERE fch.table_name = ? AND fch.record_id = ?
ORDER BY fch.changed_at DESC, fch.field_name ASC
`);
return stmt.all(tableName, recordId);
}
/**
* Check if a field has any change history
*/
export function hasFieldHistory(tableName, recordId, fieldName) {
const stmt = db.prepare(`
SELECT COUNT(*) as count
FROM field_change_history
WHERE table_name = ? AND record_id = ? AND field_name = ?
`);
const result = stmt.get(tableName, recordId, fieldName);
return result.count > 0;
}
/**
* Get the most recent change for a field
*/
export function getLatestFieldChange(tableName, recordId, fieldName) {
const stmt = db.prepare(`
SELECT
fch.*,
u.name as changed_by_name,
u.username as changed_by_username
FROM field_change_history fch
LEFT JOIN users u ON fch.changed_by = u.id
WHERE fch.table_name = ? AND fch.record_id = ? AND fch.field_name = ?
ORDER BY fch.changed_at DESC
LIMIT 1
`);
return stmt.get(tableName, recordId, fieldName);
}

View File

@@ -6,7 +6,7 @@ export function getNotesByProjectId(project_id) {
`
SELECT n.*,
u.name as created_by_name,
u.email as created_by_email
u.username as created_by_username
FROM notes n
LEFT JOIN users u ON n.created_by = u.id
WHERE n.project_id = ?
@@ -31,7 +31,7 @@ export function getNotesByTaskId(task_id) {
`
SELECT n.*,
u.name as created_by_name,
u.email as created_by_email
u.username as created_by_username
FROM notes n
LEFT JOIN users u ON n.created_by = u.id
WHERE n.task_id = ?
@@ -64,7 +64,7 @@ export function getAllNotesWithUsers() {
`
SELECT n.*,
u.name as created_by_name,
u.email as created_by_email,
u.username as created_by_username,
p.project_name,
COALESCE(pt.custom_task_name, t.name) as task_name
FROM notes n
@@ -85,7 +85,7 @@ export function getNotesByCreator(userId) {
`
SELECT n.*,
u.name as created_by_name,
u.email as created_by_email,
u.username as created_by_username,
p.project_name,
COALESCE(pt.custom_task_name, t.name) as task_name
FROM notes n

View File

@@ -1,5 +1,6 @@
import db from "../db.js";
import { addNoteToTask } from "./notes.js";
import { getUserLanguage, serverT, translateStatus, translatePriority } from "../serverTranslations.js";
// Get all task templates (for dropdown selection)
export function getAllTaskTemplates() {
@@ -182,8 +183,10 @@ export function updateProjectTaskStatus(taskId, status, userId = null) {
// Add system note for status change (only if status actually changed)
if (result.changes > 0 && oldStatus !== status) {
const taskName = currentTask.task_name || "Unknown task";
const logMessage = `Status changed from "${oldStatus}" to "${status}"`;
const language = getUserLanguage(); // Default to Polish for now
const fromStatus = translateStatus(oldStatus, language);
const toStatus = translateStatus(status, language);
const logMessage = `${serverT("Status changed from", language)} "${fromStatus}" ${serverT("to", language)} "${toStatus}"`;
addNoteToTask(taskId, logMessage, true, userId);
}
@@ -359,41 +362,48 @@ export function updateProjectTask(taskId, updates, userId = null) {
// Log the update
if (userId) {
const language = getUserLanguage(); // Default to Polish for now
const changes = [];
if (
updates.priority !== undefined &&
updates.priority !== currentTask.priority
) {
const oldPriority = translatePriority(currentTask.priority, language) || serverT("None", language);
const newPriority = translatePriority(updates.priority, language) || serverT("None", language);
changes.push(
`Priority: ${currentTask.priority || "None"}${
updates.priority || "None"
}`
`${serverT("Priority", language)}: ${oldPriority}${newPriority}`
);
}
if (updates.status !== undefined && updates.status !== currentTask.status) {
const oldStatus = translateStatus(currentTask.status, language) || serverT("None", language);
const newStatus = translateStatus(updates.status, language) || serverT("None", language);
changes.push(
`Status: ${currentTask.status || "None"} ${updates.status || "None"}`
`${serverT("Status", language)}: ${oldStatus}${newStatus}`
);
}
if (
updates.assigned_to !== undefined &&
updates.assigned_to !== currentTask.assigned_to
) {
changes.push(`Assignment updated`);
changes.push(serverT("Assignment updated", language));
}
if (
updates.date_started !== undefined &&
updates.date_started !== currentTask.date_started
) {
const oldDate = currentTask.date_started || serverT("None", language);
const newDate = updates.date_started || serverT("None", language);
changes.push(
`Date started: ${currentTask.date_started || "None"}${
updates.date_started || "None"
}`
`${serverT("Date started", language)}: ${oldDate}${newDate}`
);
}
if (changes.length > 0) {
const logMessage = `Task updated: ${changes.join(", ")}`;
const logMessage = `${serverT("Task updated", language)}: ${changes.join(", ")}`;
addNoteToTask(taskId, logMessage, true, userId);
}
}

View File

@@ -0,0 +1,79 @@
// Server-side translations for system messages
// This is separate from the client-side translation system
const serverTranslations = {
pl: {
"Status changed from": "Status zmieniony z",
"to": "na",
"Priority": "Priorytet",
"Status": "Status",
"Assignment updated": "Przypisanie zaktualizowane",
"Date started": "Data rozpoczęcia",
"None": "Brak",
"Task updated": "Zadanie zaktualizowane",
"pending": "oczekujące",
"in_progress": "w trakcie",
"completed": "ukończone",
"cancelled": "anulowane",
"on_hold": "wstrzymane",
"low": "niski",
"normal": "normalny",
"medium": "średni",
"high": "wysoki",
"urgent": "pilny"
},
en: {
"Status changed from": "Status changed from",
"to": "to",
"Priority": "Priority",
"Status": "Status",
"Assignment updated": "Assignment updated",
"Date started": "Date started",
"None": "None",
"Task updated": "Task updated",
"pending": "pending",
"in_progress": "in_progress",
"completed": "completed",
"cancelled": "cancelled",
"on_hold": "on_hold",
"low": "low",
"normal": "normal",
"medium": "medium",
"high": "high",
"urgent": "urgent"
}
};
// Get user's preferred language from request headers or default to Polish
export function getUserLanguage(req = null) {
// For now, default to Polish. In the future, this could be determined from:
// - Request headers (Accept-Language)
// - User profile settings
// - Session data
return 'pl';
}
// Translate a key for server-side use
export function serverT(key, language = 'pl') {
if (serverTranslations[language] && serverTranslations[language][key]) {
return serverTranslations[language][key];
}
// Fallback to English if Polish not found
if (language !== 'en' && serverTranslations.en[key]) {
return serverTranslations.en[key];
}
// Return the key itself if no translation found
return key;
}
// Helper function to translate status values
export function translateStatus(status, language = 'pl') {
return serverT(status, language);
}
// Helper function to translate priority values
export function translatePriority(priority, language = 'pl') {
return serverT(priority, language);
}