Files
Momento/memento-note/app/api/mobile/flashcards/generate/route.ts
Antigravity 0fa8978395
Some checks failed
CI / Lint, Unit Tests & Build (push) Failing after 1m32s
CI / Deploy production (on server) (push) Has been skipped
feat: mobile app complet + flashcards fixes + drag handle améliorations
Mobile app:
- Révision flashcards : liste decks, session flip-card SM-2, couleurs harmonisées web
- Génération flashcards depuis note (FlashcardSheet + route /api/mobile/flashcards/generate)
- Audio Whisper : hook useAudioRecorder reécrit, MicButton avec erreurs
- IA : AISheet (améliorer/clarifier/résumer), TitleSheet (titre automatique)
- Suppression note (soft delete + confirmation Alert)
- Note du jour : titre lisible + HTML (plus JSON TipTap brut)
- Parser TipTap→HTML côté mobile (tipTapToHtml)
- Icône 🎓 dans header note → génération flashcards
- Endpoint flashcardGenerate dans config.ts

Web fixes:
- Bug flashcards groupées par carnet → deck par note (migration + schema)
- Bug filtre 'cartes dues' ignoré (suppression fallback buildSessionQueue)
- Suppression UI création deck manuelle (inutile)
- Fix setViewType is not defined dans home-client.tsx

Drag handle menu:
- Fix : clearNodes() avant transformation (heading→liste/code/citation)
- Ajout : option 'Texte' (paragraphe) dans Transformer en
- Ajout : Monter / Descendre le bloc
- Ajout : Copier le contenu du bloc
- Fix : sous-menu hover stable (délai 200ms)
- Fix : Supprimer en rouge via classe --danger (plus :first-child)
- i18n : nouvelles clés dans 15 locales

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-29 18:49:40 +00:00

85 lines
3.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getMobileUserId } from '@/lib/mobile-auth'
import { generateFlashcardsFromNote, type FlashcardStyle } from '@/lib/flashcards/generate-flashcards'
import { stripHtmlToText } from '@/lib/flashcards/deck-utils'
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements'
export async function POST(req: NextRequest) {
const userId = getMobileUserId(req)
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
const body = await req.json().catch(() => ({}))
const noteId = typeof body.noteId === 'string' ? body.noteId : null
const count = typeof body.count === 'number' ? Math.min(body.count, 20) : 10
const styleRaw = typeof body.style === 'string' ? body.style : 'qa'
const style: FlashcardStyle = ['qa', 'cloze', 'concept'].includes(styleRaw) ? (styleRaw as FlashcardStyle) : 'qa'
if (!noteId) return NextResponse.json({ error: 'noteId requis' }, { status: 400 })
const note = await prisma.note.findFirst({
where: { id: noteId, userId, trashedAt: null },
select: { id: true, title: true, content: true, notebookId: true, language: true },
})
if (!note) return NextResponse.json({ error: 'Note introuvable' }, { status: 404 })
const textContent = stripHtmlToText(note.content)
if (textContent.length < 80) {
return NextResponse.json({ error: 'Contenu insuffisant pour générer des flashcards (minimum 80 caractères)' }, { status: 400 })
}
try {
await checkEntitlementOrThrow(userId, 'ai_flashcard')
} catch (err) {
if (err instanceof QuotaExceededError) {
return NextResponse.json({ error: err.currentQuota === 0 ? 'Fonctionnalité non disponible sur votre abonnement' : 'Quota IA atteint' }, { status: 402 })
}
throw err
}
const cards = await generateFlashcardsFromNote({
title: note.title || 'Sans titre',
textContent,
count,
style,
language: note.language || undefined,
})
if (cards.length === 0) {
return NextResponse.json({ error: 'Génération échouée — aucune carte produite' }, { status: 500 })
}
// Chercher un deck existant pour cette note, ou en créer un
const existing = await prisma.flashcard.findFirst({
where: { noteId: note.id, deck: { userId } },
select: { deckId: true },
})
let deckId: string
if (existing) {
deckId = existing.deckId
// Supprimer les anciennes cartes pour les remplacer
await prisma.flashcard.deleteMany({ where: { noteId: note.id, deckId } })
} else {
const deck = await prisma.flashcardDeck.create({
data: { userId, notebookId: note.notebookId, name: note.title || 'Sans titre' },
})
deckId = deck.id
}
await prisma.flashcard.createMany({
data: cards.map((c) => ({
deckId,
noteId: note.id,
front: c.front,
back: c.back,
type: c.type,
})),
})
await prisma.flashcardDeck.update({ where: { id: deckId }, data: { updatedAt: new Date() } })
incrementUsageAsync(userId, 'ai_flashcard')
return NextResponse.json({ deckId, count: cards.length, cards })
}