feat: add branches feature, security audit, and multi-branch support

This commit is contained in:
dev
2026-09-09 09:41:07 +03:00
parent 7a003e5df6
commit d6e589d2f5
19 changed files with 1377 additions and 82 deletions
+4
View File
@@ -196,6 +196,10 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
.photo-item .p-actions button{background:none;border:none;cursor:pointer;font-size:1rem;color:var(--muted);padding:4px}
.photo-item .p-actions .p-edit:hover{color:var(--accent)}
.photo-item .p-actions .p-del:hover{color:#ef4444}
.photo-item .p-actions .p-cover:hover{color:#8b5cf6}
.photo-item .p-actions .p-cover.active{color:#8b5cf6}
.photo-item .p-actions .p-cover:disabled{cursor:default;opacity:.75}
.photo-item .p-actions .p-cover:disabled:hover{color:var(--muted)}
.edit-modal input[type=file]{padding:8px;cursor:pointer}
.edit-modal input[type=file]::file-selector-button{background:var(--bg);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:6px 12px;font-size:.8rem;font-weight:600;cursor:pointer;margin-right:10px;transition:border-color .15s}
.edit-modal input[type=file]::file-selector-button:hover{border-color:var(--accent)}
+1
View File
@@ -28,6 +28,7 @@ const NAV = [
{ page: 'links', label: 'Ссылки' },
{ page: 'students', label: 'Ученики' },
{ page: 'groups', label: 'Группы' },
{ page: 'branches', label: 'Филиалы' },
{ page: 'audit', label: 'Аудит' },
{ page: 'settings', label: 'Настройки' }
];
+3
View File
@@ -69,6 +69,9 @@ function fmtTime(t) {
function dt(t) {
if (!t) return '';
if (typeof t === 'object') {
return esc(JSON.stringify(t).slice(0, 120));
}
try {
const o = JSON.parse(t);
return esc(JSON.stringify(o).slice(0, 120));
+253
View File
@@ -0,0 +1,253 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Филиалы — Админ-панель</title>
<link rel="stylesheet" href="admin.css">
</head>
<body data-page="branches">
<div class="layout">
<div class="sidebar" id="sidebar"></div>
<div class="main">
<div class="page-head">
<h2>Филиалы</h2>
<p class="page-sub">Управление филиалами и привязка групп</p>
</div>
<div class="actions-row" style="margin-bottom:16px">
<button class="btn-primary" onclick="openBranchModal()" id="addBranchBtn">
<span style="font-size:1.2rem">+</span> Добавить филиал
</button>
</div>
<div class="branches-grid" id="branchesGrid">
<div class="empty">Загрузка…</div>
</div>
</div>
</div>
<!-- Branch Modal -->
<div class="modal-overlay" id="branchModal" onclick="if(event.target===this)closeBranchModal()">
<div class="edit-modal" style="max-width:480px">
<h3 id="branchModalTitle">Создать филиал</h3>
<form id="branchForm" class="settings-stack" style="gap:12px">
<input type="hidden" name="id" id="branchId">
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Название <span style="color:#ef4444">*</span></label>
<input type="text" name="name" class="settings-input" required placeholder="Например: Центральный офис" autocomplete="off">
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Адрес</label>
<input type="text" name="address" class="settings-input" placeholder="Улица, дом, офис">
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Телефон</label>
<input type="text" name="phone" class="settings-input" placeholder="+7 (XXX) XXX-XX-XX">
</div>
</div>
<div class="card-foot" style="justify-content:flex-end;gap:8px">
<button type="button" class="btn-primary ghost" onclick="closeBranchModal()">Отмена</button>
<button type="submit" class="btn-primary" id="branchSubmitBtn">Создать</button>
</div>
</form>
</div>
</div>
<div class="modal-overlay" id="imgModal" onclick="this.classList.remove('open')">
<img id="imgModalSrc" alt="">
</div>
<div class="toast" id="toast"></div>
<script src="admin.js"></script>
<script>
let branches = [];
async function loadBranches() {
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
if (!res.ok) return;
branches = await res.json();
renderBranches();
}
function renderBranches() {
const el = document.getElementById('branchesGrid');
if (!branches.length) {
el.innerHTML = '<div class="empty" style="grid-column:1/-1">Филиалов пока нет. Нажмите «Добавить филиал».</div>';
return;
}
el.innerHTML = branches.map(b => `
<div class="branch-card" data-id="${b.id}">
<div class="branch-header">
<span class="branch-name">${esc(b.name)}</span>
<span class="branch-badge">${b.groups_count} ${plural(b.groups_count, 'группа', 'группы', 'групп')}</span>
</div>
${b.address ? `<div class="branch-meta">📍 ${esc(b.address)}</div>` : ''}
${b.phone ? `<div class="branch-meta">📞 ${esc(b.phone)}</div>` : ''}
<div class="branch-actions">
<button class="branch-edit" onclick="openBranchModal(${b.id})" title="Редактировать">✎</button>
${b.groups_count === 0 ? `<button class="branch-delete" onclick="deleteBranch(${b.id})" title="Удалить">&times;</button>` : ''}
</div>
</div>
`).join('');
}
function plural(n, one, few, many) {
n = Math.abs(n) % 100; const n1 = n % 10;
if (n > 10 && n < 20) return many;
if (n1 > 1 && n1 < 5) return few;
if (n1 === 1) return one;
return many;
}
function openBranchModal(id = null) {
const modal = document.getElementById('branchModal');
const form = document.getElementById('branchForm');
const title = document.getElementById('branchModalTitle');
const submitBtn = document.getElementById('branchSubmitBtn');
form.reset();
document.getElementById('branchId').value = '';
if (id) {
const b = branches.find(x => x.id === id);
if (!b) return;
title.textContent = 'Редактировать филиал';
submitBtn.textContent = 'Сохранить';
form.name.value = b.name;
form.address.value = b.address || '';
form.phone.value = b.phone || '';
document.getElementById('branchId').value = b.id;
} else {
title.textContent = 'Создать филиал';
submitBtn.textContent = 'Создать';
}
modal.classList.add('open');
setTimeout(() => form.name.focus(), 100);
}
function closeBranchModal() {
document.getElementById('branchModal').classList.remove('open');
}
document.getElementById('branchForm').addEventListener('submit', async (e) => {
e.preventDefault();
const fd = new FormData(e.target);
const id = fd.get('id');
const name = fd.get('name').trim();
const address = fd.get('address').trim();
const phone = fd.get('phone').trim();
if (!name) { alert('Название обязательно'); return; }
const url = id ? `${API}/api/branches/${id}` : `${API}/api/branches`;
const method = id ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
headers: hdrJson(),
body: JSON.stringify({ name, address: address || null, phone: phone || null })
});
if (res.ok) {
showToast(id ? 'Филиал обновлён' : 'Филиал создан');
closeBranchModal();
loadBranches();
} else { const err = await res.json(); alert(err.error || 'Ошибка'); }
});
async function deleteBranch(id) {
if (!confirm('Удалить этот филиал?')) return;
const res = await fetch(`${API}/api/branches/${id}`, { method: 'DELETE', headers: hdr() });
if (res.ok) {
showToast('Филиал удалён');
loadBranches();
} else { const err = await res.json(); alert(err.error || 'Ошибка'); }
}
(async () => {
if (await checkAuth()) {
buildSidebar(document.body.dataset.page);
loadBranches();
}
})();
</script>
<style>
.branches-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 12px;
}
.branch-card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px;
display: flex;
flex-direction: column;
gap: 8px;
transition: box-shadow .15s, border-color .15s;
}
.branch-card:hover {
box-shadow: 0 4px 16px rgba(0,0,0,.08);
border-color: var(--accent);
}
.branch-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.branch-name {
font-weight: 600;
font-size: .95rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.branch-badge {
font-size: .7rem;
font-weight: 600;
color: var(--accent);
background: rgba(37,99,235,.1);
padding: 2px 8px;
border-radius: 999px;
white-space: nowrap;
flex-shrink: 0;
}
.branch-meta {
font-size: .78rem;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.branch-actions {
display: flex;
justify-content: flex-end;
gap: 6px;
margin-top: 4px;
}
.branch-actions button {
background: none;
border: none;
color: var(--muted);
cursor: pointer;
font-size: 1rem;
padding: 6px 8px;
border-radius: 6px;
transition: background .15s, color .15s;
}
.branch-actions button:hover {
background: var(--bg);
color: var(--text);
}
.branch-actions .branch-delete:hover {
color: #ef4444;
background: rgba(239,68,68,.1);
}
@media (max-width: 640px) {
.branches-grid { grid-template-columns: 1fr; }
}
</style>
</body>
</html>
+71 -19
View File
@@ -35,25 +35,37 @@
</div>
<div class="modal-overlay" id="photoFormModal" onclick="if(event.target===this)closePhotoForm()">
<div class="edit-modal">
<div class="edit-modal" style="max-width:480px">
<h3 id="photoFormTitle">Добавить фото</h3>
<div>
<label>Выбрать файл (jpg/png и т.п.)</label>
<input type="file" id="photoFile" accept="image/*">
</div>
<div id="photoFormPreview" class="photo-preview" style="display:none"><img id="photoPreviewImg" alt=""></div>
<div>
<label>Подпись</label>
<textarea id="photoCaption" placeholder="Например: выступление, тренировка..."></textarea>
</div>
<div>
<label>Дата съёмки</label>
<input type="date" id="photoTakenAt">
</div>
<div class="actions">
<button class="cancel" onclick="closePhotoForm()">Отмена</button>
<button class="save" onclick="savePhotoForm()">Сохранить</button>
</div>
<form id="photoForm" class="settings-stack" style="gap:12px">
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Выбрать файл (jpg/png и т.п.) <span style="color:#ef4444">*</span></label>
<input type="file" id="photoFile" accept="image/*">
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<div id="photoFormPreview" class="photo-preview" style="display:none"><img id="photoPreviewImg" alt=""></div>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Подпись</label>
<textarea id="photoCaption" class="settings-input" placeholder="Например: выступление, тренировка..."></textarea>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Дата съёмки</label>
<input type="date" id="photoTakenAt" class="settings-input">
</div>
</div>
<div class="card-foot" style="justify-content:flex-end;gap:8px">
<button type="button" class="btn-primary ghost" onclick="closePhotoForm()">Отмена</button>
<button type="submit" class="btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
@@ -64,6 +76,8 @@
// --- Groups ---
const DAYS = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
let branchesCache = [];
let allGroups = [];
let currentCover = null;
async function loadBranchesCache() {
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
@@ -79,6 +93,7 @@ async function loadGroups() {
await loadBranchesCache();
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
const groups = await res.json();
allGroups = groups;
const list = document.getElementById('groupList');
if (!groups.length) { list.innerHTML = '<div style="color:var(--muted);text-align:center;padding:32px">Нет групп</div>'; return; }
list.innerHTML = `<div class="group-grid">` + groups.map(g => {
@@ -173,6 +188,8 @@ let editingPhotoId = null;
async function openPhotos(groupId, groupName) {
currentGroupId = groupId;
currentGroupName = groupName;
const g = allGroups.find(x => String(x.id) === String(groupId));
currentCover = g ? g.cover_path : null;
photoPage = 1;
editingPhotoId = null;
document.getElementById('photosTitle').textContent = `Фото — ${groupName}`;
@@ -207,12 +224,14 @@ function fmtPhotoDate(d) { return d ? d.split('-').reverse().join('.') : ''; }
function photoHTML(p) {
const taken = p.taken_at ? `Дата: ${fmtPhotoDate(p.taken_at)}` : '';
const uploaded = `Загружено: ${new Date(p.created_at).toLocaleDateString('ru')}`;
const isCover = currentCover && p.photo_path === currentCover;
return `
<div class="photo-item">
<div class="photo-item" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}">
<img src="${API}${p.photo_path}" onclick="showImg('${API}${p.photo_path}')" alt="">
<div class="p-cap">${esc(p.caption || '')}</div>
<div class="p-date">${taken ? taken + ' · ' : ''}${uploaded}</div>
<div class="p-actions">
<button class="p-cover${isCover ? ' active' : ''}" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" title="${isCover ? 'Текущая обложка' : 'Сделать обложкой'}" ${isCover ? 'disabled' : ''}>🖼️</button>
<button class="p-edit" onclick="openEditPhoto(${p.id})" title="Редактировать">✎</button>
<button class="p-del" onclick="deletePhoto(${p.id})" title="Удалить">&times;</button>
</div>
@@ -335,6 +354,10 @@ async function exportGroupUrls(groupId, groupName) {
document.getElementById('newGroup').addEventListener('keydown', e => { if (e.key === 'Enter') addGroup(); });
document.getElementById('photoFile').addEventListener('change', previewPhotoFile);
document.getElementById('photoForm').addEventListener('submit', e => {
e.preventDefault();
savePhotoForm();
});
// Event delegation for group cover clicks
document.getElementById('groupList').addEventListener('click', e => {
@@ -346,6 +369,35 @@ document.getElementById('groupList').addEventListener('click', e => {
}
});
// Event delegation for photo actions in modal
document.getElementById('photoGrid').addEventListener('click', async e => {
const coverBtn = e.target.closest('.p-cover');
if (coverBtn) {
const photoId = parseInt(coverBtn.dataset.photoId, 10);
const photoPath = coverBtn.dataset.photoPath;
if (!isNaN(photoId)) {
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${photoId}/cover`, {
method: 'PUT',
headers: hdrJson(),
});
if (res.ok) {
const g = await res.json();
currentCover = g.cover_path || null;
showToast('Обложка обновлена');
loadGroupPhotos();
loadGroups();
} else {
const err = await res.json();
alert(err.error || 'Ошибка');
}
} catch (err) {
alert('Ошибка сети: ' + err.message);
}
}
}
});
async function populateNewGroupBranch() {
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
if (res.ok) {
+79 -23
View File
@@ -36,25 +36,40 @@
</div>
<div class="modal-overlay" id="editModal" onclick="if(event.target===this)closeEdit()">
<div class="edit-modal">
<div class="edit-modal" style="max-width:480px">
<h3>Редактирование записи</h3>
<div>
<label>Фамилия и имя</label>
<input type="text" id="editName" list="studentEditList">
<datalist id="studentEditList"></datalist>
</div>
<div>
<label>Группа</label>
<select id="editGroup"></select>
</div>
<div>
<label>Что делала(а)</label>
<textarea id="editDesc"></textarea>
</div>
<div class="actions">
<button class="cancel" onclick="closeEdit()">Отмена</button>
<button class="save" onclick="saveEdit()">Сохранить</button>
</div>
<form id="editForm" class="settings-stack" style="gap:12px">
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Фамилия и имя <span style="color:#ef4444">*</span></label>
<input type="text" id="editName" class="settings-input" list="studentEditList" required autocomplete="off">
<datalist id="studentEditList"></datalist>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Группа <span style="color:#ef4444">*</span></label>
<select id="editGroup" class="settings-input" required></select>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Что делала(а) <span style="color:#ef4444">*</span></label>
<textarea id="editDesc" class="settings-input" required></textarea>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Прикрепить файлы</label>
<input type="file" id="editFiles" multiple accept=".pdf,.doc,.docx,.txt,.md,.html,.htm,.zip,.rar,.7z,.jpg,.jpeg,.png,.gif,.webp">
<div class="files-preview" id="editFilesPreview"></div>
</div>
</div>
<div class="card-foot" style="justify-content:flex-end;gap:8px">
<button type="button" class="btn-primary ghost" onclick="closeEdit()">Отмена</button>
<button type="submit" class="btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
@@ -297,6 +312,8 @@ async function openEdit(id) {
function closeEdit() {
document.getElementById('editModal').classList.remove('open');
document.getElementById('editFiles').value = '';
document.getElementById('editFilesPreview').innerHTML = '';
editId = null;
}
@@ -311,11 +328,27 @@ async function saveEdit() {
headers: hdrJson(),
body: JSON.stringify({ student_name: name, group_id, description })
});
if (res.ok) {
closeEdit();
loadEntries();
showToast('Запись обновлена');
} else { const err = await res.json(); alert(err.error); }
if (!res.ok) { const err = await res.json(); alert(err.error); return; }
const files = document.getElementById('editFiles').files;
if (files.length) {
const formData = new FormData();
for (const f of files) formData.append('files', f);
const uploadRes = await fetch(`${API}/api/entries/${editId}/files`, {
method: 'POST',
headers: { 'X-Admin-Token': token },
body: formData
});
if (!uploadRes.ok) {
const err = await uploadRes.json().catch(() => ({}));
alert(err.error || 'Ошибка загрузки файлов');
return;
}
}
closeEdit();
loadEntries();
showToast('Запись обновлена');
}
async function delEntry(id) {
@@ -333,6 +366,29 @@ document.getElementById('searchInput').addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => { page = 1; loadEntries(); }, 300);
});
document.getElementById('editForm').addEventListener('submit', (e) => {
e.preventDefault();
saveEdit();
});
document.getElementById('editFiles').addEventListener('change', (e) => {
const preview = document.getElementById('editFilesPreview');
preview.innerHTML = '';
Array.from(e.target.files).forEach((f, i) => {
const div = document.createElement('div');
div.className = 'file-preview-item';
div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem';
div.innerHTML = `<span>${esc(f.name)}</span> <span style="color:var(--muted)">${(f.size/1024).toFixed(1)} KB</span> <button type="button" onclick="removeEditFile(${i})" style="background:none;border:none;color:var(--muted);cursor:pointer;font-size:1.1rem;line-height:1">✕</button>`;
preview.appendChild(div);
});
});
function removeEditFile(index) {
const input = document.getElementById('editFiles');
const dt = new DataTransfer();
Array.from(input.files).forEach((f, i) => { if (i !== index) dt.items.add(f); });
input.files = dt.files;
input.dispatchEvent(new Event('change'));
}
async function exportCSV() {
const p = new URLSearchParams();
+47 -27
View File
@@ -30,39 +30,51 @@
</div>
<div class="modal-overlay" id="batchModal" onclick="if(event.target===this)closeBatchAdd()">
<div class="edit-modal">
<div class="edit-modal" style="max-width:480px">
<h3>Пакетное добавление учеников</h3>
<div>
<label>Имена — каждое с новой строки</label>
<textarea id="batchText" placeholder="Иванов Иван&#10;Петров Пётр&#10;Сидоров Сидор"></textarea>
</div>
<div>
<label>Группа (необязательно)</label>
<select id="batchGroup"><option value="">— без группы —</option></select>
</div>
<div class="actions">
<button class="cancel" onclick="closeBatchAdd()">Отмена</button>
<button class="save" onclick="batchAdd()">Добавить</button>
</div>
<form id="batchForm" class="settings-stack" style="gap:12px">
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Имена — каждое с новой строки <span style="color:#ef4444">*</span></label>
<textarea id="batchText" class="settings-input" style="min-height:120px" required placeholder="Иванов Иван&#10;Петров Пётр&#10;Сидоров Сидор"></textarea>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Группа (необязательно)</label>
<select id="batchGroup" class="settings-input"><option value="">— без группы —</option></select>
</div>
</div>
<div class="card-foot" style="justify-content:flex-end;gap:8px">
<button type="button" class="btn-primary ghost" onclick="closeBatchAdd()">Отмена</button>
<button type="submit" class="btn-primary">Добавить</button>
</div>
</form>
</div>
</div>
<div class="modal-overlay" id="attachModal" onclick="if(event.target===this)closeBatchAttach()">
<div class="edit-modal">
<div class="edit-modal" style="max-width:480px">
<h3>Прикрепить к группе</h3>
<div>
<label>Группа</label>
<select id="attachGroup"><option value="">— выберите группу —</option></select>
</div>
<div>
<label>Ученики</label>
<input type="text" id="attachSearch" class="search-input" placeholder="Поиск по имени..." style="width:100%;margin-bottom:8px">
<div class="attach-list" id="attachList"></div>
</div>
<div class="actions">
<button class="cancel" onclick="closeBatchAttach()">Отмена</button>
<button class="save" onclick="batchAttach()">Прикрепить</button>
</div>
<form id="attachForm" class="settings-stack" style="gap:12px">
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Группа <span style="color:#ef4444">*</span></label>
<select id="attachGroup" class="settings-input" required><option value="">— выберите группу —</option></select>
</div>
</div>
<div class="settings-row">
<div class="settings-field" style="flex:1">
<label>Ученики</label>
<input type="text" id="attachSearch" class="settings-input" placeholder="Поиск по имени..." style="margin-bottom:8px">
<div class="attach-list" id="attachList"></div>
</div>
</div>
<div class="card-foot" style="justify-content:flex-end;gap:8px">
<button type="button" class="btn-primary ghost" onclick="closeBatchAttach()">Отмена</button>
<button type="submit" class="btn-primary">Прикрепить</button>
</div>
</form>
</div>
</div>
@@ -188,6 +200,10 @@ async function batchAdd() {
}
document.getElementById('newStudent').addEventListener('keydown', e => { if (e.key === 'Enter') addStudent(); });
document.getElementById('batchForm').addEventListener('submit', e => {
e.preventDefault();
batchAdd();
});
document.getElementById('studentSearch').addEventListener('input', () => {
clearTimeout(sSearchTimer);
sSearchTimer = setTimeout(() => { sPage = 1; renderStudents(); }, 300);
@@ -278,6 +294,10 @@ async function batchAttach() {
} else { const e = await res.json(); alert(e.error); }
}
document.getElementById('attachForm').addEventListener('submit', e => {
e.preventDefault();
batchAttach();
});
document.getElementById('attachSearch').addEventListener('input', () => {
clearTimeout(aSearchTimer);
aSearchTimer = setTimeout(renderAttachList, 300);