feat(notes): vues structurées tableau/kanban, flashcards et MCP robuste
Some checks failed
CI / Lint, Test & Build (push) Failing after 57s
CI / Deploy production (on server) (push) Has been skipped

Ajoute la base organisable par carnet (schéma, champs partagés, valeurs par note)
avec activation guidée, tableau éditable, kanban et suppression de colonnes.
Corrige le multiselect en vue tableau et enrichit sidebar, grille et i18n FR/EN.
Inclut aussi les améliorations flashcards SM-2, l'audit consentement IA et la
robustesse du serveur MCP (config, validation, rate-limit, métriques).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Antigravity
2026-05-24 23:03:16 +00:00
parent ecd7e57c2e
commit 0784c94242
63 changed files with 10133 additions and 619 deletions

View File

@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import prisma from '@/lib/prisma'
/**
* PATCH /api/flashcards/[id]
* Update front and/or back of a flashcard.
*/
export async function PATCH(
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: cardId } = await params
const body = await request.json()
const front = typeof body.front === 'string' ? body.front.trim() : undefined
const back = typeof body.back === 'string' ? body.back.trim() : undefined
if (!front && !back) {
return NextResponse.json({ error: 'Nothing to update' }, { status: 400 })
}
const card = await prisma.flashcard.findFirst({
where: { id: cardId, deck: { userId: session.user.id } },
})
if (!card) {
return NextResponse.json({ error: 'Card not found' }, { status: 404 })
}
const updated = await prisma.flashcard.update({
where: { id: cardId },
data: {
...(front !== undefined && { front }),
...(back !== undefined && { back }),
},
})
return NextResponse.json({ card: { id: updated.id, front: updated.front, back: updated.back } })
} catch (error) {
console.error('[flashcards/[id] PATCH]', error)
return NextResponse.json({ error: 'Failed to update card' }, { status: 500 })
}
}
/**
* DELETE /api/flashcards/[id]
* Delete a single flashcard.
*/
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: cardId } = await params
const card = await prisma.flashcard.findFirst({
where: { id: cardId, deck: { userId: session.user.id } },
})
if (!card) {
return NextResponse.json({ error: 'Card not found' }, { status: 404 })
}
await prisma.flashcard.delete({ where: { id: cardId } })
return NextResponse.json({ ok: true })
} catch (error) {
console.error('[flashcards/[id] DELETE]', error)
return NextResponse.json({ error: 'Failed to delete card' }, { status: 500 })
}
}

View File

@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import prisma from '@/lib/prisma'
import { getDeckDetail } from '@/lib/flashcards/deck-queries'
export async function GET(
@@ -35,3 +36,35 @@ export async function GET(
return NextResponse.json({ error: 'Failed to load deck' }, { status: 500 })
}
}
/**
* DELETE /api/flashcards/decks/[id]
* Permanently deletes the deck and all its cards (cascade via Prisma).
*/
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 } = await params
const deck = await prisma.flashcardDeck.findFirst({
where: { id, userId: session.user.id },
})
if (!deck) {
return NextResponse.json({ error: 'Deck not found' }, { status: 404 })
}
await prisma.flashcardDeck.delete({ where: { id } })
return NextResponse.json({ ok: true })
} catch (error) {
console.error('[flashcards/decks/[id] DELETE]', error)
return NextResponse.json({ error: 'Failed to delete deck' }, { status: 500 })
}
}

View File

@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { Prisma } from '@prisma/client'
import { auth } from '@/auth'
import prisma from '@/lib/prisma'
import { prisma } from '@/lib/prisma'
import { getOrCreateDeckForNotebook } from '@/lib/flashcards/deck-utils'
import type { FlashcardStyle } from '@/lib/flashcards/generate-flashcards'
@@ -12,6 +13,13 @@ interface CardInput {
export async function POST(request: NextRequest) {
try {
if (!prisma.flashcard || !prisma.flashcardDeck) {
return NextResponse.json(
{ error: 'Flashcards client outdated. Restart the app after prisma generate.', errorKey: 'flashcards.schemaMissing' },
{ status: 503 },
)
}
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
@@ -103,6 +111,15 @@ export async function POST(request: NextRequest) {
})
} catch (error) {
console.error('[flashcards/save]', error)
return NextResponse.json({ error: 'Failed to save flashcards' }, { status: 500 })
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === 'P2021' || error.code === 'P2022') {
return NextResponse.json(
{ error: 'Flashcards schema not migrated. Run prisma migrate deploy.', errorKey: 'flashcards.schemaMissing' },
{ status: 503 },
)
}
}
const message = error instanceof Error ? error.message : 'Failed to save flashcards'
return NextResponse.json({ error: message }, { status: 500 })
}
}

View File

@@ -13,19 +13,26 @@ export async function GET() {
const userId = session.user.id
const now = new Date()
const oneYearAgo = new Date()
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1)
// Récupérer les reviews de la dernière année + toutes les cartes
const [reviews, allCards] = await Promise.all([
prisma.flashcardReview.findMany({
where: { card: { deck: { userId } } },
where: {
card: { deck: { userId } },
reviewedAt: { gte: oneYearAgo },
},
select: { reviewedAt: true, grade: true },
orderBy: { reviewedAt: 'desc' },
take: 500,
orderBy: { reviewedAt: 'asc' },
}),
prisma.flashcard.findMany({
where: { deck: { userId } },
select: { id: true, interval: true, easinessFactor: true, front: true, deck: { select: { name: true } } },
select: { id: true, interval: true, easinessFactor: true, front: true, deck: { select: { id: true, name: true } } },
}),
])
// --- Heatmap (90 derniers jours) ---
const heatmapMap = new Map<string, number>()
for (const r of reviews) {
const day = r.reviewedAt.toISOString().slice(0, 10)
@@ -36,33 +43,62 @@ export async function GET() {
.sort((a, b) => a.date.localeCompare(b.date))
.slice(-90)
// --- Taux de rétention global (cartes maîtrisées / total) ---
const totalCards = allCards.length
const masteredCount = allCards.filter((c) => isCardMastered(c.interval)).length
// Maîtrisée = interval >= 7 jours (cohérent avec deck-queries)
const masteredCount = allCards.filter((c) => c.interval >= 7).length
const retentionRate = totalCards > 0 ? Math.round((masteredCount / totalCards) * 100) : 0
// --- Rétention par semaine : vrai taux de succès (grade >= 3) sur les reviews réelles ---
const weekMs = 7 * 24 * 60 * 60 * 1000
const retentionByWeek: { week: string; rate: number }[] = []
const retentionByWeek: { week: string; rate: number; total: number }[] = []
for (let i = 7; i >= 0; i--) {
const weekEnd = new Date(now.getTime() - i * weekMs)
const weekStart = new Date(weekEnd.getTime() - weekMs)
const cardsAtWeek = allCards.filter((c) => c.interval >= 7 * (8 - i))
const masteredAtWeek = cardsAtWeek.filter((c) => isCardMastered(c.interval)).length
const rate = cardsAtWeek.length > 0
? Math.round((masteredAtWeek / cardsAtWeek.length) * 100)
: retentionRate
const weekReviews = reviews.filter((r) => {
const t = r.reviewedAt.getTime()
return t >= weekStart.getTime() && t < weekEnd.getTime()
})
const total = weekReviews.length
const successful = weekReviews.filter((r) => r.grade >= 3).length
// Si aucune review cette semaine, on laisse null pour distinguer "pas de données" vs "0%"
const rate = total > 0 ? Math.round((successful / total) * 100) : -1
retentionByWeek.push({
week: weekStart.toISOString().slice(0, 10),
rate,
total,
})
}
// --- Streak (jours consécutifs avec au moins 1 review) ---
const reviewDays = new Set(reviews.map((r) => r.reviewedAt.toISOString().slice(0, 10)))
let streak = 0
for (let d = 0; d < 365; d++) {
const day = new Date(now)
day.setDate(day.getDate() - d)
const key = day.toISOString().slice(0, 10)
if (reviewDays.has(key)) {
streak++
} else {
// On tolère le jour actuel s'il n'a pas encore eu de review (on commence à hier)
if (d === 0) continue
break
}
}
// --- Cartes difficiles (facteur d'aisance le plus bas) ---
const difficultCards = [...allCards]
.sort((a, b) => a.easinessFactor - b.easinessFactor)
.slice(0, 5)
.slice(0, 10)
.map((c) => ({
id: c.id,
front: c.front.slice(0, 120),
front: c.front.slice(0, 200),
easinessFactor: c.easinessFactor,
deckId: c.deck.id,
deckName: c.deck.name,
}))
@@ -72,6 +108,9 @@ export async function GET() {
retentionByWeek,
difficultCards,
totalReviews: reviews.length,
streak,
totalCards,
masteredCount,
})
} catch (error) {
console.error('[flashcards/stats]', error)

View File

@@ -0,0 +1,204 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { MAX_PROPERTIES_PER_NOTEBOOK } from '@/lib/structured-views/types'
import { isValidPropertyType } from '@/lib/structured-views/property-utils'
import { buildNoteValuesMap, parseViewSettings, serializeSchema } from '@/lib/structured-views/schema-serialize'
async function assertNotebookAccess(notebookId: string, userId: string) {
return prisma.notebook.findFirst({
where: { id: notebookId, userId, trashedAt: null },
select: { id: true },
})
}
const schemaInclude = {
properties: { orderBy: { position: 'asc' as const } },
} as const
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
try {
const { id: notebookId } = await params
const notebook = await assertNotebookAccess(notebookId, session.user.id)
if (!notebook) {
return NextResponse.json({ success: false, error: 'Notebook not found' }, { status: 404 })
}
const raw = await prisma.notebookSchema.findUnique({
where: { notebookId },
include: schemaInclude,
})
const schema = serializeSchema(raw)
if (!schema) {
return NextResponse.json({ success: true, data: { schema: null, noteValues: {} } })
}
const notes = await prisma.note.findMany({
where: { notebookId, userId: session.user.id, trashedAt: null },
select: { id: true },
})
const noteIds = notes.map((n) => n.id)
const rows = noteIds.length
? await prisma.noteProperty.findMany({
where: { noteId: { in: noteIds } },
include: { property: { select: { type: true } } },
})
: []
const noteValues = buildNoteValuesMap(noteIds, rows)
return NextResponse.json({ success: true, data: { schema, noteValues } })
} catch (error) {
console.error('GET notebook schema:', error)
return NextResponse.json({ success: false, error: 'Failed to load schema' }, { status: 500 })
}
}
export async function POST(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
try {
const { id: notebookId } = await params
const notebook = await assertNotebookAccess(notebookId, session.user.id)
if (!notebook) {
return NextResponse.json({ success: false, error: 'Notebook not found' }, { status: 404 })
}
const existing = await prisma.notebookSchema.findUnique({ where: { notebookId } })
if (existing) {
const raw = await prisma.notebookSchema.findUnique({
where: { notebookId },
include: schemaInclude,
})
return NextResponse.json({ success: true, data: { schema: serializeSchema(raw) } })
}
const created = await prisma.notebookSchema.create({
data: { notebookId },
include: schemaInclude,
})
return NextResponse.json({ success: true, data: { schema: serializeSchema(created) } })
} catch (error) {
console.error('POST notebook schema:', error)
return NextResponse.json({ success: false, error: 'Failed to create schema' }, { status: 500 })
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
try {
const { id: notebookId } = await params
const notebook = await assertNotebookAccess(notebookId, session.user.id)
if (!notebook) {
return NextResponse.json({ success: false, error: 'Notebook not found' }, { status: 404 })
}
const body = await request.json()
const action = typeof body.action === 'string' ? body.action : ''
let schema = await prisma.notebookSchema.findUnique({ where: { notebookId } })
if (!schema) {
schema = await prisma.notebookSchema.create({ data: { notebookId } })
}
if (action === 'addProperty') {
const name = typeof body.name === 'string' ? body.name.trim() : ''
const type = typeof body.type === 'string' ? body.type : ''
if (!name || !isValidPropertyType(type)) {
return NextResponse.json({ success: false, error: 'Invalid property' }, { status: 400 })
}
const count = await prisma.notebookProperty.count({ where: { schemaId: schema.id } })
if (count >= MAX_PROPERTIES_PER_NOTEBOOK) {
return NextResponse.json({ success: false, error: 'Max properties reached' }, { status: 400 })
}
let options: string[] = []
if (type === 'select' || type === 'multiselect') {
options = Array.isArray(body.options)
? body.options
.filter((o: unknown): o is string => typeof o === 'string' && o.trim().length > 0)
.map((o: string) => o.trim())
: []
if (options.length === 0) {
return NextResponse.json({ success: false, error: 'Options required' }, { status: 400 })
}
}
await prisma.notebookProperty.create({
data: {
schemaId: schema.id,
name,
type,
options: options.length ? JSON.stringify(options) : null,
position: count,
},
})
} else if (action === 'deleteProperty') {
const propertyId = typeof body.propertyId === 'string' ? body.propertyId : ''
if (!propertyId) {
return NextResponse.json({ success: false, error: 'propertyId required' }, { status: 400 })
}
const currentSettings = parseViewSettings(schema.viewSettings)
await prisma.notebookProperty.deleteMany({
where: { id: propertyId, schemaId: schema.id },
})
if (currentSettings.kanbanGroupPropertyId === propertyId) {
await prisma.notebookSchema.update({
where: { id: schema.id },
data: { viewSettings: JSON.stringify({ ...currentSettings, kanbanGroupPropertyId: null }) },
})
}
} else if (action === 'updateViewSettings') {
const current = parseViewSettings(schema.viewSettings)
const next: Record<string, unknown> = { ...current }
if ('kanbanGroupPropertyId' in body) {
next.kanbanGroupPropertyId =
typeof body.kanbanGroupPropertyId === 'string' ? body.kanbanGroupPropertyId : null
}
await prisma.notebookSchema.update({
where: { id: schema.id },
data: { viewSettings: JSON.stringify(next) },
})
} else if (action === 'disable') {
await prisma.notebookSchema.delete({ where: { id: schema.id } })
return NextResponse.json({ success: true, data: { schema: null } })
} else {
return NextResponse.json({ success: false, error: 'Unknown action' }, { status: 400 })
}
const raw = await prisma.notebookSchema.findUnique({
where: { notebookId },
include: schemaInclude,
})
return NextResponse.json({ success: true, data: { schema: serializeSchema(raw) } })
} catch (error) {
console.error('PATCH notebook schema:', error)
return NextResponse.json({ success: false, error: 'Failed to update schema' }, { status: 500 })
}
}

View File

@@ -0,0 +1,105 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { isValidPropertyType, serializePropertyValue } from '@/lib/structured-views/property-utils'
import { parseStoredPropertyValue } from '@/lib/structured-views/property-utils'
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
try {
const { id: noteId } = await params
const note = await prisma.note.findFirst({
where: { id: noteId, userId: session.user.id, trashedAt: null },
select: { id: true, notebookId: true },
})
if (!note?.notebookId) {
return NextResponse.json({ success: false, error: 'Note not found' }, { status: 404 })
}
const schema = await prisma.notebookSchema.findUnique({
where: { notebookId: note.notebookId },
include: { properties: true },
})
if (!schema) {
return NextResponse.json({ success: false, error: 'Schema not found' }, { status: 404 })
}
const body = await request.json()
const updates = body.properties && typeof body.properties === 'object'
? body.properties as Record<string, unknown>
: null
if (!updates) {
return NextResponse.json({ success: false, error: 'Invalid payload' }, { status: 400 })
}
const propertyById = new Map(schema.properties.map((p) => [p.id, p]))
const result: Record<string, unknown> = {}
for (const [propertyId, value] of Object.entries(updates)) {
const prop = propertyById.get(propertyId)
if (!prop || !isValidPropertyType(prop.type)) continue
const serialized = serializePropertyValue(prop.type, value)
if (serialized == null) {
await prisma.noteProperty.deleteMany({ where: { noteId, propertyId } })
result[propertyId] = parseStoredPropertyValue(prop.type, null)
} else {
await prisma.noteProperty.upsert({
where: { noteId_propertyId: { noteId, propertyId } },
create: { noteId, propertyId, value: serialized },
update: { value: serialized },
})
result[propertyId] = parseStoredPropertyValue(prop.type, serialized)
}
}
return NextResponse.json({ success: true, data: { values: result } })
} catch (error) {
console.error('PATCH note properties:', error)
return NextResponse.json({ success: false, error: 'Failed to update properties' }, { status: 500 })
}
}
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
try {
const { id: noteId } = await params
const note = await prisma.note.findFirst({
where: { id: noteId, userId: session.user.id },
select: { id: true },
})
if (!note) {
return NextResponse.json({ success: false, error: 'Note not found' }, { status: 404 })
}
const rows = await prisma.noteProperty.findMany({
where: { noteId },
include: { property: { select: { type: true } } },
})
const values: Record<string, unknown> = {}
for (const row of rows) {
if (!isValidPropertyType(row.property.type)) continue
values[row.propertyId] = parseStoredPropertyValue(row.property.type, row.value)
}
return NextResponse.json({ success: true, data: { values } })
} catch (error) {
console.error('GET note properties:', error)
return NextResponse.json({ success: false, error: 'Failed to load properties' }, { status: 500 })
}
}

View File

@@ -36,31 +36,48 @@ export async function POST(req: NextRequest) {
// Hash/Anonymize IP address for strict GDPR compliance
const anonymizedIp = ip ? createHash('sha256').update(ip).digest('hex') : null
// Create persistent audit log of this consent decision
await prisma.aiConsentLog.create({
data: {
userId,
consent,
ipAddress: anonymizedIp,
userAgent,
},
})
// If remember is requested, persist state in UserAISettings
if (remember) {
await prisma.userAISettings.upsert({
where: { userId },
create: {
let auditOk = true
try {
await prisma.aiConsentLog.create({
data: {
userId,
aiProcessingConsent: consent,
},
update: {
aiProcessingConsent: consent,
consent,
ipAddress: anonymizedIp,
userAgent,
},
})
} catch (auditError) {
auditOk = false
console.error('[POST /api/user/ai-consent] audit log failed:', auditError)
}
if (remember) {
try {
await prisma.userAISettings.upsert({
where: { userId },
create: {
userId,
aiProcessingConsent: consent,
},
update: {
aiProcessingConsent: consent,
},
})
} catch (settingsError) {
console.error('[POST /api/user/ai-consent] settings upsert failed:', settingsError)
return NextResponse.json({ error: 'settings_update_failed' }, { status: 500 })
}
}
if (!auditOk) {
return NextResponse.json({
success: true,
auditLogged: false,
warning: 'audit_log_failed',
})
}
return NextResponse.json({ success: true })
return NextResponse.json({ success: true, auditLogged: true })
} catch (error) {
console.error('[POST /api/user/ai-consent] failed:', error)
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })