feat: schedule VK conversation messages

This commit is contained in:
nyan404 committed 2026-09-06 18:13:16 +03:00
1 parent f7c5eb994e
commit 4590070bbc
9 files changed
+314 -2

No files matched your search

+10 -1
View File
@@ -91,6 +91,7 @@
<nav class="tabs" aria-label="Раздел админской панели">
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-selected="true">Отчёты</button>
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-selected="false">Заявки</button>
<button class="admin-tab tab" type="button" data-admin-view="vk" aria-selected="false">Беседы VK</button>
</nav>
<section id="reportsView" class="admin-section">
<header class="topbar">
@@ -115,6 +116,11 @@
<button id="load" type="button">Обновить</button>
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
</section>
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
<header class="topbar"><div><h2 id="vkTitle">Беседы VK</h2><p class="intro">Реестр бесед и расписания сообщений. Время указано в часовом поясе расписания.</p></div><div class="record-count" id="vkCount">Не загружено</div></header>
<section class="controls"><button id="loadVk" type="button">Обновить</button><label class="control-group">Текст шаблона<input id="vkTemplateText" maxlength="4096" placeholder="Сообщение для рассылки"></label><button id="saveVkTemplate" type="button">Создать шаблон</button></section>
<p class="error" id="vkError" role="alert"></p><div class="table-wrap"><table><thead><tr><th>Беседа</th><th>Статус</th><th>Рассылка</th><th>Добавлена</th><th>Последняя отправка</th><th>Ошибка</th></tr></thead><tbody id="vkRows"><tr><td class="empty" colspan="6">Загрузка…</td></tr></tbody></table></div>
</section>
<p class="error" id="error" role="alert"></p>
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div>
</section>
@@ -150,6 +156,8 @@
const galleryCounter = document.querySelector('#galleryCounter');
let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all';
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports', updatesSocket = null, updatesRetry = null;
async function loadVk() { const errorNode=document.querySelector('#vkError'); errorNode.textContent=''; try { const response=await fetch('/api/admin/vk/conversations'); const data=await response.json(); if(!response.ok) throw new Error(data.error||'Не удалось загрузить беседы'); const rowsNode=document.querySelector('#vkRows'); rowsNode.replaceChildren(); document.querySelector('#vkCount').textContent=`${(data.items||[]).length} бесед`; (data.items||[]).forEach(item=>{const row=document.createElement('tr'); const name=document.createElement('td'); name.textContent=`${item.title||'Без названия'} · ${item.peer_id} / chat ${item.chat_id}`; const status=document.createElement('td'); status.textContent=item.status||'—'; const toggle=document.createElement('button'); toggle.type='button'; toggle.textContent=item.mailing_enabled?'Выключить':'Включить'; toggle.onclick=async()=>{toggle.disabled=true; await fetch(`/api/admin/vk/conversations/${item.peer_id}`,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({mailing_enabled:!item.mailing_enabled})}); loadVk();}; const mailing=document.createElement('td'); mailing.append(toggle); const added=document.createElement('td'); added.textContent=displayDate(item.added_at); const success=document.createElement('td'); success.textContent=displayDate(item.last_success_at); const lastError=document.createElement('td'); lastError.textContent=item.last_error||item.removal_reason||'—'; row.append(name,status,mailing,added,success,lastError); rowsNode.append(row); }); } catch(err) { errorNode.textContent=err.message; } }
async function createVkTemplate() { const textValue=document.querySelector('#vkTemplateText').value.trim(); if(!textValue)return; const response=await fetch('/api/admin/vk/templates',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:'Шаблон VK',text:textValue,active:true})}); if(!response.ok){const data=await response.json();document.querySelector('#vkError').textContent=data.error||'Не удалось создать шаблон';return;} document.querySelector('#vkTemplateText').value=''; }
// Extracts the primary person identity from a stored report payload.
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
@@ -208,10 +216,11 @@
// Closes the photo gallery dialog.
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
// Switches between report and application admin views.
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); }
function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelector('#vkView').classList.toggle('hidden', view !== 'vk'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); if(view==='vk')loadVk(); }
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', load); kittenFilter.addEventListener('change', load); [reportPeriod, reportDateFrom, reportDateTo].forEach(control => control.addEventListener('change', load)); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); load(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
document.querySelector('#loadApplications').addEventListener('click', loadApplications); [applicationPeriod, applicationDateFrom, applicationDateTo].forEach(control => control.addEventListener('change', loadApplications)); document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); loadApplications(); }));
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
restoreAdminSession();
</script>
</body>