-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathroute.ts
More file actions
203 lines (174 loc) · 6.52 KB
/
route.ts
File metadata and controls
203 lines (174 loc) · 6.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import { db } from '@sim/db'
import { workflowFolder } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { captureServerEvent } from '@/lib/posthog/server'
import { performDeleteFolder } from '@/lib/workflows/orchestration'
import { checkForCircularReference, isFolderEffectivelyLockedDb } from '@/lib/workflows/utils'
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
const logger = createLogger('FoldersIDAPI')
const updateFolderSchema = z.object({
name: z.string().optional(),
color: z.string().optional(),
isExpanded: z.boolean().optional(),
parentId: z.string().nullable().optional(),
sortOrder: z.number().int().min(0).optional(),
isLocked: z.boolean().optional(),
})
// PUT - Update a folder
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id } = await params
const body = await request.json()
const validationResult = updateFolderSchema.safeParse(body)
if (!validationResult.success) {
logger.error('Folder update validation failed:', {
errors: validationResult.error.errors,
})
const errorMessages = validationResult.error.errors
.map((err) => `${err.path.join('.')}: ${err.message}`)
.join(', ')
return NextResponse.json({ error: `Validation failed: ${errorMessages}` }, { status: 400 })
}
const { name, color, isExpanded, parentId, sortOrder, isLocked } = validationResult.data
// Verify the folder exists
const existingFolder = await db
.select()
.from(workflowFolder)
.where(eq(workflowFolder.id, id))
.then((rows) => rows[0])
if (!existingFolder) {
return NextResponse.json({ error: 'Folder not found' }, { status: 404 })
}
// Check if user has write permissions for the workspace
const workspacePermission = await getUserEntityPermissions(
session.user.id,
'workspace',
existingFolder.workspaceId
)
if (!workspacePermission || workspacePermission === 'read') {
return NextResponse.json(
{ error: 'Write access required to update folders' },
{ status: 403 }
)
}
// If toggling isLocked, require admin permission
if (isLocked !== undefined && workspacePermission !== 'admin') {
return NextResponse.json(
{ error: 'Admin access required to lock/unlock folders' },
{ status: 403 }
)
}
// If folder is effectively locked, only allow isLocked toggle (admin) and isExpanded toggle
const effectivelyLocked = await isFolderEffectivelyLockedDb(id)
if (effectivelyLocked) {
const hasNonAllowedUpdates =
name !== undefined ||
color !== undefined ||
parentId !== undefined ||
sortOrder !== undefined
if (hasNonAllowedUpdates) {
return NextResponse.json({ error: 'Folder is locked' }, { status: 403 })
}
}
// Prevent setting a folder as its own parent or creating circular references
if (parentId && parentId === id) {
return NextResponse.json({ error: 'Folder cannot be its own parent' }, { status: 400 })
}
// Check for circular references if parentId is provided
if (parentId) {
const wouldCreateCycle = await checkForCircularReference(id, parentId)
if (wouldCreateCycle) {
return NextResponse.json(
{ error: 'Cannot create circular folder reference' },
{ status: 400 }
)
}
}
const updates: Record<string, unknown> = { updatedAt: new Date() }
if (name !== undefined) updates.name = name.trim()
if (color !== undefined) updates.color = color
if (isExpanded !== undefined) updates.isExpanded = isExpanded
if (parentId !== undefined) updates.parentId = parentId || null
if (sortOrder !== undefined) updates.sortOrder = sortOrder
if (isLocked !== undefined) updates.isLocked = isLocked
const [updatedFolder] = await db
.update(workflowFolder)
.set(updates)
.where(eq(workflowFolder.id, id))
.returning()
logger.info('Updated folder:', { id, updates })
return NextResponse.json({ folder: updatedFolder })
} catch (error) {
logger.error('Error updating folder:', { error })
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
// DELETE - Delete a folder and all its contents
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id } = await params
// Verify the folder exists
const existingFolder = await db
.select()
.from(workflowFolder)
.where(eq(workflowFolder.id, id))
.then((rows) => rows[0])
if (!existingFolder) {
return NextResponse.json({ error: 'Folder not found' }, { status: 404 })
}
const workspacePermission = await getUserEntityPermissions(
session.user.id,
'workspace',
existingFolder.workspaceId
)
if (workspacePermission !== 'admin') {
return NextResponse.json(
{ error: 'Admin access required to delete folders' },
{ status: 403 }
)
}
const effectivelyLocked = await isFolderEffectivelyLockedDb(id)
if (effectivelyLocked) {
return NextResponse.json({ error: 'Folder is locked' }, { status: 403 })
}
const result = await performDeleteFolder({
folderId: id,
workspaceId: existingFolder.workspaceId,
userId: session.user.id,
folderName: existingFolder.name,
})
if (!result.success) {
const status =
result.errorCode === 'not_found' ? 404 : result.errorCode === 'validation' ? 400 : 500
return NextResponse.json({ error: result.error }, { status })
}
captureServerEvent(
session.user.id,
'folder_deleted',
{ workspace_id: existingFolder.workspaceId },
{ groups: { workspace: existingFolder.workspaceId } }
)
return NextResponse.json({
success: true,
deletedItems: result.deletedItems,
})
} catch (error) {
logger.error('Error deleting folder:', { error })
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}