feat: Add NoteForm, ProjectForm, and ProjectTaskForm components

- Implemented NoteForm for adding notes to projects.
- Created ProjectForm for managing project details with contract selection.
- Developed ProjectTaskForm for adding tasks to projects, supporting both templates and custom tasks.

feat: Add ProjectTasksSection component

- Introduced ProjectTasksSection to display and manage tasks for a specific project.
- Includes functionality for adding, updating, and deleting tasks.

feat: Create TaskTemplateForm for managing task templates

- Added TaskTemplateForm for creating new task templates with required wait days.

feat: Implement UI components

- Created reusable UI components: Badge, Button, Card, Input, Loading, Navigation.
- Enhanced user experience with consistent styling and functionality.

feat: Set up database and queries

- Initialized SQLite database with tables for contracts, projects, tasks, project tasks, and notes.
- Implemented queries for managing contracts, projects, tasks, and notes.

chore: Add error handling and loading states

- Improved error handling in forms and data fetching.
- Added loading states for better user feedback during data operations.
This commit is contained in:
Chop
2025-06-02 22:07:05 +02:00
parent aa1eb99ce9
commit d0586f2876
43 changed files with 3272 additions and 137 deletions

6
.gitignore vendored
View File

@@ -39,3 +39,9 @@ yarn-error.log*
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts next-env.d.ts
# database
/data
# kosz
/kosz

20
Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
# Use Node.js 22.11.0 as the base image
FROM node:22.11.0
# Set the working directory
WORKDIR /app
# Copy package.json and package-lock.json (if any)
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the app
COPY . .
# Expose the default Next.js port
EXPOSE 3000
# Start the dev server
CMD ["npm", "run", "dev"]

12
docker-compose.yml Normal file
View File

@@ -0,0 +1,12 @@
version: "3.9"
services:
app:
build: .
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
- NODE_ENV=development

665
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,15 +9,17 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"better-sqlite3": "^11.10.0",
"date-fns": "^4.1.0",
"next": "15.1.8",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0"
"next": "15.1.8"
}, },
"devDependencies": { "devDependencies": {
"postcss": "^8", "@eslint/eslintrc": "^3",
"tailwindcss": "^3.4.1",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "15.1.8", "eslint-config-next": "15.1.8",
"@eslint/eslintrc": "^3" "postcss": "^8",
"tailwindcss": "^3.4.1"
} }
} }

View File

@@ -0,0 +1,39 @@
import db from "@/lib/db";
import { NextResponse } from "next/server";
export async function GET() {
const contracts = db
.prepare(
`
SELECT contract_id, contract_number, contract_name FROM contracts
`
)
.all();
return NextResponse.json(contracts);
}
export async function POST(req) {
const data = await req.json();
db.prepare(
`
INSERT INTO contracts (
contract_number,
contract_name,
customer_contract_number,
customer,
investor,
date_signed,
finish_date
) VALUES (?, ?, ?, ?, ?, ?, ?)
`
).run(
data.contract_number,
data.contract_name,
data.customer_contract_number,
data.customer,
data.investor,
data.date_signed,
data.finish_date
);
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,44 @@
import db from "@/lib/db";
import { NextResponse } from "next/server";
export async function POST(req) {
const { project_id, task_id, note } = await req.json();
if (!note || (!project_id && !task_id)) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}
db.prepare(
`
INSERT INTO notes (project_id, task_id, note)
VALUES (?, ?, ?)
`
).run(project_id || null, task_id || null, note);
return NextResponse.json({ success: true });
}
export async function DELETE(_, { params }) {
const { id } = params;
db.prepare("DELETE FROM notes WHERE note_id = ?").run(id);
return NextResponse.json({ success: true });
}
export async function PUT(req, { params }) {
const noteId = params.id;
const { note } = await req.json();
if (!note || !noteId) {
return NextResponse.json({ error: "Missing note or ID" }, { status: 400 });
}
db.prepare(
`
UPDATE notes SET note = ? WHERE note_id = ?
`
).run(note, noteId);
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,40 @@
import {
updateProjectTaskStatus,
deleteProjectTask,
} from "@/lib/queries/tasks";
import { NextResponse } from "next/server";
// PATCH: Update project task status
export async function PATCH(req, { params }) {
try {
const { status } = await req.json();
if (!status) {
return NextResponse.json(
{ error: "Status is required" },
{ status: 400 }
);
}
updateProjectTaskStatus(params.id, status);
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json(
{ error: "Failed to update project task" },
{ status: 500 }
);
}
}
// DELETE: Delete a project task
export async function DELETE(req, { params }) {
try {
deleteProjectTask(params.id);
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json(
{ error: "Failed to delete project task" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,52 @@
import {
getAllTaskTemplates,
getProjectTasks,
createProjectTask,
} from "@/lib/queries/tasks";
import { NextResponse } from "next/server";
// GET: Get all project tasks or task templates based on query params
export async function GET(req) {
const { searchParams } = new URL(req.url);
const projectId = searchParams.get("project_id");
if (projectId) {
// Get tasks for a specific project
const tasks = getProjectTasks(projectId);
return NextResponse.json(tasks);
} else {
// Default: return all task templates
const templates = getAllTaskTemplates();
return NextResponse.json(templates);
}
}
// POST: Create a new project task
export async function POST(req) {
try {
const data = await req.json();
if (!data.project_id) {
return NextResponse.json(
{ error: "project_id is required" },
{ status: 400 }
);
}
// Check if it's a template task or custom task
if (!data.task_template_id && !data.custom_task_name) {
return NextResponse.json(
{ error: "Either task_template_id or custom_task_name is required" },
{ status: 400 }
);
}
const result = createProjectTask(data);
return NextResponse.json({ success: true, id: result.lastInsertRowid });
} catch (error) {
return NextResponse.json(
{ error: "Failed to create project task" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,22 @@
import {
getProjectById,
updateProject,
deleteProject,
} from "@/lib/queries/projects";
import { NextResponse } from "next/server";
export async function GET(_, { params }) {
const project = getProjectById(params.id);
return NextResponse.json(project);
}
export async function PUT(req, { params }) {
const data = await req.json();
updateProject(params.id, data);
return NextResponse.json({ success: true });
}
export async function DELETE(_, { params }) {
deleteProject(params.id);
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,17 @@
import { getAllProjects, createProject } from "@/lib/queries/projects";
import initializeDatabase from "@/lib/init-db";
import { NextResponse } from "next/server";
// Make sure the DB is initialized before queries run
initializeDatabase();
export async function GET() {
const projects = getAllProjects();
return NextResponse.json(projects);
}
export async function POST(req) {
const data = await req.json();
createProject(data);
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,20 @@
import db from "@/lib/db";
import { NextResponse } from "next/server";
// POST: create new template
export async function POST(req) {
const { name, max_wait_days } = await req.json();
if (!name) {
return NextResponse.json({ error: "Name is required" }, { status: 400 });
}
db.prepare(
`
INSERT INTO tasks (name, max_wait_days, is_standard)
VALUES (?, ?, 1)
`
).run(name, max_wait_days || 0);
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,8 @@
import { getAllTaskTemplates } from "@/lib/queries/tasks";
import { NextResponse } from "next/server";
// GET: Get all task templates
export async function GET() {
const templates = getAllTaskTemplates();
return NextResponse.json(templates);
}

View File

@@ -0,0 +1,10 @@
import ContractForm from "@/components/ContractForm";
export default function NewContractPage() {
return (
<div className="p-4 max-w-2xl mx-auto">
<h1 className="text-xl font-bold mb-4">Nowa umowa</h1>
<ContractForm />
</div>
);
}

View File

@@ -0,0 +1,39 @@
import db from "@/lib/db";
import { NextResponse } from "next/server";
export async function GET() {
const contracts = db
.prepare(
`
SELECT contract_id, contract_number, contract_name FROM contracts
`
)
.all();
return NextResponse.json(contracts);
}
export async function POST(req) {
const data = await req.json();
db.prepare(
`
INSERT INTO contracts (
contract_number,
contract_name,
customer_contract_number,
customer,
investor,
date_signed,
finish_date
) VALUES (?, ?, ?, ?, ?, ?, ?)
`
).run(
data.contract_number,
data.contract_name,
data.customer_contract_number,
data.customer,
data.investor,
data.date_signed,
data.finish_date
);
return NextResponse.json({ success: true });
}

View File

@@ -7,15 +7,54 @@
--foreground: #171717; --foreground: #171717;
} }
@media (prefers-color-scheme: dark) { /* @media (prefers-color-scheme: dark) {
:root { :root {
--background: #0a0a0a; --background: #0a0a0a;
--foreground: #ededed; --foreground: #ededed;
} }
} } */
body { body {
color: var(--foreground); color: var(--foreground);
background: var(--background); background: var(--background);
font-family: Arial, Helvetica, sans-serif; font-family: Helvetica, Arial, sans-serif;
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
/* Focus styles */
.focus-ring {
@apply focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2;
}
/* Animation utilities */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-fade-in {
animation: fadeIn 0.3s ease-out;
} }

View File

@@ -1,5 +1,6 @@
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css"; import "./globals.css";
import Navigation from "@/components/ui/Navigation";
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans", variable: "--font-geist-sans",
@@ -12,8 +13,8 @@ const geistMono = Geist_Mono({
}); });
export const metadata = { export const metadata = {
title: "Create Next App", title: "Project Management Panel",
description: "Generated by create next app", description: "Professional project management dashboard",
}; };
export default function RootLayout({ children }) { export default function RootLayout({ children }) {
@@ -22,7 +23,8 @@ export default function RootLayout({ children }) {
<body <body
className={`${geistSans.variable} ${geistMono.variable} antialiased`} className={`${geistSans.variable} ${geistMono.variable} antialiased`}
> >
{children} <Navigation />
<main>{children}</main>
</body> </body>
</html> </html>
); );

View File

@@ -1,101 +1,360 @@
import Image from "next/image"; "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";
export default function Home() { export default function Home() {
return ( const [stats, setStats] = useState({
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> totalProjects: 0,
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start"> activeProjects: 0,
<Image pendingTasks: 0,
className="dark:invert" completedTasks: 0,
src="/next.svg" });
alt="Next.js logo" const [recentProjects, setRecentProjects] = useState([]);
width={180} const [loading, setLoading] = useState(true);
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
src/app/page.js
</code>
.
</li>
<li>Save and see your changes instantly.</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row"> useEffect(() => {
<a const fetchDashboardData = async () => {
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5" try {
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" // Fetch projects for stats and recent projects
target="_blank" const projectsRes = await fetch("/api/projects");
rel="noopener noreferrer" const projects = await projectsRes.json();
>
<Image setStats({
className="dark:invert" totalProjects: projects.length,
src="/vercel.svg" activeProjects: projects.filter(
alt="Vercel logomark" (p) => new Date(p.finish_date) >= new Date()
width={20} ).length,
height={20} pendingTasks: 0, // You might want to fetch this from tasks API
/> completedTasks: 0, // You might want to fetch this from tasks API
Deploy now });
</a>
<a setRecentProjects(projects.slice(0, 5));
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44" } catch (error) {
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" console.error("Failed to fetch dashboard data:", error);
target="_blank" } finally {
rel="noopener noreferrer" setLoading(false);
> }
Read our docs };
</a>
fetchDashboardData();
}, []);
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-6xl mx-auto p-6">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<p className="text-gray-600 mt-1">
Overview of your projects and tasks
</p>
</div> </div>
</main>
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center"> {/* Stats Cards */}
<a <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
className="flex items-center gap-2 hover:underline hover:underline-offset-4" <Card>
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" <CardContent className="p-6">
target="_blank" <div className="flex items-center">
rel="noopener noreferrer" <div className="flex-1">
<p className="text-sm font-medium text-gray-600">
Total Projects
</p>
<p className="text-2xl font-bold text-gray-900">
{stats.totalProjects}
</p>
</div>
<div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
<svg
className="w-6 h-6 text-blue-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
> >
<Image <path
aria-hidden strokeLinecap="round"
src="/file.svg" strokeLinejoin="round"
alt="File icon" strokeWidth={2}
width={16} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
height={16}
/> />
Learn </svg>
</a> </div>
<a </div>
className="flex items-center gap-2 hover:underline hover:underline-offset-4" </CardContent>
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" </Card>
target="_blank"
rel="noopener noreferrer" <Card>
<CardContent className="p-6">
<div className="flex items-center">
<div className="flex-1">
<p className="text-sm font-medium text-gray-600">
Active Projects
</p>
<p className="text-2xl font-bold text-gray-900">
{stats.activeProjects}
</p>
</div>
<div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
<svg
className="w-6 h-6 text-green-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
> >
<Image <path
aria-hidden strokeLinecap="round"
src="/window.svg" strokeLinejoin="round"
alt="Window icon" strokeWidth={2}
width={16} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
height={16}
/> />
Examples </svg>
</a> </div>
<a </div>
className="flex items-center gap-2 hover:underline hover:underline-offset-4" </CardContent>
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" </Card>
target="_blank"
rel="noopener noreferrer" <Card>
<CardContent className="p-6">
<div className="flex items-center">
<div className="flex-1">
<p className="text-sm font-medium text-gray-600">
Pending Tasks
</p>
<p className="text-2xl font-bold text-gray-900">
{stats.pendingTasks}
</p>
</div>
<div className="w-10 h-10 bg-yellow-100 rounded-full flex items-center justify-center">
<svg
className="w-6 h-6 text-yellow-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
> >
<Image <path
aria-hidden strokeLinecap="round"
src="/globe.svg" strokeLinejoin="round"
alt="Globe icon" strokeWidth={2}
width={16} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
height={16}
/> />
Go to nextjs.org </svg>
</a> </div>
</footer> </div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center">
<div className="flex-1">
<p className="text-sm font-medium text-gray-600">
Completed Tasks
</p>
<p className="text-2xl font-bold text-gray-900">
{stats.completedTasks}
</p>
</div>
<div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
<svg
className="w-6 h-6 text-purple-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 13l4 4L19 7"
/>
</svg>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Recent Projects */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900">
Recent Projects
</h2>
<Link href="/projects">
<Button variant="outline" size="sm">
View All
</Button>
</Link>
</div>
</CardHeader>
<CardContent className="p-0">
{loading ? (
<div className="p-6">
<div className="animate-pulse space-y-3">
{[...Array(3)].map((_, i) => (
<div key={i} className="flex items-center space-x-3">
<div className="w-3 h-3 bg-gray-200 rounded-full"></div>
<div className="flex-1 space-y-1">
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
<div className="h-3 bg-gray-200 rounded w-1/2"></div>
</div>
</div>
))}
</div>
</div>
) : recentProjects.length === 0 ? (
<div className="p-6 text-center">
<p className="text-gray-500">No projects yet.</p>
<Link href="/projects/new" className="mt-2 inline-block">
<Button variant="primary" size="sm">
Create First Project
</Button>
</Link>
</div>
) : (
<div className="divide-y divide-gray-200">
{recentProjects.map((project) => (
<div
key={project.project_id}
className="p-4 hover:bg-gray-50 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex-1 min-w-0">
<Link
href={`/projects/${project.project_id}`}
className="text-sm font-medium text-blue-600 hover:text-blue-800 truncate block"
>
{project.project_name}
</Link>
<p className="text-xs text-gray-500 mt-1">
{project.city} Due: {project.finish_date}
</p>
</div>
<Badge
variant={
new Date(project.finish_date) >= new Date()
? "success"
: "danger"
}
size="xs"
>
{new Date(project.finish_date) >= new Date()
? "Active"
: "Overdue"}
</Badge>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Quick Actions */}
<Card>
<CardHeader>
<h2 className="text-xl font-semibold text-gray-900">
Quick Actions
</h2>
</CardHeader>
<CardContent className="space-y-4">
<Link href="/projects/new" className="block">
<div className="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer">
<div className="flex items-center">
<div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mr-3">
<svg
className="w-6 h-6 text-blue-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
</div>
<div>
<h3 className="text-sm font-medium text-gray-900">
New Project
</h3>
<p className="text-xs text-gray-500">
Create a new project
</p>
</div>
</div>
</div>
</Link>
<Link href="/contracts/new" className="block">
<div className="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer">
<div className="flex items-center">
<div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center mr-3">
<svg
className="w-6 h-6 text-green-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
</div>
<div>
<h3 className="text-sm font-medium text-gray-900">
New Contract
</h3>
<p className="text-xs text-gray-500">
Add a new contract
</p>
</div>
</div>
</div>
</Link>
<Link href="/tasks/templates/new" className="block">
<div className="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer">
<div className="flex items-center">
<div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center mr-3">
<svg
className="w-6 h-6 text-purple-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
/>
</svg>
</div>
<div>
<h3 className="text-sm font-medium text-gray-900">
Task Template
</h3>
<p className="text-xs text-gray-500">
Create task template
</p>
</div>
</div>
</div>
</Link>
</CardContent>
</Card>
</div>
</div>
</div> </div>
); );
} }

View File

@@ -0,0 +1,15 @@
import ProjectForm from "@/components/ProjectForm";
export default async function EditProjectPage({ params }) {
const res = await fetch(`http://localhost:3000/api/projects/${params.id}`, {
cache: "no-store",
});
const project = await res.json();
return (
<div className="p-4 max-w-2xl mx-auto">
<h1 className="text-xl font-bold mb-4">Edit Project</h1>
<ProjectForm initialData={project} />
</div>
);
}

View File

@@ -0,0 +1,234 @@
import {
getProjectWithContract,
getNotesForProject,
} from "@/lib/queries/projects";
import NoteForm from "@/components/NoteForm";
import ProjectTasksSection from "@/components/ProjectTasksSection";
import { Card, CardHeader, CardContent } from "@/components/ui/Card";
import Button from "@/components/ui/Button";
import Badge from "@/components/ui/Badge";
import Link from "next/link";
import { differenceInCalendarDays, parseISO } from "date-fns";
export default async function ProjectViewPage({ params }) {
const project = getProjectWithContract(params.id);
const notes = getNotesForProject(params.id);
const daysRemaining = differenceInCalendarDays(
parseISO(project.finish_date),
new Date()
);
if (!project) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<Card>
<CardContent className="text-center py-8">
<p className="text-red-600 text-lg">Project not found.</p>
<Link href="/projects" className="mt-4 inline-block">
<Button variant="primary">Back to Projects</Button>
</Link>
</CardContent>
</Card>
</div>
);
}
const getDeadlineVariant = (days) => {
if (days < 0) return "danger";
if (days <= 7) return "warning";
return "success";
};
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-6xl mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<Link href="/projects">
<Button variant="outline" size="sm">
<svg
className="w-4 h-4 mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
</svg>
Back to Projects
</Button>
</Link>
<Link href={`/projects/${params.id}/edit`}>
<Button variant="secondary">Edit Project</Button>
</Link>
</div>
<div className="flex items-center gap-4 mb-6">
<h1 className="text-3xl font-bold text-gray-900">
{project.project_name}
</h1>
<Badge variant={getDeadlineVariant(daysRemaining)} size="md">
{daysRemaining === 0
? "Due Today"
: daysRemaining > 0
? `${daysRemaining} days left`
: `${Math.abs(daysRemaining)} days overdue`}
</Badge>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<h2 className="text-xl font-semibold text-gray-900">
Project Information
</h2>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<span className="text-sm font-medium text-gray-500">
Location
</span>
<p className="text-gray-900">{project.city}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Address
</span>
<p className="text-gray-900">{project.address}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Plot
</span>
<p className="text-gray-900">{project.plot}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
District
</span>
<p className="text-gray-900">{project.district}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Unit
</span>
<p className="text-gray-900">{project.unit}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Deadline
</span>
<p className="text-gray-900">{project.finish_date}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">WP</span>
<p className="text-gray-900">{project.wp}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Investment Number
</span>
<p className="text-gray-900">{project.investment_number}</p>
</div>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Contact
</span>
<p className="text-gray-900">{project.contact}</p>
</div>
{project.notes && (
<div>
<span className="text-sm font-medium text-gray-500">
Notes
</span>
<p className="text-gray-900">{project.notes}</p>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<h2 className="text-xl font-semibold text-gray-900">
Contract Details
</h2>
</CardHeader>
<CardContent className="space-y-4">
<div>
<span className="text-sm font-medium text-gray-500">
Contract Number
</span>
<p className="text-gray-900">{project.contract_number}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Contract Name
</span>
<p className="text-gray-900">{project.contract_name}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Customer
</span>
<p className="text-gray-900">{project.customer}</p>
</div>
<div>
<span className="text-sm font-medium text-gray-500">
Investor
</span>
<p className="text-gray-900">{project.investor}</p>
</div>
</CardContent>
</Card>
</div>
<ProjectTasksSection projectId={params.id} />
<Card>
<CardHeader>
<h2 className="text-xl font-semibold text-gray-900">Notes</h2>
</CardHeader>
<CardContent>
<div className="mb-6">
<NoteForm projectId={params.id} />
</div>
{notes.length === 0 ? (
<div className="text-center py-8">
<div className="text-gray-400 mb-2">
<svg
className="w-12 h-12 mx-auto"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a1 1 0 110 2h-3a1 1 0 01-1-1v-1H8v1a1 1 0 01-1 1H4a1 1 0 110-2V4zm3 1h2v4a1 1 0 001 1h1a1 1 0 100-2v-1a2 2 0 00-2-2H7a1 1 0 000 2z"
/>
</svg>
</div>
<p className="text-gray-500">No notes yet.</p>
</div>
) : (
<div className="space-y-3">
{notes.map((n) => (
<div
key={n.note_id}
className="border border-gray-200 p-4 rounded-lg bg-gray-50"
>
<p className="text-sm text-gray-500 mb-2">{n.note_date}</p>
<p className="text-gray-900">{n.note}</p>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,10 @@
import ProjectForm from "@/components/ProjectForm";
export default function NewProjectPage() {
return (
<div className="p-4 max-w-2xl mx-auto">
<h1 className="text-xl font-bold mb-4">New Project</h1>
<ProjectForm />
</div>
);
}

154
src/app/projects/page.js Normal file
View File

@@ -0,0 +1,154 @@
"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";
export default function ProjectListPage() {
const [projects, setProjects] = useState([]);
useEffect(() => {
fetch("/api/projects")
.then((res) => res.json())
.then(setProjects);
}, []);
async function handleDelete(id) {
const confirmed = confirm("Are you sure you want to delete this project?");
if (!confirmed) return;
const res = await fetch(`/api/projects/${id}`, {
method: "DELETE",
});
if (res.ok) {
setProjects((prev) => prev.filter((p) => p.project_id !== id));
}
}
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-6xl mx-auto p-6">
<div className="flex justify-between items-center mb-8">
<div>
<h1 className="text-3xl font-bold text-gray-900">Projects</h1>
<p className="text-gray-600 mt-1">Manage and track your projects</p>
</div>
<Link href="/projects/new">
<Button variant="primary" size="lg">
<svg
className="w-5 h-5 mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
Add Project
</Button>
</Link>
</div>
{projects.length === 0 ? (
<Card>
<CardContent className="text-center py-12">
<div className="text-gray-400 mb-4">
<svg
className="w-16 h-16 mx-auto"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm0 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V8zm0 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1v-2z"
clipRule="evenodd"
/>
</svg>
</div>
<h3 className="text-lg font-medium text-gray-900 mb-2">
No projects yet
</h3>
<p className="text-gray-500 mb-6">
Get started by creating your first project
</p>
<Link href="/projects/new">
<Button variant="primary">Create First Project</Button>
</Link>
</CardContent>
</Card>
) : (
<div className="space-y-4">
{projects.map((project) => (
<Card
key={project.project_id}
className="hover:shadow-md transition-shadow"
>
<CardContent className="p-6">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
<Link
href={`/projects/${project.project_id}`}
className="text-xl font-semibold text-blue-600 hover:text-blue-800 transition-colors truncate"
>
{project.project_name}
</Link>
<Badge variant="primary" size="sm">
{project.project_number}
</Badge>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm text-gray-600 mb-4">
<div>
<span className="font-medium">Location:</span>{" "}
{project.city}
</div>
<div>
<span className="font-medium">Finish Date:</span>{" "}
{project.finish_date}
</div>
<div>
<span className="font-medium">Contract:</span>{" "}
{project.contract_number}
</div>
</div>
<div className="flex items-center gap-4">
<Link href={`/projects/${project.project_id}`}>
<Button variant="outline" size="sm">
View Details
</Button>
</Link>
<Link href={`/projects/${project.project_id}/edit`}>
<Button variant="secondary" size="sm">
Edit
</Button>
</Link>
</div>
</div>
<div className="ml-4 flex-shrink-0">
<Button
variant="danger"
size="sm"
onClick={() => handleDelete(project.project_id)}
>
Delete
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,10 @@
import TaskTemplateForm from "@/components/TaskTemplateForm";
export default function NewTaskTemplatePage() {
return (
<div className="p-4 max-w-xl mx-auto">
<h1 className="text-xl font-bold mb-4">New Task Template</h1>
<TaskTemplateForm />
</div>
);
}

View File

@@ -0,0 +1,115 @@
import db from "@/lib/db";
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";
export default function TaskTemplatesPage() {
const templates = db
.prepare(
`
SELECT * FROM tasks WHERE is_standard = 1 ORDER BY name ASC
`
)
.all();
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-6xl mx-auto p-6">
<div className="flex justify-between items-center mb-8">
<div>
<h1 className="text-3xl font-bold text-gray-900">Task Templates</h1>
<p className="text-gray-600 mt-1">Manage reusable task templates</p>
</div>
<Link href="/tasks/templates/new">
<Button variant="primary" size="lg">
<svg
className="w-5 h-5 mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
New Template
</Button>
</Link>
</div>
{templates.length === 0 ? (
<Card>
<CardContent className="text-center py-12">
<div className="text-gray-400 mb-4">
<svg
className="w-16 h-16 mx-auto"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm0 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V8zm0 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1v-2z"
clipRule="evenodd"
/>
</svg>
</div>
<h3 className="text-lg font-medium text-gray-900 mb-2">
No task templates yet
</h3>
<p className="text-gray-500 mb-6">
Create reusable task templates to streamline your workflow
</p>
<Link href="/tasks/templates/new">
<Button variant="primary">Create First Template</Button>
</Link>
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{templates.map((template) => (
<Card
key={template.task_id}
className="hover:shadow-md transition-shadow"
>
<CardContent className="p-6">
<div className="flex items-start justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-900 truncate pr-2">
{template.name}
</h3>
<Badge variant="primary" size="sm">
{template.max_wait_days} days
</Badge>
</div>
{template.description && (
<p className="text-gray-600 text-sm mb-4 line-clamp-2">
{template.description}
</p>
)}
<div className="flex items-center justify-between">
<span className="text-xs text-gray-500">
Template ID: {template.task_id}
</span>
<div className="flex space-x-2">
<Button variant="outline" size="sm">
Edit
</Button>
<Button variant="secondary" size="sm">
Duplicate
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,74 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function ContractForm() {
const [form, setForm] = useState({
contract_number: "",
contract_name: "",
customer_contract_number: "",
customer: "",
investor: "",
date_signed: "",
finish_date: "",
});
const router = useRouter();
function handleChange(e) {
setForm({ ...form, [e.target.name]: e.target.value });
}
async function handleSubmit(e) {
e.preventDefault();
console.log("Submitting form:", form);
const res = await fetch("/api/contracts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
if (res.ok) {
router.push("/projects"); // or /contracts if you plan a listing
} else {
alert(
"Wystąpił błąd podczas dodawania umowy. Sprawdź dane i spróbuj ponownie."
);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
{[
["contract_number", "Numer Umowy"],
["contract_name", "Nazwa Umowy"],
["customer_contract_number", "Numer Umowy (Klienta)"],
["customer", "Zleceniodawca"],
["investor", "Inwestor"],
["date_signed", "Data zawarcia"],
["finish_date", "Data zakończenia"],
].map(([name, label]) => (
<div key={name}>
<label className="block font-medium">{label}</label>
<input
type={name.includes("date") ? "date" : "text"}
name={name}
value={form[name] || ""}
onChange={handleChange}
className="border p-2 w-full"
/>
</div>
))}
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded"
>
Dodaj umowę
</button>
</form>
);
}

View File

@@ -0,0 +1,46 @@
"use client";
import React, { useState } from "react";
export default function NoteForm({ projectId }) {
const [note, setNote] = useState("");
const [status, setStatus] = useState(null);
async function handleSubmit(e) {
e.preventDefault();
const res = await fetch("/api/notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ project_id: projectId, note }),
});
if (res.ok) {
setNote("");
setStatus("Note added");
window.location.reload();
} else {
setStatus("Failed to save note");
}
}
return (
<form onSubmit={handleSubmit} className="space-y-2 mb-4">
<textarea
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder="Add a new note..."
className="border p-2 w-full"
rows={3}
required
/>
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded"
>
Add Note
</button>
{status && <p className="text-sm text-gray-600">{status}</p>}
</form>
);
}

View File

@@ -0,0 +1,111 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
export default function ProjectForm({ initialData = null }) {
const [form, setForm] = useState({
contract_id: "",
project_name: "",
address: "",
plot: "",
district: "",
unit: "",
city: "",
investment_number: "",
finish_date: "",
wp: "",
contact: "",
notes: "",
...initialData,
});
const [contracts, setContracts] = useState([]);
const router = useRouter();
const isEdit = !!initialData;
useEffect(() => {
fetch("/api/contracts")
.then((res) => res.json())
.then(setContracts);
}, []);
function handleChange(e) {
setForm({ ...form, [e.target.name]: e.target.value });
}
async function handleSubmit(e) {
e.preventDefault();
const res = await fetch(
isEdit ? `/api/projects/${initialData.project_id}` : "/api/projects",
{
method: isEdit ? "PUT" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
}
);
if (res.ok) {
router.push("/projects");
} else {
alert("Failed to save project.");
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
{/* Contract Dropdown */}
<div>
<label className="block font-medium">Umowa</label>
<select
name="contract_id"
value={form.contract_id || ""}
onChange={handleChange}
className="border p-2 w-full"
required
>
<option value="">Wybierz umowę</option>
{contracts.map((contract) => (
<option key={contract.contract_id} value={contract.contract_id}>
{contract.contract_number} {contract.contract_name}
</option>
))}
</select>
</div>
{/* Other fields */}
{[
["project_name", "Nazwa projektu"],
["address", "Lokalizacja"],
["plot", "Działka"],
["district", "Obręb ewidencyjny"],
["unit", "Jednostka ewidencyjna"],
["city", "Miejscowość"],
["investment_number", "Numer inwestycjny"],
["finish_date", "Termin realizacji"],
["wp", "WP"],
["contact", "Dane kontaktowe"],
["notes", "Notatki"],
].map(([name, label]) => (
<div key={name}>
<label className="block font-medium">{label}</label>
<input
type={name === "finish_date" ? "date" : "text"}
name={name}
value={form[name] || ""}
onChange={handleChange}
className="border p-2 w-full"
/>
</div>
))}
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded"
>
{isEdit ? "Update" : "Create"} Project
</button>
</form>
);
}

View File

@@ -0,0 +1,178 @@
"use client";
import { useState, useEffect } from "react";
import Button from "./ui/Button";
import Badge from "./ui/Badge";
export default function ProjectTaskForm({ projectId, onTaskAdded }) {
const [taskTemplates, setTaskTemplates] = useState([]);
const [taskType, setTaskType] = useState("template"); // "template" or "custom"
const [selectedTemplate, setSelectedTemplate] = useState("");
const [customTaskName, setCustomTaskName] = useState("");
const [customMaxWaitDays, setCustomMaxWaitDays] = useState("");
const [priority, setPriority] = useState("normal");
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
// Fetch available task templates
fetch("/api/tasks/templates")
.then((res) => res.json())
.then(setTaskTemplates);
}, []);
async function handleSubmit(e) {
e.preventDefault();
// Validate based on task type
if (taskType === "template" && !selectedTemplate) return;
if (taskType === "custom" && !customTaskName.trim()) return;
setIsSubmitting(true);
try {
const requestData = {
project_id: parseInt(projectId),
priority,
};
if (taskType === "template") {
requestData.task_template_id = parseInt(selectedTemplate);
} else {
requestData.custom_task_name = customTaskName.trim();
requestData.custom_max_wait_days = parseInt(customMaxWaitDays) || 0;
}
const res = await fetch("/api/project-tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestData),
});
if (res.ok) {
// Reset form
setSelectedTemplate("");
setCustomTaskName("");
setCustomMaxWaitDays("");
setPriority("normal");
if (onTaskAdded) onTaskAdded();
} else {
alert("Failed to add task to project.");
}
} catch (error) {
alert("Error adding task to project.");
} finally {
setIsSubmitting(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-3">
Task Type
</label>
<div className="flex space-x-6">
<label className="flex items-center">
<input
type="radio"
value="template"
checked={taskType === "template"}
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>
</label>
<label className="flex items-center">
<input
type="radio"
value="custom"
checked={taskType === "custom"}
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>
</label>
</div>
</div>
{taskType === "template" ? (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Select Task Template
</label>{" "}
<select
value={selectedTemplate}
onChange={(e) => setSelectedTemplate(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"
required
>
<option value="">Choose a task template...</option>
{taskTemplates.map((template) => (
<option key={template.task_id} value={template.task_id}>
{template.name} ({template.max_wait_days} days)
</option>
))}
</select>
</div>
) : (
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Task Name
</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..."
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Max Wait Days
</label>
<input
type="number"
value={customMaxWaitDays}
onChange={(e) => setCustomMaxWaitDays(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="0"
min="0"
/>
</div>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
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>
</select>
</div>
<div className="flex justify-end">
<Button
type="submit"
variant="primary"
disabled={
isSubmitting ||
(taskType === "template" && !selectedTemplate) ||
(taskType === "custom" && !customTaskName.trim())
}
>
{isSubmitting ? "Adding..." : "Add Task"}
</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,241 @@
"use client";
import { useState, useEffect } from "react";
import ProjectTaskForm from "./ProjectTaskForm";
import { Card, CardHeader, CardContent } from "./ui/Card";
import Button from "./ui/Button";
import Badge from "./ui/Badge";
export default function ProjectTasksSection({ projectId }) {
const [projectTasks, setProjectTasks] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchProjectTasks = async () => {
try {
const res = await fetch(`/api/project-tasks?project_id=${projectId}`);
const tasks = await res.json();
setProjectTasks(tasks);
} catch (error) {
console.error("Failed to fetch project tasks:", error);
} finally {
setLoading(false);
}
};
fetchProjectTasks();
}, [projectId]);
const refetchTasks = async () => {
try {
const res = await fetch(`/api/project-tasks?project_id=${projectId}`);
const tasks = await res.json();
setProjectTasks(tasks);
} catch (error) {
console.error("Failed to fetch project tasks:", error);
}
};
const handleTaskAdded = () => {
refetchTasks(); // Refresh the list
};
const handleStatusChange = async (taskId, newStatus) => {
try {
const res = await fetch(`/api/project-tasks/${taskId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status: newStatus }),
});
if (res.ok) {
refetchTasks(); // Refresh the list
} else {
alert("Failed to update task status");
}
} catch (error) {
alert("Error updating task status");
}
};
const handleDeleteTask = async (taskId) => {
if (!confirm("Are you sure you want to delete this task?")) return;
try {
const res = await fetch(`/api/project-tasks/${taskId}`, {
method: "DELETE",
});
if (res.ok) {
refetchTasks(); // Refresh the list
} else {
alert("Failed to delete task");
}
} catch (error) {
alert("Error deleting task");
}
};
const getPriorityVariant = (priority) => {
switch (priority) {
case "urgent":
return "urgent";
case "high":
return "high";
case "normal":
return "normal";
case "low":
return "low";
default:
return "default";
}
};
const getStatusVariant = (status) => {
switch (status) {
case "completed":
return "success";
case "in_progress":
return "primary";
case "pending":
return "warning";
case "cancelled":
return "danger";
default:
return "default";
}
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-gray-900">Project Tasks</h2>
<Badge variant="default" className="text-sm">
{projectTasks.length} {projectTasks.length === 1 ? "task" : "tasks"}
</Badge>
</div>
{/* Add New Task Card */}
<Card>
<CardHeader>
<h3 className="text-lg font-medium text-gray-900">Add New Task</h3>
</CardHeader>
<CardContent>
<ProjectTaskForm
projectId={projectId}
onTaskAdded={handleTaskAdded}
/>
</CardContent>
</Card>
{/* Current Tasks */}
<Card>
<CardHeader>
<h3 className="text-lg font-medium text-gray-900">Current Tasks</h3>
</CardHeader>
<CardContent className="p-0">
{loading ? (
<div className="p-6 text-center">
<div className="animate-pulse">
<div className="h-4 bg-gray-200 rounded w-1/4 mx-auto mb-2"></div>
<div className="h-3 bg-gray-200 rounded w-1/6 mx-auto"></div>
</div>
</div>
) : projectTasks.length === 0 ? (
<div className="p-6 text-center">
<div className="text-gray-400 mb-2">
<svg
className="w-12 h-12 mx-auto"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zm0 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V8zm0 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1v-2z"
clipRule="evenodd"
/>
</svg>
</div>
<p className="text-gray-500 text-sm">
No tasks assigned to this project yet.
</p>
<p className="text-gray-400 text-xs mt-1">
Add a task above to get started.
</p>
</div>
) : (
<div className="divide-y divide-gray-200">
{projectTasks.map((task) => (
<div
key={task.id}
className="p-6 hover:bg-gray-50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-3">
<h4 className="text-base font-medium text-gray-900 truncate">
{task.task_name}
</h4>
<Badge
variant={getPriorityVariant(task.priority)}
size="sm"
>
{task.priority}
</Badge>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm text-gray-600 mb-4">
<div>
<span className="font-medium">Max wait days:</span>{" "}
{task.max_wait_days}
</div>
<div>
<span className="font-medium">Type:</span>{" "}
{task.task_type || "template"}
</div>
<div>
<span className="font-medium">Added:</span>{" "}
{new Date(task.date_added).toLocaleDateString()}
</div>
</div>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-700">
Status:
</span>
<select
value={task.status}
onChange={(e) =>
handleStatusChange(task.id, e.target.value)
}
className="px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
>
<option value="pending">Pending</option>
<option value="in_progress">In Progress</option>
<option value="completed">Completed</option>
<option value="cancelled">Cancelled</option>
</select>
<Badge
variant={getStatusVariant(task.status)}
size="sm"
>
{task.status.replace("_", " ")}
</Badge>
</div>
</div>
<div className="ml-4 flex-shrink-0">
<Button
variant="danger"
size="sm"
onClick={() => handleDeleteTask(task.id)}
className="text-xs"
>
Delete
</Button>
</div>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

View File

@@ -0,0 +1,61 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function TaskTemplateForm() {
const [name, setName] = useState("");
const [max_wait_days, setRequiredWaitDays] = useState("");
const router = useRouter();
async function handleSubmit(e) {
e.preventDefault();
const res = await fetch("/api/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
max_wait_days: parseInt(max_wait_days, 10) || 0,
}),
});
if (res.ok) {
router.push("/tasks/templates");
} else {
alert("Failed to create task template.");
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block font-medium">Name</label>
<input
type="text"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
className="border p-2 w-full"
required
/>
</div>
<div>
<label className="block font-medium">Required Wait Days</label>
<input
type="number"
name="max_wait_days"
value={max_wait_days}
onChange={(e) => setRequiredWaitDays(e.target.value)}
className="border p-2 w-full"
/>
</div>
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded"
>
Create Template
</button>
</form>
);
}

View File

@@ -0,0 +1,41 @@
"use client";
const Badge = ({
children,
variant = "default",
size = "sm",
className = "",
}) => {
const variants = {
default: "bg-gray-100 text-gray-800",
primary: "bg-blue-100 text-blue-800",
success: "bg-green-100 text-green-800",
warning: "bg-yellow-100 text-yellow-800",
danger: "bg-red-100 text-red-800",
urgent: "bg-red-500 text-white",
high: "bg-orange-500 text-white",
normal: "bg-blue-500 text-white",
low: "bg-gray-500 text-white",
};
const sizes = {
xs: "px-2 py-0.5 text-xs",
sm: "px-2.5 py-0.5 text-xs",
md: "px-3 py-1 text-sm",
};
return (
<span
className={`
inline-flex items-center rounded-full font-medium
${variants[variant]}
${sizes[size]}
${className}
`}
>
{children}
</span>
);
};
export default Badge;

View File

@@ -0,0 +1,54 @@
"use client";
import { forwardRef } from "react";
const buttonVariants = {
primary: "bg-blue-600 hover:bg-blue-700 text-white",
secondary:
"bg-gray-100 hover:bg-gray-200 text-gray-900 border border-gray-300",
danger: "bg-red-600 hover:bg-red-700 text-white",
success: "bg-green-600 hover:bg-green-700 text-white",
outline: "border border-blue-600 text-blue-600 hover:bg-blue-50",
};
const buttonSizes = {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2 text-sm",
lg: "px-6 py-3 text-base",
};
const Button = forwardRef(
(
{
children,
variant = "primary",
size = "md",
disabled = false,
className = "",
...props
},
ref
) => {
return (
<button
ref={ref}
className={`
inline-flex items-center justify-center rounded-lg font-medium transition-colors
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
disabled:opacity-50 disabled:cursor-not-allowed
${buttonVariants[variant]}
${buttonSizes[size]}
${className}
`}
disabled={disabled}
{...props}
>
{children}
</button>
);
}
);
Button.displayName = "Button";
export default Button;

42
src/components/ui/Card.js Normal file
View File

@@ -0,0 +1,42 @@
"use client";
import { forwardRef } from "react";
const Card = forwardRef(({ children, className = "", ...props }, ref) => {
return (
<div
ref={ref}
className={`
bg-white rounded-lg border border-gray-200 shadow-sm
${className}
`}
{...props}
>
{children}
</div>
);
});
Card.displayName = "Card";
const CardHeader = ({ children, className = "" }) => {
return (
<div className={`px-6 py-4 border-b border-gray-200 ${className}`}>
{children}
</div>
);
};
const CardContent = ({ children, className = "" }) => {
return <div className={`px-6 py-4 ${className}`}>{children}</div>;
};
const CardFooter = ({ children, className = "" }) => {
return (
<div className={`px-6 py-4 border-t border-gray-200 ${className}`}>
{children}
</div>
);
};
export { Card, CardHeader, CardContent, CardFooter };

104
src/components/ui/Input.js Normal file
View File

@@ -0,0 +1,104 @@
"use client";
import { forwardRef } from "react";
const Input = forwardRef(
({ label, error, className = "", type = "text", ...props }, ref) => {
return (
<div className="space-y-1">
{label && (
<label className="block text-sm font-medium text-gray-700">
{label}
</label>
)}
<input
ref={ref}
type={type}
className={`
w-full px-3 py-2 border border-gray-300 rounded-lg
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500
disabled:bg-gray-50 disabled:text-gray-500
${
error
? "border-red-300 focus:ring-red-500 focus:border-red-500"
: ""
}
${className}
`}
{...props}
/>
{error && <p className="text-sm text-red-600">{error}</p>}
</div>
);
}
);
Input.displayName = "Input";
const Select = forwardRef(
({ label, error, children, className = "", ...props }, ref) => {
return (
<div className="space-y-1">
{label && (
<label className="block text-sm font-medium text-gray-700">
{label}
</label>
)}
<select
ref={ref}
className={`
w-full px-3 py-2 border border-gray-300 rounded-lg
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500
disabled:bg-gray-50 disabled:text-gray-500
${
error
? "border-red-300 focus:ring-red-500 focus:border-red-500"
: ""
}
${className}
`}
{...props}
>
{children}
</select>
{error && <p className="text-sm text-red-600">{error}</p>}
</div>
);
}
);
Select.displayName = "Select";
const Textarea = forwardRef(
({ label, error, className = "", ...props }, ref) => {
return (
<div className="space-y-1">
{label && (
<label className="block text-sm font-medium text-gray-700">
{label}
</label>
)}
<textarea
ref={ref}
className={`
w-full px-3 py-2 border border-gray-300 rounded-lg
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500
disabled:bg-gray-50 disabled:text-gray-500
${
error
? "border-red-300 focus:ring-red-500 focus:border-red-500"
: ""
}
${className}
`}
{...props}
/>
{error && <p className="text-sm text-red-600">{error}</p>}
</div>
);
}
);
Textarea.displayName = "Textarea";
export { Input, Select, Textarea };

View File

@@ -0,0 +1,39 @@
"use client";
const LoadingSpinner = ({ size = "md", className = "" }) => {
const sizes = {
sm: "w-4 h-4",
md: "w-6 h-6",
lg: "w-8 h-8",
xl: "w-12 h-12",
};
return (
<div
className={`animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 ${sizes[size]} ${className}`}
></div>
);
};
const LoadingCard = ({ className = "" }) => (
<div className={`animate-pulse ${className}`}>
<div className="bg-white rounded-lg border border-gray-200 shadow-sm p-6">
<div className="space-y-3">
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
<div className="h-3 bg-gray-200 rounded w-1/2"></div>
<div className="h-3 bg-gray-200 rounded w-2/3"></div>
</div>
</div>
</div>
);
const LoadingList = ({ items = 3, className = "" }) => (
<div className={`space-y-4 ${className}`}>
{Array.from({ length: items }).map((_, index) => (
<LoadingCard key={index} />
))}
</div>
);
export { LoadingSpinner, LoadingCard, LoadingList };
export default LoadingSpinner;

View File

@@ -0,0 +1,52 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
const Navigation = () => {
const pathname = usePathname();
const isActive = (path) => {
if (path === "/") return pathname === "/";
return pathname.startsWith(path);
};
const navItems = [
{ href: "/", label: "Dashboard" },
{ href: "/projects", label: "Projects" },
{ href: "/tasks/templates", label: "Task Templates" },
{ href: "/contracts", label: "Contracts" },
];
return (
<nav className="bg-white border-b border-gray-200">
<div className="max-w-6xl mx-auto px-6">
<div className="flex items-center justify-between h-16">
<div className="flex items-center">
<Link href="/" className="text-xl font-bold text-gray-900">
Project Panel
</Link>
</div>
<div className="flex space-x-8">
{navItems.map((item) => (
<Link
key={item.href}
href={item.href}
className={`px-3 py-2 rounded-md text-sm font-medium transition-colors ${
isActive(item.href)
? "bg-blue-100 text-blue-700"
: "text-gray-600 hover:text-gray-900 hover:bg-gray-50"
}`}
>
{item.label}
</Link>
))}
</div>
</div>
</div>
</nav>
);
};
export default Navigation;

4
src/lib/db.js Normal file
View File

@@ -0,0 +1,4 @@
// src/lib/db.ts
import Database from "better-sqlite3";
const db = new Database("data/database.sqlite");
export default db;

85
src/lib/init-db.js Normal file
View File

@@ -0,0 +1,85 @@
import db from "./db";
export default function initializeDatabase() {
db.exec(`
-- Table: contracts
CREATE TABLE IF NOT EXISTS contracts (
contract_id INTEGER PRIMARY KEY AUTOINCREMENT,
contract_number TEXT NOT NULL,
contract_name TEXT,
customer_contract_number TEXT,
customer TEXT,
investor TEXT,
date_signed TEXT,
finish_date TEXT
);
-- Table: projects
CREATE TABLE IF NOT EXISTS projects (
project_id INTEGER PRIMARY KEY AUTOINCREMENT,
contract_id INTEGER,
project_name TEXT NOT NULL,
project_number TEXT NOT NULL,
address TEXT,
plot TEXT,
district TEXT,
unit TEXT,
city TEXT,
investment_number TEXT,
finish_date TEXT,
wp TEXT,
contact TEXT,
notes TEXT,
FOREIGN KEY (contract_id) REFERENCES contracts(contract_id)
);
-- Table: tasks
CREATE TABLE IF NOT EXISTS tasks (
task_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
max_wait_days INTEGER DEFAULT 0,
is_standard INTEGER NOT NULL DEFAULT 0
); -- Table: project_tasks
CREATE TABLE IF NOT EXISTS project_tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
task_template_id INTEGER,
custom_task_name TEXT,
custom_max_wait_days INTEGER DEFAULT 0,
status TEXT NOT NULL DEFAULT 'pending',
date_added TEXT DEFAULT CURRENT_TIMESTAMP,
priority TEXT DEFAULT 'normal',
FOREIGN KEY (project_id) REFERENCES projects(project_id),
FOREIGN KEY (task_template_id) REFERENCES tasks(task_id)
);
-- Table: notes
CREATE TABLE IF NOT EXISTS notes (
note_id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER,
task_id INTEGER,
note TEXT NOT NULL,
note_date TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (project_id) REFERENCES projects(project_id),
FOREIGN KEY (task_id) REFERENCES project_tasks(id)
);
`);
// Migration: Add custom task columns if they don't exist
try {
db.exec(`
ALTER TABLE project_tasks ADD COLUMN custom_task_name TEXT;
`);
} catch (e) {
// Column already exists, ignore error
}
try {
db.exec(`
ALTER TABLE project_tasks ADD COLUMN custom_max_wait_days INTEGER DEFAULT 0;
`);
} catch (e) {
// Column already exists, ignore error
}
}

View File

14
src/lib/queries/notes.js Normal file
View File

@@ -0,0 +1,14 @@
import db from "../db.js";
export function getNotesByProjectId(project_id) {
return db
.prepare(`SELECT * FROM notes WHERE project_id = ? ORDER BY note_date DESC`)
.all(project_id);
}
export function addNoteToProject(project_id, note) {
db.prepare(`INSERT INTO notes (project_id, note) VALUES (?, ?)`).run(
project_id,
note
);
}

105
src/lib/queries/projects.js Normal file
View File

@@ -0,0 +1,105 @@
import db from "../db.js";
export function getAllProjects() {
return db.prepare("SELECT * FROM projects ORDER BY finish_date DESC").all();
}
export function getProjectById(id) {
return db.prepare("SELECT * FROM projects WHERE project_id = ?").get(id);
}
export function createProject(data) {
// 1. Get the max project_number under this contract
const existing = db
.prepare(
`
SELECT MAX(project_number) as max_number
FROM projects
WHERE contract_id = ?
`
)
.get(data.contract_id);
const nextNumber = (existing.max_number || 0) + 1;
const stmt = db.prepare(`
INSERT INTO projects (
contract_id, project_name, project_number, address, plot, district, unit, city, investment_number, finish_date,
wp, contact, notes
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
data.contract_id,
data.project_name,
parseInt(nextNumber),
data.address,
data.plot,
data.district,
data.unit,
data.city,
data.investment_number,
data.finish_date,
data.wp,
data.contact,
data.notes
);
}
export function updateProject(id, data) {
const stmt = db.prepare(`
UPDATE projects SET
contract_id = ?, project_name = ?, project_number = ?, address = ?, plot = ?, district = ?, unit = ?, city = ?,
investment_number = ?, finish_date = ?, wp = ?, contact = ?, notes = ?
WHERE project_id = ?
`);
stmt.run(
data.contract_id,
data.project_name,
data.project_number,
data.address,
data.plot,
data.district,
data.unit,
data.city,
data.investment_number,
data.finish_date,
data.wp,
data.contact,
data.notes,
id
);
}
export function deleteProject(id) {
db.prepare("DELETE FROM projects WHERE project_id = ?").run(id);
}
export function getProjectWithContract(id) {
return db
.prepare(
`
SELECT
p.*,
c.contract_number,
c.contract_name,
c.customer,
c.investor
FROM projects p
LEFT JOIN contracts c ON p.contract_id = c.contract_id
WHERE p.project_id = ?
`
)
.get(id);
}
export function getNotesForProject(projectId) {
return db
.prepare(
`
SELECT * FROM notes
WHERE project_id = ?
ORDER BY note_date DESC
`
)
.all(projectId);
}

76
src/lib/queries/tasks.js Normal file
View File

@@ -0,0 +1,76 @@
import db from "../db.js";
// Get all task templates (for dropdown selection)
export function getAllTaskTemplates() {
return db
.prepare("SELECT * FROM tasks WHERE is_standard = 1 ORDER BY name ASC")
.all();
}
// Get project tasks for a specific project
export function getProjectTasks(projectId) {
return db
.prepare(
`
SELECT
pt.*,
COALESCE(pt.custom_task_name, t.name) as task_name,
COALESCE(pt.custom_max_wait_days, t.max_wait_days) as max_wait_days,
CASE
WHEN pt.task_template_id IS NOT NULL THEN 'template'
ELSE 'custom'
END as task_type
FROM project_tasks pt
LEFT JOIN tasks t ON pt.task_template_id = t.task_id
WHERE pt.project_id = ?
ORDER BY pt.date_added DESC
`
)
.all(projectId);
}
// Create a new project task
export function createProjectTask(data) {
if (data.task_template_id) {
// Creating from template
const stmt = db.prepare(`
INSERT INTO project_tasks (project_id, task_template_id, status, priority)
VALUES (?, ?, ?, ?)
`);
return stmt.run(
data.project_id,
data.task_template_id,
data.status || "pending",
data.priority || "normal"
);
} else {
// Creating custom task
const stmt = db.prepare(`
INSERT INTO project_tasks (project_id, custom_task_name, custom_max_wait_days, status, priority)
VALUES (?, ?, ?, ?, ?)
`);
return stmt.run(
data.project_id,
data.custom_task_name,
data.custom_max_wait_days || 0,
data.status || "pending",
data.priority || "normal"
);
}
}
// Update project task status
export function updateProjectTaskStatus(taskId, status) {
const stmt = db.prepare(`
UPDATE project_tasks
SET status = ?
WHERE id = ?
`);
return stmt.run(status, taskId);
}
// Delete a project task
export function deleteProjectTask(taskId) {
const stmt = db.prepare("DELETE FROM project_tasks WHERE id = ?");
return stmt.run(taskId);
}