"use server"; import { prisma } from "@/lib/prisma"; import { revalidatePath } from "next/cache"; export async function logActivity(userId: string, action: string, entityType: string, entityId: string, details?: string) { try { await prisma.activityLog.create({ data: { userId, action, entityType, entityId, details } }); } catch (e) { console.error("Activity Logging Failed", e); } } export async function getTasks() { try { const tasks = await prisma.task.findMany({ include: { assignee: { select: { name: true, image: true, id: true } }, sprint: { select: { name: true, id: true } }, tags: true, comments: true, timeLogs: true }, orderBy: { createdAt: 'desc' } }); return { success: true, data: tasks }; } catch (error) { return { success: false, error: "Failed to fetch tasks" }; } } export async function createTask(formData: FormData) { const title = formData.get("title") as string; const description = formData.get("description") as string; const type = formData.get("type") as string; const priority = formData.get("priority") as string; const sprintId = formData.get("sprintId") as string; const assigneeId = formData.get("assigneeId") as string; const parentId = formData.get("parentId") as string; try { let finalSprintId = sprintId || null; // Inherit sprint from parent if not specified if (parentId && !finalSprintId) { const parent = await prisma.task.findUnique({ where: { id: parentId } }); if (parent) finalSprintId = parent.sprintId; } const task = await prisma.task.create({ data: { title, description, type, priority, sprintId: finalSprintId, assigneeId: assigneeId || null, parentId: parentId || null } }); if (assigneeId) { // In a perfect world we pass userId here, but initial creation often happens in contexts where we might just // want to log it as 'System' or ignore. // For now, let's assume if an action happens, we might not always have userId unless passed. } revalidatePath("/tasks"); return { success: true }; } catch (error) { console.error("Create Task Error:", error); return { success: false, error: "Failed to create task" }; } } export async function updateTaskStatus(taskId: string, status: string, userId?: string) { try { const task = await prisma.task.update({ where: { id: taskId }, data: { status } }); if (userId) { await logActivity(userId, `updated status to ${status}`, 'TASK', taskId, `Task: ${task.title}`); } revalidatePath("/tasks"); return { success: true }; } catch (error) { return { success: false, error: "Failed to update status" }; } } export async function getTaskDetails(taskId: string) { try { const task = await prisma.task.findUnique({ where: { id: taskId }, include: { assignee: true, sprint: true, tags: true, comments: { include: { user: true }, orderBy: { createdAt: 'desc' } }, timeLogs: { include: { user: true }, orderBy: { date: 'desc' } }, subTasks: { include: { assignee: true } } } }); return { success: true, data: task }; } catch (error) { return { success: false, error: "Failed to fetch task details" }; } } export async function updateTaskField(taskId: string, field: string, value: any, userId?: string) { try { let data: any = {}; let logAction = ""; let logDetails = ""; if (field === 'estimatedTime') { data[field] = parseFloat(value); logAction = `updated estimate to ${value}h`; } else if (field === 'sprintId') { const sprintId = value === '' ? null : value; data[field] = sprintId; // Fetch sprint name for log? logAction = sprintId ? `moved to sprint` : `removed from sprint`; } else if (field === 'assigneeId') { const assigneeId = value === '' ? null : value; data[field] = assigneeId; logAction = assigneeId ? `assigned user` : `unassigned user`; } else { data[field] = value; logAction = `updated ${field}`; } const task = await prisma.task.update({ where: { id: taskId }, data, include: { sprint: true, assignee: true } }); if (userId) { // Refine details based on what we know now if (field === 'sprintId') { logDetails = task.sprint ? `Sprint: ${task.sprint.name}` : 'Backlog'; } else if (field === 'assigneeId') { logDetails = task.assignee ? `User: ${task.assignee.name}` : 'Unassigned'; } else { logDetails = `Task: ${task.title}`; } await logActivity(userId, logAction, 'TASK', taskId, logDetails); } revalidatePath("/tasks"); return { success: true }; } catch (error) { console.error(`Update Field Error (${field}):`, error); return { success: false, error: "Failed to update task" }; } } export async function addComment(taskId: string, userId: string, content: string) { try { await prisma.comment.create({ data: { taskId, userId, content } }); const task = await prisma.task.findUnique({ where: { id: taskId } }); await logActivity(userId, `commented on`, 'TASK', taskId, `Task: ${task?.title || taskId}`); revalidatePath(`/tasks`); // In case it's visible there return { success: true }; } catch (error) { console.error("Add Comment Error:", error); return { success: false, error: "Failed to add comment" }; } } export async function addTag(taskId: string, tagName: string, userId?: string) { try { let tag = await prisma.tag.findUnique({ where: { name: tagName } }); if (!tag) { tag = await prisma.tag.create({ data: { name: tagName, color: 'blue' } }); } const task = await prisma.task.update({ where: { id: taskId }, data: { tags: { connect: { id: tag.id } } } }); if (userId) { await logActivity(userId, `added tag ${tagName}`, 'TASK', taskId, `Task: ${task.title}`); } revalidatePath("/tasks"); return { success: true }; } catch (error) { return { success: false, error: "Failed to add tag" }; } } export async function removeTag(taskId: string, tagId: string, userId?: string) { // Added userId optional try { await prisma.task.update({ where: { id: taskId }, data: { tags: { disconnect: { id: tagId } } } }); // We could log removal here too if we passed userId if (userId) { await logActivity(userId, `removed tag`, 'TASK', taskId, ""); } revalidatePath("/tasks"); return { success: true }; } catch (error) { return { success: false, error: "Failed to remove tag" }; } } export async function logTime(taskId: string, userId: string, duration: number, description: string) { try { await prisma.timeLog.create({ data: { taskId, userId, duration: parseFloat(duration.toString()), description } }); const task = await prisma.task.findUnique({ where: { id: taskId }, include: { timeLogs: true } }); if (task) { const total = task.timeLogs.reduce((acc, log) => acc + log.duration, 0) + parseFloat(duration.toString()); await prisma.task.update({ where: { id: taskId }, data: { loggedTime: total } }); await logActivity(userId, `logged ${duration}h`, 'TASK', taskId, `Task: ${task.title}. Desc: ${description}`); } revalidatePath("/tasks"); return { success: true }; } catch (error) { console.error("Log Time Error:", error); return { success: false, error: "Failed to log time" }; } } export async function getActivityLogs() { try { const logs = await prisma.activityLog.findMany({ include: { user: { select: { name: true, image: true, email: true } } }, orderBy: { createdAt: 'desc' }, take: 100 }); return { success: true, data: logs }; } catch (error) { return { success: false, error: "Failed to fetch logs" }; } } export async function deleteTask(taskId: string, userId?: string) { try { const task = await prisma.task.findUnique({ where: { id: taskId } }); if (!task) return { success: false, error: "Task not found" }; await prisma.task.delete({ where: { id: taskId } }); if (userId) { await logActivity(userId, `deleted task`, 'TASK', taskId, `Task Title: ${task.title}`); } revalidatePath("/tasks"); revalidatePath("/sprints"); return { success: true }; } catch (error) { return { success: false, error: "Failed to delete task" }; } }