@@ -42,7 +42,72 @@ class businessLogicProject{
4242 } ) ;
4343 }
4444
45- updateProject ( ) {
45+ async updateProject ( projectId : string , projectData : Partial < any > , userId : number ) {
46+
47+ return knex . transaction ( async ( trx ) => {
48+
49+ // Busca projeto e valida autoria
50+ const existingProject = await trx ( 'Projects' )
51+ . where ( { projectID : projectId } )
52+ . first ( ) ;
53+
54+ if ( ! existingProject ) {
55+ throw new Error ( "Projeto não encontrado." ) ;
56+ }
57+
58+ if ( existingProject . creatorID !== userId ) {
59+ throw new Error ( "Você não tem permissão para editar este projeto." ) ;
60+ }
61+
62+ // Prepara campos da tabela PRINCIPAL (Projects)
63+ const fieldsToUpdate : any = { } ;
64+
65+ if ( projectData . title !== undefined ) fieldsToUpdate . title = projectData . title ;
66+ if ( projectData . description !== undefined ) fieldsToUpdate . description = projectData . description ;
67+ if ( projectData . status !== undefined ) fieldsToUpdate . status = projectData . status ;
68+ if ( projectData . startDate !== undefined ) fieldsToUpdate . startDate = projectData . startDate ;
69+
70+ // Atualiza o 'updatedAt' se houver mudanças nos campos principais
71+ if ( Object . keys ( fieldsToUpdate ) . length > 0 ) {
72+ fieldsToUpdate . updatedAt = new Date ( ) ;
73+
74+ await trx ( 'Projects' )
75+ . where ( { projectID : projectId } )
76+ . update ( fieldsToUpdate ) ;
77+ }
78+
79+ // Atualiza a tabela de relacionamento (ProjectsKeywords)
80+ if ( projectData . technologies !== undefined ) {
81+
82+ // Remove TODAS as associações antigas desse projeto
83+ await trx ( 'ProjectsKeywords' )
84+ . where ( { projectID : projectId } )
85+ . del ( ) ;
86+
87+ // Se a nova lista não estiver vazia, insere as novas
88+ if ( Array . isArray ( projectData . technologies ) && projectData . technologies . length > 0 ) {
89+
90+ // Busca os IDs das tags (Keywords) baseadas no nome (string) enviado pelo front
91+ const keywordIDs = await trx ( 'Keywords' )
92+ . whereIn ( 'tag' , projectData . technologies )
93+ . select ( 'keywordID' ) ;
94+
95+ // Prepara o array de inserção
96+ const linksToInsert = keywordIDs . map ( ( k : any ) => ( {
97+ projectID : projectId ,
98+ keywordID : k . keywordID
99+ } ) ) ;
100+
101+ // Insere
102+ if ( linksToInsert . length > 0 ) {
103+ await trx ( 'ProjectsKeywords' ) . insert ( linksToInsert ) ;
104+ }
105+ }
106+ }
107+
108+ // Retorna o projeto atualizado
109+ return await trx ( 'Projects' ) . where ( { projectID : projectId } ) . first ( ) ;
110+ } ) ;
46111 }
47112
48113 async userProjects ( creatorID : number ) {
0 commit comments