feat: Implement task notes functionality with CRUD operations and integrate into project tasks section

This commit is contained in:
Chop
2025-06-03 20:46:37 +02:00
parent a9afebdda5
commit 330744daf9
9 changed files with 309 additions and 20 deletions

View File

@@ -0,0 +1,73 @@
import {
getNotesByTaskId,
addNoteToTask,
deleteNote,
} from "@/lib/queries/notes";
import { NextResponse } from "next/server";
// GET: Get notes for a specific task
export async function GET(req) {
const { searchParams } = new URL(req.url);
const taskId = searchParams.get("task_id");
if (!taskId) {
return NextResponse.json({ error: "task_id is required" }, { status: 400 });
}
try {
const notes = getNotesByTaskId(taskId);
return NextResponse.json(notes);
} catch (error) {
console.error("Error fetching task notes:", error);
return NextResponse.json(
{ error: "Failed to fetch task notes" },
{ status: 500 }
);
}
}
// POST: Add a note to a task
export async function POST(req) {
try {
const { task_id, note } = await req.json();
if (!task_id || !note) {
return NextResponse.json(
{ error: "task_id and note are required" },
{ status: 400 }
);
}
addNoteToTask(task_id, note);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error adding task note:", error);
return NextResponse.json(
{ error: "Failed to add task note" },
{ status: 500 }
);
}
}
// DELETE: Delete a note
export async function DELETE(req) {
try {
const { searchParams } = new URL(req.url);
const noteId = searchParams.get("note_id");
if (!noteId) {
return NextResponse.json(
{ error: "note_id is required" },
{ status: 400 }
);
}
deleteNote(noteId);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error deleting note:", error);
return NextResponse.json(
{ error: "Failed to delete note" },
{ status: 500 }
);
}
}

View File

@@ -1,7 +1,8 @@
import ProjectForm from "@/components/ProjectForm"; import ProjectForm from "@/components/ProjectForm";
export default async function EditProjectPage({ params }) { export default async function EditProjectPage({ params }) {
const res = await fetch(`http://localhost:3000/api/projects/${params.id}`, { const { id } = await params;
const res = await fetch(`http://localhost:3000/api/projects/${id}`, {
cache: "no-store", cache: "no-store",
}); });
const project = await res.json(); const project = await res.json();

View File

@@ -13,8 +13,9 @@ import PageContainer from "@/components/ui/PageContainer";
import PageHeader from "@/components/ui/PageHeader"; import PageHeader from "@/components/ui/PageHeader";
export default async function ProjectViewPage({ params }) { export default async function ProjectViewPage({ params }) {
const project = getProjectWithContract(params.id); const { id } = await params;
const notes = getNotesForProject(params.id); const project = getProjectWithContract(id);
const notes = getNotesForProject(id);
const daysRemaining = differenceInCalendarDays( const daysRemaining = differenceInCalendarDays(
parseISO(project.finish_date), parseISO(project.finish_date),
new Date() new Date()
@@ -70,8 +71,8 @@ export default async function ProjectViewPage({ params }) {
</svg> </svg>
Back to Projects Back to Projects
</Button> </Button>
</Link> </Link>{" "}
<Link href={`/projects/${params.id}/edit`}> <Link href={`/projects/${id}/edit`}>
<Button variant="secondary">Edit Project</Button> <Button variant="secondary">Edit Project</Button>
</Link> </Link>
</div> </div>
@@ -142,7 +143,6 @@ export default async function ProjectViewPage({ params }) {
)} )}
</CardContent> </CardContent>
</Card> </Card>
<Card> <Card>
<CardHeader> <CardHeader>
<h2 className="text-xl font-semibold text-gray-900"> <h2 className="text-xl font-semibold text-gray-900">
@@ -175,10 +175,10 @@ export default async function ProjectViewPage({ params }) {
<p className="text-gray-900">{project.investor}</p> <p className="text-gray-900">{project.investor}</p>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>{" "}
</div> </div>
<ProjectTasksSection projectId={params.id} /> <ProjectTasksSection projectId={id} />
<Card> <Card>
<CardHeader> <CardHeader>
@@ -186,7 +186,7 @@ export default async function ProjectViewPage({ params }) {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="mb-6"> <div className="mb-6">
<NoteForm projectId={params.id} /> <NoteForm projectId={id} />
</div> </div>
{notes.length === 0 ? ( {notes.length === 0 ? (
<div className="text-center py-8"> <div className="text-center py-8">

View File

@@ -6,10 +6,11 @@ import Button from "@/components/ui/Button";
import TaskTemplateForm from "@/components/TaskTemplateForm"; import TaskTemplateForm from "@/components/TaskTemplateForm";
export default async function EditTaskTemplatePage({ params }) { export default async function EditTaskTemplatePage({ params }) {
const { id } = await params;
// Fetch the task template // Fetch the task template
const template = db const template = db
.prepare("SELECT * FROM tasks WHERE task_id = ? AND is_standard = 1") .prepare("SELECT * FROM tasks WHERE task_id = ? AND is_standard = 1")
.get(params.id); .get(id);
if (!template) { if (!template) {
notFound(); notFound();

View File

@@ -10,6 +10,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
const [selectedTemplate, setSelectedTemplate] = useState(""); const [selectedTemplate, setSelectedTemplate] = useState("");
const [customTaskName, setCustomTaskName] = useState(""); const [customTaskName, setCustomTaskName] = useState("");
const [customMaxWaitDays, setCustomMaxWaitDays] = useState(""); const [customMaxWaitDays, setCustomMaxWaitDays] = useState("");
const [customDescription, setCustomDescription] = useState("");
const [priority, setPriority] = useState("normal"); const [priority, setPriority] = useState("normal");
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
@@ -40,6 +41,7 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
} else { } else {
requestData.custom_task_name = customTaskName.trim(); requestData.custom_task_name = customTaskName.trim();
requestData.custom_max_wait_days = parseInt(customMaxWaitDays) || 0; requestData.custom_max_wait_days = parseInt(customMaxWaitDays) || 0;
requestData.custom_description = customDescription.trim();
} }
const res = await fetch("/api/project-tasks", { const res = await fetch("/api/project-tasks", {
@@ -47,12 +49,12 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestData), body: JSON.stringify(requestData),
}); });
if (res.ok) { if (res.ok) {
// Reset form // Reset form
setSelectedTemplate(""); setSelectedTemplate("");
setCustomTaskName(""); setCustomTaskName("");
setCustomMaxWaitDays(""); setCustomMaxWaitDays("");
setCustomDescription("");
setPriority("normal"); setPriority("normal");
if (onTaskAdded) onTaskAdded(); if (onTaskAdded) onTaskAdded();
} else { } else {
@@ -141,6 +143,18 @@ export default function ProjectTaskForm({ projectId, onTaskAdded }) {
min="0" min="0"
/> />
</div> </div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
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)..."
rows={3}
/>
</div>
</div> </div>
)} )}

View File

@@ -9,12 +9,34 @@ import Badge from "./ui/Badge";
export default function ProjectTasksSection({ projectId }) { export default function ProjectTasksSection({ projectId }) {
const [projectTasks, setProjectTasks] = useState([]); const [projectTasks, setProjectTasks] = useState([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [taskNotes, setTaskNotes] = useState({});
const [newNote, setNewNote] = useState({});
const [loadingNotes, setLoadingNotes] = useState({});
useEffect(() => { useEffect(() => {
const fetchProjectTasks = async () => { const fetchProjectTasks = async () => {
try { try {
const res = await fetch(`/api/project-tasks?project_id=${projectId}`); const res = await fetch(`/api/project-tasks?project_id=${projectId}`);
const tasks = await res.json(); const tasks = await res.json();
setProjectTasks(tasks); setProjectTasks(tasks);
// Fetch notes for each task
const notesPromises = tasks.map(async (task) => {
try {
const notesRes = await fetch(`/api/task-notes?task_id=${task.id}`);
const notes = await notesRes.json();
return { taskId: task.id, notes };
} catch (error) {
console.error(`Failed to fetch notes for task ${task.id}:`, error);
return { taskId: task.id, notes: [] };
}
});
const notesResults = await Promise.all(notesPromises);
const notesMap = {};
notesResults.forEach(({ taskId, notes }) => {
notesMap[taskId] = notes;
});
setTaskNotes(notesMap);
} catch (error) { } catch (error) {
console.error("Failed to fetch project tasks:", error); console.error("Failed to fetch project tasks:", error);
} finally { } finally {
@@ -24,12 +46,30 @@ export default function ProjectTasksSection({ projectId }) {
fetchProjectTasks(); fetchProjectTasks();
}, [projectId]); }, [projectId]);
const refetchTasks = async () => { const refetchTasks = async () => {
try { try {
const res = await fetch(`/api/project-tasks?project_id=${projectId}`); const res = await fetch(`/api/project-tasks?project_id=${projectId}`);
const tasks = await res.json(); const tasks = await res.json();
setProjectTasks(tasks); setProjectTasks(tasks);
// Refresh notes for all tasks
const notesPromises = tasks.map(async (task) => {
try {
const notesRes = await fetch(`/api/task-notes?task_id=${task.id}`);
const notes = await notesRes.json();
return { taskId: task.id, notes };
} catch (error) {
console.error(`Failed to fetch notes for task ${task.id}:`, error);
return { taskId: task.id, notes: [] };
}
});
const notesResults = await Promise.all(notesPromises);
const notesMap = {};
notesResults.forEach(({ taskId, notes }) => {
notesMap[taskId] = notes;
});
setTaskNotes(notesMap);
} catch (error) { } catch (error) {
console.error("Failed to fetch project tasks:", error); console.error("Failed to fetch project tasks:", error);
} }
@@ -55,7 +95,6 @@ export default function ProjectTasksSection({ projectId }) {
alert("Error updating task status"); alert("Error updating task status");
} }
}; };
const handleDeleteTask = async (taskId) => { const handleDeleteTask = async (taskId) => {
if (!confirm("Are you sure you want to delete this task?")) return; if (!confirm("Are you sure you want to delete this task?")) return;
try { try {
@@ -72,6 +111,59 @@ export default function ProjectTasksSection({ projectId }) {
alert("Error deleting task"); alert("Error deleting task");
} }
}; };
const handleAddNote = async (taskId) => {
const noteContent = newNote[taskId]?.trim();
if (!noteContent) return;
setLoadingNotes((prev) => ({ ...prev, [taskId]: true }));
try {
const res = await fetch("/api/task-notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
task_id: taskId,
note: noteContent,
}),
});
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 }));
setNewNote((prev) => ({ ...prev, [taskId]: "" }));
} else {
alert("Failed to add note");
}
} catch (error) {
alert("Error adding note");
} finally {
setLoadingNotes((prev) => ({ ...prev, [taskId]: false }));
}
};
const handleDeleteNote = async (noteId, taskId) => {
if (!confirm("Are you sure you want to delete this note?")) return;
try {
const res = await fetch(`/api/task-notes?note_id=${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("Failed to delete note");
}
} catch (error) {
alert("Error deleting note");
}
};
const getPriorityVariant = (priority) => { const getPriorityVariant = (priority) => {
switch (priority) { switch (priority) {
case "urgent": case "urgent":
@@ -177,8 +269,15 @@ export default function ProjectTasksSection({ projectId }) {
> >
{task.priority} {task.priority}
</Badge> </Badge>
</div> </div>{" "}
{/* Task Description */}
{task.description && (
<div className="mb-4">
<p className="text-sm text-gray-700 bg-gray-50 p-3 rounded-md">
{task.description}
</p>
</div>
)}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm text-gray-600 mb-4"> <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm text-gray-600 mb-4">
<div> <div>
<span className="font-medium">Max wait days:</span>{" "} <span className="font-medium">Max wait days:</span>{" "}
@@ -193,8 +292,7 @@ export default function ProjectTasksSection({ projectId }) {
{new Date(task.date_added).toLocaleDateString()} {new Date(task.date_added).toLocaleDateString()}
</div> </div>
</div> </div>
<div className="flex items-center gap-3 mb-4">
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-700"> <span className="text-sm font-medium text-gray-700">
Status: Status:
</span> </span>
@@ -217,6 +315,80 @@ export default function ProjectTasksSection({ projectId }) {
{task.status.replace("_", " ")} {task.status.replace("_", " ")}
</Badge> </Badge>
</div> </div>
{/* Notes Section */}
<div className="border-t pt-4">
<h5 className="text-sm font-medium text-gray-900 mb-3">
Notes ({taskNotes[task.id]?.length || 0})
</h5>
{/* Existing Notes */}
{taskNotes[task.id] &&
taskNotes[task.id].length > 0 && (
<div className="space-y-2 mb-3">
{taskNotes[task.id].map((note) => (
<div
key={note.note_id}
className="bg-blue-50 p-3 rounded-md flex justify-between items-start"
>
<div className="flex-1">
<p className="text-sm text-gray-800">
{note.note}
</p>
<p className="text-xs text-gray-500 mt-1">
{new Date(
note.note_date
).toLocaleDateString()}{" "}
at{" "}
{new Date(
note.note_date
).toLocaleTimeString()}
</p>
</div>
<button
onClick={() =>
handleDeleteNote(note.note_id, task.id)
}
className="ml-2 text-red-500 hover:text-red-700 text-xs font-bold"
title="Delete note"
>
×
</button>
</div>
))}
</div>
)}
{/* Add New Note */}
<div className="flex gap-2">
<input
type="text"
placeholder="Add a note..."
value={newNote[task.id] || ""}
onChange={(e) =>
setNewNote((prev) => ({
...prev,
[task.id]: e.target.value,
}))
}
className="flex-1 px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
onKeyPress={(e) => {
if (e.key === "Enter") {
handleAddNote(task.id);
}
}}
/>
<Button
size="sm"
variant="primary"
onClick={() => handleAddNote(task.id)}
disabled={
loadingNotes[task.id] || !newNote[task.id]?.trim()
}
>
{loadingNotes[task.id] ? "Adding..." : "Add"}
</Button>
</div>
</div>
</div> </div>
<div className="ml-4 flex-shrink-0"> <div className="ml-4 flex-shrink-0">

View File

@@ -81,7 +81,6 @@ export default function initializeDatabase() {
} catch (e) { } catch (e) {
// Column already exists, ignore error // Column already exists, ignore error
} }
// Migration: Add description column to tasks table // Migration: Add description column to tasks table
try { try {
db.exec(` db.exec(`
@@ -90,4 +89,13 @@ export default function initializeDatabase() {
} catch (e) { } catch (e) {
// Column already exists, ignore error // Column already exists, ignore error
} }
// Migration: Add description column to project_tasks table
try {
db.exec(`
ALTER TABLE project_tasks ADD COLUMN custom_description TEXT;
`);
} catch (e) {
// Column already exists, ignore error
}
} }

View File

@@ -12,3 +12,20 @@ export function addNoteToProject(project_id, note) {
note note
); );
} }
export function getNotesByTaskId(task_id) {
return db
.prepare(`SELECT * FROM notes WHERE task_id = ? ORDER BY note_date DESC`)
.all(task_id);
}
export function addNoteToTask(task_id, note) {
db.prepare(`INSERT INTO notes (task_id, note) VALUES (?, ?)`).run(
task_id,
note
);
}
export function deleteNote(note_id) {
db.prepare(`DELETE FROM notes WHERE note_id = ?`).run(note_id);
}

View File

@@ -16,6 +16,7 @@ export function getAllProjectTasks() {
pt.*, pt.*,
COALESCE(pt.custom_task_name, t.name) as task_name, COALESCE(pt.custom_task_name, t.name) as task_name,
COALESCE(pt.custom_max_wait_days, t.max_wait_days) as max_wait_days, COALESCE(pt.custom_max_wait_days, t.max_wait_days) as max_wait_days,
COALESCE(pt.custom_description, t.description) as description,
CASE CASE
WHEN pt.task_template_id IS NOT NULL THEN 'template' WHEN pt.task_template_id IS NOT NULL THEN 'template'
ELSE 'custom' ELSE 'custom'
@@ -42,6 +43,7 @@ export function getProjectTasks(projectId) {
pt.*, pt.*,
COALESCE(pt.custom_task_name, t.name) as task_name, COALESCE(pt.custom_task_name, t.name) as task_name,
COALESCE(pt.custom_max_wait_days, t.max_wait_days) as max_wait_days, COALESCE(pt.custom_max_wait_days, t.max_wait_days) as max_wait_days,
COALESCE(pt.custom_description, t.description) as description,
CASE CASE
WHEN pt.task_template_id IS NOT NULL THEN 'template' WHEN pt.task_template_id IS NOT NULL THEN 'template'
ELSE 'custom' ELSE 'custom'
@@ -72,13 +74,14 @@ export function createProjectTask(data) {
} else { } else {
// Creating custom task // Creating custom task
const stmt = db.prepare(` const stmt = db.prepare(`
INSERT INTO project_tasks (project_id, custom_task_name, custom_max_wait_days, status, priority) INSERT INTO project_tasks (project_id, custom_task_name, custom_max_wait_days, custom_description, status, priority)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
`); `);
return stmt.run( return stmt.run(
data.project_id, data.project_id,
data.custom_task_name, data.custom_task_name,
data.custom_max_wait_days || 0, data.custom_max_wait_days || 0,
data.custom_description || "",
data.status || "pending", data.status || "pending",
data.priority || "normal" data.priority || "normal"
); );