Files
Momento/memento-note/app/api/brainstorm/[sessionId]/route.ts
Antigravity 5728452b4a
Some checks failed
CI / Lint, Test & Build (push) Failing after 17s
CI / Deploy production (on server) (push) Has been skipped
feat: add slides generation tool with multiple slide types
- Add slides.tool.ts with support for title, bullets, chart, stats, table, cards, timeline, quote, comparison, equation, image, summary slide types
- Chart types: bar, horizontal-bar, line, donut, radar
- Integrate with agent executor and canvas system
- Add multilingual support (en/fr)
- Various UI improvements and bug fixes

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 17:18:48 +00:00

217 lines
6.5 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
function resolveAccessRole(
brainstormSession: any,
userId: string | null
): 'owner' | 'editor' | 'viewer' | 'guest' | 'none' {
if (!userId) {
return brainstormSession.isPublic ? 'guest' : 'none'
}
if (brainstormSession.userId === userId) return 'owner'
const participant = brainstormSession.participants?.find(
(p: any) => p.userId === userId
)
if (participant) return participant.role
const acceptedShare = brainstormSession.shares?.find(
(s: any) => s.userId === userId && s.status === 'accepted'
)
if (acceptedShare) return acceptedShare.permission
return brainstormSession.isPublic ? 'guest' : 'none'
}
function filterNoteRefsByRole(ideas: any[], role: string): any[] {
const allowedVis = role === 'owner'
? ['public', 'participants', 'owner_only']
: role === 'editor'
? ['public', 'participants', 'owner_only']
: role === 'viewer'
? ['public', 'participants']
: ['public']
return ideas.map((idea: any) => ({
...idea,
noteRefs: (idea.noteRefs || []).filter(
(ref: any) => allowedVis.includes(ref.visibility || 'participants')
),
}))
}
function sanitizeForGuest(session: any): any {
const { participants, shares, ...rest } = session
const filteredIdeas = filterNoteRefsByRole(rest.ideas || [], 'guest')
return {
...rest,
ideas: filteredIdeas,
sourceNote: null,
exportedNote: null,
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> }
) {
const authSession = await auth()
const userId = authSession?.user?.id || null
try {
const { sessionId } = await params
const brainstormSession = await prisma.brainstormSession.findFirst({
where: { id: sessionId },
include: {
ideas: {
orderBy: [{ waveNumber: 'asc' }, { createdAt: 'asc' }],
include: {
noteRefs: {
include: {
note: { select: { id: true, title: true } },
},
},
},
},
sourceNote: {
select: { id: true, title: true },
},
exportedNote: {
select: { id: true, title: true },
},
participants: {
where: userId ? { userId } : undefined,
select: { userId: true, role: true },
},
shares: userId
? {
where: { userId, status: 'accepted' },
select: { userId: true, permission: true },
}
: false,
},
})
if (!brainstormSession) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
const creatorIds = [...new Set(brainstormSession.ideas.map((i: any) => i.createdBy).filter(Boolean))]
const creators = creatorIds.length > 0
? await prisma.user.findMany({ where: { id: { in: creatorIds } }, select: { id: true, name: true, image: true } })
: []
const creatorMap = new Map(creators.map((c: any) => [c.id, c]))
for (const idea of brainstormSession.ideas) {
(idea as any).creator = (idea as any).createdBy ? creatorMap.get((idea as any).createdBy) || null : null
}
const role = resolveAccessRole(brainstormSession, userId)
if (role === 'none') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
let responseData: any = brainstormSession
if (role === 'guest') {
responseData = sanitizeForGuest(brainstormSession)
} else if (role === 'viewer') {
const { participants: _p, shares: _s, ...rest } = brainstormSession as any
responseData = {
...rest,
ideas: filterNoteRefsByRole(rest.ideas || [], 'viewer'),
}
} else {
const { participants: _p, shares: _s, ...rest } = brainstormSession as any
responseData = rest
}
return NextResponse.json({
success: true,
data: responseData,
_meta: { role, canEdit: ['owner', 'editor'].includes(role) || (role === 'guest' && brainstormSession.guestCanEdit) },
})
} catch (error) {
console.error('Error fetching brainstorm session:', error)
return NextResponse.json(
{ error: 'Failed to fetch session' },
{ status: 500 }
)
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> }
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const { sessionId } = await params
const body = await request.json()
const brainstormSession = await prisma.brainstormSession.findFirst({
where: { id: sessionId, userId: session.user.id },
})
if (!brainstormSession) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
const updates: Record<string, any> = {}
if (typeof body.isPublic === 'boolean') updates.isPublic = body.isPublic
if (typeof body.guestCanEdit === 'boolean') updates.guestCanEdit = body.guestCanEdit
if (typeof body.seedIdea === 'string' && body.seedIdea.trim()) updates.seedIdea = body.seedIdea.trim()
if (Object.keys(updates).length === 0) {
return NextResponse.json({ error: 'No valid fields to update' }, { status: 400 })
}
const updated = await prisma.brainstormSession.update({
where: { id: sessionId },
data: updates,
})
return NextResponse.json({ success: true, data: updated })
} catch (error) {
console.error('Error updating brainstorm session:', error)
return NextResponse.json(
{ error: 'Failed to update session' },
{ status: 500 }
)
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> }
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const { sessionId } = await params
const brainstormSession = await prisma.brainstormSession.findFirst({
where: { id: sessionId, userId: session.user.id },
})
if (!brainstormSession) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
await prisma.brainstormSession.delete({
where: { id: sessionId },
})
return NextResponse.json({ success: true })
} catch (error) {
console.error('Error deleting brainstorm session:', error)
return NextResponse.json(
{ error: 'Failed to delete session' },
{ status: 500 }
)
}
}