// Редактирование статей. Все маршруты доступны только редакторам и админам: // проверка стоит здесь, на сервере, а не только в интерфейсе. import fs from 'node:fs/promises'; import path from 'node:path'; import { Router } from 'express'; import multer from 'multer'; import { nanoid } from 'nanoid'; import sharp from 'sharp'; import { z } from 'zod'; import { Prisma } from '@prisma/client'; import type { RevisionDto } from '@kb/shared'; import { requireRole } from '../auth.js'; import { prisma } from '../db.js'; import { HttpError } from '../http.js'; import { deriveFacts, linkAssets, renderArticle, rerenderAll, updateSearchIndex } from '../services/articles.js'; import { storeImage, uploadPath } from '../services/images.js'; export const editRouter = Router(); editRouter.use(requireRole('EDITOR')); const MB = 1024 * 1024; export const MAX_IMAGE = 15 * MB; export const MAX_DOC = 30 * MB; // Файлы принимаем в память: дальше картинку всё равно пережимает sharp, а документ проверяем по содержимому const uploadImage = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_IMAGE, files: 1 } }).single('file'); const uploadDoc = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_DOC, files: 1 } }).single('file'); const meta = z.object({ title: z.string().trim().min(2, 'Укажите название').max(200), summary: z.string().trim().max(500).default(''), sectionId: z.string().min(1, 'Выберите раздел'), tags: z.array(z.string().trim().min(1).max(60)).max(30).default([]), equipment: z.array(z.string().trim().min(1).max(80)).max(30).default([]), docCode: z .string() .trim() .max(200) .nullish() .transform((v) => v || null), pinned: z.boolean().default(false), visibility: z.enum(['PRIVATE', 'PUBLIC']).default('PRIVATE'), order: z.number().int().min(0).max(9999).default(0), }); const body = z.object({ md: z.string().max(400_000), meta }); const TRANSLIT: Record = { а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya', }; /** «Стойка въезда — слаботочка» → stoyka-vezda-slabotochka */ export function slugify(title: string): string { const s = [...title.toLowerCase()] .map((ch) => TRANSLIT[ch] ?? ch) .join('') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, 60) .replace(/-+$/, ''); return s || 'statya'; } async function uniqueSlug(base: string): Promise { for (let i = 1; ; i++) { const slug = i === 1 ? base : `${base}-${i}`; if (!(await prisma.article.findUnique({ where: { slug }, select: { id: true } }))) return slug; } } async function getArticle(id: string) { const art = await prisma.article.findUnique({ where: { id } }); if (!art) throw new HttpError(404, 'Статья не найдена'); return art; } // Данные для редактора: опубликованный текст, несохранённый черновик, вложения editRouter.get('/articles/:slug', async (req, res) => { const art = await prisma.article.findUnique({ where: { slug: String(req.params.slug) }, include: { attachments: { orderBy: { createdAt: 'asc' } } }, }); if (!art) throw new HttpError(404, 'Статья не найдена'); res.json({ id: art.id, slug: art.slug, status: art.status, version: art.version, updatedAt: art.updatedAt.toISOString(), md: art.bodyMd, meta: { title: art.title, summary: art.summary, sectionId: art.sectionId, tags: art.tags, equipment: art.equipment, docCode: art.docCode, pinned: art.pinned, visibility: art.visibility, order: art.order, }, draft: art.draftMd !== null ? { md: art.draftMd, meta: art.draftMeta, at: art.draftAt?.toISOString() ?? null } : null, attachments: art.attachments.map((a) => ({ id: a.id, filename: a.filename, url: `/uploads/${a.path}`, size: a.size })), }); }); // Новая статья: создаётся черновиком, читатели её не видят до публикации editRouter.post('/articles', async (req, res) => { const input = z.object({ title: meta.shape.title, sectionId: meta.shape.sectionId }).parse(req.body); const section = await prisma.section.findUnique({ where: { id: input.sectionId } }); if (!section) throw new HttpError(400, 'Раздел не найден'); const slug = await uniqueSlug(slugify(input.title)); const last = await prisma.article.aggregate({ where: { sectionId: section.id }, _max: { order: true } }); const art = await prisma.article.create({ data: { slug, title: input.title, sectionId: section.id, bodyMd: '', bodyHtml: '', status: 'DRAFT', order: (last._max.order ?? 0) + 1, authorId: req.user!.id, }, }); res.status(201).json({ id: art.id, slug: art.slug }); }); // Автосохранение и кнопка «Черновик»: пишем в отдельные поля, опубликованный текст не трогаем editRouter.put('/articles/:id/draft', async (req, res) => { const input = body.parse(req.body); const art = await getArticle(String(req.params.id)); const draftAt = new Date(); await prisma.article.update({ where: { id: art.id }, data: { draftMd: input.md, draftMeta: input.meta as unknown as Prisma.InputJsonValue, draftAt }, }); res.json({ at: draftAt.toISOString() }); }); editRouter.delete('/articles/:id/draft', async (req, res) => { const art = await getArticle(String(req.params.id)); await prisma.article.update({ where: { id: art.id }, data: { draftMd: null, draftMeta: Prisma.JsonNull, draftAt: null } }); // Prisma.JsonNull: так в JSON-поле пишется NULL res.status(204).end(); }); // Публикация: новая версия, запись в историю, пересчёт HTML и поискового индекса editRouter.post('/articles/:id/publish', async (req, res) => { const input = body.extend({ comment: z.string().trim().max(200).optional() }).parse(req.body); const art = await getArticle(String(req.params.id)); const section = await prisma.section.findUnique({ where: { id: input.meta.sectionId } }); if (!section) throw new HttpError(400, 'Раздел не найден'); if (!input.md.trim()) throw new HttpError(400, 'Нельзя опубликовать пустую статью'); const md = input.md.replace(/\r\n?/g, '\n').trim() + '\n'; const first = art.status === 'DRAFT' && art.version === 1 && !art.bodyMd; const changed = md !== art.bodyMd || input.meta.title !== art.title; const version = first ? 1 : changed ? art.version + 1 : art.version; const titleChanged = input.meta.title !== art.title; await prisma.$transaction(async (tx) => { // Закреплённой (шпаргалкой) может быть только одна статья if (input.meta.pinned) await tx.article.updateMany({ where: { pinned: true, id: { not: art.id } }, data: { pinned: false } }); await tx.article.update({ where: { id: art.id }, data: { ...input.meta, bodyMd: md, version, status: 'PUBLISHED', updatedAt: new Date(), draftMd: null, draftMeta: Prisma.JsonNull, draftAt: null, }, }); if (first || changed) { await tx.articleRevision.upsert({ where: { articleId_version: { articleId: art.id, version } }, create: { articleId: art.id, version, title: input.meta.title, bodyMd: md, authorId: req.user!.id, comment: input.comment }, update: { title: input.meta.title, bodyMd: md, authorId: req.user!.id, comment: input.comment, createdAt: new Date() }, }); } const render = await renderArticle(md, tx); await tx.article.update({ where: { id: art.id }, data: { bodyHtml: render.html, facts: deriveFacts(md, input.meta.pinned, render) as unknown as Prisma.InputJsonValue }, }); await updateSearchIndex(art.id, { ...input.meta, render }, tx); await linkAssets(art.id, render, tx); }); // Новая статья или новое название: в других статьях [[ссылки]] на неё должны показать актуальное название if (first || titleChanged) await rerenderAll(); res.json({ slug: art.slug, version, at: new Date().toISOString() }); }); editRouter.post('/articles/:id/unpublish', async (req, res) => { const art = await getArticle(String(req.params.id)); await prisma.article.update({ where: { id: art.id }, data: { status: 'DRAFT' } }); res.status(204).end(); }); editRouter.delete('/articles/:id', requireRole('ADMIN'), async (req, res) => { const art = await getArticle(String(req.params.id)); await prisma.article.delete({ where: { id: art.id } }); await rerenderAll(); res.status(204).end(); }); // ---------- История версий ---------- editRouter.get('/articles/:id/revisions', async (req, res) => { const rows = await prisma.articleRevision.findMany({ where: { articleId: String(req.params.id) }, orderBy: { version: 'desc' }, include: { author: { select: { name: true } } }, }); const list: RevisionDto[] = rows.map((r) => ({ id: r.id, version: r.version, createdAt: r.createdAt.toISOString(), authorName: r.author?.name ?? null, comment: r.comment, })); res.json(list); }); editRouter.get('/articles/:id/revisions/:version', async (req, res) => { const rev = await prisma.articleRevision.findUnique({ where: { articleId_version: { articleId: String(req.params.id), version: Number(req.params.version) || 0 } }, }); if (!rev) throw new HttpError(404, 'Версия не найдена'); res.json({ version: rev.version, title: rev.title, md: rev.bodyMd }); }); // ---------- Загрузка картинок ---------- const IMAGE_FORMATS = new Set(['jpeg', 'png', 'webp', 'gif', 'heif', 'tiff']); editRouter.post('/images', uploadImage, async (req, res) => { const file = req.file; if (!file) throw new HttpError(400, 'Файл не получен'); // Тип определяем по содержимому, а не по имени или заголовку: sharp читает сам файл let format: string | undefined; try { format = (await sharp(file.buffer).metadata()).format; } catch { format = undefined; } if (!format || !IMAGE_FORMATS.has(format)) throw new HttpError(400, 'Это не картинка (нужен JPG, PNG, WebP или HEIC)'); const now = new Date(); const key = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${nanoid(12)}`; const img = await storeImage(file.buffer, key); const articleId = typeof req.body?.articleId === 'string' && req.body.articleId ? req.body.articleId : null; await prisma.asset.create({ data: { path: img.path, mime: 'image/webp', size: img.size, width: img.width, height: img.height, uploadedById: req.user!.id, articleId }, }); res.status(201).json({ url: `/uploads/${img.path}`, width: img.width, height: img.height }); }); // ---------- Исходники (PDF, DOCX…) ---------- // Расширение → с каких байтов должен начинаться файл const DOC_SIGNATURES: Record = { pdf: [[0x25, 0x50, 0x44, 0x46]], // %PDF docx: [[0x50, 0x4b, 0x03, 0x04]], // ZIP xlsx: [[0x50, 0x4b, 0x03, 0x04]], doc: [[0xd0, 0xcf, 0x11, 0xe0]], // старый формат Office xls: [[0xd0, 0xcf, 0x11, 0xe0]], dwg: [[0x41, 0x43, 0x31, 0x30]], // AC10 }; editRouter.post('/articles/:id/attachments', uploadDoc, async (req, res) => { const art = await getArticle(String(req.params.id)); const file = req.file; if (!file) throw new HttpError(400, 'Файл не получен'); // multer отдаёт имя в latin1: возвращаем нормальный UTF-8 const original = Buffer.from(file.originalname, 'latin1').toString('utf8'); const ext = path.extname(original).slice(1).toLowerCase(); const signatures = DOC_SIGNATURES[ext]; if (!signatures) throw new HttpError(400, 'Можно прикрепить PDF, DOC, DOCX, XLS, XLSX или DWG'); if (!signatures.some((sig) => sig.every((b, i) => file.buffer[i] === b))) { throw new HttpError(400, 'Содержимое файла не соответствует расширению'); } const base = slugify(path.basename(original, path.extname(original))).replace(/-/g, '_') || 'file'; const rel = `originals/${art.id}/${base}.${ext}`; const abs = uploadPath(rel); await fs.mkdir(path.dirname(abs), { recursive: true }); await fs.writeFile(abs, file.buffer); const data = { filename: `${base}.${ext}`, size: file.size }; const att = await prisma.attachment.upsert({ where: { articleId_path: { articleId: art.id, path: rel } }, create: { articleId: art.id, path: rel, ...data }, update: data, }); res.status(201).json({ id: att.id, filename: att.filename, url: `/uploads/${att.path}`, size: att.size }); }); editRouter.delete('/attachments/:id', async (req, res) => { const att = await prisma.attachment.findUnique({ where: { id: String(req.params.id) } }); if (!att) throw new HttpError(404, 'Файл не найден'); await prisma.attachment.delete({ where: { id: att.id } }); // Файл стартового импорта может быть общим для нескольких статей: удаляем с диска, только если больше не нужен if (!(await prisma.attachment.count({ where: { path: att.path } }))) { await fs.rm(uploadPath(att.path), { force: true }); } res.status(204).end(); });