public/assets/js/task_manager_calendar.js
Вот содержимое файла public/assets/js/task_manager_calendar.js
:
// Calendar Management for Task Manager
// Initialize the Calendar
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('taskCalendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
locale: 'en', // Default locale can be changed
events: function(info, successCallback, failureCallback) {
// Fetch events for the calendar
fetch('/index.php?route=extension/task_manager/getCalendarTasks', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(tasks => {
let events = tasks.map(task => {
return {
id: task.id,
title: task.title,
start: task.due_date,
end: task.due_date,
description: task.description,
status: task.status,
priority: task.priority,
classNames: [task.status.toLowerCase()]
};
});
successCallback(events);
})
.catch(error => {
console.error('Error fetching calendar tasks:', error);
failureCallback(error);
});
},
eventClick: function(info) {
let taskId = info.event.id;
// Show task details when clicked on a calendar event
showTaskDetailsInCalendar(taskId);
},
editable: true,
droppable: true, // Enable drag-and-drop feature for tasks
drop: function(info) {
let taskId = info.event.id;
let newDate = info.event.startStr;
// Update task date in the backend after drop
updateTaskDueDate(taskId, newDate);
}
});
calendar.render();
});
// Show Task Details in Calendar View
function showTaskDetailsInCalendar(taskId) {
fetch(`/index.php?route=extension/task_manager/getTaskDetails&id=${taskId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(task => {
let taskDetails = `
<h4>${task.title}</h4>
<p><strong>Status:</strong> ${task.status}</p>
<p><strong>Priority:</strong> ${task.priority}</p>
<p><strong>Due Date:</strong> ${task.due_date}</p>
<p><strong>Description:</strong> ${task.description}</p>
`;
// Show the task details in a modal or a separate section
document.getElementById('taskDetailsModal').innerHTML = taskDetails;
$('#taskDetailsModal').modal('show');
})
.catch(error => {
console.error('Error fetching task details:', error);
});
}
// Update task due date after drag-and-drop on the calendar
function updateTaskDueDate(taskId, newDate) {
fetch('/index.php?route=extension/task_manager/updateTaskDueDate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: taskId, new_due_date: newDate })
})
.then(response => response.json())
.then(result => {
if (result.success) {
alert('Task due date updated successfully!');
} else {
alert('Error updating task due date!');
}
})
.catch(error => console.error('Error updating task due date:', error));
}
// Create Task from Calendar
document.getElementById('createTaskFromCalendarForm').addEventListener('submit', function(event) {
event.preventDefault();
let title = document.getElementById('calendarTaskTitle').value;
let description = document.getElementById('calendarTaskDescription').value;
let priority = document.getElementById('calendarTaskPriority').value;
let dueDate = document.getElementById('calendarTaskDueDate').value;
// Prepare task data
let taskData = {
title: title,
description: description,
priority: priority,
due_date: dueDate
};
// Send request to create a task
fetch('/index.php?route=extension/task_manager/createTaskFromCalendar', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(taskData)
})
.then(response => response.json())
.then(result => {
if (result.success) {
alert('Task created successfully from calendar!');
// Refresh the calendar to show the newly created task
$('#taskCalendar').fullCalendar('refetchEvents');
} else {
alert('Error creating task from calendar!');
}
})
.catch(error => console.error('Error creating task from calendar:', error));
});
Описание:
-
Инициализация календаря: Используется FullCalendar для отображения задач на календаре. Календарь загружает задачи через AJAX с помощью запроса к серверу
/index.php?route=extension/task_manager/getCalendarTasks
. -
Обработка клика по задаче: При клике на задачу в календаре отображаются детали задачи в модальном окне с помощью функции
showTaskDetailsInCalendar
. -
Перетаскивание задач: Когда задача перетаскивается на новый день, обновляется дата выполнения задачи в базе данных с помощью
updateTaskDueDate
. -
Создание задачи через календарь: Задачи можно создавать прямо из календаря через форму. Созданные задачи отправляются через AJAX на сервер для сохранения.
-
Поддержка drag-and-drop: Календарь поддерживает перетаскивание задач с автоматическим обновлением их дат.
Этот скрипт интегрирует задачи с календарем и позволяет удобно управлять задачами через интерфейс.