Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): delete relationship assignments (#90087)

Arthur Moreira de Deus55350251bce1
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index e7de041d728c..7d93f48703bf 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -3562,6 +3562,14 @@ def get_accessible_account_id(team_id: int, account_id: str, user_access_control
return str(account.id) if account is not None else None
+def get_editable_account_id(team_id: int, account_id: str, user_access_control: "UserAccessControl") -> str | None:
+ """The account_id when the caller can edit that account, else None."""
+ account = _resolve_accessible_account(team_id, user_access_control, account_id=account_id)
+ if account is None or not user_access_control.check_access_level_for_object(account, required_level="editor"):
+ return None
+ return str(account.id)
+
+
def list_account_channel_summaries(
team_id: int,
account_id: str,
@@ -4414,6 +4422,25 @@ def end_account_relationship(
return _to_account_relationship(relationship)
+def delete_account_relationship(
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ relationship_id: str | UUID,
+ actor: "User | None" = None,
+) -> bool:
+ try:
+ _relationships_logic.delete_relationship(
+ team_id=team_id,
+ account_id=account_id,
+ relationship_id=str(relationship_id),
+ actor=actor,
+ )
+ except _relationships_logic.AccountRelationshipNotFound:
+ return False
+ return True
+
+
# --- EventStream ---
diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.py
index c7b024ee5857..edbb4361768b 100644
--- a/products/customer_analytics/backend/logic/relationships.py
+++ b/products/customer_analytics/backend/logic/relationships.py
@@ -131,6 +131,36 @@ def end_relationship(
return relationship
+def delete_relationship(
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ relationship_id: str,
+ actor: User | None = None,
+) -> None:
+ with transaction.atomic():
+ relationship = (
+ AccountRelationship.objects.for_team(team_id)
+ .select_related("definition", "user", "account__team")
+ .select_for_update(of=("self",))
+ .filter(id=relationship_id, account_id=account_id)
+ .first()
+ )
+ if relationship is None:
+ raise AccountRelationshipNotFound(relationship_id)
+ was_active = relationship.ended_at is None
+ relationship.delete()
+ if was_active:
+ _schedule_relationship_changed_event(
+ account=relationship.account,
+ definition=relationship.definition,
+ previous_user=relationship.user,
+ current_user=None,
+ actor=actor,
+ workflow_id=None,
+ )
+
+
def _schedule_relationship_changed_event(
*,
account: Account,
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 1760597a9e24..97e1c31402d3 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -29,6 +29,7 @@ from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
@@ -2186,6 +2187,13 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
return Response(CustomPropertyValueSerializer(value).data, status=status.HTTP_201_CREATED)
+class AccountRelationshipDeletePermission(BasePermission):
+ message = TeamMemberStrictManagementPermission.message
+
+ def has_permission(self, request: Request, view: Any) -> bool:
+ return request.method != "DELETE" or TeamMemberStrictManagementPermission().has_permission(request, view)
+
+
@extend_schema(
tags=["customer_analytics"],
parameters=[
@@ -2200,6 +2208,7 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):
scope_object = "account"
serializer_class = AccountRelationshipSerializer
+ permission_classes = [AccountRelationshipDeletePermission]
pagination_class = None
def _accessible_account_id(self) -> str | None:
@@ -2269,6 +2278,23 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(AccountRelationshipSerializer(relationship).data)
+ @extend_schema(request=None, responses={204: None})
+ def destroy(self, request: Request, *args, **kwargs) -> Response:
+ account_id = api.get_editable_account_id(
+ self.team_id, self.parents_query_dict["account_id"], user_access_control=self.user_access_control
+ )
+ if account_id is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ deleted = api.delete_account_relationship(
+ team_id=self.team_id,
+ account_id=account_id,
+ relationship_id=self.kwargs["pk"],
+ actor=cast(User, request.user),
+ )
+ if not deleted:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
_EVENT_STREAM_ID_PARAM = OpenApiParameter(
"id",
diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.py
index eede186181d2..aa42079f7126 100644
--- a/products/customer_analytics/backend/test/test_events.py
+++ b/products/customer_analytics/backend/test/test_events.py
@@ -407,6 +407,37 @@ class TestAccountRelationshipChangedEvent(BaseTest):
assert properties["current_user_id"] is None
assert properties["current_user_email"] is None
+ @parameterized.expand([("active", False), ("ended", True)])
+ def test_hard_delete_emits_only_for_active_assignment(self, mock_capture, _case, ended):
+ relationship = self._assign()
+ mock_capture.reset_mock()
+ if ended:
+ with self.captureOnCommitCallbacks(execute=True):
+ facade.end_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ relationship_id=relationship.id,
+ actor=self.user,
+ )
+ mock_capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ assert facade.delete_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ relationship_id=relationship.id,
+ actor=self.user,
+ )
+
+ if ended:
+ mock_capture.assert_not_called()
+ else:
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["properties"]["change_type"] == "unassigned"
+ assert event["properties"]["previous_user_id"] == self.user.id
+ assert event["properties"]["current_user_id"] is None
+
def test_assigning_same_user_emits_nothing(self, mock_capture):
self._assign()
mock_capture.reset_mock()
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 98a8b83a9468..4b12409fe60a 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -2740,6 +2740,73 @@ class TestAccountRelationshipViewSet(APIBaseTest):
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+ @parameterized.expand([("active", False), ("ended", True)])
+ def test_admin_hard_deletes_relationship(self, _case, ended):
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(
+ level=OrganizationMembership.Level.ADMIN
+ )
+ definition = self._create_relationship_definition()
+ relationship = relationships_logic.assign(
+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
+ )
+ if ended:
+ relationships_logic.end_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=str(relationship.id)
+ )
+
+ response = self.client.delete(f"{self.endpoint}{relationship.id}/")
+
+ self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
+ self.assertFalse(AccountRelationship.objects.for_team(self.team.id).filter(id=relationship.id).exists())
+
+ def test_non_admin_cannot_hard_delete_relationship(self):
+ definition = self._create_relationship_definition()
+ relationship = relationships_logic.assign(
+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
+ )
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.client.force_login(member)
+
+ response = self.client.delete(f"{self.endpoint}{relationship.id}/")
+
+ self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)
+ self.assertTrue(AccountRelationship.objects.for_team(self.team.id).filter(id=relationship.id).exists())
+
+ def test_account_viewer_cannot_hard_delete_relationship_as_customer_analytics_editor(self):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ definition = self._create_relationship_definition()
+ relationship = relationships_logic.assign(
+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
+ )
+ account_viewer = User.objects.create_and_join(
+ self.organization, "[email protected]", "testtest"
+ )
+ membership = OrganizationMembership.objects.get(user=account_viewer, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_analytics",
+ resource_id=None,
+ access_level="editor",
+ organization_member=membership,
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(self.account.id),
+ access_level="viewer",
+ organization_member=membership,
+ )
+ self.client.force_login(account_viewer)
+
+ response = self.client.delete(f"{self.endpoint}{relationship.id}/")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+ self.assertTrue(AccountRelationship.objects.for_team(self.team.id).filter(id=relationship.id).exists())
+
class TestAccountSupportTicketViewSet(APIBaseTest):
def setUp(self):
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 9fa80e580a32..c757a1634496 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -28,7 +28,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
└── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Feature requests/Usage/Spend/Opportunities/Conversations/Meetings/Event stream)
├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)
├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId; staff get a compact, region-aware admin link)
- ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, current assignments sorted on top)
+ ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, admin-only hard-delete controls with confirmation, current assignments sorted on top)
├── (feature requests) AccountFeatureRequestsExpansion (accountFeatureRequestsLogic, keyed by accountId — linked requests and link-existing flow)
├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)
├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)
@@ -49,7 +49,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |
| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |
| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). It debounces name and email searches. US-region orgs use the org-members endpoint. When it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion then searched and paginated in pages of 20 client-side. Both sources include the member's organization access level. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. A missing view (local dev) degrades to the normal empty state. |
-| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |
+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint), `endRelationship` (per active row, POSTs the end endpoint), and `deleteRelationship` (admin-only, confirmation-gated hard delete). All mutations share the `relationshipSaving` guard, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |
| `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests in server pages of five with debounced search, then searches a bounded server page of accessible, editable active requests for the link picker. Request links carry the account's Feature requests deep link as their origin, so the detail breadcrumb returns to the same account tab. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. |
| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |
| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |
@@ -304,6 +304,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |
| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |
| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end) |
+| `customer analytics accounts relationship deleted` | `accountRelationshipsLogic` `deleteRelationship` listener (after the DELETE succeeds) | _(none - count only; relationship and account identifiers stay out)_ |
| `customer analytics account tags updated` | `accountsLogic` `updateAccountTags` listener (after the debounced PATCH succeeds; dispatched by the tags cell editor) | `tag_count` (tag names kept out — they can name customers) |
| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` (incl. the "Copy link to account" row, `link_key: 'copy-account-link'`) | `link_key`, `has_destination` |
| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
index 4fbd974be1c4..2d9668041856 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
@@ -1,7 +1,15 @@
import { useActions, useValues } from 'kea'
-import { IconX } from '@posthog/icons'
-import { LemonButton, LemonSelect, LemonTable, LemonTableColumns, LemonTag, ProfilePicture } from '@posthog/lemon-ui'
+import { IconTrash, IconX } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonModal,
+ LemonSelect,
+ LemonTable,
+ LemonTableColumns,
+ LemonTag,
+ ProfilePicture,
+} from '@posthog/lemon-ui'
import { MemberSelect } from 'lib/components/MemberSelect'
import { TZLabel } from 'lib/components/TZLabel'
@@ -22,11 +30,19 @@ export function AccountRelationshipsExpansion({ accountId }: { accountId: string
relationshipDefinitions,
assignDefinition,
assignDefinitionId,
+ canDeleteRelationships,
relationshipSaving,
+ relationshipToDelete,
} = useValues(accountRelationshipsLogic({ accountId }))
- const { setDefinitionFilter, setAssignDefinitionId, assignRelationship, endRelationship } = useActions(
- accountRelationshipsLogic({ accountId })
- )
+ const {
+ setDefinitionFilter,
+ setAssignDefinitionId,
+ assignRelationship,
+ endRelationship,
+ openDeleteConfirmation,
+ closeDeleteConfirmation,
+ deleteRelationship,
+ } = useActions(accountRelationshipsLogic({ accountId }))
const columns: LemonTableColumns<AccountRelationshipApi> = [
{
@@ -68,14 +84,29 @@ export function AccountRelationshipsExpansion({ accountId }: { accountId: string
key: 'actions',
width: 0,
render: (_, relationship) =>
- relationship.ended_at ? null : (
- <LemonButton
- size="xsmall"
- icon={<IconX />}
- tooltip={`End this ${relationship.definition.name} assignment`}
- disabledReason={relationshipSaving ? 'Saving…' : undefined}
- onClick={() => endRelationship(relationship)}
- />
+ relationship.ended_at && !canDeleteRelationships ? null : (
+ <div className="flex justify-end gap-1">
+ {!relationship.ended_at && (
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ tooltip={`End this ${relationship.definition.name} assignment`}
+ disabledReason={relationshipSaving ? 'Saving…' : undefined}
+ onClick={() => endRelationship(relationship)}
+ />
+ )}
+ {canDeleteRelationships && (
+ <LemonButton
+ size="xsmall"
+ status="danger"
+ icon={<IconTrash />}
+ tooltip="Delete assignment"
+ disabledReason={relationshipSaving ? 'Saving…' : undefined}
+ data-attr="account-relationships-delete-button"
+ onClick={() => openDeleteConfirmation(relationship)}
+ />
+ )}
+ </div>
),
},
]
@@ -145,6 +176,42 @@ export function AccountRelationshipsExpansion({ accountId }: { accountId: string
relationships === null ? 'Failed to load relationships.' : 'No assignments on this account yet.'
}
/>
+ <LemonModal
+ isOpen={relationshipToDelete !== null}
+ onClose={() => !relationshipSaving && closeDeleteConfirmation()}
+ title="Delete assignment?"
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeDeleteConfirmation}
+ disabledReason={relationshipSaving ? 'Deleting…' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ status="danger"
+ loading={relationshipSaving}
+ data-attr="account-relationships-delete-confirm-button"
+ onClick={() => {
+ if (relationshipToDelete) {
+ deleteRelationship(relationshipToDelete)
+ }
+ }}
+ >
+ Delete assignment
+ </LemonButton>
+ </>
+ }
+ >
+ {relationshipToDelete && (
+ <p className="mb-0">
+ This permanently deletes the {relationshipToDelete.definition.name} assignment. This can't be
+ undone.
+ </p>
+ )}
+ </LemonModal>
</div>
)
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts
index ba7118ed9232..a3d82e1b413c 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts
@@ -1,8 +1,13 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
import { expectLogic } from 'kea-test-utils'
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { teamLogic } from 'scenes/teamLogic'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import type { UserBasicType } from '~/types'
+import type { TeamPublicType, UserBasicType } from '~/types'
import type {
AccountRelationshipApi,
@@ -12,6 +17,7 @@ import type {
import { accountRelationshipsLogic } from './accountRelationshipsLogic'
const RELATIONSHIPS_URL = '/api/projects/:team_id/accounts/:account_id/relationships/'
+const RELATIONSHIP_URL = '/api/projects/:team_id/accounts/:account_id/relationships/:id/'
const CSM: AccountRelationshipDefinitionApi = { id: 'def-1', name: 'CSM', description: null, is_single_holder: true }
const AE: AccountRelationshipDefinitionApi = {
@@ -70,6 +76,19 @@ describe('accountRelationshipsLogic', () => {
])
})
+ it.each([
+ [OrganizationMembershipLevel.Admin, true],
+ [OrganizationMembershipLevel.Member, false],
+ ])('allows membership level %s to delete assignments: %s', async (membershipLevel, expected) => {
+ await expectLogic(logic).toDispatchActions(['loadRelationshipsSuccess'])
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ effective_membership_level: membershipLevel,
+ } as TeamPublicType)
+
+ expect(logic.values.canDeleteRelationships).toBe(expected)
+ })
+
it('assigning posts the definition and user, then reloads the timeline', async () => {
let postedBody: Record<string, unknown> | null = null
useMocks({
@@ -92,4 +111,21 @@ describe('accountRelationshipsLogic', () => {
])
expect(postedBody).toEqual({ definition: AE.id, user: 7 })
})
+
+ it('deletes an assignment and closes the confirmation', async () => {
+ const relationship = buildRelationship()
+ useMocks({ delete: { [RELATIONSHIP_URL]: {} } })
+ await expectLogic(logic).toDispatchActions(['loadRelationshipsSuccess'])
+
+ logic.actions.openDeleteConfirmation(relationship)
+ logic.actions.deleteRelationship(relationship)
+ await expectLogic(logic).toDispatchActions([
+ 'relationshipSaveStarted',
+ 'closeDeleteConfirmation',
+ 'loadRelationships',
+ 'relationshipSaveFinished',
+ ])
+
+ expect(logic.values.relationshipToDelete).toBeNull()
+ })
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
index a9120629ecbd..80ea6d2aaa56 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
@@ -2,14 +2,16 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
+import { OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
-import type { UserBasicType } from '~/types'
+import type { TeamPublicType, TeamType, UserBasicType } from '~/types'
import {
accountsRelationshipsCreate,
+ accountsRelationshipsDestroy,
accountsRelationshipsEndCreate,
accountsRelationshipsList,
} from 'products/customer_analytics/frontend/generated/api'
@@ -35,14 +37,17 @@ function refreshAccountsList(): void {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountRelationshipsLogicValues {
relationshipDefinitions: AccountRelationshipDefinitionApi[] // accountsColumnConfigLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
currentTeamId: number | null // teamLogic
activeRelationships: AccountRelationshipApi[]
assignDefinition: AccountRelationshipDefinitionApi | null
assignDefinitionId: string | null
+ canDeleteRelationships: boolean
definitionFilter: string | null
definitionFilterOptions: AccountRelationshipDefinitionApi[]
displayedRelationships: AccountRelationshipApi[]
relationshipSaving: boolean
+ relationshipToDelete: AccountRelationshipApi | null
relationships: AccountRelationshipApi[] | null
relationshipsLoading: boolean
}
@@ -56,6 +61,12 @@ export interface accountRelationshipsLogicActions {
definition: AccountRelationshipDefinitionApi
user: UserBasicType
}
+ closeDeleteConfirmation: () => {
+ value: true
+ }
+ deleteRelationship: (relationship: AccountRelationshipApi) => {
+ relationship: AccountRelationshipApi
+ }
endRelationship: (relationship: AccountRelationshipApi) => {
relationship: AccountRelationshipApi
}
@@ -74,6 +85,9 @@ export interface accountRelationshipsLogicActions {
relationships: AccountRelationshipApi[]
payload?: any
}
+ openDeleteConfirmation: (relationship: AccountRelationshipApi) => {
+ relationship: AccountRelationshipApi
+ }
relationshipSaveFinished: () => {
value: true
}
@@ -92,6 +106,7 @@ export interface accountRelationshipsLogicActions {
export interface accountRelationshipsLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ canDeleteRelationships: (currentTeam: TeamPublicType | TeamType | null) => boolean
activeRelationships: (relationships: AccountRelationshipApi[] | null) => AccountRelationshipApi[]
displayedRelationships: (
relationships: AccountRelationshipApi[] | null,
@@ -117,9 +132,12 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
props({} as AccountRelationshipsLogicProps),
key((props) => props.accountId),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], accountsColumnConfigLogic, ['relationshipDefinitions']],
+ values: [teamLogic, ['currentTeam', 'currentTeamId'], accountsColumnConfigLogic, ['relationshipDefinitions']],
})),
actions({
+ openDeleteConfirmation: (relationship: AccountRelationshipApi) => ({ relationship }),
+ closeDeleteConfirmation: true,
+ deleteRelationship: (relationship: AccountRelationshipApi) => ({ relationship }),
assignRelationship: (definition: AccountRelationshipDefinitionApi, user: UserBasicType) => ({
definition,
user,
@@ -163,8 +181,21 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
relationshipSaveFinished: () => false,
},
],
+ relationshipToDelete: [
+ null as AccountRelationshipApi | null,
+ {
+ openDeleteConfirmation: (_, { relationship }) => relationship,
+ closeDeleteConfirmation: () => null,
+ },
+ ],
}),
selectors({
+ canDeleteRelationships: [
+ (s) => [s.currentTeam],
+ (currentTeam: TeamPublicType | TeamType | null): boolean =>
+ !!currentTeam?.effective_membership_level &&
+ currentTeam.effective_membership_level >= OrganizationMembershipLevel.Admin,
+ ],
activeRelationships: [
(s) => [s.relationships],
(relationships: AccountRelationshipApi[] | null): AccountRelationshipApi[] =>
@@ -258,6 +289,24 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
actions.relationshipSaveFinished()
}
},
+ deleteRelationship: async ({ relationship }) => {
+ if (values.relationshipSaving) {
+ return
+ }
+ actions.relationshipSaveStarted()
+ try {
+ await accountsRelationshipsDestroy(String(values.currentTeamId), props.accountId, relationship.id)
+ posthog.capture(AccountsEvents.RelationshipDeleted)
+ actions.closeDeleteConfirmation()
+ actions.loadRelationships()
+ refreshAccountsList()
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.deleteRelationship' })
+ lemonToast.error(`Failed to delete ${relationship.definition.name} assignment`)
+ } finally {
+ actions.relationshipSaveFinished()
+ }
+ },
})),
afterMount(({ actions }) => {
actions.loadRelationships()
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 323078244011..a13194b13473 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -41,6 +41,7 @@ export const AccountsEvents = {
ViewSelected: 'customer analytics accounts view selected',
ViewDeleted: 'customer analytics accounts view deleted',
RoleAssigned: 'customer analytics account role assigned',
+ RelationshipDeleted: 'customer analytics accounts relationship deleted',
TagsUpdated: 'customer analytics account tags updated',
LinkClicked: 'customer analytics account link clicked',
NoteClicked: 'customer analytics account note clicked',
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 8691cfebd4e6..550afcf4f215 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -597,6 +597,22 @@ export const accountsRelationshipsCreate = async (
})
}
+export const getAccountsRelationshipsDestroyUrl = (projectId: string, accountId: string, id: string) => {
+ return `/api/projects/${projectId}/accounts/${accountId}/relationships/${id}/`
+}
+
+export const accountsRelationshipsDestroy = async (
+ projectId: string,
+ accountId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAccountsRelationshipsDestroyUrl(projectId, accountId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getAccountsRelationshipsEndCreateUrl = (projectId: string, accountId: string, id: string) => {
return `/api/projects/${projectId}/accounts/${accountId}/relationships/${id}/end/`
}
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index aa42fca5a58f..9a3d90a87e13 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -365,6 +365,9 @@ tools:
assignment is returned unchanged. For single-holder definitions, assigning a new user automatically ends the
current holder's assignment.
feature_flag: customer-analytics-csp
+ accounts-relationships-destroy:
+ operation: accounts_relationships_destroy
+ enabled: false
accounts-relationships-end-create:
operation: accounts_relationships_end_create
enabled: true