feat: Implement task editing functionality with validation and user assignment

This commit is contained in:
Chop
2025-07-10 23:35:17 +02:00
parent 92f458e59b
commit 51d37fc65a
3 changed files with 372 additions and 26 deletions

View File

@@ -1,13 +1,45 @@
import { import {
updateProjectTaskStatus, updateProjectTaskStatus,
deleteProjectTask, deleteProjectTask,
updateProjectTask,
} from "@/lib/queries/tasks"; } from "@/lib/queries/tasks";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { withUserAuth } from "@/lib/middleware/auth"; import { withUserAuth } from "@/lib/middleware/auth";
// PATCH: Update project task status // PUT: Update project task (general update)
async function updateProjectTaskHandler(req, { params }) { async function updateProjectTaskHandler(req, { params }) {
try { try {
const { id } = await params;
const updates = await req.json();
// Validate that we have at least one field to update
const allowedFields = ["priority", "status", "assigned_to", "date_started"];
const hasValidFields = Object.keys(updates).some((key) =>
allowedFields.includes(key)
);
if (!hasValidFields) {
return NextResponse.json(
{ error: "No valid fields provided for update" },
{ status: 400 }
);
}
updateProjectTask(id, updates, req.user?.id || null);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error updating task:", error);
return NextResponse.json(
{ error: "Failed to update project task", details: error.message },
{ status: 500 }
);
}
}
// PATCH: Update project task status
async function updateProjectTaskStatusHandler(req, { params }) {
try {
const { id } = await params;
const { status } = await req.json(); const { status } = await req.json();
if (!status) { if (!status) {
@@ -17,7 +49,7 @@ async function updateProjectTaskHandler(req, { params }) {
); );
} }
updateProjectTaskStatus(params.id, status, req.user?.id || null); updateProjectTaskStatus(id, status, req.user?.id || null);
return NextResponse.json({ success: true }); return NextResponse.json({ success: true });
} catch (error) { } catch (error) {
console.error("Error updating task status:", error); console.error("Error updating task status:", error);
@@ -31,16 +63,19 @@ async function updateProjectTaskHandler(req, { params }) {
// DELETE: Delete a project task // DELETE: Delete a project task
async function deleteProjectTaskHandler(req, { params }) { async function deleteProjectTaskHandler(req, { params }) {
try { try {
deleteProjectTask(params.id); const { id } = await params;
const result = deleteProjectTask(id);
return NextResponse.json({ success: true }); return NextResponse.json({ success: true });
} catch (error) { } catch (error) {
console.error("Error in deleteProjectTaskHandler:", error);
return NextResponse.json( return NextResponse.json(
{ error: "Failed to delete project task" }, { error: "Failed to delete project task", details: error.message },
{ status: 500 } { status: 500 }
); );
} }
} }
// Protected routes - require authentication // Protected routes - require authentication
export const PATCH = withUserAuth(updateProjectTaskHandler); export const PUT = withUserAuth(updateProjectTaskHandler);
export const PATCH = withUserAuth(updateProjectTaskStatusHandler);
export const DELETE = withUserAuth(deleteProjectTaskHandler); export const DELETE = withUserAuth(deleteProjectTaskHandler);

View File

@@ -17,6 +17,15 @@ export default function ProjectTasksSection({ projectId }) {
const [showAddTaskModal, setShowAddTaskModal] = useState(false); const [showAddTaskModal, setShowAddTaskModal] = useState(false);
const [expandedDescriptions, setExpandedDescriptions] = useState({}); const [expandedDescriptions, setExpandedDescriptions] = useState({});
const [expandedNotes, setExpandedNotes] = useState({}); const [expandedNotes, setExpandedNotes] = useState({});
const [editingTask, setEditingTask] = useState(null);
const [showEditTaskModal, setShowEditTaskModal] = useState(false);
const [editTaskForm, setEditTaskForm] = useState({
priority: "",
date_started: "",
status: "",
assigned_to: "",
});
const [users, setUsers] = useState([]);
useEffect(() => { useEffect(() => {
const fetchProjectTasks = async () => { const fetchProjectTasks = async () => {
try { try {
@@ -49,22 +58,38 @@ export default function ProjectTasksSection({ projectId }) {
} }
}; };
// Fetch users for assignment dropdown
const fetchUsers = async () => {
try {
const res = await fetch("/api/project-tasks/users");
const usersData = await res.json();
setUsers(usersData);
} catch (error) {
console.error("Failed to fetch users:", error);
}
};
fetchProjectTasks(); fetchProjectTasks();
fetchUsers();
}, [projectId]); }, [projectId]);
// Handle escape key to close modal // Handle escape key to close modals
useEffect(() => { useEffect(() => {
const handleEscape = (e) => { const handleEscape = (e) => {
if (e.key === "Escape" && showAddTaskModal) { if (e.key === "Escape") {
if (showEditTaskModal) {
handleCloseEditModal();
} else if (showAddTaskModal) {
setShowAddTaskModal(false); setShowAddTaskModal(false);
} }
}
}; };
document.addEventListener("keydown", handleEscape); document.addEventListener("keydown", handleEscape);
return () => document.removeEventListener("keydown", handleEscape); return () => document.removeEventListener("keydown", handleEscape);
}, [showAddTaskModal]); }, [showAddTaskModal, showEditTaskModal]);
// Prevent body scroll when modal is open and handle map z-index // Prevent body scroll when modal is open and handle map z-index
useEffect(() => { useEffect(() => {
if (showAddTaskModal) { if (showAddTaskModal || showEditTaskModal) {
// Prevent body scroll // Prevent body scroll
document.body.style.overflow = "hidden"; document.body.style.overflow = "hidden";
@@ -111,7 +136,7 @@ export default function ProjectTasksSection({ projectId }) {
nav.style.zIndex = ""; nav.style.zIndex = "";
}); });
}; };
}, [showAddTaskModal]); }, [showAddTaskModal, showEditTaskModal]);
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}`);
@@ -171,10 +196,11 @@ export default function ProjectTasksSection({ projectId }) {
if (res.ok) { if (res.ok) {
refetchTasks(); // Refresh the list refetchTasks(); // Refresh the list
} else { } else {
alert("Failed to delete task"); const errorData = await res.json();
alert("Failed to delete task: " + (errorData.error || "Unknown error"));
} }
} catch (error) { } catch (error) {
alert("Error deleting task"); alert("Error deleting task: " + error.message);
} }
}; };
@@ -210,26 +236,66 @@ export default function ProjectTasksSection({ projectId }) {
} }
}; };
const handleDeleteNote = async (noteId, taskId) => { const handleEditTask = (task) => {
if (!confirm("Are you sure you want to delete this note?")) return; setEditingTask(task);
// Format date for HTML input (YYYY-MM-DD)
let dateStarted = "";
if (task.date_started) {
const date = new Date(task.date_started);
if (!isNaN(date.getTime())) {
dateStarted = date.toISOString().split("T")[0];
}
}
const formData = {
priority: task.priority || "",
date_started: dateStarted,
status: task.status || "",
assigned_to: task.assigned_to || "",
};
setEditTaskForm(formData);
setShowEditTaskModal(true);
};
const handleUpdateTask = async () => {
if (!editingTask) return;
try { try {
const res = await fetch(`/api/task-notes?note_id=${noteId}`, { const res = await fetch(`/api/project-tasks/${editingTask.id}`, {
method: "DELETE", method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
priority: editTaskForm.priority,
date_started: editTaskForm.date_started || null,
status: editTaskForm.status,
assigned_to: editTaskForm.assigned_to || null,
}),
}); });
if (res.ok) { if (res.ok) {
// Refresh notes for this task refetchTasks();
const notesRes = await fetch(`/api/task-notes?task_id=${taskId}`); handleCloseEditModal();
const notes = await notesRes.json();
setTaskNotes((prev) => ({ ...prev, [taskId]: notes }));
} else { } else {
alert("Failed to delete note"); alert("Failed to update task");
} }
} catch (error) { } catch (error) {
alert("Error deleting note"); alert("Error updating task");
} }
}; };
const handleCloseEditModal = () => {
setShowEditTaskModal(false);
setEditingTask(null);
setEditTaskForm({
priority: "",
date_started: "",
status: "",
assigned_to: "",
});
};
const getPriorityVariant = (priority) => { const getPriorityVariant = (priority) => {
switch (priority) { switch (priority) {
case "urgent": case "urgent":
@@ -447,7 +513,7 @@ export default function ProjectTasksSection({ projectId }) {
{task.date_started {task.date_started
? formatDate(task.date_started) ? formatDate(task.date_started)
: "Not started"} : "Not started"}
</td>{" "} </td>
<td className="px-4 py-4"> <td className="px-4 py-4">
<TaskStatusDropdownSimple <TaskStatusDropdownSimple
task={task} task={task}
@@ -464,6 +530,14 @@ export default function ProjectTasksSection({ projectId }) {
> >
Notes ({taskNotes[task.id]?.length || 0}) Notes ({taskNotes[task.id]?.length || 0})
</button> </button>
<Button
variant="outline"
size="sm"
onClick={() => handleEditTask(task)}
className="text-xs"
>
Edit
</Button>
<Button <Button
variant="danger" variant="danger"
size="sm" size="sm"
@@ -594,6 +668,134 @@ export default function ProjectTasksSection({ projectId }) {
)} )}
</CardContent> </CardContent>
</Card> </Card>
{/* Edit Task Modal */}
{showEditTaskModal && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]">
<div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-900">
Edit Task:{" "}
{editingTask?.custom_task_name || editingTask?.task_name}
</h3>
<button
onClick={handleCloseEditModal}
className="text-gray-400 hover:text-gray-600"
>
<svg
className="w-5 h-5"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</button>
</div>
<div className="space-y-4">
{/* Assignment */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Assigned To
</label>
<select
value={editTaskForm.assigned_to}
onChange={(e) =>
setEditTaskForm((prev) => ({
...prev,
assigned_to: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
>
<option value="">Unassigned</option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.name}
</option>
))}
</select>
</div>
{/* Priority */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Priority
</label>
<select
value={editTaskForm.priority}
onChange={(e) =>
setEditTaskForm((prev) => ({
...prev,
priority: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
>
<option value="">Select Priority</option>
<option value="low">Low</option>
<option value="normal">Normal</option>
<option value="high">High</option>
<option value="urgent">Urgent</option>
</select>
</div>
{/* Date Started */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Date Started
</label>
<input
type="date"
value={editTaskForm.date_started}
onChange={(e) =>
setEditTaskForm((prev) => ({
...prev,
date_started: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
{/* Status */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Status
</label>
<select
value={editTaskForm.status}
onChange={(e) =>
setEditTaskForm((prev) => ({
...prev,
status: e.target.value,
}))
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
>
<option value="">Select Status</option>
<option value="pending">Pending</option>
<option value="in_progress">In Progress</option>
<option value="completed">Completed</option>
<option value="cancelled">Cancelled</option>
</select>
</div>
</div>
<div className="flex items-center justify-end gap-3 mt-6">
<Button variant="outline" onClick={handleCloseEditModal}>
Cancel
</Button>
<Button variant="primary" onClick={handleUpdateTask}>
Update Task
</Button>
</div>
</div>
</div>
)}
</div> </div>
); );
} }

View File

@@ -192,8 +192,13 @@ export function updateProjectTaskStatus(taskId, status, userId = null) {
// Delete a project task // Delete a project task
export function deleteProjectTask(taskId) { export function deleteProjectTask(taskId) {
const stmt = db.prepare("DELETE FROM project_tasks WHERE id = ?"); // First delete all related task notes
return stmt.run(taskId); const deleteNotesStmt = db.prepare("DELETE FROM notes WHERE task_id = ?");
deleteNotesStmt.run(taskId);
// Then delete the task itself
const deleteTaskStmt = db.prepare("DELETE FROM project_tasks WHERE id = ?");
return deleteTaskStmt.run(taskId);
} }
// Get project tasks assigned to a specific user // Get project tasks assigned to a specific user
@@ -291,3 +296,107 @@ export function getAllUsersForTaskAssignment() {
) )
.all(); .all();
} }
// Update project task (general update for edit modal)
export function updateProjectTask(taskId, updates, userId = null) {
// Get current task for logging
const getCurrentTask = db.prepare(`
SELECT
pt.*,
COALESCE(pt.custom_task_name, t.name) as task_name
FROM project_tasks pt
LEFT JOIN tasks t ON pt.task_template_id = t.task_id
WHERE pt.id = ?
`);
const currentTask = getCurrentTask.get(taskId);
if (!currentTask) {
throw new Error(`Task with ID ${taskId} not found`);
}
// Build dynamic update query
const fields = [];
const values = [];
if (updates.priority !== undefined) {
fields.push("priority = ?");
values.push(updates.priority);
}
if (updates.status !== undefined) {
fields.push("status = ?");
values.push(updates.status);
// Handle status-specific timestamp updates
if (currentTask.status === "pending" && updates.status === "in_progress") {
fields.push("date_started = CURRENT_TIMESTAMP");
} else if (updates.status === "completed") {
fields.push("date_completed = CURRENT_TIMESTAMP");
}
}
if (updates.assigned_to !== undefined) {
fields.push("assigned_to = ?");
values.push(updates.assigned_to || null);
}
if (updates.date_started !== undefined) {
fields.push("date_started = ?");
values.push(updates.date_started || null);
}
// Always update the updated_at timestamp
fields.push("updated_at = CURRENT_TIMESTAMP");
values.push(taskId);
const stmt = db.prepare(`
UPDATE project_tasks
SET ${fields.join(", ")}
WHERE id = ?
`);
const result = stmt.run(...values);
// Log the update
if (userId) {
const changes = [];
if (
updates.priority !== undefined &&
updates.priority !== currentTask.priority
) {
changes.push(
`Priority: ${currentTask.priority || "None"}${
updates.priority || "None"
}`
);
}
if (updates.status !== undefined && updates.status !== currentTask.status) {
changes.push(
`Status: ${currentTask.status || "None"}${updates.status || "None"}`
);
}
if (
updates.assigned_to !== undefined &&
updates.assigned_to !== currentTask.assigned_to
) {
changes.push(`Assignment updated`);
}
if (
updates.date_started !== undefined &&
updates.date_started !== currentTask.date_started
) {
changes.push(
`Date started: ${currentTask.date_started || "None"}${
updates.date_started || "None"
}`
);
}
if (changes.length > 0) {
const logMessage = `Task updated: ${changes.join(", ")}`;
addNoteToTask(taskId, logMessage, true, userId);
}
}
return result;
}