@@ -141,6 +141,23 @@ export async function DELETE(
141141 )
142142 }
143143
144+ // Check if deleting this folder would delete the last workflow(s) in the workspace
145+ const workflowsInFolder = await countWorkflowsInFolderRecursively (
146+ id ,
147+ existingFolder . workspaceId
148+ )
149+ const totalWorkflowsInWorkspace = await db
150+ . select ( { id : workflow . id } )
151+ . from ( workflow )
152+ . where ( eq ( workflow . workspaceId , existingFolder . workspaceId ) )
153+
154+ if ( workflowsInFolder > 0 && workflowsInFolder >= totalWorkflowsInWorkspace . length ) {
155+ return NextResponse . json (
156+ { error : 'Cannot delete folder containing the only workflow(s) in the workspace' } ,
157+ { status : 400 }
158+ )
159+ }
160+
144161 // Recursively delete folder and all its contents
145162 const deletionStats = await deleteFolderRecursively ( id , existingFolder . workspaceId )
146163
@@ -202,6 +219,34 @@ async function deleteFolderRecursively(
202219 return stats
203220}
204221
222+ /**
223+ * Counts the number of workflows in a folder and all its subfolders recursively.
224+ */
225+ async function countWorkflowsInFolderRecursively (
226+ folderId : string ,
227+ workspaceId : string
228+ ) : Promise < number > {
229+ let count = 0
230+
231+ const workflowsInFolder = await db
232+ . select ( { id : workflow . id } )
233+ . from ( workflow )
234+ . where ( and ( eq ( workflow . folderId , folderId ) , eq ( workflow . workspaceId , workspaceId ) ) )
235+
236+ count += workflowsInFolder . length
237+
238+ const childFolders = await db
239+ . select ( { id : workflowFolder . id } )
240+ . from ( workflowFolder )
241+ . where ( and ( eq ( workflowFolder . parentId , folderId ) , eq ( workflowFolder . workspaceId , workspaceId ) ) )
242+
243+ for ( const childFolder of childFolders ) {
244+ count += await countWorkflowsInFolderRecursively ( childFolder . id , workspaceId )
245+ }
246+
247+ return count
248+ }
249+
205250// Helper function to check for circular references
206251async function checkForCircularReference ( folderId : string , parentId : string ) : Promise < boolean > {
207252 let currentParentId : string | null = parentId
0 commit comments