документы

This commit is contained in:
2026-02-24 23:08:35 +05:00
parent 27b7197569
commit 72541292f5
4 changed files with 645 additions and 285 deletions

View File

@@ -22,11 +22,11 @@ async function loadTasks() {
}
if (creatorFilter) {
params.push(`creator=${encodeURIComponent(creatorFilter)}`); // было creator_id, теперь creator
params.push(`creator=${encodeURIComponent(creatorFilter)}`);
}
if (assigneeFilter) {
params.push(`assignee=${encodeURIComponent(assigneeFilter)}`); // было assignee_id, теперь assignee
params.push(`assignee=${encodeURIComponent(assigneeFilter)}`);
}
if (deadlineFilter) {
@@ -38,7 +38,7 @@ async function loadTasks() {
}
if (typeFilter) {
params.push(`task_type=${encodeURIComponent(typeFilter)}`); // было type, теперь task_type
params.push(`task_type=${encodeURIComponent(typeFilter)}`);
}
url += params.join('&');
@@ -53,6 +53,12 @@ async function loadTasks() {
tasks = await response.json();
console.log(`Загружено ${tasks.length} задач`);
// Загружаем поля документа для задач типа "document"
await loadDocumentFieldsForTasks();
// Загружаем файлы для развернутых задач
await loadFilesForExpandedTasks();
// Обновляем отображение
const activeSection = document.querySelector('.section.active');
if (activeSection) {
@@ -77,12 +83,64 @@ async function loadTasks() {
}
}
// Новая функция для загрузки полей документов
async function loadDocumentFieldsForTasks() {
const documentTasks = tasks.filter(task => task.task_type === 'document');
if (documentTasks.length === 0) {
return;
}
console.log(`Загрузка полей документов для ${documentTasks.length} задач`);
// Загружаем поля для каждой задачи
for (const task of documentTasks) {
try {
const docResponse = await fetch(`/api/tasks/${task.id}/document-fields`);
if (docResponse.ok) {
const docData = await docResponse.json();
task.document_fields = docData.data || {};
console.log(`✅ Загружены поля для задачи ${task.id}:`, task.document_fields);
} else {
task.document_fields = {};
}
} catch (error) {
console.error(`Ошибка загрузки полей документа для задачи ${task.id}:`, error);
task.document_fields = {};
}
}
}
// Новая функция для загрузки файлов развернутых задач
async function loadFilesForExpandedTasks() {
const expandedTasksArray = tasks.filter(task => expandedTasks.has(task.id));
if (expandedTasksArray.length === 0) {
return;
}
await Promise.all(expandedTasksArray.map(async (task) => {
try {
const filesResponse = await fetch(`/api/tasks/${task.id}/files`);
if (filesResponse.ok) {
task.files = await filesResponse.json();
} else {
task.files = [];
}
} catch (error) {
console.error(`Ошибка загрузки файлов для задачи ${task.id}:`, error);
task.files = [];
}
}));
}
function showTasksWithoutDate() {
showingTasksWithoutDate = true;
const btn = document.getElementById('tasks-no-date-btn');
if (btn) btn.classList.add('active');
loadTasksWithoutDate();
}
function resetAllFilters() {
document.getElementById('status-filter').value = 'active,in_progress,assigned,overdue,rework';
document.getElementById('creator-filter').value = '';
@@ -92,6 +150,7 @@ function resetAllFilters() {
document.getElementById('search-tasks').value = '';
loadTasks();
}
async function loadTasksWithoutDate() {
try {
const response = await fetch('/api/tasks');
@@ -120,14 +179,15 @@ async function loadTasksWithoutDate() {
}
}));
// Загружаем поля документов
await loadDocumentFieldsForTasks();
renderTasks();
} catch (error) {
console.error('Ошибка загрузки задач без срока:', error);
}
}
// удален async function createTask(event)
async function openEditModal(taskId) {
try {
const response = await fetch(`/api/tasks/${taskId}`);
@@ -188,7 +248,6 @@ async function updateTask(event) {
return;
}
// Используем editSelectedUsers
const assignedUserIds = editSelectedUsers;
const formData = new FormData();
@@ -226,12 +285,10 @@ async function updateTask(event) {
function openCopyModal(taskId) {
document.getElementById('copy-task-id').value = taskId;
// Устанавливаем дату по умолчанию (через 7 дней)
const defaultDate = new Date();
defaultDate.setDate(defaultDate.getDate() + 7);
document.getElementById('copy-due-date').value = defaultDate.toISOString().substring(0, 16);
// Сбрасываем выбранных пользователей
copySelectedUsers = [];
renderCopyUsersChecklist(users);
@@ -256,7 +313,6 @@ async function copyTask(event) {
return;
}
// Используем copySelectedUsers
const assignedUserIds = copySelectedUsers;
if (assignedUserIds.length === 0) {
@@ -501,53 +557,41 @@ async function updateStatus(taskId, userId, status) {
function canUserEditTask(task) {
if (!currentUser) return false;
// Администратор может всё
if (currentUser.role === 'admin') return true;
// Пользователи с ролью 'tasks' могут редактировать любые задачи
if (currentUser.role === 'tasks') return true;
// Создатель может редактировать свою задачу
if (parseInt(task.created_by) === currentUser.id) {
// Но если задача уже назначена другим пользователям,
// создатель может только просматривать
if (task.assignments && task.assignments.length > 0) {
// Проверяем, назначена ли задача другим пользователям (не только себе)
const assignedToOthers = task.assignments.some(assignment =>
parseInt(assignment.user_id) !== currentUser.id
);
if (assignedToOthers) {
// Создатель может только просматривать и закрывать задачу
return true;
}
}
return true;
}
// Исполнитель может менять только свой статус
if (task.assignments) {
const isExecutor = task.assignments.some(assignment =>
parseInt(assignment.user_id) === currentUser.id
);
if (isExecutor) {
// Исполнитель может менять только статус
return false;
}
}
return false;
}
// функция для проверки прав на добавление файлов
function canUserAddFilesToTask(task) {
if (!currentUser) return false;
// Администратор может всё
if (currentUser.role === 'admin') return true;
// Создатель задачи может добавлять файлы
if (parseInt(task.created_by) === currentUser.id) return true;
// Исполнитель задачи может добавлять файлы
if (task.assignments) {
const isExecutor = task.assignments.some(assignment =>
parseInt(assignment.user_id) === currentUser.id
@@ -556,4 +600,22 @@ function canUserAddFilesToTask(task) {
}
return false;
}
}
// Добавляем отладочную функцию
function debugDocumentFields() {
console.log('=== ОТЛАДКА ПОЛЕЙ ДОКУМЕНТОВ ===');
const documentTasks = tasks.filter(task => task.task_type === 'document');
console.log(`Найдено ${documentTasks.length} задач типа "document"`);
documentTasks.forEach(task => {
console.log(`Задача ${task.id}:`, {
title: task.title,
document_fields: task.document_fields || 'НЕТ ПОЛЕЙ'
});
});
console.log('================================');
}
// Вызываем отладку после загрузки (можно вызвать вручную из консоли)
window.debugDocumentFields = debugDocumentFields;