feat: publication IA (magazine/brief/essay) + fixes critique
Publication IA: - 4 templates (magazine, brief, essay, simple) avec CSS riche - Rewrite IA (article/exercises/tutorial/reference/mixed) - Modération avec timeout 12s + fallback safe - Quotas publish_enhance par tier (basic=2, pro=15, business=100) - Détection contenu stale (hash) - Migration DB publishedContent/publishedTemplate/publishedSourceHash Fixes: - cheerio v1.2: Element -> AnyNode (domhandler), decodeEntities cast - _isShared ajouté au type Note (champ virtuel serveur) - callout colors PDF export: extraction fonction pure testable - admin/published: guard note.userId null - Cmd+S fonctionne en mode dialog (pas seulement fullPage) i18n: - 23 clés publish* traduites dans les 15 locales - Extension Web Clipper: 13 locales mise à jour Tests: - callout-colors.test.ts (6 tests) - note-visible-in-view.test.ts (5 tests) - entitlements.test.ts + byok-entitlements.test.ts: mock usageLog + unstubAllEnvs - 199/199 tests passent Tracker: user-stories.md sync avec sprint-status.yaml
This commit is contained in:
@@ -43,7 +43,7 @@ export async function DELETE(request: NextRequest) {
|
||||
where: { id: noteId },
|
||||
select: { userId: true, publicSlug: true },
|
||||
})
|
||||
if (note) {
|
||||
if (note && note.userId) {
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
userId: note.userId,
|
||||
|
||||
@@ -4,6 +4,7 @@ import prisma from '@/lib/prisma'
|
||||
import { exerciseGeneratorService } from '@/lib/ai/services/exercise-generator.service'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
import { preprocessMathInHtml } from '@/lib/text/math-preprocess'
|
||||
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -17,6 +18,8 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'noteId is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
|
||||
|
||||
try {
|
||||
await reserveUsageOrThrow(session.user.id, 'reformulate')
|
||||
} catch (err) {
|
||||
@@ -47,19 +50,27 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// Create exercise notes in the same notebook
|
||||
const lang = language || 'fr'
|
||||
const exerciseLabel = lang === 'fr' ? 'Exercice' : lang === 'fa' ? 'تمرین' : 'Exercise'
|
||||
const answerLabel = lang === 'fr' ? 'Corrigé' : lang === 'fa' ? 'پاسخ' : 'Answer'
|
||||
const exerciseLabel = lang === 'fr' ? 'Exercice' : lang === 'fa' ? 'تمرین' : lang === 'ar' ? 'تمرين' : lang === 'de' ? 'Übung' : lang === 'es' ? 'Ejercicio' : lang === 'it' ? 'Esercizio' : lang === 'pt' ? 'Exercício' : lang === 'ru' ? 'Упражнение' : lang === 'zh' ? '练习' : lang === 'ja' ? '練習' : lang === 'ko' ? '연습' : lang === 'nl' ? 'Oefening' : lang === 'pl' ? 'Ćwiczenie' : lang === 'hi' ? 'अभ्यास' : 'Exercise'
|
||||
const answerLabel = lang === 'fr' ? 'Corrigé' : lang === 'fa' ? 'پاسخ' : lang === 'ar' ? 'الحل' : lang === 'de' ? 'Lösung' : lang === 'es' ? 'Solución' : lang === 'it' ? 'Soluzione' : lang === 'pt' ? 'Solução' : lang === 'ru' ? 'Решение' : lang === 'zh' ? '解答' : lang === 'ja' ? '解答' : lang === 'ko' ? '해답' : lang === 'nl' ? 'Oplossing' : lang === 'pl' ? 'Rozwiązanie' : lang === 'hi' ? 'हल' : 'Solution'
|
||||
const statementLabel = lang === 'fr' ? 'Énoncé' : lang === 'fa' ? 'صورت مسئله' : lang === 'ar' ? 'السؤال' : lang === 'de' ? 'Aufgabe' : lang === 'es' ? 'Enunciado' : lang === 'it' ? 'Testo' : lang === 'pt' ? 'Enunciado' : lang === 'ru' ? 'Задание' : lang === 'zh' ? '题目' : lang === 'ja' ? '問題' : lang === 'ko' ? '문제' : lang === 'nl' ? 'Opgave' : lang === 'pl' ? 'Zadanie' : lang === 'hi' ? 'प्रश्न' : 'Statement'
|
||||
const revealLabel = lang === 'fr' ? 'cliquer pour révéler' : lang === 'fa' ? 'برای نمایش کلیک کنید' : lang === 'ar' ? 'انقر للكشف' : lang === 'de' ? 'zum Anzeigen klicken' : lang === 'es' ? 'haz clic para ver' : lang === 'it' ? 'clicca per rivelare' : lang === 'pt' ? 'clique para revelar' : lang === 'ru' ? 'нажмите, чтобы открыть' : lang === 'zh' ? '点击查看' : lang === 'ja' ? 'クリックして表示' : lang === 'ko' ? '클릭하여 보기' : lang === 'nl' ? 'klik om te onthullen' : lang === 'pl' ? 'kliknij, aby zobaczyć' : lang === 'hi' ? 'देखने के लिए क्लिक करें' : 'click to reveal'
|
||||
const difficultyMap: Record<string, Record<string, string>> = {
|
||||
facile: { fr: 'facile', en: 'easy', fa: 'آسان', ar: 'سهل', de: 'einfach', es: 'fácil', it: 'facile', pt: 'fácil', ru: 'лёгкий', zh: '简单', ja: '易しい', ko: '쉬움', nl: 'makkelijk', pl: 'łatwy', hi: 'आसान' },
|
||||
moyen: { fr: 'moyen', en: 'medium', fa: 'متوسط', ar: 'متوسط', de: 'mittel', es: 'medio', it: 'medio', pt: 'médio', ru: 'средний', zh: '中等', ja: '普通', ko: '보통', nl: 'gemiddeld', pl: 'średni', hi: 'मध्यम' },
|
||||
difficile: { fr: 'difficile', en: 'hard', fa: 'دشوار', ar: 'صعب', de: 'schwer', es: 'difícil', it: 'difficile', pt: 'difícil', ru: 'сложный', zh: '困难', ja: '難しい', ko: '어려움', nl: 'moeilijk', pl: 'trudny', hi: 'कठिन' },
|
||||
}
|
||||
|
||||
const createdNotes = []
|
||||
for (let i = 0; i < exercises.length; i++) {
|
||||
const ex = exercises[i]
|
||||
const difficultyEmoji = ex.difficulty === 'facile' ? '🟢' : ex.difficulty === 'moyen' ? '🟡' : '🔴'
|
||||
const difficultyLocalized = (difficultyMap[ex.difficulty]?.[lang]) || ex.difficulty
|
||||
|
||||
const rawContent = `
|
||||
<div data-type="callout-block" data-callout-type="warning"><p><strong>${exerciseLabel} ${i + 1}</strong> — ${difficultyEmoji} ${ex.difficulty}</p></div>
|
||||
<h2>Énoncé</h2>
|
||||
<div data-type="callout-block" data-callout-type="warning"><p><strong>${exerciseLabel} ${i + 1}</strong> — ${difficultyEmoji} ${difficultyLocalized}</p></div>
|
||||
<h2>${statementLabel}</h2>
|
||||
<p>${ex.question}</p>
|
||||
<div data-type="toggle-block" data-opened="false"><p><strong>${answerLabel}</strong> — cliquer pour révéler</p><h3>Solution</h3><p>${ex.answer}</p></div>
|
||||
<div data-type="toggle-block" data-opened="false"><p><strong>${answerLabel}</strong> — ${revealLabel}</p><h3>${answerLabel}</h3><p>${ex.answer}</p></div>
|
||||
`.trim()
|
||||
|
||||
const content = preprocessMathInHtml(rawContent)
|
||||
|
||||
77
memento-note/app/api/ai/notebook-publish/route.ts
Normal file
77
memento-note/app/api/ai/notebook-publish/route.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { notebookPublishAnalyzerService } from '@/lib/ai/services/notebook-publish-analyzer.service'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { notebookId, language } = await request.json()
|
||||
if (!notebookId) {
|
||||
return NextResponse.json({ error: 'notebookId is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
|
||||
|
||||
try {
|
||||
await reserveUsageOrThrow(session.user.id, 'publish_enhance')
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
const isTierLocked = err.currentQuota === 0
|
||||
return NextResponse.json(
|
||||
{ error: isTierLocked ? 'feature_locked' : 'quota_exceeded', errorKey: isTierLocked ? 'ai.featureLocked' : 'ai.quotaExceeded' },
|
||||
{ status: 402 },
|
||||
)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
const notebook = await prisma.notebook.findFirst({
|
||||
where: { id: notebookId, userId: session.user.id, trashedAt: null },
|
||||
select: { id: true, name: true },
|
||||
})
|
||||
if (!notebook) return NextResponse.json({ error: 'Notebook not found' }, { status: 404 })
|
||||
|
||||
const notes = await prisma.note.findMany({
|
||||
where: { notebookId, userId: session.user.id, trashedAt: null, isArchived: false },
|
||||
select: { id: true, title: true, content: true },
|
||||
orderBy: { order: 'asc' },
|
||||
})
|
||||
|
||||
if (notes.length === 0) {
|
||||
return NextResponse.json({ error: 'No notes found' }, { status: 400 })
|
||||
}
|
||||
|
||||
const notesForService = notes.map(n => {
|
||||
const stripped = (n.content || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
const wordCount = stripped.split(' ').filter(Boolean).length
|
||||
return {
|
||||
id: n.id,
|
||||
title: n.title || '',
|
||||
wordCount,
|
||||
preview: stripped.slice(0, 200),
|
||||
}
|
||||
})
|
||||
|
||||
const analysis = await notebookPublishAnalyzerService.analyze(
|
||||
notebook.name,
|
||||
notesForService,
|
||||
language || 'fr',
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
notes: analysis.notes,
|
||||
description: analysis.description,
|
||||
noteTitles: Object.fromEntries(notes.map(n => [n.id, n.title || ''])),
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error('[notebook-publish/analyze] Error:', error)
|
||||
return NextResponse.json({ error: error.message || 'Failed to analyze' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { notebookWizardService, type WizardProfile } from '@/lib/ai/services/notebook-wizard.service'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -17,6 +18,8 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'Profile and topic are required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
|
||||
|
||||
try {
|
||||
await reserveUsageOrThrow(session.user.id, 'reformulate')
|
||||
} catch (err) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { studyPlannerService } from '@/lib/ai/services/study-planner.service'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -16,6 +17,8 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'notebookId and examDate are required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
|
||||
|
||||
try {
|
||||
await reserveUsageOrThrow(session.user.id, 'reformulate')
|
||||
} catch (err) {
|
||||
@@ -41,15 +44,18 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const userLang = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { theme: true },
|
||||
select: { language: true },
|
||||
})
|
||||
|
||||
const notesForService = notes.map(n => ({ id: n.id, title: n.title ?? '' }))
|
||||
const plan = await studyPlannerService.generate(notesForService, examDate)
|
||||
const plan = await studyPlannerService.generate(notesForService, examDate, userLang?.language || 'fr')
|
||||
|
||||
// Set reminders on notes based on the plan
|
||||
// Set the first occurrence reminder for each note (subsequent occurrences ignored)
|
||||
const seenNoteIds = new Set<string>()
|
||||
for (const day of plan.days) {
|
||||
for (const noteId of day.noteIds) {
|
||||
if (seenNoteIds.has(noteId)) continue
|
||||
seenNoteIds.add(noteId)
|
||||
try {
|
||||
const reminderDate = new Date(day.date)
|
||||
reminderDate.setHours(9, 0, 0, 0)
|
||||
|
||||
@@ -277,10 +277,10 @@ Fais un résumé concis (max 200 mots) de cette conversation. Garde les informat
|
||||
- Natural tone, neither corporate nor too casual.
|
||||
- No unnecessary intro phrases. Answer directly.
|
||||
- No upsell questions at the end. If you have useful additional info, just give it.
|
||||
- If the user says "Momento" they mean Momento (this app).
|
||||
- If the user says "Memento" they mean Memento (this app).
|
||||
|
||||
## About Momento
|
||||
Momento is an intelligent note-taking application. Key features include:
|
||||
## About Memento
|
||||
Memento is an intelligent note-taking application. Key features include:
|
||||
- **Notes & Editor**: Create rich Markdown notes with an integrated AI Copilot to rewrite, summarize, or translate content.
|
||||
- **Organization**: Group notes into Notebooks and tag them with Labels.
|
||||
- **Search**: Advanced semantic search to find notes by meaning, not just keywords, and Web Search integration.
|
||||
@@ -336,10 +336,10 @@ Available types: bar, horizontal-bar, line, area, pie, radar. NEVER use Mermaid
|
||||
## Règles de ton
|
||||
- Ton naturel, direct, sans phrases d'intro inutiles.
|
||||
- Pas de question upsell à la fin.
|
||||
- Si l'utilisateur dit "Momento" il parle de Momento (cette application).
|
||||
- Si l'utilisateur dit "Memento" il parle de Memento (cette application).
|
||||
|
||||
## À propos de Momento
|
||||
Momento est une application de prise de notes intelligente. Ses fonctionnalités : Éditeur Markdown riche, Copilot IA, Organisation par Carnets, Recherche sémantique, Agents IA, Lab.
|
||||
## À propos de Memento
|
||||
Memento est une application de prise de notes intelligente. Ses fonctionnalités : Éditeur Markdown riche, Copilot IA, Organisation par Carnets, Recherche sémantique, Agents IA, Lab.
|
||||
|
||||
## Outils disponibles
|
||||
Tu as accès à : note_search, note_read, note_find_and_update, document_search, task_extract, web_search, web_scrape, insert_chart.
|
||||
@@ -387,7 +387,7 @@ Types disponibles : bar, horizontal-bar, line, area, pie, radar. JAMAIS utiliser
|
||||
|
||||
## قوانین لحن
|
||||
- لحن طبیعی، مستقیم، بدون مقدمه اضافی.
|
||||
- اگر کاربر "Momento" میگوید، منظورش Memento (این برنامه) است.`,
|
||||
- اگر کاربر "Memento" میگوید، منظورش Memento (این برنامه) است.`,
|
||||
},
|
||||
es: {
|
||||
contextWithNotes: `## Notas del usuario\n\n${contextNotes}\n\nCuando uses información de las notas anteriores, cita el título de la nota fuente entre paréntesis.`,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* POST /api/integrations/readwise/sync
|
||||
* Syncs Readwise highlights into Momento notes.
|
||||
* Syncs Readwise highlights into Memento notes.
|
||||
* Each book/article becomes a note with all its highlights listed.
|
||||
*
|
||||
* Query params:
|
||||
|
||||
116
memento-note/app/api/notebooks/[id]/publish/route.ts
Normal file
116
memento-note/app/api/notebooks/[id]/publish/route.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
|
||||
export async function GET(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
const { id: notebookId } = await params
|
||||
const site = await prisma.notebookSite.findUnique({
|
||||
where: { notebookId },
|
||||
select: { slug: true, isPublic: true, publishedAt: true, template: true, selectedNoteIds: true },
|
||||
})
|
||||
return NextResponse.json({ site: site || null })
|
||||
} catch (error: any) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
function toSlug(str: string): string {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.trim()
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.slice(0, 40)
|
||||
}
|
||||
|
||||
function generateNotebookSlug(name: string): string {
|
||||
const base = toSlug(name) || 'carnet'
|
||||
const suffix = Math.random().toString(36).slice(2, 7)
|
||||
return `${base}-${suffix}`
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: notebookId } = await params
|
||||
const { selectedNoteIds, template, description } = await request.json()
|
||||
|
||||
if (!selectedNoteIds || !Array.isArray(selectedNoteIds) || selectedNoteIds.length === 0) {
|
||||
return NextResponse.json({ error: 'selectedNoteIds is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const notebook = await prisma.notebook.findFirst({
|
||||
where: { id: notebookId, userId: session.user.id, trashedAt: null },
|
||||
select: { id: true, name: true, site: { select: { slug: true } } },
|
||||
})
|
||||
if (!notebook) return NextResponse.json({ error: 'Notebook not found' }, { status: 404 })
|
||||
|
||||
// Reuse existing slug or generate a new one
|
||||
const slug = notebook.site?.slug || generateNotebookSlug(notebook.name)
|
||||
|
||||
const site = await prisma.notebookSite.upsert({
|
||||
where: { notebookId },
|
||||
create: {
|
||||
notebookId,
|
||||
slug,
|
||||
isPublic: true,
|
||||
template: template || 'magazine',
|
||||
selectedNoteIds: JSON.stringify(selectedNoteIds),
|
||||
description: description || null,
|
||||
},
|
||||
update: {
|
||||
isPublic: true,
|
||||
template: template || 'magazine',
|
||||
selectedNoteIds: JSON.stringify(selectedNoteIds),
|
||||
description: description || null,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ slug: site.slug, url: `/c/${site.slug}` })
|
||||
} catch (error: any) {
|
||||
console.error('[notebooks/publish] Error:', error)
|
||||
return NextResponse.json({ error: error.message || 'Failed to publish' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: notebookId } = await params
|
||||
|
||||
const notebook = await prisma.notebook.findFirst({
|
||||
where: { id: notebookId, userId: session.user.id },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!notebook) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
await prisma.notebookSite.deleteMany({ where: { notebookId } })
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error: any) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,31 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { contentModerationService } from '@/lib/ai/services/content-moderation.service'
|
||||
import { contentModerationService, type ModerationResult } from '@/lib/ai/services/content-moderation.service'
|
||||
import { publishEnhanceService } from '@/lib/ai/services/publish-enhance.service'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
import { hasUserAiConsent } from '@/lib/consent/server-consent'
|
||||
import { isPublishTemplateId } from '@/lib/publish/types'
|
||||
import { computePublishedSourceHash, renderPublishedTemplate, renderRewrittenTemplate } from '@/lib/publish/template-render'
|
||||
|
||||
const MODERATION_TIMEOUT_MS = 12_000
|
||||
|
||||
async function moderateWithFallback(title: string, content: string): Promise<ModerationResult> {
|
||||
try {
|
||||
return await Promise.race([
|
||||
contentModerationService.moderate(title, content),
|
||||
new Promise<ModerationResult>((resolve) => {
|
||||
setTimeout(() => resolve({
|
||||
verdict: 'safe',
|
||||
categories: ['safe'],
|
||||
reason: 'Moderation timeout',
|
||||
}), MODERATION_TIMEOUT_MS)
|
||||
}),
|
||||
])
|
||||
} catch {
|
||||
return { verdict: 'safe', categories: ['safe'], reason: 'Moderation indisponible' }
|
||||
}
|
||||
}
|
||||
|
||||
function generateSlug(title: string): string {
|
||||
const base = title
|
||||
@@ -14,11 +38,70 @@ function generateSlug(title: string): string {
|
||||
return `${base}-${Math.random().toString(36).slice(2, 8)}`
|
||||
}
|
||||
|
||||
async function ensureSlug(noteId: string, title: string, existingSlug: string | null): Promise<string> {
|
||||
let slug = existingSlug
|
||||
if (!slug) {
|
||||
slug = generateSlug(title || 'note')
|
||||
const existing = await prisma.note.findUnique({ where: { publicSlug: slug } })
|
||||
if (existing && existing.id !== noteId) slug = `${slug}-${Date.now().toString(36)}`
|
||||
}
|
||||
return slug
|
||||
}
|
||||
|
||||
async function notifyFlaggedAdmins(noteId: string, title: string, reason: string) {
|
||||
const admins = await prisma.user.findMany({ where: { role: 'ADMIN' }, select: { id: true } })
|
||||
for (const admin of admins) {
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
userId: admin.id,
|
||||
type: 'content_flagged',
|
||||
title: 'Contenu sensible publié',
|
||||
message: `La note "${title}" a été publiée avec un contenu potentiellement sensible: ${reason}`,
|
||||
actionUrl: '/admin/published',
|
||||
relatedId: noteId,
|
||||
},
|
||||
}).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
type PublishUpdateData = {
|
||||
isPublic: boolean
|
||||
publicSlug: string | null
|
||||
publishedAt: Date | null
|
||||
publishedContent?: string | null
|
||||
publishedTemplate?: string | null
|
||||
publishedSourceHash?: string | null
|
||||
}
|
||||
|
||||
/** Tolerates stale Prisma client during dev (before server restart). */
|
||||
async function updateNotePublishState(noteId: string, data: PublishUpdateData) {
|
||||
try {
|
||||
await prisma.note.update({ where: { id: noteId }, data })
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
if (msg.includes('publishedContent') || msg.includes('Unknown argument')) {
|
||||
const { publishedContent, publishedTemplate, publishedSourceHash, ...core } = data
|
||||
await prisma.note.update({ where: { id: noteId }, data: core })
|
||||
return
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { noteId, action } = await request.json()
|
||||
const body = await request.json()
|
||||
const { noteId, action, mode, template, language, rewrite } = body as {
|
||||
noteId?: string
|
||||
action?: string
|
||||
mode?: 'simple' | 'ai'
|
||||
template?: string
|
||||
language?: string
|
||||
rewrite?: boolean
|
||||
}
|
||||
|
||||
if (!noteId) return NextResponse.json({ error: 'noteId required' }, { status: 400 })
|
||||
|
||||
const note = await prisma.note.findFirst({
|
||||
@@ -28,14 +111,96 @@ export async function POST(request: NextRequest) {
|
||||
if (!note) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
if (action === 'publish') {
|
||||
// --- AI Moderation ---
|
||||
let moderation
|
||||
try {
|
||||
moderation = await contentModerationService.moderate(note.title || '', note.content || '')
|
||||
} catch {
|
||||
moderation = { verdict: 'safe' as const, categories: ['safe'], reason: 'Moderation indisponible' }
|
||||
const publishMode = mode === 'ai' ? 'ai' : 'simple'
|
||||
|
||||
if (publishMode === 'ai') {
|
||||
if (!(await hasUserAiConsent())) {
|
||||
return NextResponse.json({ error: 'ai_consent_required' }, { status: 403 })
|
||||
}
|
||||
if (!template || !isPublishTemplateId(template)) {
|
||||
return NextResponse.json({ error: 'Invalid template' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
await reserveUsageOrThrow(session.user.id, 'publish_enhance')
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
const isTierLocked = err.currentQuota === 0
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: isTierLocked ? 'feature_locked' : 'quota_exceeded',
|
||||
errorKey: isTierLocked ? 'ai.featureLocked' : 'ai.quotaExceeded',
|
||||
upgradeTier: err.upgradeTier,
|
||||
},
|
||||
{ status: 402 },
|
||||
)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
let renderedHtml: string
|
||||
let textForModeration: string
|
||||
|
||||
try {
|
||||
if (rewrite) {
|
||||
const spec = await publishEnhanceService.rewrite(
|
||||
note.title || '',
|
||||
note.content || '',
|
||||
template,
|
||||
language || 'fr',
|
||||
)
|
||||
renderedHtml = renderRewrittenTemplate(spec, template, note.content || '')
|
||||
textForModeration = `${spec.summary}\n${spec.body.replace(/<[^>]+>/g, ' ')}`
|
||||
} else {
|
||||
const spec = await publishEnhanceService.enhance(
|
||||
note.title || '',
|
||||
note.content || '',
|
||||
template,
|
||||
language || 'fr',
|
||||
)
|
||||
renderedHtml = renderPublishedTemplate(spec, template, note.content || '')
|
||||
textForModeration = [spec.summary, spec.pullQuote, spec.epigraph, ...(spec.keyPoints || [])].join('\n')
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[publish] AI generation failed:', err)
|
||||
return NextResponse.json({ error: 'ai_generation_failed' }, { status: 500 })
|
||||
}
|
||||
|
||||
const moderation = await moderateWithFallback(note.title || '', textForModeration)
|
||||
if (moderation.verdict === 'blocked') {
|
||||
return NextResponse.json({
|
||||
error: 'blocked',
|
||||
reason: moderation.reason,
|
||||
categories: moderation.categories,
|
||||
}, { status: 403 })
|
||||
}
|
||||
if (moderation.verdict === 'flagged') {
|
||||
await notifyFlaggedAdmins(note.id, note.title || '', moderation.reason)
|
||||
}
|
||||
|
||||
const slug = await ensureSlug(note.id, note.title || '', note.publicSlug)
|
||||
const sourceHash = computePublishedSourceHash(note.content || '')
|
||||
|
||||
await updateNotePublishState(noteId, {
|
||||
isPublic: true,
|
||||
publicSlug: slug,
|
||||
publishedAt: new Date(),
|
||||
publishedContent: renderedHtml,
|
||||
publishedTemplate: template,
|
||||
publishedSourceHash: sourceHash,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
slug,
|
||||
mode: 'ai',
|
||||
template,
|
||||
moderation: moderation.verdict === 'flagged' ? 'flagged' : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// Simple publish — contenu brut de la note
|
||||
const moderation = await moderateWithFallback(note.title || '', note.content || '')
|
||||
if (moderation.verdict === 'blocked') {
|
||||
return NextResponse.json({
|
||||
error: 'blocked',
|
||||
@@ -43,46 +208,36 @@ export async function POST(request: NextRequest) {
|
||||
categories: moderation.categories,
|
||||
}, { status: 403 })
|
||||
}
|
||||
|
||||
// flagged → publish but notify admins
|
||||
if (moderation.verdict === 'flagged') {
|
||||
const admins = await prisma.user.findMany({ where: { role: 'ADMIN' }, select: { id: true } })
|
||||
for (const admin of admins) {
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
userId: admin.id,
|
||||
type: 'content_flagged',
|
||||
title: 'Contenu sensible publié',
|
||||
message: `La note "${note.title}" a été publiée avec un contenu potentiellement sensible: ${moderation.reason}`,
|
||||
actionUrl: '/admin/published',
|
||||
relatedId: note.id,
|
||||
},
|
||||
}).catch(() => {})
|
||||
}
|
||||
await notifyFlaggedAdmins(note.id, note.title || '', moderation.reason)
|
||||
}
|
||||
|
||||
let slug = note.publicSlug
|
||||
if (!slug) {
|
||||
slug = generateSlug(note.title || 'note')
|
||||
const existing = await prisma.note.findUnique({ where: { publicSlug: slug } })
|
||||
if (existing && existing.id !== noteId) slug = `${slug}-${Date.now().toString(36)}`
|
||||
}
|
||||
await prisma.note.update({
|
||||
where: { id: noteId },
|
||||
data: { isPublic: true, publicSlug: slug, publishedAt: new Date() },
|
||||
const slug = await ensureSlug(note.id, note.title || '', note.publicSlug)
|
||||
await updateNotePublishState(noteId, {
|
||||
isPublic: true,
|
||||
publicSlug: slug,
|
||||
publishedAt: new Date(),
|
||||
publishedContent: null,
|
||||
publishedTemplate: null,
|
||||
publishedSourceHash: null,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
slug,
|
||||
mode: 'simple',
|
||||
moderation: moderation.verdict === 'flagged' ? 'flagged' : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (action === 'unpublish') {
|
||||
await prisma.note.update({
|
||||
where: { id: noteId },
|
||||
data: { isPublic: false, publicSlug: null, publishedAt: null },
|
||||
await updateNotePublishState(noteId, {
|
||||
isPublic: false,
|
||||
publicSlug: null,
|
||||
publishedAt: null,
|
||||
publishedContent: null,
|
||||
publishedTemplate: null,
|
||||
publishedSourceHash: null,
|
||||
})
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ const DEMO_NOTES: Record<string, DemoNote[]> = {
|
||||
<li><strong>Designing Data-Intensive Applications</strong> — Martin Kleppmann · Architecture systèmes</li>
|
||||
<li><strong>The Pragmatic Programmer</strong> — Hunt & Thomas · Bonnes pratiques développement</li>
|
||||
</ul>
|
||||
<p>Prochaine lecture : Building a Second Brain (lien avec Momento évident).</p>`,
|
||||
<p>Prochaine lecture : Building a Second Brain (lien avec Memento évident).</p>`,
|
||||
},
|
||||
{
|
||||
title: 'Notes de formation React — Hooks avancés',
|
||||
@@ -132,7 +132,7 @@ const DEMO_NOTES: Record<string, DemoNote[]> = {
|
||||
<li><strong>Designing Data-Intensive Applications</strong> — Martin Kleppmann · Systems architecture</li>
|
||||
<li><strong>The Pragmatic Programmer</strong> — Hunt & Thomas · Development best practices</li>
|
||||
</ul>
|
||||
<p>Next read: Building a Second Brain (obvious connection to Momento).</p>`,
|
||||
<p>Next read: Building a Second Brain (obvious connection to Memento).</p>`,
|
||||
},
|
||||
{
|
||||
title: 'React Training Notes — Advanced Hooks',
|
||||
|
||||
@@ -375,7 +375,7 @@ export async function GET() {
|
||||
<body>
|
||||
<div id="sidebar">
|
||||
<div id="sidebar-header">
|
||||
<h1>Momento</h1>
|
||||
<h1>Memento</h1>
|
||||
<p>Offline Workspace Export</p>
|
||||
</div>
|
||||
<div id="search-bar">
|
||||
|
||||
Reference in New Issue
Block a user