chore: save working baseline before v3.0 architecture refactoring
This commit is contained in:
@@ -4,7 +4,7 @@ FILE: modules/web_api/static/js/chat/core.js
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / static / js / chat
|
||||
ROLE: Клиентский интерфейс диалога, Drag-and-Drop вложений, блокировка ввода
|
||||
при активных кнопках, динамический вызов инлайн-редактора и двусторонний Diff.
|
||||
при активных кнопках, вызов инлайн-редактора, Diff и карточки скачивания файлов.
|
||||
===============================================================================
|
||||
*/
|
||||
|
||||
@@ -89,8 +89,8 @@ function handleActionButtonClick(text) {
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
return text
|
||||
if (text === null || text === undefined) return "";
|
||||
return String(text)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
@@ -170,13 +170,11 @@ function buildHighlightedPromptHtml(newRawText, originalBaselineText) {
|
||||
const fullItemStr = `${subMatch[1]}.${subMatch[2]}. ${cleanContent}`;
|
||||
|
||||
if (!origMap.has(key) || origMap.get(key).content !== cleanContent) {
|
||||
// Добавленный или изменённый пункт
|
||||
formattedLines.push(` <span class="text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300">${escapeHtml(fullItemStr)}</span>`);
|
||||
} else {
|
||||
formattedLines.push(` ${escapeHtml(fullItemStr)}`);
|
||||
}
|
||||
} else if (secMatch && !anyLower(secMatch[2].slice(0, 15))) {
|
||||
// Заголовок раздела
|
||||
currentSection = parseInt(secMatch[1]);
|
||||
formattedLines.push(escapeHtml(trimmed));
|
||||
} else {
|
||||
@@ -184,7 +182,6 @@ function buildHighlightedPromptHtml(newRawText, originalBaselineText) {
|
||||
}
|
||||
}
|
||||
|
||||
// Добавляем удаленные пункты (были в оригинале, но отсутствуют в новом тексте)
|
||||
for (let [origKey, origObj] of origMap.entries()) {
|
||||
if (!handledNewKeys.has(origKey)) {
|
||||
const strikeMarkup = ` <span class="line-through text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300 opacity-80">${origKey}. ${escapeHtml(origObj.content)} [УДАЛЕНИЕ]</span>`;
|
||||
@@ -382,14 +379,45 @@ async function sendMessage(e) {
|
||||
interactiveWidgetHtml = renderInteractiveTaskCard(actionData.tasks);
|
||||
}
|
||||
|
||||
let snapshotsWidgetHtml = "";
|
||||
if (actionData && actionData.type === "SNAPSHOTS_CARD" && typeof renderSnapshotsCard === "function") {
|
||||
snapshotsWidgetHtml = renderSnapshotsCard(actionData.data);
|
||||
}
|
||||
|
||||
// ⭐️ БЛОК КАРТОЧКИ СКАЧИВАНИЯ ФАЙЛА
|
||||
let fileDownloadHtml = "";
|
||||
if (actionData && actionData.type === "FILE_DOWNLOAD_CARD") {
|
||||
fileDownloadHtml = `
|
||||
<div class="mt-3 p-3 bg-emerald-50 border border-emerald-200 rounded-xl flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 min-w-0">
|
||||
<i class="fa-solid fa-file-lines text-emerald-600 text-lg shrink-0"></i>
|
||||
<div class="truncate">
|
||||
<div class="text-xs font-bold text-slate-900 truncate">${escapeHtml(actionData.filename)}</div>
|
||||
<div class="text-[11px] text-emerald-700">Готов к скачиванию (задач: ${actionData.tasks_count || '—'})</div>
|
||||
</div>
|
||||
</div>
|
||||
<a href="${actionData.download_url}" download="${escapeHtml(actionData.filename)}"
|
||||
class="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white font-semibold rounded-lg text-xs flex items-center gap-1.5 transition shrink-0 shadow-sm">
|
||||
<i class="fa-solid fa-download"></i>
|
||||
<span>Скачать</span>
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const isWideWidget = actionData && (actionData.type === "TASK_INTERACTIVE_CARD" || actionData.type === "PROMPT_PREVIEW");
|
||||
const maxWidthClass = isWideWidget ? "max-w-4xl w-full" : "max-w-2xl";
|
||||
|
||||
const botMsgHtml = `
|
||||
<div class="chat-message-card bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm max-w-2xl mb-3" data-original-baseline="${escapeHtml(baselineText)}">
|
||||
<div class="chat-message-card bg-white border border-slate-200 rounded-2xl p-4 shadow-sm ${maxWidthClass} mb-3" data-original-baseline="${escapeHtml(baselineText)}">
|
||||
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ${assistantTitle}
|
||||
</p>
|
||||
<div class="prompt-preview-diff-view text-slate-800 text-xs sm:text-sm whitespace-pre-wrap leading-relaxed">${replyText}</div>
|
||||
${previewEditorHtml}
|
||||
${interactiveWidgetHtml}
|
||||
${snapshotsWidgetHtml}
|
||||
${fileDownloadHtml}
|
||||
${actionButtonsHtml}
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -1,208 +1,445 @@
|
||||
/**
|
||||
/*
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/chat/task_widget.js
|
||||
ROLE: Генеративный UI интерактивных карточек задач внутри диалога чата
|
||||
(фильтры, inline-чекбоксы статусов, быстрое добавление и удаление).
|
||||
ROLE: Интерактивные виджеты задач и срезов СКУД (SNAPSHOTS_CARD) с чекбоксами.
|
||||
===============================================================================
|
||||
*/
|
||||
|
||||
let activeWidgetTasksMap = new Map();
|
||||
window.activeTaskFilter = window.activeTaskFilter || 'IN_PROGRESS';
|
||||
window.currentTasksCache = window.currentTasksCache || [];
|
||||
|
||||
function renderTaskItemsHtml(tasks, filterStatus) {
|
||||
const filtered = tasks.filter(t => {
|
||||
if (filterStatus === "ALL") return true;
|
||||
return t.status === filterStatus;
|
||||
});
|
||||
function getAuthHeaders() {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (token) {
|
||||
headers['Authorization'] = 'Bearer ' + token;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const label = filterStatus === 'BACKLOG' ? 'В планах' : filterStatus === 'IN_PROGRESS' ? 'В работе' : filterStatus === 'COMPLETED' ? 'Завершенные' : 'Все';
|
||||
return `<div class="text-slate-400 text-xs py-4 text-center">Нет задач со статусом «${label}»</div>`;
|
||||
window.sendChatAction = function(actionText) {
|
||||
const input = document.getElementById("user-input");
|
||||
if (input && typeof sendMessage === "function") {
|
||||
input.value = actionText;
|
||||
if (typeof setInputLocked === "function") setInputLocked(false);
|
||||
sendMessage();
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// РЕНДЕРИНГ КАРТОЧКИ СРЕЗОВ СКУД (SNAPSHOTS_CARD) С ЧЕКБОКСАМИ
|
||||
// ============================================================================
|
||||
function renderSnapshotsCard(data) {
|
||||
if (!data || !data.snapshots || !Array.isArray(data.snapshots)) return '';
|
||||
const queryDate = data.query_date || 'выбранную дату';
|
||||
const snapshots = data.snapshots;
|
||||
|
||||
if (snapshots.length === 0) {
|
||||
return `
|
||||
<div class="p-6 bg-slate-50 border border-slate-200 rounded-xl text-center text-xs text-slate-500 my-2">
|
||||
📸 За дату <b>${queryDate}</b> сохраненных снапшотов не найдено.
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return filtered.map(t => {
|
||||
const isDone = t.status === "COMPLETED";
|
||||
const isProgress = t.status === "IN_PROGRESS";
|
||||
const checkedAttr = isDone ? "checked" : "";
|
||||
const textClass = isDone ? "line-through text-slate-400" : "text-slate-800 font-medium";
|
||||
const rowsHtml = snapshots.map((s, idx) => {
|
||||
const snapId = s.snapshot_id || `ID-${idx}`;
|
||||
const snapTime = s.snapshot_time ? s.snapshot_time.split(' ')[1] || s.snapshot_time : '—';
|
||||
const count = s.record_count || 0;
|
||||
const isFinal = snapId.startsWith('Y');
|
||||
|
||||
let statusPill = `<span class="text-[10px] bg-slate-100 text-slate-600 px-2 py-0.5 rounded border border-slate-200">В планах</span>`;
|
||||
if (isDone) {
|
||||
statusPill = `<span class="text-[10px] bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded border border-emerald-300 font-semibold">Завершено</span>`;
|
||||
} else if (isProgress) {
|
||||
statusPill = `<span class="text-[10px] bg-amber-50 text-amber-700 px-2 py-0.5 rounded border border-amber-300 font-semibold">В работе</span>`;
|
||||
}
|
||||
|
||||
let prioPill = "";
|
||||
if (t.priority === "HIGH") {
|
||||
prioPill = `<span class="text-[9px] bg-red-50 text-red-700 font-bold px-1.5 py-0.5 rounded border border-red-200 uppercase">HIGH</span>`;
|
||||
if (isFinal) {
|
||||
return `
|
||||
<div class="p-2.5 bg-purple-50/60 rounded-lg border border-purple-200 shadow-sm flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<span class="w-4 flex justify-center text-purple-400" title="Итоговый срез защищен">
|
||||
<i class="fa-solid fa-lock text-[11px]"></i>
|
||||
</span>
|
||||
<span class="font-mono text-xs font-bold px-2 py-0.5 rounded bg-purple-100 text-purple-800 border border-purple-300">
|
||||
#${snapId}
|
||||
</span>
|
||||
<div class="flex items-center gap-3 text-xs text-slate-600">
|
||||
<span class="flex items-center gap-1 font-semibold text-purple-900">
|
||||
<i class="fa-regular fa-clock text-purple-600 text-[11px]"></i> ${snapTime}
|
||||
</span>
|
||||
<span class="flex items-center gap-1 text-slate-500">
|
||||
<i class="fa-solid fa-users text-slate-400 text-[11px]"></i> ${count} записей
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-[10px] font-bold text-purple-700 bg-purple-100 border border-purple-200 px-2 py-0.5 rounded">
|
||||
Итоговый Y-срез
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="flex items-center justify-between p-2.5 bg-slate-50 hover:bg-slate-100/80 rounded-xl border border-slate-200 transition gap-2" id="widget-task-${t.task_id}">
|
||||
<div class="flex items-center gap-2.5 flex-1 min-w-0">
|
||||
<input type="checkbox" ${checkedAttr} onchange="toggleTaskStatusInline('${t.task_id}', this.checked)"
|
||||
class="w-4 h-4 text-indigo-600 rounded border-slate-300 focus:ring-indigo-500 cursor-pointer">
|
||||
<div class="flex flex-col min-w-0 flex-1">
|
||||
<div class="flex items-center gap-1.5 mb-0.5">
|
||||
<span class="font-mono text-[11px] font-bold text-slate-700">${t.task_id}</span>
|
||||
${prioPill}
|
||||
${statusPill}
|
||||
</div>
|
||||
<span class="text-xs ${textClass} truncate leading-tight">${escapeHtml(t.title)}</span>
|
||||
<div class="p-2.5 bg-white rounded-lg border border-slate-200 shadow-sm hover:border-slate-300 transition flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<input type="checkbox" value="${snapId}" onchange="window.updateSelectedSnapshots(this)"
|
||||
class="snapshot-item-checkbox rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 w-4 h-4 cursor-pointer">
|
||||
<span class="font-mono text-xs font-bold px-2 py-0.5 rounded bg-slate-100 text-slate-700 border border-slate-200">
|
||||
#${snapId}
|
||||
</span>
|
||||
<div class="flex items-center gap-3 text-xs text-slate-600">
|
||||
<span class="flex items-center gap-1 font-semibold text-slate-800">
|
||||
<i class="fa-regular fa-clock text-indigo-500 text-[11px]"></i> ${snapTime}
|
||||
</span>
|
||||
<span class="flex items-center gap-1 text-slate-500">
|
||||
<i class="fa-solid fa-users text-slate-400 text-[11px]"></i> ${count} записей
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onclick="deleteTaskInline('${t.task_id}')" class="text-slate-400 hover:text-red-500 p-1.5 transition rounded-lg hover:bg-red-50" title="Удалить задачу">
|
||||
<button type="button" onclick="window.sendChatAction('удали снапшот ${snapId}')"
|
||||
class="p-1 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded border border-transparent hover:border-rose-200 transition"
|
||||
title="Удалить срез">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function renderInteractiveTaskCard(tasks) {
|
||||
if (!tasks || !Array.isArray(tasks)) return "";
|
||||
const widgetId = "task_widget_" + Date.now();
|
||||
activeWidgetTasksMap.set(widgetId, { tasks: tasks, filter: "ALL" });
|
||||
|
||||
const itemsHtml = renderTaskItemsHtml(tasks, "ALL");
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="task-widget-card mt-3 bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm space-y-3" id="${widgetId}">
|
||||
<div class="flex items-center gap-1 pb-2 border-b border-slate-100 overflow-x-auto no-scrollbar text-xs font-semibold">
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'ALL', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200">Все</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'IN_PROGRESS', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">В работе</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'BACKLOG', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">В планах</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'COMPLETED', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">Завершенные</button>
|
||||
<div class="snapshots-widget-root w-full max-w-4xl mx-auto my-2 bg-slate-50 border border-slate-300 rounded-xl shadow-md overflow-hidden flex flex-col">
|
||||
<div class="px-4 py-2.5 bg-white border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="bg-indigo-600 text-white p-1.5 rounded-lg flex items-center justify-center">
|
||||
<i class="fa-solid fa-camera text-xs"></i>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs font-bold text-slate-800">Реестр срезов СКУД</span>
|
||||
<span class="text-xs text-slate-500 ml-1">за ${queryDate}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<label class="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer select-none">
|
||||
<input type="checkbox" onchange="window.toggleSelectAllSnapshots(this)" class="select-all-snapshots-cb rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 w-3.5 h-3.5">
|
||||
<span>Выбрать все</span>
|
||||
</label>
|
||||
<span class="text-[11px] font-semibold bg-indigo-50 text-indigo-700 border border-indigo-200 px-2 py-0.5 rounded-full">
|
||||
Срезов: ${snapshots.length}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="widget-items-container space-y-2 max-h-72 overflow-y-auto pr-1">
|
||||
${itemsHtml}
|
||||
<div class="p-3 flex flex-col gap-2">
|
||||
${rowsHtml}
|
||||
</div>
|
||||
|
||||
<div class="pt-2 border-t border-slate-100 flex items-center gap-2">
|
||||
<input type="text" placeholder="Новая задача..." class="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 focus:outline-none focus:border-indigo-600 focus:bg-white transition" onkeydown="if(event.key==='Enter') addTaskInline('${widgetId}', this)">
|
||||
<button type="button" onclick="addTaskInline('${widgetId}', this.previousElementSibling)" class="bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white px-3 py-1.5 rounded-xl text-xs font-semibold shadow-sm transition flex items-center gap-1">
|
||||
<i class="fa-solid fa-plus text-[10px]"></i> Добавить
|
||||
<!-- ПОДВАЛ С КНОПКОЙ УДАЛЕНИЯ ВЫБРАННЫХ -->
|
||||
<div class="snapshot-bulk-actions-footer hidden px-4 py-2 bg-rose-50/70 border-t border-rose-200 flex items-center justify-between">
|
||||
<span class="text-xs text-rose-800 font-medium bulk-selected-counter">Выбрано: 0</span>
|
||||
<button type="button" onclick="window.submitBulkDeleteSnapshots(this)"
|
||||
class="px-3 py-1.5 bg-rose-600 hover:bg-rose-700 active:bg-rose-800 text-white font-bold rounded-lg text-xs flex items-center gap-1.5 transition shadow-sm">
|
||||
<i class="fa-solid fa-trash-can"></i>
|
||||
<span>Удалить выбранные</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function filterTaskWidget(widgetId, status, btnEl) {
|
||||
const state = activeWidgetTasksMap.get(widgetId);
|
||||
if (!state) return;
|
||||
state.filter = status;
|
||||
// ⭐️ Обработчики чекбоксов
|
||||
window.toggleSelectAllSnapshots = function(masterCb) {
|
||||
const root = masterCb.closest('.snapshots-widget-root');
|
||||
if (!root) return;
|
||||
const checkboxes = root.querySelectorAll('.snapshot-item-checkbox');
|
||||
checkboxes.forEach(cb => cb.checked = masterCb.checked);
|
||||
window.syncBulkDeleteFooter(root);
|
||||
};
|
||||
|
||||
const widgetEl = document.getElementById(widgetId);
|
||||
if (!widgetEl) return;
|
||||
window.updateSelectedSnapshots = function(itemCb) {
|
||||
const root = itemCb.closest('.snapshots-widget-root');
|
||||
if (!root) return;
|
||||
window.syncBulkDeleteFooter(root);
|
||||
};
|
||||
|
||||
widgetEl.querySelectorAll(".widget-tab-btn").forEach(b => {
|
||||
b.className = "widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700";
|
||||
window.syncBulkDeleteFooter = function(root) {
|
||||
const checkboxes = root.querySelectorAll('.snapshot-item-checkbox:checked');
|
||||
const footer = root.querySelector('.snapshot-bulk-actions-footer');
|
||||
const counter = root.querySelector('.bulk-selected-counter');
|
||||
const masterCb = root.querySelector('.select-all-snapshots-cb');
|
||||
const allCheckboxes = root.querySelectorAll('.snapshot-item-checkbox');
|
||||
|
||||
if (masterCb) {
|
||||
masterCb.checked = allCheckboxes.length > 0 && checkboxes.length === allCheckboxes.length;
|
||||
}
|
||||
|
||||
if (checkboxes.length > 0) {
|
||||
if (footer) footer.classList.remove('hidden');
|
||||
if (counter) counter.innerText = `Выбрано дневных срезов: ${checkboxes.length}`;
|
||||
} else {
|
||||
if (footer) footer.classList.add('hidden');
|
||||
}
|
||||
};
|
||||
|
||||
// Одиночная корзина в строке снапшота:
|
||||
// onclick="window.sendChatAction('удали снапшот ${snapId}')"
|
||||
|
||||
// Кнопка пакетного удаления в подвале карточки:
|
||||
window.submitBulkDeleteSnapshots = function(btnEl) {
|
||||
const root = btnEl.closest('.snapshots-widget-root');
|
||||
if (!root) return;
|
||||
const selected = Array.from(root.querySelectorAll('.snapshot-item-checkbox:checked')).map(cb => cb.value);
|
||||
if (selected.length === 0) return;
|
||||
window.sendChatAction(`удали снапшоты ${selected.join(', ')}`);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// РЕНДЕРИНГ КАРТОЧКИ ЗАДАЧ (TASK_INTERACTIVE_CARD)
|
||||
// ============================================================================
|
||||
function renderInteractiveTaskCard(tasks) {
|
||||
if (!tasks || !Array.isArray(tasks)) return '';
|
||||
window.currentTasksCache = tasks;
|
||||
|
||||
const counts = {
|
||||
ALL: tasks.length,
|
||||
IN_PROGRESS: tasks.filter(t => t.status === 'IN_PROGRESS' || t.status === 'PROGRESS').length,
|
||||
PLANNED: tasks.filter(t => t.status === 'BACKLOG' || t.status === 'PLANNED').length,
|
||||
COMPLETED: tasks.filter(t => t.status === 'COMPLETED' || t.status === 'DONE').length
|
||||
};
|
||||
|
||||
const currentFilter = window.activeTaskFilter || 'IN_PROGRESS';
|
||||
|
||||
const filteredTasks = tasks.filter(t => {
|
||||
const s = (t.status || 'BACKLOG').toUpperCase();
|
||||
if (currentFilter === 'ALL') return true;
|
||||
if (currentFilter === 'IN_PROGRESS') return s === 'IN_PROGRESS' || s === 'PROGRESS';
|
||||
if (currentFilter === 'PLANNED') return s === 'BACKLOG' || s === 'PLANNED';
|
||||
if (currentFilter === 'COMPLETED') return s === 'COMPLETED' || s === 'DONE';
|
||||
return true;
|
||||
});
|
||||
btnEl.className = "widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200";
|
||||
|
||||
const container = widgetEl.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, status);
|
||||
}
|
||||
const getPrioBadge = (prio) => {
|
||||
const p = (prio || 'MEDIUM').toUpperCase();
|
||||
if (p === 'HIGH' || p === 'CRITICAL') return '<span class="text-[10px] px-2 py-0.5 rounded font-bold bg-rose-100 text-rose-700 border border-rose-200">🔥 HIGH</span>';
|
||||
if (p === 'LOW') return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-slate-100 text-slate-600 border border-slate-200">☕ LOW</span>';
|
||||
return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-amber-100 text-amber-700 border border-amber-200">⚡ MEDIUM</span>';
|
||||
};
|
||||
|
||||
const getStatusBadge = (status) => {
|
||||
const s = (status || 'BACKLOG').toUpperCase();
|
||||
if (s === 'IN_PROGRESS' || s === 'PROGRESS') return '<span class="text-[10px] px-2 py-0.5 rounded font-bold bg-blue-50 text-blue-700 border border-blue-200">⚙️ В работе</span>';
|
||||
if (s === 'COMPLETED' || s === 'DONE') return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">✓ Готово</span>';
|
||||
return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-slate-50 text-slate-600 border border-slate-200">📋 В планах</span>';
|
||||
};
|
||||
|
||||
const taskRows = filteredTasks.map(t => {
|
||||
const id = t.id;
|
||||
const title = t.title || 'Без названия';
|
||||
const isDone = t.status === 'COMPLETED' || t.status === 'DONE';
|
||||
const isInProgress = t.status === 'IN_PROGRESS' || t.status === 'PROGRESS';
|
||||
|
||||
const actionBtn = isInProgress
|
||||
? `<button type="button" onclick="window.sendChatAction('заверши задачу ${id}')" class="px-2.5 py-1 text-xs font-semibold rounded bg-emerald-50 text-emerald-700 border border-emerald-300 hover:bg-emerald-100 transition-colors shadow-sm" title="Завершить задачу">✓ Готово</button>`
|
||||
: (!isDone
|
||||
? `<button type="button" onclick="window.sendChatAction('возьми в работу задачу ${id}')" class="px-2.5 py-1 text-xs font-semibold rounded bg-blue-50 text-blue-700 border border-blue-300 hover:bg-blue-100 transition-colors shadow-sm" title="Взять в работу">⚙️ В работу</button>`
|
||||
: '');
|
||||
|
||||
return `
|
||||
<div id="task-card-${id}" class="p-3 bg-white rounded-lg border border-slate-200 shadow-sm hover:border-slate-300 transition-all flex flex-col gap-2">
|
||||
<div class="task-view-mode flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 flex-wrap flex-1 min-w-0">
|
||||
<span class="text-xs font-bold px-1.5 py-0.5 rounded bg-slate-100 text-slate-700 border border-slate-200">#${id}</span>
|
||||
<span class="text-sm font-medium text-slate-900 truncate" title="${title}">${title}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5 shrink-0">
|
||||
${actionBtn}
|
||||
<button type="button" onclick="window.openTaskInlineEditor(${id})" class="p-1 text-xs text-slate-500 hover:text-indigo-600 hover:bg-slate-50 rounded border border-slate-200 transition-colors" title="Редактировать">✏️</button>
|
||||
<button type="button" onclick="window.sendChatAction('удали задачу ${id}')" class="p-1 text-xs text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded border border-slate-200 transition-colors" title="Удалить">🗑️</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="task-view-mode flex items-center gap-2 text-xs text-slate-500 flex-wrap">
|
||||
${getPrioBadge(t.priority)}
|
||||
${getStatusBadge(t.status)}
|
||||
<span class="px-1.5 py-0.5 rounded bg-slate-50 border border-slate-200 text-slate-600 font-mono text-[11px]">${t.module || 'general'}</span>
|
||||
${t.due_date ? `<span class="text-slate-500">📅 срок: <b>${t.due_date}</b></span>` : ''}
|
||||
${t.created_at ? `<span class="text-slate-400">создана: ${t.created_at.split(' ')[0]}</span>` : ''}
|
||||
</div>
|
||||
|
||||
<!-- ФОРМА ИНЛАЙН РЕДАКТИРОВАНИЯ -->
|
||||
<div id="task-editor-${id}" class="hidden flex flex-col gap-2 pt-2 border-t border-slate-100">
|
||||
<input type="text" id="task-edit-title-${id}" value="${title.replace(/"/g, '"')}" class="w-full text-xs px-2.5 py-1.5 border border-slate-300 rounded focus:border-indigo-500 focus:outline-none bg-slate-50" placeholder="Описание задачи..." />
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<input type="date" id="task-edit-date-${id}" value="${t.due_date || ''}" class="text-xs px-2 py-1 border border-slate-300 rounded focus:border-indigo-500 focus:outline-none bg-slate-50" />
|
||||
<select id="task-edit-prio-${id}" class="text-xs px-2 py-1 border border-slate-300 rounded focus:border-indigo-500 focus:outline-none bg-slate-50">
|
||||
<option value="LOW" ${t.priority === 'LOW' ? 'selected' : ''}>☕ LOW</option>
|
||||
<option value="MEDIUM" ${t.priority === 'MEDIUM' || !t.priority ? 'selected' : ''}>⚡ MEDIUM</option>
|
||||
<option value="HIGH" ${t.priority === 'HIGH' ? 'selected' : ''}>🔥 HIGH</option>
|
||||
<option value="CRITICAL" ${t.priority === 'CRITICAL' ? 'selected' : ''}>🚨 CRITICAL</option>
|
||||
</select>
|
||||
<button type="button" onclick="window.saveTaskInlineEdit(${id})" class="px-2.5 py-1 text-xs font-semibold rounded bg-indigo-600 text-white hover:bg-indigo-700 transition-colors shadow-sm">Сохранить</button>
|
||||
<button type="button" onclick="window.closeTaskInlineEditor(${id})" class="px-2 py-1 text-xs font-medium rounded text-slate-500 hover:bg-slate-100 transition-colors">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const emptyState = `
|
||||
<div class="p-8 text-center text-slate-400">
|
||||
<div class="text-3xl mb-2">📭</div>
|
||||
<div class="text-sm font-medium">Нет задач в категории «${currentFilter}»</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return `
|
||||
<div class="task-widget-root w-full max-w-4xl mx-auto my-2 bg-slate-50 border border-slate-300 rounded-xl shadow-md overflow-hidden flex flex-col">
|
||||
<div class="px-4 py-3 bg-white border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<button type="button" onclick="window.switchTaskFilter('IN_PROGRESS', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'IN_PROGRESS' ? 'bg-blue-600 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
⚙️ В работе (${counts.IN_PROGRESS})
|
||||
</button>
|
||||
<button type="button" onclick="window.switchTaskFilter('PLANNED', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'PLANNED' ? 'bg-indigo-600 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
📋 В планах (${counts.PLANNED})
|
||||
</button>
|
||||
<button type="button" onclick="window.switchTaskFilter('COMPLETED', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'COMPLETED' ? 'bg-emerald-600 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
✓ Готово (${counts.COMPLETED})
|
||||
</button>
|
||||
<button type="button" onclick="window.switchTaskFilter('ALL', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'ALL' ? 'bg-slate-800 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
Все (${counts.ALL})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="window.toggleCreateTaskForm(this)" class="px-3 py-1.5 text-xs font-bold rounded-md bg-indigo-600 hover:bg-indigo-700 text-white transition-all shadow-sm flex items-center gap-1">
|
||||
➕ Добавить задачу
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="new-task-creation-form hidden p-3 bg-indigo-50/70 border-b border-indigo-100 flex flex-col gap-2">
|
||||
<div class="text-xs font-bold text-indigo-900">Новая задача:</div>
|
||||
<input type="text" class="new-task-title w-full text-xs px-2.5 py-1.5 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white" placeholder="Что необходимо сделать?..." />
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<input type="date" class="new-task-date text-xs px-2 py-1 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white" />
|
||||
<select class="new-task-prio text-xs px-2 py-1 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white">
|
||||
<option value="LOW">☕ LOW (Низкий)</option>
|
||||
<option value="MEDIUM" selected>⚡ MEDIUM (Средний)</option>
|
||||
<option value="HIGH">🔥 HIGH (Высокий)</option>
|
||||
<option value="CRITICAL">🚨 CRITICAL (Критический)</option>
|
||||
</select>
|
||||
<select class="new-task-status text-xs px-2 py-1 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white">
|
||||
<option value="BACKLOG" selected>📋 В планы (Бэклог)</option>
|
||||
<option value="IN_PROGRESS">⚙️ Сразу в работу</option>
|
||||
</select>
|
||||
<button type="button" onclick="window.submitCreateTask(this)" class="px-3 py-1 text-xs font-bold rounded bg-indigo-600 text-white hover:bg-indigo-700 transition-colors shadow-sm">Создать</button>
|
||||
<button type="button" onclick="window.toggleCreateTaskForm(this)" class="px-2 py-1 text-xs font-medium rounded text-slate-500 hover:bg-slate-200 transition-colors">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-3 overflow-y-auto max-h-[70vh] flex flex-col gap-2 task-rows-container">
|
||||
${filteredTasks.length > 0 ? taskRows : emptyState}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function toggleTaskStatusInline(taskId, isChecked) {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const newStatus = isChecked ? "COMPLETED" : "BACKLOG";
|
||||
window.switchTaskFilter = function(filterName, btnEl) {
|
||||
window.activeTaskFilter = filterName;
|
||||
const root = btnEl ? btnEl.closest('.task-widget-root') : document.querySelector('.task-widget-root');
|
||||
if (root && window.currentTasksCache && window.currentTasksCache.length > 0) {
|
||||
root.outerHTML = renderInteractiveTaskCard(window.currentTasksCache);
|
||||
}
|
||||
};
|
||||
|
||||
window.toggleCreateTaskForm = function(btnEl) {
|
||||
const root = btnEl ? btnEl.closest('.task-widget-root') : document.querySelector('.task-widget-root');
|
||||
if (!root) return;
|
||||
const form = root.querySelector('.new-task-creation-form');
|
||||
if (form) {
|
||||
form.classList.toggle('hidden');
|
||||
if (!form.classList.contains('hidden')) {
|
||||
const input = form.querySelector('.new-task-title');
|
||||
if (input) input.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.submitCreateTask = async function(btnEl) {
|
||||
const root = btnEl ? btnEl.closest('.task-widget-root') : document.querySelector('.task-widget-root');
|
||||
if (!root) return;
|
||||
|
||||
const titleInput = root.querySelector('.new-task-title');
|
||||
const dateInput = root.querySelector('.new-task-date');
|
||||
const prioInput = root.querySelector('.new-task-prio');
|
||||
const statusInput = root.querySelector('.new-task-status');
|
||||
|
||||
if (!titleInput || !titleInput.value.trim()) {
|
||||
alert('Введите описание задачи');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${taskId}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
const res = await fetch('/api/v1/tasks', {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
title: titleInput.value.trim(),
|
||||
due_date: dateInput ? (dateInput.value || null) : null,
|
||||
priority: prioInput ? prioInput.value : 'MEDIUM',
|
||||
status: statusInput ? statusInput.value : 'BACKLOG'
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
for (let [wId, state] of activeWidgetTasksMap.entries()) {
|
||||
const targetTask = state.tasks.find(t => t.task_id === taskId);
|
||||
if (targetTask) {
|
||||
targetTask.status = newStatus;
|
||||
const widgetEl = document.getElementById(wId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
window.activeTaskFilter = (statusInput && statusInput.value === 'IN_PROGRESS') ? 'IN_PROGRESS' : 'PLANNED';
|
||||
window.sendChatAction('покажи задачи');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert('Ошибка создания задачи: ' + (err.detail || 'Неизвестная ошибка'));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Patch Error]", err);
|
||||
} catch (e) {
|
||||
console.error('Ошибка создания задачи:', e);
|
||||
alert('Сетевая ошибка при создании задачи');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function deleteTaskInline(taskId) {
|
||||
if (!confirm(`Удалить задачу ${taskId}?`)) return;
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
window.openTaskInlineEditor = function(id) {
|
||||
const card = document.getElementById(`task-card-${id}`);
|
||||
if (!card) return;
|
||||
card.querySelectorAll('.task-view-mode').forEach(el => el.classList.add('hidden'));
|
||||
const editor = document.getElementById(`task-editor-${id}`);
|
||||
if (editor) editor.classList.remove('hidden');
|
||||
};
|
||||
|
||||
window.closeTaskInlineEditor = function(id) {
|
||||
const card = document.getElementById(`task-card-${id}`);
|
||||
if (!card) return;
|
||||
card.querySelectorAll('.task-view-mode').forEach(el => el.classList.remove('hidden'));
|
||||
const editor = document.getElementById(`task-editor-${id}`);
|
||||
if (editor) editor.classList.add('hidden');
|
||||
};
|
||||
|
||||
window.saveTaskInlineEdit = async function(id) {
|
||||
const titleInput = document.getElementById(`task-edit-title-${id}`);
|
||||
const dateInput = document.getElementById(`task-edit-date-${id}`);
|
||||
const prioInput = document.getElementById(`task-edit-prio-${id}`);
|
||||
|
||||
if (!titleInput || !titleInput.value.trim()) {
|
||||
alert('Описание задачи не может быть пустым');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${taskId}`, {
|
||||
method: "DELETE",
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
const res = await fetch(`/api/v1/tasks/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
title: titleInput.value.trim(),
|
||||
due_date: dateInput ? (dateInput.value || null) : null,
|
||||
priority: prioInput ? prioInput.value : 'MEDIUM'
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
for (let [wId, state] of activeWidgetTasksMap.entries()) {
|
||||
state.tasks = state.tasks.filter(t => t.task_id !== taskId);
|
||||
const widgetEl = document.getElementById(wId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter);
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
window.sendChatAction('покажи задачи');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert('Ошибка обновления задачи: ' + (err.detail || 'Неизвестная ошибка'));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Delete Error]", err);
|
||||
} catch (e) {
|
||||
console.error('Ошибка сохранения задачи:', e);
|
||||
alert('Сетевая ошибка при обновлении задачи');
|
||||
}
|
||||
}
|
||||
|
||||
async function addTaskInline(widgetId, inputEl) {
|
||||
if (!inputEl) return;
|
||||
const title = inputEl.value.trim();
|
||||
if (!title) return;
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ title: title, priority: "MEDIUM", module: "general" })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
inputEl.value = "";
|
||||
const tasksRes = await fetch("/api/v1/tasks", {
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
const updatedTasks = await tasksRes.json();
|
||||
|
||||
const state = activeWidgetTasksMap.get(widgetId);
|
||||
if (state) {
|
||||
state.tasks = updatedTasks;
|
||||
const widgetEl = document.getElementById(widgetId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(updatedTasks, state.filter);
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Add Error]", err);
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user