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
111 lines
6.6 KiB
TypeScript
111 lines
6.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { auth } from '@/auth'
|
|
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 {
|
|
const session = await auth()
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const { noteId, count, language } = await request.json()
|
|
if (!noteId) {
|
|
return NextResponse.json({ error: 'noteId is required' }, { status: 400 })
|
|
}
|
|
|
|
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
|
|
|
|
try {
|
|
await reserveUsageOrThrow(session.user.id, 'reformulate')
|
|
} 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 note = await prisma.note.findUnique({
|
|
where: { id: noteId },
|
|
select: { id: true, title: true, content: true, notebookId: true },
|
|
})
|
|
|
|
if (!note) {
|
|
return NextResponse.json({ error: 'Note not found' }, { status: 404 })
|
|
}
|
|
|
|
const exercises = await exerciseGeneratorService.generate(
|
|
note.title || 'Sans titre',
|
|
note.content,
|
|
{ count: count || 5, language: language || 'fr' }
|
|
)
|
|
|
|
// Create exercise notes in the same notebook
|
|
const lang = language || 'fr'
|
|
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} ${difficultyLocalized}</p></div>
|
|
<h2>${statementLabel}</h2>
|
|
<p>${ex.question}</p>
|
|
<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)
|
|
|
|
const created = await prisma.note.create({
|
|
data: {
|
|
title: `${exerciseLabel} ${i + 1} — ${note.title || ''}`,
|
|
content,
|
|
userId: session.user.id,
|
|
notebookId: note.notebookId,
|
|
type: 'richtext',
|
|
order: 999 + i,
|
|
},
|
|
})
|
|
createdNotes.push(created)
|
|
|
|
void (async () => {
|
|
try {
|
|
const { embeddingService } = await import('@/lib/ai/services/embedding.service')
|
|
const { upsertNoteEmbedding } = await import('@/lib/embeddings')
|
|
const { chunkIndexingService } = await import('@/lib/ai/services/chunk-indexing.service')
|
|
const { embedding } = await embeddingService.generateNoteEmbedding(created.title, content)
|
|
await upsertNoteEmbedding(created.id, embedding)
|
|
await chunkIndexingService.indexNote(created.id, created.title, content)
|
|
} catch {}
|
|
})()
|
|
}
|
|
|
|
|
|
return NextResponse.json({
|
|
exercises: createdNotes.map(n => ({ id: n.id, title: n.title })),
|
|
})
|
|
} catch (error: any) {
|
|
console.error('[Exercise Generator] Error:', error)
|
|
return NextResponse.json({ error: error.message || 'Failed to generate exercises' }, { status: 500 })
|
|
}
|
|
}
|