diff --git a/src/main/kotlin/com/terraformation/backend/customer/OrganizationService.kt b/src/main/kotlin/com/terraformation/backend/customer/OrganizationService.kt index 02ac6b3ef693..352eec37c14a 100644 --- a/src/main/kotlin/com/terraformation/backend/customer/OrganizationService.kt +++ b/src/main/kotlin/com/terraformation/backend/customer/OrganizationService.kt @@ -123,11 +123,22 @@ class OrganizationService( requirePermissions { deleteOrganization(organizationId) } dslContext.transaction { _ -> - val users = organizationStore.fetchUsers(organizationId) + val allUsers = organizationStore.fetchUsers(organizationId) + + // Fetch all users that aren't a Terraformation Contact (which cannot be removed by org + // owners in the client). This allows us to check for the last remaining Owner. + val users = allUsers.filter { user -> user.role != Role.TerraformationContact } if (users.size != 1 || users[0].userId != currentUser().userId) { throw OrganizationHasOtherUsersException(organizationId) } + // The backend will handle deletion of the Terraformation Contact when the organization is + // being deleted. + val tfContact = allUsers.findLast { user -> user.role == Role.TerraformationContact } + if (tfContact != null) { + systemUser.run { organizationStore.removeUser(organizationId, tfContact.userId) } + } + organizationStore.removeUser( organizationId, currentUser().userId, allowRemovingLastOwner = true) } diff --git a/src/test/kotlin/com/terraformation/backend/customer/OrganizationServiceTest.kt b/src/test/kotlin/com/terraformation/backend/customer/OrganizationServiceTest.kt index a14747a5ae46..e62cba6fe7ca 100644 --- a/src/test/kotlin/com/terraformation/backend/customer/OrganizationServiceTest.kt +++ b/src/test/kotlin/com/terraformation/backend/customer/OrganizationServiceTest.kt @@ -135,6 +135,22 @@ internal class OrganizationServiceTest : DatabaseTest(), RunsAsUser { assertEquals(expected, actual) } + @Test + fun `deleteOrganization removes Terraformation Contact user from organization`() { + val tfContactUserId = UserId(5) + insertUser() + insertUser(userId = tfContactUserId, email = "tfcontact@terraformation.com") + insertOrganization() + insertOrganizationUser(role = Role.Owner) + insertOrganizationUser(userId = tfContactUserId, role = Role.TerraformationContact) + + service.deleteOrganization(organizationId) + + val expected = emptyList() + val actual = dslContext.selectFrom(ORGANIZATION_USERS).fetch() + assertEquals(expected, actual) + } + @Test fun `deleteOrganization publishes event on success`() { insertUser()