add soft delete with trash page and group photo chronology with styling
This commit is contained in:
+12
@@ -17,6 +17,7 @@ CREATE TABLE IF NOT EXISTS entries (
|
||||
group_id INT NOT NULL REFERENCES groups(id),
|
||||
description TEXT NOT NULL,
|
||||
photo_path VARCHAR(255),
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
@@ -45,6 +46,17 @@ INSERT INTO groups (name) VALUES
|
||||
('Advanced')
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_photos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
||||
photo_path VARCHAR(255) NOT NULL,
|
||||
caption TEXT,
|
||||
taken_at DATE,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_group_photos_group_id ON group_photos(group_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS project_files (
|
||||
id SERIAL PRIMARY KEY,
|
||||
entry_id INT NOT NULL REFERENCES entries(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -44,3 +44,16 @@ CREATE TABLE IF NOT EXISTS project_files (
|
||||
UPDATE project_files SET token = md5(random()::text || clock_timestamp()::text) WHERE token IS NULL;
|
||||
ALTER TABLE project_files ALTER COLUMN token SET NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS project_files_token_key ON project_files(token);
|
||||
|
||||
ALTER TABLE entries ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_photos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
||||
photo_path VARCHAR(255) NOT NULL,
|
||||
caption TEXT,
|
||||
taken_at DATE,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_group_photos_group_id ON group_photos(group_id);
|
||||
+44
-1
@@ -137,7 +137,7 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
|
||||
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:100;display:none;align-items:center;justify-content:center}
|
||||
.modal-overlay.open{display:flex}
|
||||
.modal-overlay img{max-width:90%;max-height:90dvh;border-radius:var(--radius)}
|
||||
.modal-overlay > img{max-width:90%;max-height:90dvh;border-radius:var(--radius)}
|
||||
.edit-modal{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:24px;max-width:420px;width:90%;display:flex;flex-direction:column;gap:16px}
|
||||
.edit-modal h3{font-size:1.1rem;font-weight:600}
|
||||
.edit-modal label{font-size:.8rem;color:var(--muted);margin-bottom:4px}
|
||||
@@ -153,3 +153,46 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.edit-modal .actions button:hover{opacity:.85}
|
||||
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#16a34a;color:#fff;padding:12px 24px;border-radius:var(--radius);font-size:.9rem;opacity:0;transition:opacity .3s;pointer-events:none;z-index:200}
|
||||
.toast.show{opacity:1}
|
||||
|
||||
/* --- Фото группы (хронология) --- */
|
||||
.group-cover{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:10px;cursor:pointer;display:block;background:var(--bg)}
|
||||
.group-cover:hover{opacity:.9}
|
||||
.empty-cover{background:var(--bg);border:1px dashed var(--border);display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:1.6rem;cursor:pointer}
|
||||
.empty-cover:hover{border-color:var(--accent);color:var(--accent)}
|
||||
.photo-btn{background:var(--bg);border:1px solid var(--border);color:var(--accent);border-radius:8px;padding:8px 14px;font-size:.85rem;font-weight:600;cursor:pointer;transition:all .15s}
|
||||
.photo-btn:hover{border-color:var(--accent);opacity:.85}
|
||||
.gallery-modal{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:24px;max-width:860px;width:94%;max-height:90dvh;display:flex;flex-direction:column;gap:16px;overflow:hidden}
|
||||
.gallery-head{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.gallery-head h3{font-size:1.1rem;font-weight:600}
|
||||
.gallery-head .upload-btn{background:var(--accent);color:#fff;border:none;border-radius:8px;padding:9px 16px;font-size:.85rem;font-weight:600;cursor:pointer;transition:opacity .15s}
|
||||
.gallery-head .upload-btn:hover{opacity:.85}
|
||||
.gallery-foot{display:flex;justify-content:flex-end}
|
||||
.gallery-foot .cancel{background:var(--border);color:var(--text);border:none;border-radius:8px;padding:10px 20px;font-size:.9rem;font-weight:600;cursor:pointer;transition:opacity .15s}
|
||||
.gallery-foot .cancel:hover{opacity:.85}
|
||||
.photo-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;overflow:auto;padding:2px}
|
||||
.photo-item{background:var(--bg);border:1px solid var(--border);border-radius:10px;overflow:hidden;display:flex;flex-direction:column}
|
||||
.photo-item img{width:100%;aspect-ratio:4/3;object-fit:cover;cursor:pointer;display:block;transition:opacity .15s}
|
||||
.photo-item img:hover{opacity:.9}
|
||||
.photo-item .p-cap{padding:8px 10px;font-size:.78rem;color:var(--text);min-height:1.2em;white-space:pre-wrap;word-break:break-word}
|
||||
.photo-item .p-date{font-size:.72rem;color:var(--muted);padding:0 10px 6px}
|
||||
.photo-item .p-actions{display:flex;justify-content:flex-end;gap:4px;padding:6px 8px;border-top:1px solid var(--border)}
|
||||
.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}
|
||||
.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)}
|
||||
.photo-preview{margin-top:4px;text-align:center}
|
||||
.photo-preview img{max-width:100%;max-height:220px;border-radius:8px;overflow:hidden}
|
||||
|
||||
/* --- Корзина --- */
|
||||
.trash-head{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:16px}
|
||||
.trash-muted{color:var(--muted);font-size:.85rem}
|
||||
.danger-btn{background:#ef4444;color:#fff;border:none;border-radius:8px;padding:9px 16px;font-size:.85rem;font-weight:600;cursor:pointer;transition:opacity .15s}
|
||||
.danger-btn:hover{opacity:.85}
|
||||
.danger-btn:disabled{opacity:.4;cursor:not-allowed}
|
||||
.restore-btn{background:var(--accent);color:#fff;border:none;border-radius:8px;padding:8px 12px;font-size:.8rem;font-weight:600;cursor:pointer;white-space:nowrap;transition:opacity .15s}
|
||||
.restore-btn:hover{opacity:.85}
|
||||
.del-btn{background:none;border:none;color:#ef4444;cursor:pointer;font-size:1.15rem;padding:4px;flex-shrink:0}
|
||||
.del-btn:hover{opacity:.8}
|
||||
.trash-time{color:var(--muted);font-size:.75rem;margin-top:8px}
|
||||
@@ -23,6 +23,7 @@ function doLogout() {
|
||||
const NAV = [
|
||||
{ page: 'dashboard', label: 'Дашборд' },
|
||||
{ page: 'journal', label: 'Журнал' },
|
||||
{ page: 'trash', label: 'Корзина' },
|
||||
{ page: 'files', label: 'Файлы' },
|
||||
{ page: 'links', label: 'Ссылки' },
|
||||
{ page: 'students', label: 'Ученики' },
|
||||
|
||||
+182
-1
@@ -18,6 +18,44 @@
|
||||
<div class="list" id="groupList"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="photosModal" onclick="if(event.target===this)closePhotos()">
|
||||
<div class="gallery-modal">
|
||||
<div class="gallery-head">
|
||||
<h3 id="photosTitle">Фото</h3>
|
||||
<button class="upload-btn" onclick="openAddPhoto()">Загрузить фото</button>
|
||||
</div>
|
||||
<div class="photo-grid" id="photoGrid"><div class="empty">Загрузка...</div></div>
|
||||
<div class="pager" id="photosPager"></div>
|
||||
<div class="gallery-foot">
|
||||
<button class="cancel" onclick="closePhotos()">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="photoFormModal" onclick="if(event.target===this)closePhotoForm()">
|
||||
<div class="edit-modal">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
<script src="admin.js"></script>
|
||||
<script src="vendor/jszip.min.js"></script>
|
||||
@@ -34,6 +72,9 @@ async function loadGroups() {
|
||||
const schedSet = g.day_of_week != null && g.time_start && g.time_end;
|
||||
return `
|
||||
<div class="group-card">
|
||||
${g.cover_path
|
||||
? `<img class="group-cover" src="${API}${g.cover_path}" onclick="openPhotos(${g.id}, '${esc(g.name).replace(/'/g, ''')}')" title="Фото группы (хронология)" alt="">`
|
||||
: `<div class="group-cover empty-cover" onclick="openPhotos(${g.id}, '${esc(g.name).replace(/'/g, ''')}')" title="Фото группы (хронология)">📷</div>`}
|
||||
<div class="group-head">
|
||||
<input class="name-input" id="name-${g.id}" value="${esc(g.name)}">
|
||||
<button class="del" onclick="delGroup(${g.id})" title="Удалить">×</button>
|
||||
@@ -55,6 +96,7 @@ async function loadGroups() {
|
||||
<div class="group-foot">
|
||||
<div style="display:flex;gap:8px">
|
||||
<button class="save-sched" onclick="saveGroup(${g.id})">Сохранить</button>
|
||||
<button class="photo-btn" onclick="openPhotos(${g.id}, '${esc(g.name).replace(/'/g, ''')}')" title="Фото группы (хронология)">Фото</button>
|
||||
<button class="btn-link" onclick="exportGroup(${g.id}, '${esc(g.name).replace(/'/g, ''')}')" title="Экспортировать записи группы">CSV</button>
|
||||
<button class="btn-link" onclick="exportGroupUrls(${g.id}, '${esc(g.name).replace(/'/g, ''')}')" title="Скачать .url файлы учеников группы">URL</button>
|
||||
</div>
|
||||
@@ -93,11 +135,149 @@ async function addGroup() {
|
||||
}
|
||||
|
||||
async function delGroup(id) {
|
||||
if (!confirm('Удалить группу?')) return;
|
||||
if (!confirm('Удалить группу? Фото группы также будут удалены.')) return;
|
||||
await fetch(`${API}/api/groups/${id}`, { method: 'DELETE', headers: hdr() });
|
||||
loadGroups();
|
||||
}
|
||||
|
||||
// --- Фото группы (хронология) ---
|
||||
const PHOTO_PAGE_SIZE = 24;
|
||||
let currentGroupId = null;
|
||||
let currentGroupName = '';
|
||||
let photos = [];
|
||||
let photoPage = 1;
|
||||
let totalPhotos = 0;
|
||||
let editingPhotoId = null;
|
||||
|
||||
async function openPhotos(groupId, groupName) {
|
||||
currentGroupId = groupId;
|
||||
currentGroupName = groupName;
|
||||
photoPage = 1;
|
||||
editingPhotoId = null;
|
||||
document.getElementById('photosTitle').textContent = `Фото — ${groupName}`;
|
||||
document.getElementById('photosModal').classList.add('open');
|
||||
await loadGroupPhotos();
|
||||
}
|
||||
|
||||
function closePhotos() {
|
||||
document.getElementById('photosModal').classList.remove('open');
|
||||
currentGroupId = null;
|
||||
}
|
||||
|
||||
async function loadGroupPhotos() {
|
||||
const p = new URLSearchParams();
|
||||
p.set('limit', PHOTO_PAGE_SIZE);
|
||||
p.set('offset', (photoPage - 1) * PHOTO_PAGE_SIZE);
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos?${p}`, { headers: hdr() });
|
||||
const data = await res.json();
|
||||
photos = data.photos;
|
||||
totalPhotos = data.total;
|
||||
document.getElementById('photoGrid').className = 'photo-grid';
|
||||
document.getElementById('photoGrid').innerHTML = photos.length
|
||||
? photos.map(photoHTML).join('')
|
||||
: '<div class="empty" style="grid-column:1/-1">Фото пока нет. Загрузите первое фото.</div>';
|
||||
renderPager(document.getElementById('photosPager'), photoPage, Math.max(1, Math.ceil(totalPhotos / PHOTO_PAGE_SIZE)), goPhotoPage);
|
||||
}
|
||||
|
||||
function goPhotoPage(p) { photoPage = p; loadGroupPhotos(); }
|
||||
|
||||
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')}`;
|
||||
return `
|
||||
<div class="photo-item">
|
||||
<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-edit" onclick="openEditPhoto(${p.id})" title="Редактировать">✎</button>
|
||||
<button class="p-del" onclick="deletePhoto(${p.id})" title="Удалить">×</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function openAddPhoto() {
|
||||
editingPhotoId = null;
|
||||
document.getElementById('photoFormTitle').textContent = `Добавить фото — ${currentGroupName}`;
|
||||
document.getElementById('photoFile').value = '';
|
||||
document.getElementById('photoCaption').value = '';
|
||||
document.getElementById('photoTakenAt').value = '';
|
||||
document.getElementById('photoFormPreview').style.display = 'none';
|
||||
document.getElementById('photoFormModal').classList.add('open');
|
||||
}
|
||||
|
||||
async function openEditPhoto(id) {
|
||||
const p = photos.find(x => x.id === id);
|
||||
if (!p) return;
|
||||
editingPhotoId = id;
|
||||
document.getElementById('photoFormTitle').textContent = 'Редактировать фото';
|
||||
document.getElementById('photoFile').value = '';
|
||||
document.getElementById('photoCaption').value = p.caption || '';
|
||||
document.getElementById('photoTakenAt').value = p.taken_at || '';
|
||||
const prev = document.getElementById('photoFormPreview');
|
||||
const img = document.getElementById('photoPreviewImg');
|
||||
img.src = `${API}${p.photo_path}`;
|
||||
prev.style.display = 'block';
|
||||
document.getElementById('photoFormModal').classList.add('open');
|
||||
}
|
||||
|
||||
function closePhotoForm() {
|
||||
document.getElementById('photoFormModal').classList.remove('open');
|
||||
editingPhotoId = null;
|
||||
}
|
||||
|
||||
function previewPhotoFile() {
|
||||
const file = document.getElementById('photoFile').files[0];
|
||||
const prev = document.getElementById('photoFormPreview');
|
||||
if (!file) { prev.style.display = 'none'; return; }
|
||||
const img = document.getElementById('photoPreviewImg');
|
||||
img.src = URL.createObjectURL(file);
|
||||
prev.style.display = 'block';
|
||||
}
|
||||
|
||||
async function savePhotoForm() {
|
||||
const caption = document.getElementById('photoCaption').value.trim();
|
||||
const taken_at = document.getElementById('photoTakenAt').value;
|
||||
if (editingPhotoId) {
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${editingPhotoId}`, {
|
||||
method: 'PUT',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({ caption: caption || null, taken_at: taken_at || null })
|
||||
});
|
||||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
|
||||
showToast('Фото обновлено');
|
||||
} else {
|
||||
const file = document.getElementById('photoFile').files[0];
|
||||
if (!file) { alert('Выберите файл'); return; }
|
||||
const fd = new FormData();
|
||||
fd.append('photo', file);
|
||||
fd.append('caption', caption);
|
||||
fd.append('taken_at', taken_at);
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos`, {
|
||||
method: 'POST',
|
||||
headers: hdr(),
|
||||
body: fd
|
||||
});
|
||||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
|
||||
showToast('Фото добавлено в хронологию');
|
||||
}
|
||||
closePhotoForm();
|
||||
loadGroupPhotos();
|
||||
loadGroups();
|
||||
}
|
||||
|
||||
async function deletePhoto(id) {
|
||||
if (!confirm('Удалить это фото безвозвратно?')) return;
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${id}`, { method: 'DELETE', headers: hdr() });
|
||||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
|
||||
showToast('Фото удалено');
|
||||
loadGroupPhotos();
|
||||
loadGroups();
|
||||
}
|
||||
|
||||
async function exportGroup(id, name) {
|
||||
const res = await fetch(`${API}/api/entries?group_id=${id}`, { headers: hdr() });
|
||||
const { entries } = await res.json();
|
||||
@@ -133,6 +313,7 @@ async function exportGroupUrls(groupId, groupName) {
|
||||
}
|
||||
|
||||
document.getElementById('newGroup').addEventListener('keydown', e => { if (e.key === 'Enter') addGroup(); });
|
||||
document.getElementById('photoFile').addEventListener('change', previewPhotoFile);
|
||||
|
||||
(async () => {
|
||||
if (await checkAuth()) {
|
||||
|
||||
+2
-1
@@ -282,8 +282,9 @@ async function saveEdit() {
|
||||
}
|
||||
|
||||
async function delEntry(id) {
|
||||
if (!confirm('Удалить запись?')) return;
|
||||
if (!confirm('Переместить запись в корзину? Файлы и фото сохранятся.')) return;
|
||||
await fetch(`${API}/api/entries/${id}`, { method: 'DELETE', headers: hdr() });
|
||||
showToast('Запись перемещена в корзину');
|
||||
loadEntries();
|
||||
}
|
||||
|
||||
|
||||
+34
-12
@@ -28,11 +28,10 @@ body{font-family:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;background
|
||||
.card .desc{font-size:.9rem;line-height:1.45;color:#4a4f5a;white-space:pre-wrap;word-break:break-word}
|
||||
.files-block{margin-top:10px}
|
||||
.files-label{font-size:.7rem;font-weight:800;color:var(--gray);text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}
|
||||
.card .files{display:flex;flex-direction:column;gap:6px}
|
||||
.card .files a{display:flex;align-items:center;gap:8px;background:#F6F6F6;border:1px solid #EBEBEB;color:#3a3f4a;text-decoration:none;border-radius:12px;padding:6px 10px;transition:border .15s,color .15s,background .15s}
|
||||
.card .files{display:flex;flex-wrap:wrap;gap:6px;margin-top:2px}
|
||||
.card .files a{display:flex;align-items:center;justify-content:center;width:44px;height:44px;background:#F6F6F6;border:1px solid #EBEBEB;color:#3a3f4a;text-decoration:none;border-radius:12px;transition:border .15s,color .15s,background .15s}
|
||||
.card .files a:hover{border-color:var(--yellow);color:var(--dark);background:#fff}
|
||||
.card .files .ficon{font-size:1rem;line-height:1;display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:8px;flex-shrink:0}
|
||||
.card .files .fname{font-size:.74rem;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.card .files .ficon{font-size:1.25rem;line-height:1;display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;flex-shrink:0}
|
||||
.card .files a.ftype-image .ficon{background:#EAF4E8}
|
||||
.card .files a.ftype-music .ficon{background:#EAEEF6}
|
||||
.card .files a.ftype-document .ficon{background:#F6F0E0}
|
||||
@@ -45,9 +44,16 @@ body{font-family:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;background
|
||||
.lightbox{position:fixed;inset:0;background:rgba(12,14,20,.92);display:none;align-items:center;justify-content:center;z-index:100;cursor:zoom-out;padding:24px}
|
||||
.lightbox.open{display:flex}
|
||||
.lightbox img{max-width:100%;max-height:100%;border-radius:12px;box-shadow:0 20px 60px rgba(0,0,0,.5)}
|
||||
@media(max-width:1000px){.grid{grid-template-columns:repeat(3,1fr)}}
|
||||
@media(max-width:760px){.grid{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:480px){.grid{grid-template-columns:1fr}}
|
||||
#photosBlock{display:none;margin-bottom:44px}
|
||||
.photos-label{font-size:.78rem;font-weight:800;color:var(--gray);text-transform:uppercase;letter-spacing:.05em;margin-bottom:14px}
|
||||
.photos-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
|
||||
.gphoto{position:relative;border-radius:18px;overflow:hidden;background:#fff;display:block;box-shadow:0 1px 3px rgba(20,30,40,.06);text-decoration:none}
|
||||
.gphoto img{width:100%;aspect-ratio:4/3;object-fit:cover;display:block;cursor:zoom-in;transition:transform .18s ease}
|
||||
.gphoto:hover img{transform:scale(1.03)}
|
||||
.gcap{position:absolute;left:0;right:0;bottom:0;padding:22px 12px 9px;font-size:.74rem;font-weight:600;color:#fff;background:linear-gradient(transparent,rgba(0,0,0,.6));white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
@media(max-width:1000px){.grid{grid-template-columns:repeat(3,1fr)}.photos-grid{grid-template-columns:repeat(3,1fr)}}
|
||||
@media(max-width:760px){.grid{grid-template-columns:repeat(2,1fr)}.photos-grid{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:480px){.grid{grid-template-columns:1fr}.photos-grid{grid-template-columns:1fr}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -56,6 +62,10 @@ body{font-family:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;background
|
||||
<div class="chips" id="chips"></div>
|
||||
</section>
|
||||
<main class="wrap">
|
||||
<div id="photosBlock">
|
||||
<div class="photos-label">Фото группы</div>
|
||||
<div class="photos-grid" id="photosGrid"></div>
|
||||
</div>
|
||||
<div class="grid" id="grid"><div class="loading">Карточки загружаются...</div></div>
|
||||
</main>
|
||||
<div class="lightbox" id="lightbox" onclick="this.classList.remove('open')"><img id="lightboxImg" alt=""></div>
|
||||
@@ -82,11 +92,10 @@ function filesHTML(files){
|
||||
<div class="files-label">Работы резидента</div>
|
||||
<div class="files">${files.map(f=>{
|
||||
const t = fileType(f.name);
|
||||
return `<a class="ftype-${t}" ${isImageFile(f.name)
|
||||
?`href="#" onclick="showImg('/api/files/${f.token}');return false;" title="Открыть"`
|
||||
:`href="/api/files/${f.token}" download title="Скачать"`}>
|
||||
<span class="ficon">${fileIcon(t)}</span>
|
||||
<span class="fname">${esc(f.name)}</span>
|
||||
return `<a class="ftype-${t}" title="${esc(f.name)}" ${isImageFile(f.name)
|
||||
?`href="#" onclick="showImg('/api/files/${f.token}');return false;"`
|
||||
:`href="/api/files/${f.token}" download`}>
|
||||
<span class="ficon" alt="${esc(f.name)}">${fileIcon(t)}</span>
|
||||
</a>`;
|
||||
}).join('')}</div>
|
||||
</div>`;
|
||||
@@ -106,6 +115,19 @@ function filesHTML(files){
|
||||
if (data.date_from || data.date_to) chips.push(`Период: <b>${fmt(data.date_from)}</b> — <b>${fmt(data.date_to)}</b>`);
|
||||
document.getElementById('chips').innerHTML = chips.map(c => `<span class="chip">${c}</span>`).join('');
|
||||
|
||||
const pb = document.getElementById('photosBlock');
|
||||
if (data.photos && data.photos.length) {
|
||||
document.getElementById('photosGrid').innerHTML = data.photos.map(p => `
|
||||
<a class="gphoto" href="#" onclick="showImg('${p.photo_path}');return false;">
|
||||
<img src="${p.photo_path}" alt="${esc(p.caption || '')}" loading="lazy">
|
||||
${p.caption ? `<div class="gcap">${esc(p.caption)}</div>` : ''}
|
||||
</a>
|
||||
`).join('');
|
||||
pb.style.display = 'block';
|
||||
} else {
|
||||
pb.style.display = 'none';
|
||||
}
|
||||
|
||||
const grid = document.getElementById('grid');
|
||||
if (!data.entries.length) {
|
||||
grid.innerHTML = '<div class="empty"><div class="big">🎈</div>Записей пока нет</div>';
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<!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="trash">
|
||||
<div class="layout">
|
||||
<div class="sidebar" id="sidebar"></div>
|
||||
<div class="main">
|
||||
<h2>Корзина</h2>
|
||||
<div class="trash-head">
|
||||
<span class="trash-muted" id="trashInfo"></span>
|
||||
<button class="danger-btn" id="emptyBtn" onclick="emptyTrash()">Очистить корзину</button>
|
||||
</div>
|
||||
<div class="grid" id="grid"><div class="empty">Загрузка...</div></div>
|
||||
<div class="pager" id="pager"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="imgModal" onclick="this.classList.remove('open')">
|
||||
<img id="imgModalSrc">
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
<script src="admin.js"></script>
|
||||
<script>
|
||||
const PAGE_SIZE = 20;
|
||||
let currentEntries = [];
|
||||
let page = 1;
|
||||
let totalEntries = 0;
|
||||
|
||||
function isImageFile(name) {
|
||||
return /\.(jpe?g|png|gif|webp|bmp|avif|svg|ico)$/i.test(name || '');
|
||||
}
|
||||
|
||||
function filesHTML(files) {
|
||||
if (!files || !files.length) return '';
|
||||
return `<div class="entry-files">${files.map(f =>
|
||||
isImageFile(f.name)
|
||||
? `<a class="f-link" href="#" onclick="showImg('${API}/api/files/${f.token}');return false;" title="Открыть">${esc(f.name)}</a>`
|
||||
: `<a class="f-link" href="${API}/api/files/${f.token}" download title="Скачать">${esc(f.name)}</a>`
|
||||
).join('')}</div>`;
|
||||
}
|
||||
|
||||
function entryHTML(e) {
|
||||
return `
|
||||
<div class="card">
|
||||
${e.photo_path ? `<img src="${API}${e.photo_path}" onclick="showImg('${API}${e.photo_path}')" alt="">` : ''}
|
||||
<div class="info">
|
||||
<div class="name">${esc(e.student_name)}</div>
|
||||
<div class="group">${esc(e.group_name)}</div>
|
||||
<div class="desc">${esc(e.description)}</div>
|
||||
${filesHTML(e.files)}
|
||||
<div class="trash-time">Удалена: ${new Date(e.deleted_at).toLocaleString('ru')}</div>
|
||||
</div>
|
||||
<button class="restore-btn" onclick="restoreEntry(${e.id})" title="Восстановить">Восстановить</button>
|
||||
<button class="del-btn" onclick="hardDelete(${e.id})" title="Удалить навсегда (вместе с файлами)">×</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderGrid() {
|
||||
const grid = document.getElementById('grid');
|
||||
grid.className = 'grid';
|
||||
grid.innerHTML = currentEntries.length
|
||||
? currentEntries.map(entryHTML).join('')
|
||||
: '<div class="empty">Корзина пуста</div>';
|
||||
document.getElementById('trashInfo').textContent =
|
||||
totalEntries > 0 ? `Записей в корзине: ${totalEntries}` : '';
|
||||
document.getElementById('emptyBtn').disabled = totalEntries === 0;
|
||||
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalEntries / PAGE_SIZE)), goPage);
|
||||
}
|
||||
|
||||
async function loadTrash() {
|
||||
const p = new URLSearchParams();
|
||||
p.set('limit', PAGE_SIZE);
|
||||
p.set('offset', (page - 1) * PAGE_SIZE);
|
||||
const res = await fetch(`${API}/api/trash?${p}`, { headers: hdr() });
|
||||
const data = await res.json();
|
||||
currentEntries = data.entries;
|
||||
totalEntries = data.total;
|
||||
renderGrid();
|
||||
}
|
||||
|
||||
function goPage(p) { page = p; loadTrash(); }
|
||||
|
||||
async function restoreEntry(id) {
|
||||
const res = await fetch(`${API}/api/entries/${id}/restore`, { method: 'PUT', headers: hdr() });
|
||||
if (res.ok) { showToast('Запись восстановлена'); loadTrash(); }
|
||||
else { const err = await res.json(); alert(err.error || 'Ошибка'); }
|
||||
}
|
||||
|
||||
async function hardDelete(id) {
|
||||
if (!confirm('Удалить запись навсегда? Файлы и фото будут удалены безвозвратно.')) return;
|
||||
await fetch(`${API}/api/entries/${id}/permanent`, { method: 'DELETE', headers: hdr() });
|
||||
showToast('Запись удалена навсегда');
|
||||
loadTrash();
|
||||
}
|
||||
|
||||
async function emptyTrash() {
|
||||
if (totalEntries === 0) return;
|
||||
if (!confirm(`Удалить все записи из корзины (${totalEntries})? Файлы будут удалены безвозвратно.`)) return;
|
||||
const res = await fetch(`${API}/api/trash`, { method: 'DELETE', headers: hdr() });
|
||||
if (res.ok) { showToast('Корзина очищена'); page = 1; loadTrash(); }
|
||||
else { const err = await res.json(); alert(err.error || 'Ошибка'); }
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (await checkAuth()) {
|
||||
buildSidebar(document.body.dataset.page);
|
||||
loadTrash();
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -48,12 +48,45 @@ async function getSetting(key, def) {
|
||||
return rows.length ? rows[0].value : def;
|
||||
}
|
||||
|
||||
function removeUpload(file) {
|
||||
if (!file) return;
|
||||
const fp = path.join(__dirname, file.path);
|
||||
function safeUnlink(relPath) {
|
||||
if (!relPath) return;
|
||||
const fp = path.join(__dirname, String(relPath).replace(/^\/+/, ''));
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
}
|
||||
|
||||
function removeUpload(file) {
|
||||
safeUnlink(file && file.path);
|
||||
}
|
||||
|
||||
async function removeEntryFiles(entryId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT photo_path AS p FROM entries WHERE id = $1
|
||||
UNION ALL
|
||||
SELECT path AS p FROM project_files WHERE entry_id = $1`,
|
||||
[entryId]
|
||||
);
|
||||
rows.forEach(r => safeUnlink(r.p));
|
||||
}
|
||||
|
||||
async function sweepOrphanedUploads() {
|
||||
const dir = path.join(__dirname, 'uploads');
|
||||
if (!fs.existsSync(dir)) return;
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }] = await Promise.all([
|
||||
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT path AS p FROM project_files'),
|
||||
pool.query('SELECT photo_path AS p FROM group_photos'),
|
||||
]);
|
||||
const refs = new Set();
|
||||
[...photos, ...files, ...gphotos].forEach(r => refs.add('/' + String(r.p).replace(/^\/+/, '')));
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
const fp = path.join(dir, f);
|
||||
if (!fs.statSync(fp).isFile()) continue;
|
||||
if (!refs.has('/uploads/' + f)) {
|
||||
try { fs.unlinkSync(fp); } catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Settings ---
|
||||
app.get('/api/settings', requireAdmin, async (_, res) => {
|
||||
const { rows } = await pool.query('SELECT key, value FROM settings ORDER BY key');
|
||||
@@ -188,8 +221,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
}
|
||||
for (const x of data.entries) {
|
||||
await client.query(
|
||||
'INSERT INTO entries (id, student_name, group_id, description, photo_path, created_at) VALUES ($1,$2,$3,$4,$5,$6)',
|
||||
[x.id, x.student_name, x.group_id, x.description, x.photo_path ?? null, x.created_at]
|
||||
'INSERT INTO entries (id, student_name, group_id, description, photo_path, deleted_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
|
||||
[x.id, x.student_name, x.group_id, x.description, x.photo_path ?? null, x.deleted_at ?? null, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of data.project_files || []) {
|
||||
@@ -234,6 +267,7 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
}
|
||||
}
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -297,6 +331,7 @@ app.get('/api/share/:token', async (req, res) => {
|
||||
if (l.student_name) { params.push(l.student_name); conditions.push(`e.student_name = $${params.length}`); }
|
||||
if (l.date_from) { params.push(l.date_from); conditions.push(`e.created_at >= $${params.length}::date`); }
|
||||
if (l.date_to) { params.push(l.date_to); conditions.push(`e.created_at < ($${params.length}::date + interval '1 day')`); }
|
||||
conditions.push('e.deleted_at IS NULL');
|
||||
const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : '';
|
||||
const { rows: entries } = await pool.query(
|
||||
`SELECT e.*, g.name AS group_name FROM entries e
|
||||
@@ -312,6 +347,15 @@ app.get('/api/share/:token', async (req, res) => {
|
||||
fRes.rows.forEach(f => { (files[f.entry_id] = files[f.entry_id] || []).push({ token: f.token, name: f.name }); });
|
||||
}
|
||||
entries.forEach(r => { r.files = files[r.id] || []; });
|
||||
let photos = [];
|
||||
if (l.group_id) {
|
||||
const pRes = await pool.query(
|
||||
`SELECT id, photo_path, caption, taken_at, created_at FROM group_photos
|
||||
WHERE group_id = $1 ORDER BY taken_at DESC NULLS LAST, created_at DESC LIMIT 12`,
|
||||
[l.group_id]
|
||||
);
|
||||
photos = pRes.rows.map(r => ({ id: r.id, photo_path: r.photo_path, caption: r.caption, taken_at: r.taken_at, created_at: r.created_at }));
|
||||
}
|
||||
res.json({
|
||||
name: l.name,
|
||||
group_name: l.group_name,
|
||||
@@ -321,6 +365,7 @@ app.get('/api/share/:token', async (req, res) => {
|
||||
date_to: l.date_to,
|
||||
created_at: l.created_at,
|
||||
entries,
|
||||
photos,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -330,7 +375,16 @@ app.get('/s/:token', (req, res) => {
|
||||
|
||||
// --- Groups CRUD ---
|
||||
app.get('/api/groups', async (_, res) => {
|
||||
const { rows } = await pool.query('SELECT * FROM groups ORDER BY id');
|
||||
const { rows } = await pool.query(
|
||||
`SELECT g.*, gp.photo_path AS cover_path
|
||||
FROM groups g
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT photo_path FROM group_photos
|
||||
WHERE group_id = g.id
|
||||
ORDER BY taken_at DESC NULLS LAST, created_at DESC LIMIT 1
|
||||
) gp ON true
|
||||
ORDER BY g.id`
|
||||
);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
@@ -384,10 +438,73 @@ app.post('/api/groups', requireAdmin, async (req, res) => {
|
||||
});
|
||||
|
||||
app.delete('/api/groups/:id', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM group_photos WHERE group_id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
rows.forEach(r => safeUnlink(r.photo_path));
|
||||
await pool.query('DELETE FROM groups WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/groups/:id/photos', requireAdmin, async (req, res) => {
|
||||
const { limit, offset } = req.query;
|
||||
const { rows: crows } = await pool.query(
|
||||
'SELECT count(*)::int AS n FROM group_photos WHERE group_id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
const total = crows[0].n;
|
||||
let q = `SELECT * FROM group_photos WHERE group_id = $1
|
||||
ORDER BY taken_at DESC NULLS LAST, created_at DESC`;
|
||||
const qparams = [req.params.id];
|
||||
const lim = parseInt(limit, 10);
|
||||
if (lim > 0) { qparams.push(lim); q += ` LIMIT $${qparams.length}`; }
|
||||
const off = parseInt(offset, 10);
|
||||
if (off > 0) { qparams.push(off); q += ` OFFSET $${qparams.length}`; }
|
||||
const { rows } = await pool.query(q, qparams);
|
||||
res.json({ photos: rows, total });
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos', requireAdmin, upload.single('photo'), async (req, res) => {
|
||||
const { caption, taken_at } = req.body;
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO group_photos (group_id, photo_path, caption, taken_at)
|
||||
VALUES ($1, $2, $3, $4) RETURNING *`,
|
||||
[req.params.id, `/uploads/${req.file.filename}`, caption?.trim() || null, taken_at || null]
|
||||
);
|
||||
res.status(201).json(rows[0]);
|
||||
} catch (e) {
|
||||
safeUnlink(`uploads/${req.file.filename}`);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/groups/:id/photos/:photoId', requireAdmin, async (req, res) => {
|
||||
const { caption, taken_at } = req.body;
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE group_photos SET
|
||||
caption = $1,
|
||||
taken_at = $2
|
||||
WHERE id = $3 AND group_id = $4 RETURNING *`,
|
||||
[caption?.trim() || null, taken_at || null, req.params.photoId, req.params.id]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
res.json(rows[0]);
|
||||
});
|
||||
|
||||
app.delete('/api/groups/:id/photos/:photoId', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2',
|
||||
[req.params.photoId, req.params.id]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
safeUnlink(rows[0].photo_path);
|
||||
await pool.query('DELETE FROM group_photos WHERE id = $1', [req.params.photoId]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// --- Students CRUD ---
|
||||
app.get('/api/students', async (_, res) => {
|
||||
const { rows } = await pool.query(
|
||||
@@ -464,9 +581,11 @@ app.delete('/api/students/:id', requireAdmin, async (req, res) => {
|
||||
|
||||
// --- Entries ---
|
||||
app.get('/api/entries', requireAdmin, async (req, res) => {
|
||||
const { group_id, date_from, date_to, student_name, search, limit, offset } = req.query;
|
||||
const { group_id, date_from, date_to, student_name, search, limit, offset, deleted } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
if (deleted === '1') conditions.push('e.deleted_at IS NOT NULL');
|
||||
else conditions.push('e.deleted_at IS NULL');
|
||||
if (group_id) { params.push(group_id); conditions.push(`e.group_id = $${params.length}`); }
|
||||
if (date_from) { params.push(date_from); conditions.push(`e.created_at >= $${params.length}::date`); }
|
||||
if (date_to) { params.push(date_to); conditions.push(`e.created_at < ($${params.length}::date + interval '1 day')`); }
|
||||
@@ -518,6 +637,7 @@ app.get('/api/files', requireAdmin, async (req, res) => {
|
||||
const { search, student_name, group_id, date_from, date_to, limit, offset } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
conditions.push('e.deleted_at IS NULL');
|
||||
if (search) { params.push(`%${search}%`); conditions.push(`pf.name ILIKE $${params.length}`); }
|
||||
if (student_name) { params.push(student_name); conditions.push(`e.student_name = $${params.length}`); }
|
||||
if (group_id) { params.push(group_id); conditions.push(`e.group_id = $${params.length}`); }
|
||||
@@ -559,14 +679,16 @@ app.get('/api/files/:token', async (req, res) => {
|
||||
});
|
||||
|
||||
app.get('/api/stats', requireAdmin, async (_, res) => {
|
||||
const [entries, groups, students, today] = await Promise.all([
|
||||
pool.query('SELECT count(*)::int AS n FROM entries'),
|
||||
const [entries, trash, groups, students, today] = await Promise.all([
|
||||
pool.query('SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NULL'),
|
||||
pool.query('SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NOT NULL'),
|
||||
pool.query('SELECT count(*)::int AS n FROM groups'),
|
||||
pool.query('SELECT count(DISTINCT student_name)::int AS n FROM entries'),
|
||||
pool.query("SELECT count(*)::int AS n FROM entries WHERE created_at >= now()::date"),
|
||||
pool.query('SELECT count(DISTINCT student_name)::int AS n FROM entries WHERE deleted_at IS NULL'),
|
||||
pool.query("SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NULL AND created_at >= now()::date"),
|
||||
]);
|
||||
res.json({
|
||||
entries: entries.rows[0].n,
|
||||
trash: trash.rows[0].n,
|
||||
groups: groups.rows[0].n,
|
||||
students: students.rows[0].n,
|
||||
today: today.rows[0].n,
|
||||
@@ -647,27 +769,60 @@ app.put('/api/entries/:id', requireAdmin, async (req, res) => {
|
||||
});
|
||||
|
||||
app.delete('/api/entries/:id', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM entries WHERE id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
if (rows[0]?.photo_path) {
|
||||
const fp = path.join(__dirname, rows[0].photo_path);
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
}
|
||||
const fRes = await pool.query(
|
||||
'SELECT path FROM project_files WHERE entry_id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
for (const r of fRes.rows) {
|
||||
const fp = path.join(__dirname, r.path);
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
}
|
||||
await pool.query('DELETE FROM project_files WHERE entry_id = $1', [req.params.id]);
|
||||
await pool.query('UPDATE entries SET deleted_at = now() WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.put('/api/entries/:id/restore', requireAdmin, async (req, res) => {
|
||||
await pool.query('UPDATE entries SET deleted_at = NULL WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.delete('/api/entries/:id/permanent', requireAdmin, async (req, res) => {
|
||||
await removeEntryFiles(req.params.id);
|
||||
await pool.query('DELETE FROM entries WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/trash', requireAdmin, async (req, res) => {
|
||||
const { limit, offset } = req.query;
|
||||
const { rows: crows } = await pool.query(
|
||||
"SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NOT NULL"
|
||||
);
|
||||
const total = crows[0].n;
|
||||
let q = `SELECT e.*, g.name AS group_name FROM entries e
|
||||
JOIN groups g ON g.id = e.group_id
|
||||
WHERE e.deleted_at IS NOT NULL ORDER BY e.deleted_at DESC`;
|
||||
const qparams = [];
|
||||
const lim = parseInt(limit, 10);
|
||||
if (lim > 0) { qparams.push(lim); q += ` LIMIT $${qparams.length}`; }
|
||||
const off = parseInt(offset, 10);
|
||||
if (off > 0) { qparams.push(off); q += ` OFFSET $${qparams.length}`; }
|
||||
const { rows } = await pool.query(q, qparams);
|
||||
let files = {};
|
||||
if (rows.length) {
|
||||
const fRes = await pool.query(
|
||||
'SELECT entry_id, token, name FROM project_files WHERE entry_id = ANY($1) ORDER BY id',
|
||||
[rows.map(r => r.id)]
|
||||
);
|
||||
fRes.rows.forEach(f => { (files[f.entry_id] = files[f.entry_id] || []).push(f); });
|
||||
}
|
||||
rows.forEach(r => { r.files = files[r.id] || []; });
|
||||
res.json({ entries: rows, total });
|
||||
});
|
||||
|
||||
app.delete('/api/trash', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT photo_path AS p FROM entries WHERE deleted_at IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT pf.path AS p FROM project_files pf
|
||||
JOIN entries e ON e.id = pf.entry_id WHERE e.deleted_at IS NOT NULL`
|
||||
);
|
||||
rows.forEach(r => safeUnlink(r.p));
|
||||
const d = await pool.query('DELETE FROM entries WHERE deleted_at IS NOT NULL');
|
||||
res.json({ ok: true, deleted: d.rowCount });
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const HTTPS_PORT = process.env.HTTPS_PORT || 3443;
|
||||
|
||||
@@ -689,3 +844,5 @@ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
|
||||
} else {
|
||||
console.log('HTTPS: no certs found, skipping');
|
||||
}
|
||||
|
||||
sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
||||
|
||||
Reference in New Issue
Block a user