| 62 | } |
| 63 | |
| 64 | async deleteTeam(teamId, userId) { |
| 65 | // first check if the user owns other teams |
| 66 | const otherTeams = await db.TeamRole |
| 67 | .findAll({ where: { user_id: userId, role: "teamOwner", team_id: { [Op.ne]: teamId } } }); |
| 68 | |
| 69 | if (otherTeams.length < 1) { |
| 70 | return new Promise((resolve, reject) => reject(new Error("You cannot delete a team that you own if you have no other teams"))); |
| 71 | } |
| 72 | |
| 73 | // Use a transaction to ensure data consistency |
| 74 | const transaction = await db.sequelize.transaction(); |
| 75 | |
| 76 | try { |
| 77 | // Delete all related models with team_id |
| 78 | await db.PinnedDashboard.destroy({ where: { team_id: teamId }, transaction }); |
| 79 | await db.SavedQuery.destroy({ where: { team_id: teamId }, transaction }); |
| 80 | await db.Integration.destroy({ where: { team_id: teamId }, transaction }); |
| 81 | await db.OAuth.destroy({ where: { team_id: teamId }, transaction }); |
| 82 | await db.Template.destroy({ where: { team_id: teamId }, transaction }); |
| 83 | await db.Apikey.destroy({ where: { team_id: teamId }, transaction }); |
| 84 | await db.Connection.destroy({ where: { team_id: teamId }, transaction }); |
| 85 | await db.Dataset.destroy({ where: { team_id: teamId }, transaction }); |
| 86 | await db.Project.destroy({ where: { team_id: teamId }, transaction }); |
| 87 | await db.TeamRole.destroy({ where: { team_id: teamId }, transaction }); |
| 88 | |
| 89 | // Finally delete the team (this will cascade delete TeamRole and TeamInvitation) |
| 90 | await db.Team.destroy({ where: { id: teamId }, transaction }); |
| 91 | |
| 92 | // Commit the transaction |
| 93 | await transaction.commit(); |
| 94 | |
| 95 | return true; |
| 96 | } catch (error) { |
| 97 | // Rollback the transaction on error |
| 98 | await transaction.rollback(); |
| 99 | return new Promise((resolve, reject) => reject(error)); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | async transferOwnership(teamId, userId, newOwnerId) { |
| 104 | const newOwnerRole = await db.TeamRole |