From 9a509fa7423c867ff903398ab0c108a8c4bcd762 Mon Sep 17 00:00:00 2001 From: dev Date: Sun, 1 Nov 2026 11:06:23 +0300 Subject: [PATCH] =?UTF-8?q?docs:=20=D0=B2=D0=BB=D0=BE=D0=B6=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D1=81=D1=82=D0=B0=D1=82=D0=B5=D0=B9=20(doc=5Ffi?= =?UTF-8?q?les),=20=D0=BF=D0=BE=D0=B4=D0=BF=D0=B8=D1=81=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D0=B1=D0=B8=D0=B1=D0=BB=D0=B8=D0=BE=D1=82=D0=B5=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=BA=D0=B0=D1=80=D1=82=D0=B8=D0=BD=D0=BE=D0=BA,=20=D0=B1?= =?UTF-8?q?=D1=8B=D1=81=D1=82=D1=80=D0=BE=D0=B5=20=D1=80=D0=B5=D0=B4.=20?= =?UTF-8?q?=D0=BE=D1=82=D0=B7=D1=8B=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backup-restore.js | 17 ++- db/migration.sql | 16 ++ lib/docs.js | 177 +++++++++++++++++++++- public/docs-public.html | 3 + public/docs.html | 55 +++++++ public/feedback.html | 36 +++++ public/js/docs.js | 327 +++++++++++++++++++++++++++++++++++++++- public/js/feedback.js | 86 ++++++++++- public/js/journal.js | 13 +- public/js/md.js | 7 +- public/js/trash.js | 9 +- server.js | 226 ++++++++++++++++++++++++++- 12 files changed, 947 insertions(+), 25 deletions(-) diff --git a/backup-restore.js b/backup-restore.js index 0526d8c..51ee23b 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -19,14 +19,14 @@ const BACKUP_TABLES = [ 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces', - 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', + 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', ]; const BACKUP_SEQUENCE_TABLES = [ 'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages', 'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces', - 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', + 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', ]; function isSupportedBackupVersion(data) { @@ -687,6 +687,17 @@ function normalizeRestoreData(data) { id: reqInt(x.id), article_id: x.article_id == null ? null : reqInt(x.article_id), path: optUploadPath(x.path, 300) || '', + caption: optText(x.caption, 300) || null, + uploaded_by: x.uploaded_by == null ? null : reqInt(x.uploaded_by), + created_at: optTs(x.created_at), + })).filter(x => x.path); + const docFiles = (data.doc_files || []).map(x => ({ + id: reqInt(x.id), + article_id: x.article_id == null ? null : reqInt(x.article_id), + name: optText(x.name, 300) || '', + path: optUploadPath(x.path, 300) || '', + size_bytes: x.size_bytes == null ? null : reqInt(x.size_bytes), + mime: optText(x.mime, 120) || null, uploaded_by: x.uploaded_by == null ? null : reqInt(x.uploaded_by), created_at: optTs(x.created_at), })).filter(x => x.path); @@ -713,7 +724,7 @@ function normalizeRestoreData(data) { created_at: optTs(x.created_at), updated_at: optTs(x.updated_at), })).filter(x => x.source_id && x.photo_path); - return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, bookmarks, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages }; + return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, bookmarks, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles }; } module.exports = { diff --git a/db/migration.sql b/db/migration.sql index 01352a5..0ff6f0a 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -944,6 +944,22 @@ CREATE TABLE IF NOT EXISTS doc_images ( CREATE INDEX IF NOT EXISTS idx_doc_images_article ON doc_images(article_id); CREATE INDEX IF NOT EXISTS idx_doc_images_path ON doc_images(path); +ALTER TABLE doc_images ADD COLUMN IF NOT EXISTS caption TEXT; + +CREATE TABLE IF NOT EXISTS doc_files ( + id SERIAL PRIMARY KEY, + article_id INT REFERENCES doc_articles(id) ON DELETE CASCADE, + name TEXT NOT NULL, + path TEXT NOT NULL, + size_bytes BIGINT, + mime TEXT, + uploaded_by INT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_doc_files_article ON doc_files(article_id); +CREATE INDEX IF NOT EXISTS idx_doc_files_path ON doc_files(path); + CREATE TABLE IF NOT EXISTS achievement_types ( id SERIAL PRIMARY KEY, name VARCHAR(150) NOT NULL, diff --git a/lib/docs.js b/lib/docs.js index 812d5f2..ccbedcc 100644 --- a/lib/docs.js +++ b/lib/docs.js @@ -407,11 +407,25 @@ async function ensureDocsTables(pool) { id SERIAL PRIMARY KEY, article_id INT REFERENCES doc_articles(id) ON DELETE CASCADE, path TEXT NOT NULL, + caption TEXT, uploaded_by INT REFERENCES users(id) ON DELETE SET NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() )`); + await pool.query('ALTER TABLE doc_images ADD COLUMN IF NOT EXISTS caption TEXT'); await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_images_article ON doc_images(article_id)'); await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_images_path ON doc_images(path)'); + await pool.query(`CREATE TABLE IF NOT EXISTS doc_files ( + id SERIAL PRIMARY KEY, + article_id INT REFERENCES doc_articles(id) ON DELETE CASCADE, + name TEXT NOT NULL, + path TEXT NOT NULL, + size_bytes BIGINT, + mime TEXT, + uploaded_by INT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + )`); + await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_files_article ON doc_files(article_id)'); + await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_files_path ON doc_files(path)'); const { rows } = await pool.query('SELECT 1 FROM doc_sections LIMIT 1'); if (rows.length) { await refreshDefaultArticleBodies(pool); @@ -810,8 +824,9 @@ async function deleteArticle(pool, user, id) { throw httpError(403, 'Нет прав на удаление этой статьи'); } const images = await pool.query('SELECT path FROM doc_images WHERE article_id = $1', [id]); + const files = await pool.query('SELECT path FROM doc_files WHERE article_id = $1', [id]); await pool.query('DELETE FROM doc_articles WHERE id = $1', [id]); - return images.rows.map(r => r.path); + return images.rows.map(r => r.path).concat(files.rows.map(r => r.path)); } async function reorderArticles(pool, sectionId, ids) { @@ -842,6 +857,155 @@ async function registerImage(pool, { path, userId }) { return rows[0]; } +async function listDocImages(pool, user, articleId) { + if (articleId == null) { + const { rows } = await pool.query( + `SELECT id, article_id, path, caption, uploaded_by, created_at FROM doc_images + WHERE article_id IS NULL AND ($1::boolean OR uploaded_by = $2) + ORDER BY created_at DESC`, + [user.role === 'admin', user.id] + ); + return rows; + } + const { rows } = await pool.query( + `SELECT id, article_id, path, caption, uploaded_by, created_at FROM doc_images + WHERE article_id = $1 ORDER BY created_at DESC`, + [articleId] + ); + return rows; +} + +async function deleteDocImage(pool, user, id) { + const { rows } = await pool.query('SELECT * FROM doc_images WHERE id = $1', [reqInt(id)]); + if (!rows.length) throw httpError(404, 'Изображение не найдено'); + const current = rows[0]; + if (user.role !== 'admin' && current.uploaded_by !== user.id) throw httpError(403, 'Нет прав'); + if (current.article_id != null) { + const article = await getArticle(pool, user, String(current.article_id)); + if (!article.can_edit) throw httpError(403, 'Нет прав на редактирование статьи'); + } + await pool.query('DELETE FROM doc_images WHERE id = $1', [id]); + return current.path; +} + +async function updateDocImageCaption(pool, user, id, caption) { + const { rows } = await pool.query('SELECT * FROM doc_images WHERE id = $1', [reqInt(id)]); + if (!rows.length) throw httpError(404, 'Изображение не найдено'); + const current = rows[0]; + if (user.role !== 'admin' && current.uploaded_by !== user.id) throw httpError(403, 'Нет прав'); + const cap = (caption == null ? '' : String(caption)).trim().slice(0, 300); + const newCaption = cap || null; + await pool.query('UPDATE doc_images SET caption = $1 WHERE id = $2', [newCaption, id]); + let updatedBody = null; + if (current.article_id != null) { + const article = await getArticle(pool, user, String(current.article_id)); + if (article.can_edit) { + const path = current.path; + const escPath = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const re = new RegExp('!\\[[^\\]]*\\]\\(' + escPath + '(?:\\s+"[^"]*")?\\)', 'g'); + const replacement = () => newCaption ? '![' + newCaption + '](' + path + ')' : '![](' + path + ')'; + const newBody = String(article.body || '').replace(re, replacement); + if (newBody !== article.body) { + await pool.query('UPDATE doc_articles SET body = $1, updated_at = now() WHERE id = $2', [newBody, current.article_id]); + updatedBody = newBody; + } + } + } + return { path: current.path, article_id: current.article_id, caption: newCaption, body: updatedBody }; +} + +async function listAllDocImages(pool, user) { + const { rows } = await pool.query( + `SELECT id, article_id, path, uploaded_by, created_at FROM doc_images ORDER BY created_at DESC` + ); + return rows; +} + +async function listAllDocFiles(pool, user) { + const { rows } = await pool.query( + `SELECT id, article_id, name, path, size_bytes, mime, uploaded_by, created_at FROM doc_files ORDER BY created_at DESC` + ); + return rows; +} + +async function registerFile(pool, { path, name, size, mime, userId, articleId = null }) { + const { rows } = await pool.query( + `INSERT INTO doc_files (article_id, name, path, size_bytes, mime, uploaded_by) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, article_id, name, path, size_bytes, mime, uploaded_by, created_at`, + [articleId, name, path, size || null, mime || null, userId] + ); + return rows[0]; +} + +async function listDocFiles(pool, user, articleId) { + const article = await getArticle(pool, user, String(articleId)); + const { rows } = await pool.query( + `SELECT id, article_id, name, path, size_bytes, mime, uploaded_by, created_at + FROM doc_files WHERE article_id = $1 ORDER BY created_at DESC`, + [article.id] + ); + return rows; +} + +async function listUnattachedDocFiles(pool, user) { + const { rows } = await pool.query( + `SELECT id, article_id, name, path, size_bytes, mime, uploaded_by, created_at + FROM doc_files WHERE article_id IS NULL AND ($1::boolean OR uploaded_by = $2) + ORDER BY created_at DESC`, + [user.role === 'admin', user.id] + ); + return rows; +} + +async function attachDocFile(pool, user, fileId, articleId) { + const id = reqInt(fileId); + const { rows: frows } = await pool.query('SELECT * FROM doc_files WHERE id = $1', [id]); + if (!frows.length) throw httpError(404, 'Файл не найден'); + const file = frows[0]; + if (articleId == null) { + if (user.role !== 'admin' && file.uploaded_by !== user.id) throw httpError(403, 'Нет прав'); + await pool.query('UPDATE doc_files SET article_id = NULL WHERE id = $1', [id]); + return { ...file, article_id: null }; + } + const article = await getArticle(pool, user, String(articleId)); + if (!article.can_edit) throw httpError(403, 'Нет прав на редактирование статьи'); + await pool.query('UPDATE doc_files SET article_id = $1 WHERE id = $2', [article.id, id]); + return { ...file, article_id: article.id }; +} + +async function replaceDocFile(pool, user, fileId, { path, name, size, mime }) { + const id = reqInt(fileId); + const { rows } = await pool.query('SELECT * FROM doc_files WHERE id = $1', [id]); + if (!rows.length) throw httpError(404, 'Файл не найден'); + const current = rows[0]; + if (user.role !== 'admin' && current.uploaded_by !== user.id) throw httpError(403, 'Нет прав на замену файла'); + if (current.article_id != null) { + const article = await getArticle(pool, user, String(current.article_id)); + if (!article.can_edit) throw httpError(403, 'Нет прав на редактирование статьи'); + } + const { rows: upd } = await pool.query( + `UPDATE doc_files SET path = $1, name = $2, size_bytes = $3, mime = $4 WHERE id = $5 + RETURNING id, article_id, name, path, size_bytes, mime, uploaded_by, created_at`, + [path, name, size || null, mime || null, id] + ); + return { item: upd[0], oldPath: current.path }; +} + +async function deleteDocFile(pool, user, fileId) { + const id = reqInt(fileId); + const { rows } = await pool.query('SELECT * FROM doc_files WHERE id = $1', [id]); + if (!rows.length) throw httpError(404, 'Файл не найден'); + const current = rows[0]; + if (user.role !== 'admin' && current.uploaded_by !== user.id) throw httpError(403, 'Нет прав на удаление файла'); + if (current.article_id != null) { + const article = await getArticle(pool, user, String(current.article_id)); + if (!article.can_edit) throw httpError(403, 'Нет прав на редактирование статьи'); + } + await pool.query('DELETE FROM doc_files WHERE id = $1', [id]); + return current.path; +} + async function searchArticles(pool, user, query) { const q = String(query || '').trim(); if (!q || q.length < 2) return []; @@ -943,6 +1107,17 @@ module.exports = { deleteArticle, reorderArticles, registerImage, + listDocImages, + deleteDocImage, + updateDocImageCaption, + listAllImages: listAllDocImages, + listAllFiles: listAllDocFiles, + registerFile, + listDocFiles, + listUnattachedDocFiles, + attachDocFile, + replaceDocFile, + deleteDocFile, searchArticles, publicTree, publicArticle, diff --git a/public/docs-public.html b/public/docs-public.html index 5c5b1a8..f28c291 100644 --- a/public/docs-public.html +++ b/public/docs-public.html @@ -116,6 +116,9 @@ .dp-side { position: static; max-height: none; } .dp-article { padding: 20px 16px; } } + .md-figure { margin: 6px 0; text-align: center; } + .md-figure img { max-width: 100%; border-radius: 10px; border: 1px solid var(--border); cursor: zoom-in; } + .md-figure figcaption { font-size: .82rem; color: var(--muted); margin-top: 4px; font-style: italic; } diff --git a/public/docs.html b/public/docs.html index 2e1b19c..0e4ffb8 100644 --- a/public/docs.html +++ b/public/docs.html @@ -183,6 +183,33 @@ .docs-side { position: static; max-height: none; } .docs-article { padding: 20px 16px; } } + .docs-files { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; } + .docs-files-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; } + .docs-files-title { font-weight: 700; font-size: .9rem; } + .docs-files-actions { display: flex; gap: 6px; flex-wrap: wrap; } + .docs-files-hint { font-size: .78rem; color: var(--muted); } + .docs-files-table-wrap { overflow: auto; } + .docs-files-table { width: 100%; border-collapse: collapse; font-size: .82rem; } + .docs-files-table th, .docs-files-table td { border: 1px solid var(--border); padding: 6px 8px; text-align: left; vertical-align: middle; } + .docs-files-table th { background: rgba(127,127,127,.09); font-weight: 600; } + .docs-files-acts { display: flex; gap: 4px; flex-wrap: wrap; } + .docs-files-acts button { padding: 3px 8px; font-size: .75rem; } + .docs-attachments { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--border); } + .docs-attachments-title { font-weight: 700; font-size: .9rem; margin-bottom: 6px; } + .docs-attachments-list { margin: 0; padding-left: 18px; } + .docs-attachments-list li { margin: 0 0 4px; font-size: .9rem; } + .docs-attach-size { color: var(--muted); font-size: .78rem; margin-left: 6px; } + .docs-imglib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; max-height: 420px; overflow: auto; padding: 4px 0; } + .docs-imglib-item { border: 1px solid var(--border); border-radius: 8px; padding: 4px; cursor: pointer; background: var(--bg); } + .docs-imglib-item:hover { border-color: var(--accent); } + .docs-imglib-item img { width: 100%; height: 90px; object-fit: cover; border-radius: 6px; display: block; } + .docs-imglib-name { font-size: .72rem; color: var(--muted); margin-top: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .docs-caption-row { display: flex; gap: 4px; margin-top: 4px; } + .docs-caption-input { flex: 1; font-size: .75rem; padding: 3px 6px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } + .docs-caption-row button { padding: 3px 8px; font-size: .75rem; } + .md-figure { margin: 6px 0; text-align: center; } + .md-figure img { max-width: 100%; border-radius: 10px; border: 1px solid var(--border); cursor: zoom-in; } + .md-figure figcaption { font-size: .82rem; color: var(--muted); margin-top: 4px; font-style: italic; } @@ -237,6 +264,7 @@ +
@@ -244,7 +272,25 @@
+
+
+ Вложения +
+ + + +
+
+
Файлы, прикреплённые к статье. Вставить в текст — кнопка «Вставить» вставляет ссылку в Markdown.
+
+ + + +
ИмяРазмерСтатусДействия
+
+
+ @@ -277,6 +323,15 @@
+ diff --git a/public/feedback.html b/public/feedback.html index b026120..1f31dbd 100644 --- a/public/feedback.html +++ b/public/feedback.html @@ -61,6 +61,8 @@ .fb-resident-photo img { width:100%; height:100%; object-fit:cover; display:block; } #fbPromptModal { overflow:auto; align-items:flex-start; padding:4vh 16px; } #fbPromptModal > .edit-modal { margin:auto; } + #fbQuickModal { z-index:105; } + #fbImgbbModal { z-index:110; } .feedback-item { position:relative; } .feedback-item.fb-ai-made { background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 130 100'%3E%3Ctext x='128' y='92' text-anchor='end' font-family='Arial,Helvetica,sans-serif' font-weight='800' font-size='104' fill='%23808080' fill-opacity='0.1'%3EAI%3C/text%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 6px bottom 2px; background-size:auto 148px; } .fb-author { display:inline-flex; align-items:center; gap:6px; min-width:0; font-size:.78rem; color:var(--muted); border:1px solid var(--border); border-radius:999px; background:rgba(127,127,127,.08); padding:2px 10px 2px 2px; } @@ -88,6 +90,12 @@ .fb-works .fb-work-files .fb-work-thumb img { display:block; width:56px; height:56px; object-fit:cover; border-radius:8px; cursor:zoom-in; } .fb-works .fb-work-files .fb-work-file { flex:none; max-width:none; font-size:12px; line-height:1.3; color:var(--accent); text-decoration:underline; white-space:nowrap; } .fb-works-empty { font-size:.83rem; color:var(--muted); } + .fb-quick-head { display:flex; align-items:center; gap:12px; } + .fb-quick-head .fb-card-photo { cursor:pointer; } + .fb-quick-meta { min-width:0; } + .fb-quick-resident { font-weight:600; font-size:1.05rem; overflow-wrap:anywhere; } + .fb-quick-topic { font-size:.9rem; color:var(--text); margin-top:2px; overflow-wrap:anywhere; } + .fb-quick-date { font-size:.82rem; color:var(--muted); margin-top:2px; } @@ -331,6 +339,34 @@ + + diff --git a/public/js/docs.js b/public/js/docs.js index e2fe706..c4a0cf6 100644 --- a/public/js/docs.js +++ b/public/js/docs.js @@ -13,6 +13,11 @@ const hintEl = el('docsEditHint'); const searchEl = el('docsSearch'); const imageFileEl = el('docsImageFile'); + const fileInputEl = el('docsFileInput'); + const filesBodyEl = el('docsFilesBody'); + const filesPanelEl = el('docsFilesPanel'); + const imgLibModal = el('docsImageLibModal'); + const imgLibGrid = el('docsImgLibGrid'); const sectionModal = el('docsSectionModal'); const sectionTitleEl = el('docsSectionTitle'); const sectionParentEl = el('docsSectionParent'); @@ -182,6 +187,10 @@
${meta.join('')}
${actions.join('')}
${WhatIDoMD.render(article.body)}
+ ${(article.files && article.files.length) ? `
+
Вложения
+ +
` : ''} `; } @@ -203,6 +212,10 @@ if (editState && editState.dirty && !confirm('Несохранённые изменения будут потеряны. Продолжить?')) return; const data = await req('/api/docs/articles/' + encodeURIComponent(slug)); current = data.item; + try { + const fdata = await req('/api/docs/articles/' + current.id + '/files'); + current.files = fdata.items || []; + } catch (e) { current.files = []; } editState = null; if (updateHash !== false) history.replaceState(null, '', '#a=' + encodeURIComponent(current.slug)); renderArticle(); @@ -246,7 +259,8 @@ showToast('Нет разделов, где вам разрешено писать', true); return; } - editState = { id: article ? article.id : null, dirty: false }; + editState = { id: article ? article.id : null, dirty: false, files: [] }; + if (article && article.id) loadDocFiles(article.id); else renderDocFilesTable(); titleEl.value = article ? article.title : ''; bodyEl.value = article ? article.body : ''; publishedEl.checked = article ? article.is_published : true; @@ -290,6 +304,7 @@ is_public: isAdmin() ? publicEl.checked : false, }; const saveBtn = el('docsSaveBtn'); + const pendingFileIds = (editState && editState.files ? editState.files : []).filter(f => !f.article_id).map(f => f.id); saveBtn.disabled = true; try { const path = editState.id ? '/api/docs/articles/' + editState.id : '/api/docs/articles'; @@ -297,6 +312,9 @@ const data = await req(path, { method, body: JSON.stringify(payload) }); editState.dirty = false; closeEditor(); + for (const fid of pendingFileIds) { + try { await req('/api/docs/files/' + fid + '/attach', { method: 'PUT', body: JSON.stringify({ article_id: data.item.id }) }); } catch (e) {} + } await loadTree(); await openArticle(data.item.slug); showToast('Статья сохранена'); @@ -401,6 +419,223 @@ } } + function fmtBytes(n) { + n = Number(n) || 0; + if (n < 1024) return n + ' Б'; + if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' КБ'; + return (n / (1024 * 1024)).toFixed(1) + ' МБ'; + } + + async function loadDocFiles(articleId) { + if (!editState) return; + if (!articleId) { + // unsaved article: show unattached files + unattached images + try { + const [fdata, idata] = await Promise.all([ + req('/api/docs/files/unattached'), + req('/api/docs/images/unattached'), + ]); + const files = (fdata.items || []).map(x => Object.assign({}, x, { _kind: 'file', _unattached: true })); + const images = (idata.items || []).map(x => Object.assign({}, x, { _kind: 'image', name: (x.path || '').split('/').pop(), size_bytes: null, mime: 'image/*', _unattached: true })); + editState.files = files.concat(images); + renderDocFilesTable(); + } catch (e) { + editState.files = []; + renderDocFilesTable(); + } + return; + } + try { + const [fdata, idata] = await Promise.all([ + req('/api/docs/articles/' + articleId + '/files'), + req('/api/docs/articles/' + articleId + '/images'), + ]); + const files = (fdata.items || []).map(x => Object.assign({}, x, { _kind: 'file' })); + const images = (idata.items || []).map(x => Object.assign({}, x, { _kind: 'image', name: (x.path || '').split('/').pop(), size_bytes: null, mime: 'image/*' })); + editState.files = files.concat(images); + renderDocFilesTable(); + } catch (e) { + editState.files = []; + renderDocFilesTable(); + } + } + + function docFileStatus(f) { + const body = bodyEl.value || ''; + const used = body.indexOf(f.path) !== -1; + if (used) return 'В тексте'; + if (f.article_id) return 'Прикреплён'; + return 'Не привязан'; + } + + function renderDocFilesTable() { + if (!filesBodyEl) return; + const files = (editState && editState.files) || []; + if (!files.length) { + filesBodyEl.innerHTML = 'Вложений пока нет'; + return; + } + filesBodyEl.innerHTML = files.map(f => { + const isImg = f._kind === 'image'; + const thumb = isImg ? `` : ''; + const acts = f._unattached + ? (isImg + ? `` + : ` + `) + : (isImg + ? ` + ` + : ` + + + `); + const status = isImg ? 'Картинка' : (f._unattached ? 'Не привязан' : docFileStatus(f)); + const captionInput = isImg ? `
` : ''; + return ` + ${thumb}${esc(f.name)}${captionInput} + ${isImg ? '—' : fmtBytes(f.size_bytes)} + ${status} + ${acts} + `; + }).join(''); + } + + async function uploadDocFile(file, articleId) { + if (!file) return; + showToast('Загрузка файла...'); + try { + const form = new FormData(); + form.append('file', file); + if (articleId) form.append('article_id', String(articleId)); + const data = await req('/api/docs/files', { method: 'POST', body: form }); + if (editState) { + editState.files = editState.files || []; + editState.files.unshift(data.item); + renderDocFilesTable(); + } + showToast('Файл прикреплён'); + } catch (e) { + showToast(e.message, true); + } + } + + async function replaceDocFile(id) { + const input = document.createElement('input'); + input.type = 'file'; + input.onchange = async () => { + const file = input.files && input.files[0]; + if (!file) return; + showToast('Замена файла...'); + try { + const form = new FormData(); + form.append('file', file); + const data = await req('/api/docs/files/' + id + '/replace', { method: 'POST', body: form }); + const old = (editState.files || []).find(f => Number(f.id) === Number(id)); + if (old && old.path && data.item.path && bodyEl.value.indexOf(old.path) !== -1) { + bodyEl.value = bodyEl.value.split(old.path).join(data.item.path); + markDirty(); + updatePreview(); + } + if (editState) { + editState.files = (editState.files || []).map(f => Number(f.id) === Number(id) ? data.item : f); + renderDocFilesTable(); + } + showToast('Файл заменён'); + } catch (e) { + showToast(e.message, true); + } + }; + input.click(); + } + + async function detachDocFile(id) { + if (!confirm('Открепить файл от статьи?')) return; + try { + const data = await req('/api/docs/files/' + id + '/attach', { method: 'PUT', body: JSON.stringify({ article_id: null }) }); + if (editState) { + editState.files = (editState.files || []).filter(f => Number(f.id) !== Number(id)); + renderDocFilesTable(); + } + showToast('Файл откреплён'); + } catch (e) { + showToast(e.message, true); + } + } + + async function deleteDocFile(id) { + if (!confirm('Удалить файл без возможности восстановления?')) return; + try { + await req('/api/docs/files/' + id, { method: 'DELETE' }); + if (editState) { + editState.files = (editState.files || []).filter(f => Number(f.id) !== Number(id)); + renderDocFilesTable(); + } + showToast('Файл удалён'); + } catch (e) { + showToast(e.message, true); + } + } + + function isImageFile(f) { + const mime = String(f.mime || '').toLowerCase(); + if (mime.startsWith('image/')) return true; + return /\.(jpe?g|png|gif|webp|bmp|avif|ico|jfif)$/i.test(String(f.name || f.path || '')); + } + function insertDocFileLink(f) { + const md = isImageFile(f) ? `![${f.name}](${f.path})` : `[${f.name}](${f.path})`; + insertBlock(md); + } + + async function loadUnattachedDocFiles() { + try { + const data = await req('/api/docs/files/unattached'); + const items = data.items || []; + if (!items.length) { showToast('Нет незагруженных файлов', true); return; } + const prev = (editState && editState.files) || []; + const merged = prev.concat(items.map(x => Object.assign({}, x, { _unattached: true }))); + if (editState) { editState.files = merged; renderDocFilesTable(); } + } catch (e) { + showToast(e.message, true); + } + } + + async function openImageLibrary() { + if (!imgLibModal || !imgLibGrid) return; + imgLibGrid.innerHTML = '
Загрузка...
'; + imgLibModal.classList.add('open'); + try { + const data = await req('/api/docs/images'); + const items = data.items || []; + if (!items.length) { + imgLibGrid.innerHTML = '
Изображений пока нет
'; + return; + } + imgLibGrid.innerHTML = items.map(it => ` +
+ +
${esc(it.path.split('/').pop())}
+
`).join(''); + } catch (e) { + imgLibGrid.innerHTML = '
' + esc(e.message) + '
'; + } + } + + async function loadAllDocFiles() { + try { + const data = await req('/api/docs/files'); + const items = (data.items || []).map(x => Object.assign({}, x, { _all: true })); + if (editState) { + // mark which are attached to current article + const curId = editState.id; + editState.files = items.map(x => Object.assign({}, x, { _unattached: !x.article_id || Number(x.article_id) !== Number(curId) })); + renderDocFilesTable(); + } + } catch (e) { + showToast(e.message, true); + } + } + function fillParentSelect(excludeId, selectedId) { const list = sectionList().filter(s => Number(s.id) !== Number(excludeId)); sectionParentEl.innerHTML = '' + list.map(s => { @@ -623,6 +858,96 @@ imageFileEl.value = ''; if (file) await uploadImage(file); }); + if (fileInputEl) fileInputEl.addEventListener('change', async () => { + const files = [...(fileInputEl.files || [])]; + fileInputEl.value = ''; + const aid = editState && editState.id ? editState.id : null; + for (const f of files) await uploadDocFile(f, aid); + if (aid) await loadDocFiles(aid); + }); + const uploadBtn = el('docsFileUploadBtn'); + if (uploadBtn) uploadBtn.addEventListener('click', () => fileInputEl && fileInputEl.click()); + const pickerBtn = el('docsFilePickerBtn'); + if (pickerBtn) pickerBtn.addEventListener('click', async () => { + if (!editState || !editState.id) { showToast('Сначала сохраните статью', true); return; } + await loadUnattachedDocFiles(); + }); + const allBtn = el('docsFileAllBtn'); + if (allBtn) allBtn.addEventListener('click', async () => { + if (!editState || !editState.id) { showToast('Сначала сохраните статью', true); return; } + await loadAllDocFiles(); + }); + const libBtn = el('docsImgLibBtn'); + if (libBtn) libBtn.addEventListener('click', () => openImageLibrary()); + const libClose = el('docsImgLibClose'); + if (libClose) libClose.addEventListener('click', () => imgLibModal && imgLibModal.classList.remove('open')); + if (imgLibModal) imgLibModal.addEventListener('click', e => { if (e.target === imgLibModal) imgLibModal.classList.remove('open'); }); + if (imgLibGrid) imgLibGrid.addEventListener('click', e => { + const item = e.target.closest('.docs-imglib-item'); + if (!item) return; + const p = item.dataset.imgPath; + if (!p) return; + const name = p.split('/').pop().replace(/\.[^.]+$/, ''); + insertBlock(`![${name}](${p})`); + if (imgLibModal) imgLibModal.classList.remove('open'); + showToast('Картинка вставлена'); + }); + if (filesBodyEl) filesBodyEl.addEventListener('click', e => { + const btn = e.target.closest('[data-file-act]'); + if (!btn) return; + const tr = btn.closest('tr'); + const id = tr && tr.dataset.fileId; + if (!id) return; + const act = btn.dataset.fileAct; + const f = (editState.files || []).find(x => String(x.id) === String(id)); + if (act === 'insert' && f) insertDocFileLink(f); + if (act === 'caption') { + const input = tr.querySelector('.docs-caption-input'); + const val = input ? input.value : ''; + req('/api/docs/images/' + id, { method: 'PUT', body: JSON.stringify({ caption: val }) }) + .then(data => { + if (editState) { + editState.files = (editState.files || []).map(x => String(x.id) === String(id) && x._kind === 'image' ? Object.assign({}, x, { caption: data.item.caption }) : x); + renderDocFilesTable(); + } + if (data.item.body && editState) { + bodyEl.value = data.item.body; + markDirty(); + updatePreview(); + } + showToast('Подпись сохранена'); + }).catch(err => showToast(err.message, true)); + return; + } + if (act === 'replace') replaceDocFile(id); + if (act === 'detach') detachDocFile(id); + if (act === 'delete') { + const kind = tr.dataset.fileKind || (f && f._kind) || 'file'; + if (kind === 'image') { + req('/api/docs/images/' + id, { method: 'DELETE' }) + .then(() => { + if (editState) { + editState.files = (editState.files || []).filter(x => !(String(x.id) === String(id) && x._kind === 'image')); + renderDocFilesTable(); + } + showToast('Изображение удалено'); + }).catch(err => showToast(err.message, true)); + } else { + deleteDocFile(id); + } + } + if (act === 'attach') { + if (!editState || !editState.id) { showToast('Сначала сохраните статью', true); return; } + req('/api/docs/files/' + id + '/attach', { method: 'PUT', body: JSON.stringify({ article_id: editState.id }) }) + .then(data => { + if (editState) { + editState.files = (editState.files || []).map(x => String(x.id) === String(id) ? data.item : x).filter(x => x.article_id); + renderDocFilesTable(); + } + showToast('Файл прикреплён'); + }).catch(err => showToast(err.message, true)); + } + }); el('docsSaveBtn').addEventListener('click', saveArticle); el('docsCancelBtn').addEventListener('click', cancelEdit); } diff --git a/public/js/feedback.js b/public/js/feedback.js index aa472e0..c915de7 100644 --- a/public/js/feedback.js +++ b/public/js/feedback.js @@ -43,6 +43,7 @@ const actions = canWrite ? `${hasAiInfo ? `` : ''} ${f.ai_status === 'error' ? `` : ''} ${f.deleted_at ? '' : ``} + ${aiMade ? `` : ''} ${f.deleted_at ? `` : ''}` : ''; @@ -646,8 +647,10 @@ } let fbImgbbSelected = null; - async function openImgbbPicker() { - const resident = document.getElementById('fbResident').value.trim(); + let fbImgbbTextBox = 'fbText'; + async function openImgbbPicker(textId, residentName) { + fbImgbbTextBox = textId || 'fbText'; + const resident = residentName != null ? String(residentName) : document.getElementById('fbResident').value.trim(); const inp = document.getElementById('fbImgbbResident'); const list = document.getElementById('fbImgbbList'); const empty = document.getElementById('fbImgbbEmpty'); @@ -933,6 +936,72 @@ } catch (e) {} } + let quickFeedback = null; + + function setQuickTextHint() { + const ta = document.getElementById('fbQuickText'); + const hint = document.getElementById('fbQuickTextHint'); + if (ta && hint) hint.textContent = `${ta.value.length} / 5000`; + } + + async function openQuickModal(id) { + const m = document.getElementById('fbQuickModal'); + const f = feedbacks.find(x => x.id === id); + if (!m || !f) return; + quickFeedback = f; + m.classList.add('open'); + try { await loadStudentPhotos(); } catch (e) {} + const wrap = document.getElementById('fbQuickPhotoWrap'); + if (wrap) wrap.innerHTML = cardResidentPhoto(f.resident); + const res = document.getElementById('fbQuickResident'); + if (res) res.textContent = f.resident || 'Резидент не указан'; + const topic = document.getElementById('fbQuickTopic'); + if (topic) { topic.textContent = f.topic || ''; topic.hidden = !f.topic; } + const date = document.getElementById('fbQuickDate'); + if (date) date.textContent = fmtDate(f.feedback_date); + const ta = document.getElementById('fbQuickText'); + if (ta) ta.value = f.text || ''; + setQuickTextHint(); + if (window.lucide) lucide.createIcons(); + } + + function closeQuickModal() { + const m = document.getElementById('fbQuickModal'); + if (m) m.classList.remove('open'); + quickFeedback = null; + } + + async function saveQuickFeedback() { + if (!quickFeedback) return; + const ta = document.getElementById('fbQuickText'); + if (!ta) return; + const id = quickFeedback.id; + const body = { + feedback_date: quickFeedback.feedback_date || todayIso(), + group_id: quickFeedback.group_id, + resident: quickFeedback.resident || '', + topic: quickFeedback.topic || '', + past_review: quickFeedback.past_review || null, + text: ta.value.trim(), + ai_check: false, + ai_profile: quickFeedback.ai_profile || null, + short_message_ids: Array.isArray(quickFeedback.short_message_ids) ? quickFeedback.short_message_ids : [], + }; + const btn = document.getElementById('fbQuickSave'); + const prev = btn ? btn.textContent : ''; + try { + if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; } + const r = await fetch(`${API}/api/feedbacks/${id}`, { method: 'PUT', headers: {...hdr(), 'Content-Type':'application/json'}, body: JSON.stringify(body) }); + if (r.ok) { closeQuickModal(); loadFeedbacks(); return; } + const err = await r.json().catch(() => null); + alert((err && err.error) || `Ошибка ${r.status}`); + } catch (e) { + alert('Ошибка сети'); + } finally { + if (btn) { btn.disabled = false; btn.textContent = prev; } + } + } + async function loadFeedbacks() { const el = document.getElementById('feedbackList'); const st = document.getElementById('feedbackState'); @@ -1098,14 +1167,14 @@ document.getElementById('fbPastReviewWrap').style.display = e.target.checked ? '' : 'none'; if (e.target.checked) loadLastPastReview(); }); - document.getElementById('fbImgbbBtn').addEventListener('click', () => openImgbbPicker()); + document.getElementById('fbImgbbBtn').addEventListener('click', () => openImgbbPicker('fbText')); document.getElementById('fbImgbbModalClose').addEventListener('click', closeImgbbPicker); document.getElementById('fbImgbbModal').addEventListener('click', e => { if (e.target.id === 'fbImgbbModal') closeImgbbPicker(); }); document.getElementById('fbImgbbModalCancel').addEventListener('click', closeImgbbPicker); document.getElementById('fbImgbbModalOk').addEventListener('click', async () => { if (!fbImgbbSelected) return; - const text = document.getElementById('fbText'); - const hint = document.getElementById('fbTextHint'); + const text = document.getElementById(fbImgbbTextBox); + const hint = document.getElementById(fbImgbbTextBox + 'Hint'); const ok = document.getElementById('fbImgbbModalOk'); const btn = document.getElementById('fbImgbbBtn'); if (!window.WhatIDoImgBB || !window.WhatIDoImgBB.configured()) { @@ -1132,6 +1201,12 @@ document.getElementById('fbText').addEventListener('input', () => { document.getElementById('fbTextHint').textContent = `${document.getElementById('fbText').value.length} / 5000`; }); + document.getElementById('fbQuickClose').addEventListener('click', closeQuickModal); + document.getElementById('fbQuickCancel').addEventListener('click', closeQuickModal); + document.getElementById('fbQuickModal').addEventListener('click', e => { if (e.target.id === 'fbQuickModal') closeQuickModal(); }); + document.getElementById('fbQuickSave').addEventListener('click', saveQuickFeedback); + document.getElementById('fbQuickImgbbBtn').addEventListener('click', () => openImgbbPicker('fbQuickText', quickFeedback ? quickFeedback.resident : '')); + document.getElementById('fbQuickText').addEventListener('input', setQuickTextHint); document.getElementById('fbTopic').addEventListener('change', applyTopicText); document.getElementById('feedbackList').addEventListener('click', async e => { const aiinfo = e.target.closest('[data-aiinfo]'); if (aiinfo) { @@ -1147,6 +1222,7 @@ try { const r = await fetch(`${API}/api/feedbacks/${id}/sent`, { method:'PUT', headers: {...hdr(), 'Content-Type':'application/json'}, body: JSON.stringify({ sent: next }) }); if (r.ok) loadFeedbacks(); } catch (e) {} return; } + const quickBtn = e.target.closest('[data-quick]'); if (quickBtn) { openQuickModal(parseInt(quickBtn.dataset.quick, 10)); return; } const edit = e.target.closest('[data-edit]'); if (edit) { openModal({id: parseInt(edit.dataset.edit,10)}); return; } const del = e.target.closest('[data-del]'); if (del) { const id = parseInt(del.dataset.id||del.dataset.del,10); diff --git a/public/js/journal.js b/public/js/journal.js index b964b34..8b17dae 100644 --- a/public/js/journal.js +++ b/public/js/journal.js @@ -403,18 +403,23 @@ function closeReportCard() { setReportFieldsOpen(false); } +function fileExtLabel(name) { + const m = String(name || '').match(/\.[^.\/]+$/); + return m ? m[0].toLowerCase() : esc(name || ''); +} + function filesHTML(files) { if (!files || !files.length) return ''; return `
${files.map(f => { const url = `${API}/api/files/${f.token}`; + const label = fileExtLabel(f.name); let link; if (isImageFile(f.name)) { - link = `${esc(f.name)}`; + link = `${label}`; } else if (isPlayableVideoFile(f.name)) { - link = `${esc(f.name)}`; + link = `${label}`; } else { - const note = isVideoFile(f.name) ? 'Скачать (браузер не умеет играть этот формат)' : 'Скачать'; - link = `${esc(f.name)}`; + link = `${label}`; } return `${link}`; }).join('')}
`; diff --git a/public/js/md.js b/public/js/md.js index a89a3af..e8c21e8 100644 --- a/public/js/md.js +++ b/public/js/md.js @@ -27,10 +27,13 @@ return `\u0000${codes.length - 1}\u0000`; }); text = esc(text); - text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (m, alt, src) => { + text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (m, alt, src, title) => { const url = safeUrl(src.replace(/&/g, '&')); if (!url) return alt; - return `${esc(alt)}`; + const t = title ? title.replace(/&/g, '&') : ''; + const img = `${esc(alt)}`; + if (t) return `
${img}
${esc(t)}
`; + return img; }); text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => { const url = safeUrl(href.replace(/&/g, '&')); diff --git a/public/js/trash.js b/public/js/trash.js index 63bd91f..a6e817b 100644 --- a/public/js/trash.js +++ b/public/js/trash.js @@ -24,12 +24,17 @@ function isImageFile(name) { return /\.(jpe?g|jfif|png|gif|webp|bmp|avif|svg|ico)$/i.test(name || ''); } +function fileExtLabel(name) { + const m = String(name || '').match(/\.[^.\/]+$/); + return m ? m[0].toLowerCase() : esc(name || ''); +} + function filesHTML(files) { if (!files || !files.length) return ''; return `
${files.map(f => isImageFile(f.name) - ? `${esc(f.name)}` - : `${esc(f.name)}` + ? `${fileExtLabel(f.name)}` + : `${fileExtLabel(f.name)}` ).join('')}
`; } diff --git a/server.js b/server.js index 89ac834..30c4a2c 100644 --- a/server.js +++ b/server.js @@ -80,6 +80,17 @@ const { deleteArticle: deleteDocArticle, reorderArticles: reorderDocArticles, registerImage: registerDocImage, + listDocImages: listDocImages, + deleteDocImage: deleteDocImage, + updateDocImageCaption: updateDocImageCaption, + listAllImages: listAllDocImages, + listAllFiles: listAllDocFiles, + registerFile: registerFile, + listDocFiles, + listUnattachedDocFiles, + attachDocFile, + replaceDocFile, + deleteDocFile, searchArticles: searchDocArticles, publicTree: publicDocTree, publicArticle: publicDocArticle, @@ -871,7 +882,13 @@ async function sendImageThumb(res, key) { const tp = thumbFileFor(key); try { if (fs.existsSync(tp)) { - res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); + // self-heal: if the original is gone, drop the stale thumb and 404 + const origExists = await storage.head(key); + if (!origExists) { + try { fs.unlinkSync(tp); } catch {} + return res.status(404).end(); + } + res.setHeader('Cache-Control', 'public, max-age=3600'); return res.sendFile(tp); } } catch {} @@ -887,7 +904,7 @@ async function sendImageThumb(res, key) { await sharp(local).rotate().resize({ width: THUMB_WIDTH, withoutEnlargement: true }).webp({ quality: 85 }).toFile(tmp); fs.renameSync(tmp, tp); } - res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); + res.setHeader('Cache-Control', 'public, max-age=3600'); return res.sendFile(tp); } catch { try { if (fs.existsSync(tp)) fs.unlinkSync(tp); } catch {} @@ -1601,6 +1618,30 @@ const adminUpload = multer({ }, }); +const DOC_FILE_ALLOWED_EXT = new Set(['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.md', '.csv', '.rtf', '.odt', '.ods', '.odp', '.zip', '.rar', '.7z', '.json', '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.avif']); +const docFileUpload = multer({ + storage: multer.diskStorage({ + destination: (_, __, cb) => { + fs.mkdirSync('uploads', { recursive: true }); + cb(null, 'uploads'); + }, + filename: (_, file, cb) => { + const original = fixFilename(file.originalname); + const ext = path.extname(original) || '.bin'; + cb(null, `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`); + }, + }), + limits: { fileSize: MAX_FILE_UPLOAD_BYTES }, + fileFilter: (req, file, cb) => { + file.originalname = fixFilename(file.originalname); + const ext = path.extname(file.originalname).toLowerCase(); + if (!ext || !DOC_FILE_ALLOWED_EXT.has(ext)) { + return cb(new Error('Not allowed extension')); + } + cb(null, true); + }, +}); + async function getSetting(key, def) { const cached = await cacheGet('setting:' + key); if (cached !== undefined) return cached; @@ -1767,7 +1808,7 @@ async function removeEntryFiles(entryId) { async function sweepOrphanedUploads() { const dir = UPLOADS_DIR; try { fs.mkdirSync(dir, { recursive: true }); } catch {} - const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }] = await Promise.all([ + const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }, { rows: docFiles }] = 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'), @@ -1786,9 +1827,10 @@ async function sweepOrphanedUploads() { pool.query('SELECT photo_path AS p FROM bookmarks WHERE photo_path IS NOT NULL'), pool.query('SELECT photo_path AS p FROM student_face_refs'), pool.query('SELECT path AS p FROM doc_images'), + pool.query('SELECT path AS p FROM doc_files'), ]); const refs = new Set(); - [...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos].forEach(r => { + [...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos, ...docFiles].forEach(r => { const key = storage.keyFromPath(r.p); if (key) refs.add(key); }); @@ -1826,6 +1868,7 @@ const BROKEN_IMAGE_SOURCES = [ { key: 'bookmarks.photo_path', table: 'bookmarks', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Картинка закладки' }, { key: 'student_face_refs.photo_path', table: 'student_face_refs', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Эталон лица' }, { key: 'doc_images.path', table: 'doc_images', column: 'path', idColumn: 'id', kind: 'row', label: 'Картинка документации' }, + { key: 'doc_files.path', table: 'doc_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение документации' }, { key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' }, { key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' }, { key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' }, @@ -5401,7 +5444,12 @@ app.delete('/api/docs/articles/:id', requireAuth, async (req, res) => { try { const id = reqInt(req.params.id); const images = await deleteDocArticle(pool, req.user, id); - images.forEach(p => { safeUnlink(p); thumbUnlinkFor(p); }); + await Promise.all(images.map(async p => { + safeUnlink(p); + thumbUnlinkFor(p); + const key = storage.keyFromPath(p); + if (key && storage.isRemote()) { try { await storage.del(key); } catch (e) { console.error('Upload delete failed:', key, e.message); } } + })); await logAudit(req, 'docs.article.delete', { id }); res.json({ ok: true }); } catch (e) { @@ -5431,6 +5479,163 @@ app.post('/api/docs/images', requireAuth, (req, res) => { }); }); +app.get('/api/docs/articles/:id/files', requireAuth, async (req, res) => { + try { + const items = await listDocFiles(pool, req.user, reqInt(req.params.id)); + res.json({ items }); + } catch (e) { + docsError(res, e, 'Не удалось загрузить вложения', 'docs files list'); + } +}); + +app.get('/api/docs/files/unattached', requireAuth, async (req, res) => { + try { + res.json({ items: await listUnattachedDocFiles(pool, req.user) }); + } catch (e) { + docsError(res, e, 'Не удалось загрузить файлы', 'docs files unattached'); + } +}); + +app.post('/api/docs/files', requireAuth, (req, res) => { + docFileUpload.single('file')(req, res, async err => { + if (err) { + if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR }); + if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' }); + return res.status(400).json({ error: 'Недопустимый файл' }); + } + if (!req.file) return res.status(400).json({ error: 'Файл обязателен' }); + try { + const item = await registerFile(pool, { + path: `/uploads/${req.file.filename}`, + name: req.file.originalname, + size: req.file.size, + mime: req.file.mimetype, + userId: req.user.id, + articleId: req.body?.article_id ? reqInt(req.body.article_id) : null, + }); + await logAudit(req, 'docs.file.create', { id: item.id, path: item.path, article_id: item.article_id }); + res.json({ item }); + } catch (e) { + removeUpload(req.file); + docsError(res, e, 'Не удалось загрузить файл', 'docs file upload'); + } + }); +}); + +app.put('/api/docs/files/:id/attach', requireAuth, async (req, res) => { + try { + const item = await attachDocFile(pool, req.user, reqInt(req.params.id), req.body?.article_id == null ? null : reqInt(req.body.article_id)); + await logAudit(req, 'docs.file.attach', { id: item.id, article_id: item.article_id }); + res.json({ item }); + } catch (e) { + docsError(res, e, 'Не удалось изменить привязку файла', 'docs file attach'); + } +}); + +app.post('/api/docs/files/:id/replace', requireAuth, (req, res) => { + docFileUpload.single('file')(req, res, async err => { + if (err) { + if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR }); + if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' }); + return res.status(400).json({ error: 'Недопустимый файл' }); + } + if (!req.file) return res.status(400).json({ error: 'Файл обязателен' }); + try { + const { item, oldPath } = await replaceDocFile(pool, req.user, reqInt(req.params.id), { + path: `/uploads/${req.file.filename}`, + name: req.file.originalname, + size: req.file.size, + mime: req.file.mimetype, + }); + safeUnlink(oldPath); + thumbUnlinkFor(oldPath); + const oldKey = storage.keyFromPath(oldPath); + if (oldKey && storage.isRemote()) { try { await storage.del(oldKey); } catch (e) { console.error('Upload delete failed:', oldKey, e.message); } } + await logAudit(req, 'docs.file.replace', { id: item.id, old: oldPath, new: item.path }); + res.json({ item }); + } catch (e) { + removeUpload(req.file); + docsError(res, e, 'Не удалось заменить файл', 'docs file replace'); + } + }); +}); + +app.delete('/api/docs/files/:id', requireAuth, async (req, res) => { + try { + const path = await deleteDocFile(pool, req.user, reqInt(req.params.id)); + safeUnlink(path); + thumbUnlinkFor(path); + const key = storage.keyFromPath(path); + if (key && storage.isRemote()) { try { await storage.del(key); } catch (e) { console.error('Upload delete failed:', key, e.message); } } + await logAudit(req, 'docs.file.delete', { path }); + res.json({ ok: true }); + } catch (e) { + docsError(res, e, 'Не удалось удалить файл', 'docs file delete'); + } +}); + +app.get('/api/docs/images', requireAuth, async (req, res) => { + try { + res.json({ items: await listAllDocImages(pool, req.user) }); + } catch (e) { + docsError(res, e, 'Не удалось загрузить изображения', 'docs images all'); + } +}); + +app.get('/api/docs/files', requireAuth, async (req, res) => { + try { + const articleId = req.query.article_id ? reqInt(req.query.article_id) : null; + if (articleId) { + res.json({ items: await listDocFiles(pool, req.user, articleId) }); + } else { + res.json({ items: await listAllDocFiles(pool, req.user) }); + } + } catch (e) { + docsError(res, e, 'Не удалось загрузить файлы', 'docs files all'); + } +}); + +app.get('/api/docs/articles/:id/images', requireAuth, async (req, res) => { + try { + const items = await listDocImages(pool, req.user, reqInt(req.params.id)); + res.json({ items }); + } catch (e) { + docsError(res, e, 'Не удалось загрузить изображения', 'docs images list'); + } +}); + +app.get('/api/docs/images/unattached', requireAuth, async (req, res) => { + try { + res.json({ items: await listDocImages(pool, req.user, null) }); + } catch (e) { + docsError(res, e, 'Не удалось загрузить изображения', 'docs images unattached'); + } +}); + +app.put('/api/docs/images/:id', requireAuth, async (req, res) => { + try { + const result = await updateDocImageCaption(pool, req.user, reqInt(req.params.id), req.body?.caption); + await logAudit(req, 'docs.image.caption', { path: result.path, caption: result.caption }); + res.json({ item: result }); + } catch (e) { + docsError(res, e, 'Не удалось сохранить подпись', 'docs image caption'); + } +}); + +app.delete('/api/docs/images/:id', requireAuth, async (req, res) => { + try { + const path = await deleteDocImage(pool, req.user, reqInt(req.params.id)); + safeUnlink(path); + thumbUnlinkFor(path); + const key = storage.keyFromPath(path); + if (key && storage.isRemote()) { try { await storage.del(key); } catch (e) { console.error('Upload delete failed:', key, e.message); } } + await logAudit(req, 'docs.image.delete', { path }); + res.json({ ok: true }); + } catch (e) { + docsError(res, e, 'Не удалось удалить изображение', 'docs image delete'); + } +}); + app.get('/api/docs/public/tree', apiLimiter, async (req, res) => { try { res.json(await publicDocTree(pool)); @@ -6868,6 +7073,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b await client.query('DELETE FROM photo_faces'); await client.query('DELETE FROM student_face_refs'); await client.query('DELETE FROM doc_images'); + await client.query('DELETE FROM doc_files'); await client.query('DELETE FROM doc_articles'); await client.query('DELETE FROM doc_sections'); await client.query('DELETE FROM users'); @@ -6931,8 +7137,14 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b } for (const x of (ndata.doc_images || [])) { await client.query( - 'INSERT INTO doc_images (id, article_id, path, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, (SELECT id FROM users WHERE id = $4), $5)', - [x.id, x.article_id, x.path, x.uploaded_by, x.created_at || null] + 'INSERT INTO doc_images (id, article_id, path, caption, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, $4, (SELECT id FROM users WHERE id = $5), $6)', + [x.id, x.article_id, x.path, x.caption || null, x.uploaded_by, x.created_at || null] + ); + } + for (const x of (ndata.doc_files || [])) { + await client.query( + 'INSERT INTO doc_files (id, article_id, name, path, size_bytes, mime, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, $4, $5, $6, (SELECT id FROM users WHERE id = $7), $8)', + [x.id, x.article_id, x.name, x.path, x.size_bytes, x.mime, x.uploaded_by, x.created_at || null] ); } for (const x of ndata.user_branches) {