Compare commits

...

7 Commits

11 changed files with 906 additions and 116 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

@@ -9,7 +9,7 @@ import Button from "@/components/ui/Button";
import Badge from "@/components/ui/Badge"; import Badge from "@/components/ui/Badge";
import Link from "next/link"; import Link from "next/link";
import { differenceInCalendarDays, parseISO } from "date-fns"; import { differenceInCalendarDays, parseISO } from "date-fns";
import { formatDate } from "@/lib/utils"; import { formatDate, formatCoordinates } from "@/lib/utils";
import PageContainer from "@/components/ui/PageContainer"; import PageContainer from "@/components/ui/PageContainer";
import PageHeader from "@/components/ui/PageHeader"; import PageHeader from "@/components/ui/PageHeader";
import ProjectStatusDropdown from "@/components/ProjectStatusDropdown"; import ProjectStatusDropdown from "@/components/ProjectStatusDropdown";
@@ -217,7 +217,7 @@ export default async function ProjectViewPage({ params }) {
Coordinates Coordinates
</span> </span>
<p className="text-gray-900 font-medium font-mono text-sm"> <p className="text-gray-900 font-medium font-mono text-sm">
{project.coordinates} {formatCoordinates(project.coordinates)}
</p> </p>
</div> </div>
)} )}

View File

@@ -196,12 +196,6 @@ export default function ProjectListPage() {
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-24"> <th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-24">
Status Status
</th> </th>
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-24">
Created By
</th>
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-24">
Assigned To
</th>
<th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-20"> <th className="text-left px-2 py-3 font-semibold text-xs text-gray-700 w-20">
Actions Actions
</th> </th>
@@ -281,18 +275,6 @@ export default function ProjectListPage() {
? "Zakończony" ? "Zakończony"
: "-"} : "-"}
</td> </td>
<td
className="px-2 py-3 text-xs text-gray-600 truncate"
title={project.created_by_name || "Unknown"}
>
{project.created_by_name || "Unknown"}
</td>
<td
className="px-2 py-3 text-xs text-gray-600 truncate"
title={project.assigned_to_name || "Unassigned"}
>
{project.assigned_to_name || "Unassigned"}
</td>
<td className="px-2 py-3"> <td className="px-2 py-3">
<Link href={`/projects/${project.project_id}`}> <Link href={`/projects/${project.project_id}`}>
<Button <Button

View File

@@ -89,20 +89,12 @@ export default function TaskTemplatesPage() {
{template.description} {template.description}
</p> </p>
)}{" "} )}{" "}
<div className="flex items-center justify-between"> <div className="flex items-center justify-end">
<span className="text-xs text-gray-500"> <Link href={`/tasks/templates/${template.task_id}/edit`}>
Template ID: {template.task_id} <Button variant="outline" size="sm">
</span> Edit
<div className="flex space-x-2">
<Link href={`/tasks/templates/${template.task_id}/edit`}>
<Button variant="outline" size="sm">
Edit
</Button>
</Link>
<Button variant="secondary" size="sm">
Duplicate
</Button> </Button>
</div> </Link>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -73,9 +73,6 @@ export default function ProjectStatusDropdown({
} }
}; };
const handleOpen = () => { const handleOpen = () => {
console.log(
"ProjectStatusDropdown handleOpen called, setting isOpen to true"
);
setIsOpen(true); setIsOpen(true);
}; };
@@ -111,10 +108,6 @@ export default function ProjectStatusDropdown({
<button <button
ref={buttonRef} ref={buttonRef}
onClick={() => { onClick={() => {
console.log(
"ProjectStatusDropdown button clicked, current isOpen:",
isOpen
);
setIsOpen(!isOpen); setIsOpen(!isOpen);
}} }}
disabled={loading} disabled={loading}
@@ -145,17 +138,13 @@ export default function ProjectStatusDropdown({
</svg> </svg>
</Badge> </Badge>
</button>{" "} </button>{" "}
{/* Simple dropdown for debugging */} {/* Status Options Dropdown */}
{isOpen && ( {isOpen && (
<div className="absolute top-full left-0 mt-1 bg-white border-2 border-red-500 rounded-md shadow-lg z-[9999] min-w-[140px]"> <div className="absolute top-full left-0 mt-1 bg-white border border-gray-200 rounded-md shadow-lg z-[9999] min-w-[140px]">
<div className="bg-yellow-100 p-2 text-xs text-center border-b">
DEBUG: ProjectStatus Dropdown is visible
</div>
{Object.entries(statusConfig).map(([statusKey, config]) => ( {Object.entries(statusConfig).map(([statusKey, config]) => (
<button <button
key={statusKey} key={statusKey}
onClick={() => { onClick={() => {
console.log("ProjectStatus Option clicked:", statusKey);
handleChange(statusKey); handleChange(statusKey);
}} }}
className="w-full text-left px-3 py-2 hover:bg-gray-50 transition-colors first:rounded-t-md last:rounded-b-md" className="w-full text-left px-3 py-2 hover:bg-gray-50 transition-colors first:rounded-t-md last:rounded-b-md"
@@ -170,9 +159,8 @@ export default function ProjectStatusDropdown({
{/* Backdrop */} {/* Backdrop */}
{isOpen && ( {isOpen && (
<div <div
className="fixed inset-0 z-[9998] bg-black bg-opacity-10" className="fixed inset-0 z-[9998]"
onClick={() => { onClick={() => {
console.log("ProjectStatus Backdrop clicked");
setIsOpen(false); setIsOpen(false);
}} }}
/> />

View File

@@ -5,6 +5,7 @@ import { Card, CardHeader, CardContent } from "./ui/Card";
import Button from "./ui/Button"; import Button from "./ui/Button";
import Badge from "./ui/Badge"; import Badge from "./ui/Badge";
import TaskStatusDropdownSimple from "./TaskStatusDropdownSimple"; import TaskStatusDropdownSimple from "./TaskStatusDropdownSimple";
import TaskCommentsModal from "./TaskCommentsModal";
import SearchBar from "./ui/SearchBar"; import SearchBar from "./ui/SearchBar";
import { Select } from "./ui/Input"; import { Select } from "./ui/Input";
import Link from "next/link"; import Link from "next/link";
@@ -20,6 +21,8 @@ export default function ProjectTasksList() {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState(""); const [searchTerm, setSearchTerm] = useState("");
const [groupBy, setGroupBy] = useState("none"); const [groupBy, setGroupBy] = useState("none");
const [selectedTask, setSelectedTask] = useState(null);
const [showCommentsModal, setShowCommentsModal] = useState(false);
useEffect(() => { useEffect(() => {
const fetchAllTasks = async () => { const fetchAllTasks = async () => {
@@ -35,7 +38,19 @@ export default function ProjectTasksList() {
}; };
fetchAllTasks(); fetchAllTasks();
}, []); // Calculate task status based on date_added and max_wait_days }, []);
// Handle escape key to close modal
useEffect(() => {
const handleEscape = (e) => {
if (e.key === "Escape" && showCommentsModal) {
handleCloseComments();
}
};
document.addEventListener("keydown", handleEscape);
return () => document.removeEventListener("keydown", handleEscape);
}, [showCommentsModal]); // Calculate task status based on date_added and max_wait_days
const getTaskStatus = (task) => { const getTaskStatus = (task) => {
if (task.status === "completed" || task.status === "cancelled") { if (task.status === "completed" || task.status === "cancelled") {
return { type: "completed", days: 0 }; return { type: "completed", days: 0 };
@@ -230,6 +245,16 @@ export default function ProjectTasksList() {
} }
}; };
const handleShowComments = (task) => {
setSelectedTask(task);
setShowCommentsModal(true);
};
const handleCloseComments = () => {
setShowCommentsModal(false);
setSelectedTask(null);
};
const getPriorityVariant = (priority) => { const getPriorityVariant = (priority) => {
switch (priority) { switch (priority) {
case "urgent": case "urgent":
@@ -250,7 +275,7 @@ export default function ProjectTasksList() {
if (days > 3) return "warning"; if (days > 3) return "warning";
return "high"; return "high";
}; };
const TaskRow = ({ task, showTimeLeft = false }) => ( const TaskRow = ({ task, showTimeLeft = false, showMaxWait = true }) => (
<tr className="hover:bg-gray-50 border-b border-gray-200"> <tr className="hover:bg-gray-50 border-b border-gray-200">
<td className="px-4 py-3"> <td className="px-4 py-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -273,16 +298,6 @@ export default function ProjectTasksList() {
<td className="px-4 py-3 text-sm text-gray-600"> <td className="px-4 py-3 text-sm text-gray-600">
{task.address || "N/A"} {task.address || "N/A"}
</td> </td>
<td className="px-4 py-3 text-sm text-gray-600">
{task.created_by_name ? (
<div>
<div className="font-medium">{task.created_by_name}</div>
<div className="text-xs text-gray-500">{task.created_by_email}</div>
</div>
) : (
"N/A"
)}
</td>
<td className="px-4 py-3 text-sm text-gray-600"> <td className="px-4 py-3 text-sm text-gray-600">
{task.assigned_to_name ? ( {task.assigned_to_name ? (
<div> <div>
@@ -368,22 +383,34 @@ export default function ProjectTasksList() {
})() })()
)} )}
</td> </td>
<td className="px-4 py-3 text-sm text-gray-500"> {showMaxWait && (
{task.max_wait_days} days <td className="px-4 py-3 text-sm text-gray-500">
</td> {task.max_wait_days} days
</td>
)}
<td className="px-4 py-3"> <td className="px-4 py-3">
<TaskStatusDropdownSimple <div className="flex items-center gap-2">
task={task} <TaskStatusDropdownSimple
size="sm" task={task}
onStatusChange={handleStatusChange} size="sm"
/> onStatusChange={handleStatusChange}
/>
<Button
variant="secondary"
size="sm"
onClick={() => handleShowComments(task)}
title="View comments"
>
💬
</Button>
</div>
</td> </td>
</tr> </tr>
); );
const TaskTable = ({ tasks, showGrouped = false, showTimeLeft = false }) => { const TaskTable = ({ tasks, showGrouped = false, showTimeLeft = false, showMaxWait = true }) => {
const filteredTasks = filterTasks(tasks); const filteredTasks = filterTasks(tasks);
const groupedTasks = groupTasksByName(filteredTasks); const groupedTasks = groupTasksByName(filteredTasks);
const colSpan = showTimeLeft ? "10" : "9"; const colSpan = showTimeLeft && showMaxWait ? "9" : showTimeLeft || showMaxWait ? "8" : "7";
return ( return (
<div className="overflow-x-auto"> <div className="overflow-x-auto">
@@ -402,9 +429,6 @@ export default function ProjectTasksList() {
<th className="px-4 py-3 text-left text-sm font-medium text-gray-700"> <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">
Address Address
</th> </th>
<th className="px-4 py-3 text-left text-sm font-medium text-gray-700">
Created By
</th>
<th className="px-4 py-3 text-left text-sm font-medium text-gray-700"> <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">
Assigned To Assigned To
</th> </th>
@@ -416,9 +440,11 @@ export default function ProjectTasksList() {
<th className="px-4 py-3 text-left text-sm font-medium text-gray-700"> <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">
Date Info Date Info
</th> </th>
<th className="px-4 py-3 text-left text-sm font-medium text-gray-700"> {showMaxWait && (
Max Wait <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">
</th>{" "} Max Wait
</th>
)}{" "}
<th className="px-4 py-3 text-left text-sm font-medium text-gray-700"> <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">
Actions Actions
</th> </th>
@@ -442,6 +468,7 @@ export default function ProjectTasksList() {
key={task.id} key={task.id}
task={task} task={task}
showTimeLeft={showTimeLeft} showTimeLeft={showTimeLeft}
showMaxWait={showMaxWait}
/> />
))} ))}
</Fragment> </Fragment>
@@ -544,6 +571,7 @@ export default function ProjectTasksList() {
tasks={taskGroups.pending} tasks={taskGroups.pending}
showGrouped={groupBy === "task_name"} showGrouped={groupBy === "task_name"}
showTimeLeft={false} showTimeLeft={false}
showMaxWait={true}
/> />
</div> </div>
@@ -564,6 +592,7 @@ export default function ProjectTasksList() {
tasks={taskGroups.in_progress} tasks={taskGroups.in_progress}
showGrouped={groupBy === "task_name"} showGrouped={groupBy === "task_name"}
showTimeLeft={true} showTimeLeft={true}
showMaxWait={false}
/> />
</div> </div>
@@ -584,9 +613,17 @@ export default function ProjectTasksList() {
tasks={taskGroups.completed} tasks={taskGroups.completed}
showGrouped={groupBy === "task_name"} showGrouped={groupBy === "task_name"}
showTimeLeft={false} showTimeLeft={false}
showMaxWait={false}
/> />
</div> </div>
</div> </div>
{/* Comments Modal */}
<TaskCommentsModal
task={selectedTask}
isOpen={showCommentsModal}
onClose={handleCloseComments}
/>
</div> </div>
); );
} }

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") {
setShowAddTaskModal(false); if (showEditTaskModal) {
handleCloseEditModal();
} else if (showAddTaskModal) {
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":
@@ -390,7 +456,7 @@ export default function ProjectTasksSection({ projectId }) {
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Status Status
</th> </th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-48">
Actions Actions
</th> </th>
</tr> </tr>
@@ -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}
@@ -456,20 +522,69 @@ export default function ProjectTasksSection({ projectId }) {
/> />
</td> </td>
<td className="px-4 py-4"> <td className="px-4 py-4">
<div className="flex items-center gap-2"> <div className="flex items-center gap-1.5">
<button <Button
variant="ghost"
size="sm"
onClick={() => toggleNotes(task.id)} onClick={() => toggleNotes(task.id)}
className="text-xs text-blue-600 hover:text-blue-800 font-medium" className="text-xs px-2 py-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 border-0"
title={`${taskNotes[task.id]?.length || 0} notes`} title={`${taskNotes[task.id]?.length || 0} notes`}
> >
Notes ({taskNotes[task.id]?.length || 0}) <svg
</button> className="w-3 h-3 mr-1"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
/>
</svg>
{taskNotes[task.id]?.length || 0}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleEditTask(task)}
className="text-xs px-2 py-1 min-w-[60px]"
>
<svg
className="w-3 h-3 mr-1"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
Edit
</Button>
<Button <Button
variant="danger" variant="danger"
size="sm" size="sm"
onClick={() => handleDeleteTask(task.id)} onClick={() => handleDeleteTask(task.id)}
className="text-xs" className="text-xs px-2 py-1 min-w-[60px]"
> >
<svg
className="w-3 h-3 mr-1"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
Delete Delete
</Button> </Button>
</div> </div>
@@ -512,11 +627,11 @@ export default function ProjectTasksSection({ projectId }) {
> >
<div className="flex-1"> <div className="flex-1">
<div className="flex items-center gap-2 mb-1"> <div className="flex items-center gap-2 mb-1">
{note.is_system && ( {note.is_system ? (
<span className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded-full font-medium"> <span className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded-full font-medium">
System System
</span> </span>
)} ) : null}
{note.created_by_name && ( {note.created_by_name && (
<span className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded-full font-medium"> <span className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded-full font-medium">
{note.created_by_name} {note.created_by_name}
@@ -530,11 +645,6 @@ export default function ProjectTasksSection({ projectId }) {
{formatDate(note.note_date, { {formatDate(note.note_date, {
includeTime: true, includeTime: true,
})} })}
{note.created_by_name && (
<span className="ml-2">
by {note.created_by_name}
</span>
)}
</p> </p>
</div> </div>
{!note.is_system && ( {!note.is_system && (
@@ -599,6 +709,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

@@ -0,0 +1,369 @@
"use client";
import React, { useState, useEffect } from "react";
import Button from "./ui/Button";
import Badge from "./ui/Badge";
import { formatDate } from "@/lib/utils";
import { formatDistanceToNow, parseISO } from "date-fns";
export default function TaskCommentsModal({ task, isOpen, onClose }) {
const [notes, setNotes] = useState([]);
const [loading, setLoading] = useState(true);
const [newNote, setNewNote] = useState("");
const [loadingAdd, setLoadingAdd] = useState(false);
useEffect(() => {
if (isOpen && task) {
fetchNotes();
}
}, [isOpen, task]);
const fetchNotes = async () => {
if (!task?.id) return;
try {
setLoading(true);
const res = await fetch(`/api/task-notes?task_id=${task.id}`);
const data = await res.json();
setNotes(data);
} catch (error) {
console.error("Failed to fetch notes:", error);
} finally {
setLoading(false);
}
};
const handleAddNote = async () => {
if (!newNote.trim() || !task?.id) return;
try {
setLoadingAdd(true);
const res = await fetch("/api/task-notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
task_id: task.id,
note: newNote.trim(),
}),
});
if (res.ok) {
setNewNote("");
await fetchNotes(); // Refresh notes
} else {
alert("Failed to add note");
}
} catch (error) {
alert("Error adding note");
} finally {
setLoadingAdd(false);
}
};
const handleDeleteNote = async (noteId) => {
if (!confirm("Are you sure you want to delete this note?")) return;
try {
const res = await fetch("/api/task-notes", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ note_id: noteId }),
});
if (res.ok) {
await fetchNotes(); // Refresh notes
} else {
alert("Failed to delete note");
}
} catch (error) {
alert("Error deleting note");
}
};
const handleKeyDown = (e) => {
if (e.key === "Escape") {
onClose();
} else if (e.key === "Enter" && e.ctrlKey) {
handleAddNote();
}
};
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":
case "cancelled":
return "success";
case "in_progress":
return "secondary";
case "pending":
return "primary";
default:
return "default";
}
};
const formatTaskDate = (dateString, label) => {
if (!dateString) return null;
try {
const date = dateString.includes("T") ? parseISO(dateString) : new Date(dateString);
return {
label,
relative: formatDistanceToNow(date, { addSuffix: true }),
absolute: formatDate(date, { includeTime: true })
};
} catch (error) {
return { label, relative: dateString, absolute: dateString };
}
};
if (!isOpen) return null;
return (
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]"
onClick={(e) => e.target === e.currentTarget && onClose()}
>
<div className="bg-white rounded-lg w-full max-w-4xl mx-4 max-h-[90vh] flex flex-col">
{/* Header */}
<div className="p-6 border-b">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h3 className="text-xl font-semibold text-gray-900">
{task?.task_name}
</h3>
<Badge variant={getPriorityVariant(task?.priority)} size="sm">
{task?.priority}
</Badge>
<Badge variant={getStatusVariant(task?.status)} size="sm">
{task?.status?.replace('_', ' ')}
</Badge>
</div>
<p className="text-sm text-gray-600 mb-3">
Project: <span className="font-medium">{task?.project_name}</span>
</p>
</div>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-600 text-xl font-semibold ml-4"
onKeyDown={handleKeyDown}
>
×
</button>
</div>
{/* Task Details Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg">
{/* Location Information */}
{(task?.city || task?.address) && (
<div className="space-y-1">
<h4 className="text-xs font-medium text-gray-500 uppercase tracking-wide">Location</h4>
{task?.city && (
<p className="text-sm text-gray-900">{task.city}</p>
)}
{task?.address && (
<p className="text-xs text-gray-600">{task.address}</p>
)}
</div>
)}
{/* Assignment Information */}
<div className="space-y-1">
<h4 className="text-xs font-medium text-gray-500 uppercase tracking-wide">Assignment</h4>
{task?.assigned_to_name ? (
<div>
<p className="text-sm text-gray-900">{task.assigned_to_name}</p>
<p className="text-xs text-gray-600">{task.assigned_to_email}</p>
</div>
) : (
<p className="text-sm text-gray-500 italic">Unassigned</p>
)}
</div>
{/* Task Timing */}
<div className="space-y-1">
<h4 className="text-xs font-medium text-gray-500 uppercase tracking-wide">Timing</h4>
{task?.max_wait_days && (
<p className="text-xs text-gray-600">Max wait: {task.max_wait_days} days</p>
)}
{(() => {
if (task?.status === "completed" && task?.date_completed) {
const dateInfo = formatTaskDate(task.date_completed, "Completed");
return (
<div>
<p className="text-sm text-green-700 font-medium">{dateInfo.relative}</p>
<p className="text-xs text-gray-600">{dateInfo.absolute}</p>
</div>
);
} else if (task?.status === "in_progress" && task?.date_started) {
const dateInfo = formatTaskDate(task.date_started, "Started");
return (
<div>
<p className="text-sm text-blue-700 font-medium">Started {dateInfo.relative}</p>
<p className="text-xs text-gray-600">{dateInfo.absolute}</p>
</div>
);
} else if (task?.date_added) {
const dateInfo = formatTaskDate(task.date_added, "Created");
return (
<div>
<p className="text-sm text-gray-700 font-medium">Created {dateInfo.relative}</p>
<p className="text-xs text-gray-600">{dateInfo.absolute}</p>
</div>
);
}
return null;
})()}
</div>
{/* Task Description */}
{task?.description && (
<div className="space-y-1 md:col-span-2 lg:col-span-3">
<h4 className="text-xs font-medium text-gray-500 uppercase tracking-wide">Description</h4>
<p className="text-sm text-gray-900 leading-relaxed">{task.description}</p>
</div>
)}
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{loading ? (
<div className="text-center py-8">
<div className="animate-pulse space-y-4">
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
<div className="h-4 bg-gray-200 rounded w-1/2"></div>
<div className="h-4 bg-gray-200 rounded w-2/3"></div>
</div>
</div>
) : (
<div className="space-y-4">
<div className="flex items-center gap-2 mb-4">
<h5 className="text-lg font-medium text-gray-900">
Comments & Activity
</h5>
<Badge variant="secondary" size="sm">
{notes.length}
</Badge>
</div>
{notes.length === 0 ? (
<div className="text-center py-12 text-gray-500">
<div className="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
<span className="text-2xl">💬</span>
</div>
<p className="text-lg font-medium mb-1">No comments yet</p>
<p className="text-sm">Be the first to add a comment!</p>
</div>
) : (
<div className="space-y-4">
{notes.map((note) => (
<div
key={note.note_id}
className={`p-4 rounded-lg border flex justify-between items-start transition-colors ${
note.is_system
? "bg-blue-50 border-blue-200 hover:bg-blue-100"
: "bg-white border-gray-200 hover:bg-gray-50 shadow-sm"
}`}
>
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
{note.is_system ? (
<span className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded-full font-medium flex items-center gap-1">
<span>🤖</span>
System
</span>
) : (
<span className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded-full font-medium flex items-center gap-1">
<span>👤</span>
{note.created_by_name || 'User'}
</span>
)}
<span className="text-xs text-gray-500 font-medium">
{formatDate(note.note_date, {
includeTime: true,
})}
</span>
</div>
<p className="text-sm text-gray-800 leading-relaxed">
{note.note}
</p>
</div>
{!note.is_system && (
<button
onClick={() => handleDeleteNote(note.note_id)}
className="ml-3 p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
title="Delete comment"
>
<span className="text-sm">🗑</span>
</button>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
{/* Footer - Add new comment */}
<div className="p-6 border-t bg-gradient-to-r from-gray-50 to-gray-100">
<div className="space-y-4">
<div className="flex items-center gap-2">
<span className="text-lg">💬</span>
<label className="text-sm font-medium text-gray-700">
Add a comment
</label>
</div>
<textarea
value={newNote}
onChange={(e) => setNewNote(e.target.value)}
placeholder="Type your comment here... (Ctrl+Enter to submit)"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none shadow-sm"
rows={3}
onKeyDown={handleKeyDown}
/>
<div className="flex items-center justify-between">
<p className="text-xs text-gray-500 flex items-center gap-1">
<span></span>
Press Ctrl+Enter to submit or Escape to close
</p>
<div className="flex gap-3">
<Button
variant="secondary"
size="sm"
onClick={onClose}
>
Close
</Button>
<Button
variant="primary"
size="sm"
onClick={handleAddNote}
disabled={loadingAdd || !newNote.trim()}
>
{loadingAdd ? "Adding..." : "💾 Add Comment"}
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -9,6 +9,7 @@ const buttonVariants = {
danger: "bg-red-600 hover:bg-red-700 text-white", danger: "bg-red-600 hover:bg-red-700 text-white",
success: "bg-green-600 hover:bg-green-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", outline: "border border-blue-600 text-blue-600 hover:bg-blue-50",
ghost: "text-gray-600 hover:text-gray-900 hover:bg-gray-50",
}; };
const buttonSizes = { const buttonSizes = {

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

View File

@@ -88,3 +88,42 @@ export const formatDateForInput = (date) => {
return ""; return "";
} }
}; };
export const formatCoordinates = (coordinatesString) => {
if (!coordinatesString) return "";
try {
const [latStr, lngStr] = coordinatesString.split(",");
const lat = parseFloat(latStr.trim());
const lng = parseFloat(lngStr.trim());
if (isNaN(lat) || isNaN(lng)) {
return coordinatesString; // Return original if parsing fails
}
const formatDMS = (decimal, isLatitude) => {
const direction = isLatitude
? decimal >= 0
? "N"
: "S"
: decimal >= 0
? "E"
: "W";
const absolute = Math.abs(decimal);
const degrees = Math.floor(absolute);
const minutes = Math.floor((absolute - degrees) * 60);
const seconds = Math.round(((absolute - degrees) * 60 - minutes) * 60);
return `${direction}: ${degrees}°${minutes}'${seconds}"`;
};
const latDMS = formatDMS(lat, true);
const lngDMS = formatDMS(lng, false);
return `${latDMS}, ${lngDMS}`;
} catch (error) {
console.error("Error formatting coordinates:", error);
return coordinatesString;
}
};