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: review subscriptions during offboarding (#123693)

Alex Lidera5b66a655b46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 86563e03ebc3..6f92403c3002 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15655,9 +15655,9 @@ snapshots:
scenes-app-settings-organization-member-offboarding--no-resources--light:
hash: v1.k794b7964.5858a7f6b0058141bee9134870d3438e8564148e3ac5c2ae2879c551a60ea6cf.xFY9ivLhVV1pKN5UWMjkzXHzhaYFapC3vvRtwtsqro4
scenes-app-settings-organization-member-offboarding--review-resources--dark:
- hash: v1.k794b7964.6fb1e231bc80b3e7acfbed6c74ec8389130af9860c74f8ef0a28c79fc4ee3c1d.5-3-pH2WXIujOvfIFAuUm0OypDZjpijwHj5t-kD6-pI
+ hash: v1.k794b7964.50bb969851a42d76c08213d73bafd818dedf3ceee60b7585b9dfb528937872c1.Wol4-lN5gN_e_Rh1jJB4Y1xOR6zq6UOHaoE3TAOKkrE
scenes-app-settings-organization-member-offboarding--review-resources--light:
- hash: v1.k794b7964.cad1e4793a60815a10dd8f59d2d9badea8e1803cfce936c074172125f2bc1966.4Te9lMFGEdCWGqE87pLrBPKYyH7Ehe9KnWrQxdP9v1M
+ hash: v1.k794b7964.cda1cc2e98b958fb6272e514adbd5d9931ce274f0749671d2ac44ef91cfbc03e.MtNTKzbSL7vKj77Bg-fyrRVOxUqhDBwRLOeJ0u1ELGY
scenes-app-settings-project--settings-project-access-control--dark:
hash: v1.k794b7964.7554b77bd6b1d3fdc411385eff866e2fb0e442e33459268f37d116561aaa50c0.tNvJl7_UinwSpilEuRCVIkSFxqIAQY4x5_6QfXAm0hM
scenes-app-settings-project--settings-project-access-control--light:
diff --git a/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx b/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx
index 97c49f8b9223..d512484de504 100644
--- a/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx
+++ b/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx
@@ -59,6 +59,30 @@ const resources = [
team_id: 2,
project_name: 'App',
},
+ {
+ id: 'subscription:1',
+ resource_id: '1',
+ destination_type: 'email',
+ kind: 'subscription',
+ name: 'Weekly product overview',
+ url: '/project/1/subscriptions/1',
+ password_protected: false,
+ team_id: 1,
+ project_name: 'Website',
+ created_at: '2026-10-20T10:00:00Z',
+ },
+ {
+ id: 'alert:1',
+ resource_id: '1',
+ kind: 'alert',
+ name: 'Weekly usage drop',
+ url: '/project/1/alerts?alert_type=insights&alert_id=1',
+ password_protected: false,
+ team_id: 1,
+ project_name: 'Website',
+ created_at: '2026-10-20T10:00:00Z',
+ },
]
async function openMemberOffboarding(): Promise<void> {
@@ -79,6 +103,8 @@ const meta: Meta<typeof MemberOffboardingModal> = {
decorators: [
mswDecorator({
patch: {
+ '/api/projects/:project/subscriptions/:id/': () => [200, {}],
+ '/api/projects/:project/alerts/:id/': () => [200, {}],
'/api/projects/:project/:kind/:resource/sharing/': () => [204, null],
},
get: {
diff --git a/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx b/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx
index ae4324410a6a..1a4b0577f11d 100644
--- a/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx
+++ b/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx
@@ -1,41 +1,29 @@
import { useActions, useValues } from 'kea'
-import { useState } from 'react'
-import { IconDashboard, IconGraph, IconLock, IconNotebook, IconRewindPlay } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonSkeleton, LemonSwitch, LemonTable } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSkeleton, LemonTable } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
-import { Link } from 'lib/lemon-ui/Link'
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { fullNameOrEmail } from 'lib/utils/strings'
import { userLogic } from 'scenes/userLogic'
import { membersLogic } from '~/models/membersLogic'
import { memberOffboardingLogic } from './memberOffboardingLogic'
-
-const RESOURCE_ICONS = {
- dashboard: <IconDashboard />,
- insight: <IconGraph />,
- notebook: <IconNotebook />,
- recording: <IconRewindPlay />,
-}
+import { MemberOffboardingResourceSection } from './MemberOffboardingResourceSection'
export function MemberOffboardingModal(): JSX.Element {
- const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)
const {
member,
resources,
resourcesLoading,
loadError,
- keep,
removedLoading,
savingResourcesLoading,
- savingResourceIds,
- getSelectionLabel,
+ publicResources,
+ subscriptions,
} = useValues(memberOffboardingLogic)
- const { close, loadResources, setKeep, disableResources, remove } = useActions(memberOffboardingLogic)
+ const { close, loadResources, remove } = useActions(memberOffboardingLogic)
const { scopedApiKeys, scopedApiKeysLoading } = useValues(membersLogic)
const { user } = useValues(userLogic)
const isSelf = member?.user.uuid === user?.uuid
@@ -61,7 +49,10 @@ export function MemberOffboardingModal(): JSX.Element {
type="primary"
status="danger"
loading={removedLoading}
- disabledReason={disabledReason || (resourcesLoading ? 'Checking public resources…' : undefined)}
+ disabledReason={
+ disabledReason ||
+ (resourcesLoading ? 'Checking shared resources and subscriptions…' : undefined)
+ }
onClick={remove}
data-attr="confirm-org-member-offboarding"
>
@@ -79,127 +70,18 @@ export function MemberOffboardingModal(): JSX.Element {
<LemonSkeleton className="h-12" />
) : loadError ? (
<LemonBanner type="warning" action={{ children: 'Retry', onClick: loadResources }}>
- Couldn't load public resources. You can still remove the member. Their public links will stay
- unchanged.
+ Couldn't load shared resources and subscriptions. You can still remove the member. Their public
+ links and subscriptions will stay unchanged.
</LemonBanner>
) : hasResources ? (
- <section className="space-y-3">
- <h3>Publicly shared resources</h3>
- <p>
- These resources were shared by this member and are accessible to anyone with the link. You can
- disable public sharing. This won't delete them.
- </p>
- {!isSelf && (
- <div className="relative h-9">
- <div ref={setBulkBarTarget} className="absolute inset-0 [&:not(:empty)+span]:hidden" />
- <span className="flex h-full items-center text-secondary text-sm">
- {getSelectionLabel(resources!.map((resource) => resource.id))}
- </span>
- </div>
+ <div className="space-y-6">
+ {publicResources.length > 0 && (
+ <MemberOffboardingResourceSection resources={publicResources} kind="public" />
)}
- <LemonTable
- dataSource={resources ?? []}
- rowKey="id"
- bulkSelection={
- isSelf
- ? undefined
- : {
- getKey: (resource) => resource.id,
- noun: ['resource', 'resources'],
- rowAriaLabel: (resource) => `Select ${resource.name}`,
- headerAriaLabel: 'Select all resources on this page',
- clearSelectionKey: member?.user.uuid,
- isRowSelectable: () => (disabledReason ? { disabledReason } : true),
- barPortalTarget: bulkBarTarget,
- actionsPlacement: 'start',
- barClassName: 'justify-start! px-0! [&>span]:min-w-0 [&>span]:truncate',
- getSelectionLabel: ({ selectedKeys }) => getSelectionLabel(selectedKeys),
- renderActions: (ctx) => (
- <LemonButton
- type="secondary"
- status="danger"
- size="small"
- loading={savingResourceIds.length > 0}
- disabledReason={disabledReason}
- onClick={() => {
- disableResources([...ctx.selectedKeys])
- ctx.clearSelection()
- }}
- >
- Disable selected
- </LemonButton>
- ),
- }
- }
- pagination={resources!.length > 5 ? { pageSize: 5 } : undefined}
- columns={[
- {
- title: 'Resource name',
- key: 'name',
- render: (_, resource) => (
- <div className="flex items-center gap-2 min-w-0">
- <span
- className="text-lg text-secondary shrink-0"
- role="img"
- aria-label={resource.kind}
- title={resource.kind}
- >
- {RESOURCE_ICONS[resource.kind]}
- </span>
- <Link
- to={resource.url ?? undefined}
- target="_blank"
- targetBlankIcon={false}
- className="break-words min-w-0"
- data-attr="offboarding-resource-link"
- >
- {resource.name}
- </Link>
- </div>
- ),
- },
- {
- title: 'Project',
- dataIndex: 'project_name',
- key: 'project',
- width: 124,
- render: (name) => <span className="break-words">{name}</span>,
- },
- ...(!isSelf
- ? [
- {
- title: 'Publicly shared',
- key: 'disable',
- width: 112,
- render: (_: unknown, resource: NonNullable<typeof resources>[number]) => (
- <div className="flex items-center gap-2">
- <LemonSwitch
- loading={savingResourceIds.includes(resource.id)}
- checked={keep.includes(resource.id)}
- onChange={(enabled) => setKeep(resource.id, enabled)}
- disabledReason={disabledReason}
- aria-label={`Public sharing for ${resource.name}`}
- data-attr="offboarding-disable-dashboard"
- />
- {resource.password_protected && (
- <Tooltip title="Password protected">
- <span
- className="flex text-secondary"
- role="img"
- aria-label="Password protected"
- >
- <IconLock />
- </span>
- </Tooltip>
- )}
- </div>
- ),
- },
- ]
- : []),
- ]}
- />
- </section>
+ {subscriptions.length > 0 && (
+ <MemberOffboardingResourceSection resources={subscriptions} kind="subscriptions" />
+ )}
+ </div>
) : null}
{!scopedApiKeysLoading && !!scopedApiKeys?.keys.length && (
<div className="mt-4">
diff --git a/frontend/src/scenes/settings/organization/MemberOffboardingResourceSection.tsx b/frontend/src/scenes/settings/organization/MemberOffboardingResourceSection.tsx
new file mode 100644
index 000000000000..6f0d894ae3e0
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/MemberOffboardingResourceSection.tsx
@@ -0,0 +1,210 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconDashboard, IconGraph, IconLock, IconNotebook, IconRewindPlay, IconBell, IconLetter } from '@posthog/icons'
+import { LemonButton, LemonSwitch, LemonTable } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { IconSlack, IconMicrosoftTeams } from 'lib/lemon-ui/icons'
+import { Link } from 'lib/lemon-ui/Link'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { userLogic } from 'scenes/userLogic'
+
+import type { MemberOffboardingResourceApi } from 'products/platform_features/frontend/generated/api.schemas'
+import { subscriptionDestination } from 'products/subscriptions/frontend/scenes/components/subscriptionDestination'
+
+import { memberOffboardingLogic } from './memberOffboardingLogic'
+
+const DESTINATION_ICONS: Record<string, JSX.Element> = {
+ email: <IconLetter />,
+ slack: <IconSlack />,
+ teams: <IconMicrosoftTeams />,
+}
+
+const RESOURCE_ICONS = {
+ dashboard: <IconDashboard />,
+ insight: <IconGraph />,
+ notebook: <IconNotebook />,
+ recording: <IconRewindPlay />,
+ subscription: <IconBell />,
+ alert: <IconBell />,
+}
+
+export function MemberOffboardingResourceSection({
+ resources,
+ kind,
+}: {
+ resources: MemberOffboardingResourceApi[]
+ kind: 'public' | 'subscriptions'
+}): JSX.Element {
+ const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)
+ const { member, keep, removedLoading, savingResourcesLoading, savingResourceIds, getSelectionLabel } =
+ useValues(memberOffboardingLogic)
+ const { setKeep, disableResources } = useActions(memberOffboardingLogic)
+ const { user } = useValues(userLogic)
+ const isSelf = member?.user.uuid === user?.uuid
+ const disabledReason = removedLoading ? 'Removing member…' : savingResourcesLoading ? 'Saving changes…' : undefined
+ const isSubscription = kind === 'subscriptions'
+ return (
+ <section className="space-y-3">
+ <h3>{isSubscription ? 'Subscriptions and alerts' : 'Publicly shared resources'}</h3>
+ <p>
+ {isSubscription
+ ? 'These subscriptions and alerts were created by this member. You can keep or disable them.'
+ : "These resources were shared by this member and are accessible to anyone with the link. You can disable public sharing. This won't delete them."}
+ </p>
+ {!isSelf && (
+ <div className="relative h-9">
+ <div ref={setBulkBarTarget} className="absolute inset-0 [&:not(:empty)+span]:hidden" />
+ <span className="flex h-full items-center text-secondary text-sm">
+ {getSelectionLabel(resources.map((resource) => resource.id))}
+ </span>
+ </div>
+ )}
+ <LemonTable
+ dataSource={resources}
+ rowKey="id"
+ bulkSelection={
+ isSelf
+ ? undefined
+ : {
+ getKey: (resource) => resource.id,
+ noun: isSubscription
+ ? ['subscription or alert', 'subscriptions and alerts']
+ : ['resource', 'resources'],
+ rowAriaLabel: (resource) => `Select ${resource.name}`,
+ headerAriaLabel: isSubscription
+ ? 'Select all subscriptions and alerts on this page'
+ : 'Select all resources on this page',
+ clearSelectionKey: member?.user.uuid,
+ isRowSelectable: () => (disabledReason ? { disabledReason } : true),
+ barPortalTarget: bulkBarTarget,
+ actionsPlacement: 'start',
+ barClassName: 'justify-start! px-0! [&>span]:min-w-0 [&>span]:truncate',
+ getSelectionLabel: ({ selectedKeys }) => getSelectionLabel(selectedKeys),
+ renderActions: (ctx) => (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ loading={resources.some((resource) => savingResourceIds.includes(resource.id))}
+ disabledReason={disabledReason}
+ onClick={() => {
+ disableResources([...ctx.selectedKeys])
+ ctx.clearSelection()
+ }}
+ >
+ Disable selected
+ </LemonButton>
+ ),
+ }
+ }
+ pagination={resources.length > 5 ? { pageSize: 5 } : undefined}
+ columns={[
+ {
+ title: isSubscription ? 'Name' : 'Resource name',
+ key: 'name',
+ render: (_, resource) => (
+ <div className="flex items-center gap-2 min-w-0">
+ <Tooltip
+ title={
+ resource.destination_type ? (
+ <div className="text-left">
+ {subscriptionDestination(
+ resource.destination_type,
+ resource.destination ?? ''
+ ).parts.map((recipient, index) => (
+ <div key={index}>{recipient}</div>
+ ))}
+ </div>
+ ) : (
+ resource.kind
+ )
+ }
+ >
+ <span
+ className="inline-flex text-lg text-secondary shrink-0"
+ role="img"
+ aria-label={resource.destination_type ?? resource.kind}
+ tabIndex={resource.destination_type ? 0 : undefined}
+ >
+ {resource.destination_type
+ ? (DESTINATION_ICONS[resource.destination_type] ?? <IconBell />)
+ : RESOURCE_ICONS[resource.kind]}
+ </span>
+ </Tooltip>
+ <Link
+ to={resource.url ?? undefined}
+ target="_blank"
+ targetBlankIcon={false}
+ className="break-words min-w-0"
+ data-attr="offboarding-resource-link"
+ >
+ {resource.name}
+ </Link>
+ </div>
+ ),
+ },
+ {
+ title: 'Project',
+ dataIndex: 'project_name',
+ key: 'project',
+ width: 124,
+ render: (name) => <span className="break-words">{name}</span>,
+ },
+ ...(isSubscription
+ ? [
+ {
+ title: 'Created on',
+ key: 'created_at',
+ width: 96,
+ render: (_: unknown, resource: MemberOffboardingResourceApi) =>
+ resource.created_at ? (
+ <TZLabel time={resource.created_at} />
+ ) : (
+ <span className="text-secondary">Unknown</span>
+ ),
+ },
+ ]
+ : []),
+ ...(!isSelf
+ ? [
+ {
+ title: isSubscription ? 'Enabled' : 'Publicly shared',
+ key: 'disable',
+ width: 112,
+ render: (_: unknown, resource: MemberOffboardingResourceApi) => (
+ <div className="flex items-center gap-2">
+ <LemonSwitch
+ loading={savingResourceIds.includes(resource.id)}
+ checked={keep.includes(resource.id)}
+ onChange={(enabled) => setKeep(resource.id, enabled)}
+ disabledReason={disabledReason}
+ aria-label={`${isSubscription ? 'Enable' : 'Public sharing for'} ${resource.name}`}
+ data-attr={
+ isSubscription
+ ? 'offboarding-disable-subscription'
+ : 'offboarding-disable-dashboard'
+ }
+ />
+ {resource.password_protected && (
+ <Tooltip title="Password protected">
+ <span
+ className="flex text-secondary"
+ role="img"
+ aria-label="Password protected"
+ >
+ <IconLock />
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ ),
+ },
+ ]
+ : []),
+ ]}
+ />
+ </section>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts b/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts
index d1833d4028b0..800b912b62ba 100644
--- a/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts
+++ b/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts
@@ -150,6 +150,37 @@ describe('memberOffboardingLogic', () => {
expect(logic.values.savingResourcesLoading).toBe(false)
})
+ it('uses each resource’s project and API identifier for sharing updates', async () => {
+ const notebook = {
+ ...resources[0],
+ id: 'public_link:notebook:2:uuid',
+ kind: 'notebook',
+ team_id: 2,
+ resource_id: 'short-id',
+ }
+ const recording = {
+ ...resources[0],
+ id: 'public_link:recording:3:uuid',
+ kind: 'recording',
+ team_id: 3,
+ resource_id: 'session-id',
+ }
+ useMocks({
+ get: { '/api/organizations/:organization/members/:user/offboarding_preview/': [notebook, recording] },
+ })
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ await expectLogic(logic, () =>
+ logic.actions.disableResources([notebook.id, recording.id])
+ ).toFinishAllListeners()
+ expect(updates).toEqual(
+ expect.arrayContaining([
+ { path: '/api/projects/2/notebooks/short-id/sharing/', body: { enabled: false } },
+ { path: '/api/projects/3/session_recordings/session-id/sharing/', body: { enabled: false } },
+ ])
+ )
+ expect(logic.values.keep).toEqual([])
+ })
+
it('limits bulk updates to five requests in flight', async () => {
const manyResources = Array.from({ length: 12 }, (_, index) => ({
...resources[0],
@@ -201,6 +232,54 @@ describe('memberOffboardingLogic', () => {
).toBe('3 dashboards, 1 insight, 1 notebook, 1 recording')
})
+ it('reviews public links, subscriptions and alerts together and keeps them enabled by default', async () => {
+ const subscription = {
+ ...resources[0],
+ id: 'subscription:1',
+ resource_id: '1',
+ kind: 'subscription',
+ name: 'Weekly report',
+ }
+ const alert = { ...resources[0], id: 'alert:1', resource_id: '1', kind: 'alert', name: 'Usage alert' }
+ useMocks({
+ get: {
+ '/api/organizations/:organization/members/:user/offboarding_preview/': [
+ ...resources,
+ subscription,
+ alert,
+ ],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ expect(logic.values.publicResources).toEqual(resources)
+ expect(logic.values.subscriptions).toEqual([subscription, alert])
+ expect(logic.values.keep).toEqual([...resources.map((resource) => resource.id), subscription.id, alert.id])
+ useMocks({
+ patch: {
+ '/api/projects/:project/:kind/:id/': async ({ request }) => {
+ updates.push({ path: new URL(request.url).pathname, body: await request.json() })
+ return [200, {}]
+ },
+ },
+ })
+ await expectLogic(logic, () =>
+ logic.actions.disableResources([subscription.id, alert.id])
+ ).toFinishAllListeners()
+ expect(updates).toEqual(
+ expect.arrayContaining([
+ { path: '/api/projects/1/subscriptions/1/', body: { enabled: false, send_test_now: false } },
+ { path: '/api/projects/1/alerts/1/', body: { enabled: false } },
+ ])
+ )
+ expect(logic.values.keep).toEqual(resources.map((resource) => resource.id))
+ await expectLogic(logic, () => logic.actions.setKeep(subscription.id, true)).toFinishAllListeners()
+ expect(updates.at(-1)).toEqual({
+ path: '/api/projects/1/subscriptions/1/',
+ body: { enabled: true, send_test_now: false },
+ })
+ await expectLogic(logic, () => logic.actions.remove()).toDispatchActions(['removeSuccess'])
+ })
+
it('skips the resource review when leaving the organization yourself', async () => {
useMocks({ get: { '/api/organizations/:organization/members/:user/offboarding_preview/': [] } })
await expectLogic(logic, () => logic.actions.open(MOCK_DEFAULT_ORGANIZATION_MEMBER)).toFinishAllListeners()
diff --git a/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts b/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts
index b5ba2b8f4f45..7a43d1f924d8 100644
--- a/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts
+++ b/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts
@@ -11,8 +11,10 @@ import { userLogic } from 'scenes/userLogic'
import { membersLogic } from '~/models/membersLogic'
import { OrganizationMemberType } from '~/types'
+import { alertsPartialUpdate } from 'products/alerts/frontend/generated/api'
import { membersDestroy, membersOffboardingPreviewRetrieve } from 'products/platform_features/frontend/generated/api'
import type { MemberOffboardingResourceApi } from 'products/platform_features/frontend/generated/api.schemas'
+import { subscriptionsPartialUpdate } from 'products/subscriptions/frontend/generated/api'
import type { OrganizationType, UserType } from '../../../types'
@@ -24,6 +26,7 @@ export interface memberOffboardingLogicValues {
keep: string[]
loadError: string | null
member: OrganizationMemberType | null
+ publicResources: MemberOffboardingResourceApi[]
removed: boolean
removedLoading: boolean
resources: MemberOffboardingResourceApi[] | null
@@ -31,6 +34,7 @@ export interface memberOffboardingLogicValues {
savingResourceIds: string[]
savingResources: boolean
savingResourcesLoading: boolean
+ subscriptions: MemberOffboardingResourceApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -131,6 +135,8 @@ export interface memberOffboardingLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface memberOffboardingLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ publicResources: (resources: MemberOffboardingResourceApi[] | null) => MemberOffboardingResourceApi[]
+ subscriptions: (resources: MemberOffboardingResourceApi[] | null) => MemberOffboardingResourceApi[]
getSelectionLabel: (
resources: MemberOffboardingResourceApi[] | null
) => (selectedKeys: readonly string[]) => string
@@ -211,6 +217,18 @@ export const memberOffboardingLogic = kea<memberOffboardingLogicType>([
concurrency.run({
fn: async () => {
const resourceId = resource.resource_id
+ const projectId = String(resource.team_id)
+ if (resource.kind === 'subscription') {
+ await subscriptionsPartialUpdate(projectId, Number(resourceId), {
+ enabled,
+ send_test_now: false,
+ })
+ return resource.id
+ }
+ if (resource.kind === 'alert') {
+ await alertsPartialUpdate(projectId, resourceId, { enabled })
+ return resource.id
+ }
await api.sharing.update(
{
teamId: resource.team_id,
@@ -271,6 +289,16 @@ export const memberOffboardingLogic = kea<memberOffboardingLogicType>([
},
})),
selectors({
+ publicResources: [
+ (s) => [s.resources],
+ (resources: MemberOffboardingResourceApi[] | null): MemberOffboardingResourceApi[] =>
+ (resources ?? []).filter((resource) => resource.kind !== 'subscription' && resource.kind !== 'alert'),
+ ],
+ subscriptions: [
+ (s) => [s.resources],
+ (resources: MemberOffboardingResourceApi[] | null): MemberOffboardingResourceApi[] =>
+ (resources ?? []).filter((resource) => resource.kind === 'subscription' || resource.kind === 'alert'),
+ ],
getSelectionLabel: [
(s) => [s.resources],
(resources: MemberOffboardingResourceApi[] | null) =>
@@ -282,7 +310,7 @@ export const memberOffboardingLogic = kea<memberOffboardingLogicType>([
counts.set(resource.kind, (counts.get(resource.kind) ?? 0) + 1)
}
}
- const labels = ['dashboard', 'insight', 'notebook', 'recording']
+ const labels = ['dashboard', 'insight', 'notebook', 'recording', 'subscription', 'alert']
.filter((kind) => counts.has(kind))
.map((kind) => pluralize(counts.get(kind)!, kind))
return labels.join(', ')
diff --git a/posthog/api/organization_member.py b/posthog/api/organization_member.py
index 385b4ba58c76..b007f4a462f4 100644
--- a/posthog/api/organization_member.py
+++ b/posthog/api/organization_member.py
@@ -158,6 +158,8 @@ class MemberOffboardingResourceKind(TextChoices):
INSIGHT = "insight", "Insight"
NOTEBOOK = "notebook", "Notebook"
RECORDING = "recording", "Session recording"
+ SUBSCRIPTION = "subscription", "Subscription"
+ ALERT = "alert", "Alert"
class MemberOffboardingResourceSerializer(serializers.Serializer):
@@ -170,6 +172,15 @@ class MemberOffboardingResourceSerializer(serializers.Serializer):
name = serializers.CharField(help_text="The resource's display name.")
team_id = serializers.IntegerField(help_text="Project containing the resource.")
project_name = serializers.CharField(help_text="Name of the project containing the resource.")
+ created_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the subscription was created, if applicable."
+ )
+ destination_type = serializers.CharField(
+ required=False, allow_null=True, help_text="Subscription delivery channel: email, slack, or teams."
+ )
+ destination = serializers.CharField(
+ required=False, allow_null=True, help_text="Subscription recipients, Slack channels, or safe webhook host."
+ )
password_protected = serializers.BooleanField(help_text="Whether all active public links require a password.")
url = serializers.CharField(allow_null=True, help_text="Project-scoped path to open the resource in PostHog.")
diff --git a/posthog/api/test/test_organization_offboarding.py b/posthog/api/test/test_organization_offboarding.py
index 3d226a813b61..9411aea2b362 100644
--- a/posthog/api/test/test_organization_offboarding.py
+++ b/posthog/api/test/test_organization_offboarding.py
@@ -3,6 +3,8 @@ from datetime import timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import Mock, patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from parameterized import parameterized
@@ -10,9 +12,9 @@ from parameterized import parameterized
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, SessionRecording, SharingConfiguration, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.organization_offboarding import OrganizationOffboarding
from products.access_control.backend.models.access_control import AccessControl
+from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.facade.models import Insight
@@ -71,14 +73,22 @@ class TestOrganizationOffboarding(APIBaseTest):
f"/project/{self.team.pk}/dashboard/{shared.pk}",
}
- def test_preview_does_not_load_deferred_insight_queries(self) -> None:
- for index in range(3):
+ def test_preview_query_count_does_not_grow_with_insights(self) -> None:
+ insight = Insight.objects.create(team=self.team, created_by=self.departing, name="First insight")
+ SharingConfiguration.objects.create(team=self.team, insight=insight, enabled=True)
+ self.client.get(self.url + "offboarding_preview/")
+ with CaptureQueriesContext(connection) as first:
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert len(response.json()) == 1
+ for index in range(2):
insight = Insight.objects.create(team=self.team, created_by=self.departing, name=f"Insight {index}")
SharingConfiguration.objects.create(team=self.team, insight=insight, enabled=True)
- membership = OrganizationMembership.objects.get(user=self.departing, organization=self.organization)
- with self.assertNumQueries(4):
- resources = OrganizationOffboarding(membership).resources()
- assert len(resources) == 3
+ with CaptureQueriesContext(connection) as expanded:
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert len(response.json()) == 3
+ assert len(expanded) == len(first)
def test_removal_preserves_all_dashboard_tokens_and_other_members_links(self) -> None:
dashboard = Dashboard.objects.create(team=self.team, created_by=self.departing, is_shared=True)
@@ -230,6 +240,31 @@ class TestOrganizationOffboarding(APIBaseTest):
unrelated_share.refresh_from_db()
assert unrelated_share.enabled
+ def test_preview_lists_created_active_alerts_and_removal_preserves_them(self) -> None:
+ insight = Insight.objects.create(team=self.team, created_by=self.departing)
+ kept = AlertConfiguration.objects.create(
+ team=self.team, insight=insight, created_by=self.departing, name="Keep"
+ )
+ disabled = AlertConfiguration.objects.create(
+ team=self.team, insight=insight, created_by=self.departing, name="Disabled", enabled=False
+ )
+ unrelated = AlertConfiguration.objects.create(
+ team=self.team, insight=insight, created_by=self.user, name="Other"
+ )
+ kept.subscribed_users.add(self.user)
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert [item["id"] for item in response.json()] == [f"alert:{kept.pk}"]
+ assert response.json()[0]["kind"] == "alert"
+ assert self.client.delete(self.url).status_code == 204
+ kept.refresh_from_db()
+ disabled.refresh_from_db()
+ unrelated.refresh_from_db()
+ assert kept.enabled
+ assert not disabled.enabled
+ assert unrelated.enabled
+ assert kept.subscribed_users.filter(pk=self.user.pk).exists()
+
def test_self_leave_skips_resource_review_and_preserves_links_in_all_projects(self) -> None:
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
diff --git a/posthog/organization_offboarding.py b/posthog/organization_offboarding.py
index adafeab210fd..3a77b0d81aa1 100644
--- a/posthog/organization_offboarding.py
+++ b/posthog/organization_offboarding.py
@@ -7,6 +7,9 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.organization_offboarding_types import OffboardingResource
+from products.alerts.backend.facade import organization_offboarding as alerts
+from products.subscriptions.backend.facade import organization_offboarding as subscriptions
+
@frozen
class PublicResourceKind:
@@ -93,4 +96,6 @@ class OrganizationOffboarding:
def resources(self) -> list[OffboardingResource]:
resources = [resource for kind in PUBLIC_RESOURCE_KINDS for resource in self._public_resources(kind)]
+ resources.extend(alerts.list_member_offboarding_resources(self.organization_id, self.user_id))
+ resources.extend(subscriptions.list_member_offboarding_resources(self.organization_id, self.user_id))
return sorted(resources, key=lambda resource: (resource.name, resource.id))
diff --git a/posthog/organization_offboarding_types.py b/posthog/organization_offboarding_types.py
index b7db35b33009..9f0db0a8af98 100644
--- a/posthog/organization_offboarding_types.py
+++ b/posthog/organization_offboarding_types.py
@@ -1,3 +1,5 @@
+from datetime import datetime
+
from posthog.dataclasses import frozen
@@ -9,5 +11,8 @@ class OffboardingResource:
name: str
team_id: int
project_name: str
+ created_at: datetime | None = None
password_protected: bool = False
url: str | None = None
+ destination_type: str | None = None
+ destination: str | None = None
diff --git a/products/alerts/backend/facade/organization_offboarding.py b/products/alerts/backend/facade/organization_offboarding.py
new file mode 100644
index 000000000000..0110246ca734
--- /dev/null
+++ b/products/alerts/backend/facade/organization_offboarding.py
@@ -0,0 +1,7 @@
+from posthog.organization_offboarding_types import OffboardingResource
+
+from products.alerts.backend.logic.organization_offboarding import AlertOffboarding
+
+
+def list_member_offboarding_resources(organization_id: str, user_id: int) -> list[OffboardingResource]:
+ return AlertOffboarding(organization_id, user_id).resources()
diff --git a/products/alerts/backend/logic/organization_offboarding.py b/products/alerts/backend/logic/organization_offboarding.py
new file mode 100644
index 000000000000..d34f65c55ad0
--- /dev/null
+++ b/products/alerts/backend/logic/organization_offboarding.py
@@ -0,0 +1,34 @@
+from django.db.models import QuerySet
+
+from posthog.organization_offboarding_types import OffboardingResource
+
+from products.alerts.backend.models.alert import AlertConfiguration
+
+
+class AlertOffboarding:
+ def __init__(self, organization_id: str, user_id: int) -> None:
+ self.organization_id = organization_id
+ self.user_id = user_id
+
+ def _alerts(self) -> QuerySet[AlertConfiguration]:
+ return AlertConfiguration.objects.filter(
+ team__organization_id=self.organization_id,
+ created_by_id=self.user_id,
+ enabled=True,
+ insight__deleted=False,
+ )
+
+ def resources(self) -> list[OffboardingResource]:
+ return [
+ OffboardingResource(
+ id=f"alert:{alert.pk}",
+ resource_id=str(alert.pk),
+ kind="alert",
+ name=alert.name or "Untitled alert",
+ team_id=alert.team_id,
+ project_name=alert.team.name,
+ created_at=alert.created_at,
+ url=f"/project/{alert.team_id}/alerts?alert_type=insights&alert_id={alert.pk}",
+ )
+ for alert in self._alerts().select_related("team")
+ ]
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 1314c3705a3f..d89765ce4005 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -481,6 +481,8 @@ export interface OrganizationMemberGithubLoginApi {
* * `insight` - Insight
* * `notebook` - Notebook
* * `recording` - Session recording
+ * * `subscription` - Subscription
+ * * `alert` - Alert
*/
export type MemberOffboardingResourceKindEnumApi =
(typeof MemberOffboardingResourceKindEnumApi)[keyof typeof MemberOffboardingResourceKindEnumApi]
@@ -490,6 +492,8 @@ export const MemberOffboardingResourceKindEnumApi = {
Insight: 'insight',
Notebook: 'notebook',
Recording: 'recording',
+ Subscription: 'subscription',
+ Alert: 'alert',
} as const
export interface MemberOffboardingResourceApi {
@@ -502,7 +506,9 @@ export interface MemberOffboardingResourceApi {
* * `dashboard` - Dashboard
* * `insight` - Insight
* * `notebook` - Notebook
- * * `recording` - Session recording */
+ * * `recording` - Session recording
+ * * `subscription` - Subscription
+ * * `alert` - Alert */
kind: MemberOffboardingResourceKindEnumApi
/** The resource's display name. */
name: string
@@ -510,6 +516,21 @@ export interface MemberOffboardingResourceApi {
team_id: number
/** Name of the project containing the resource. */
project_name: string
+ /**
+ * When the subscription was created, if applicable.
+ * @nullable
+ */
+ created_at: string | null
+ /**
+ * Subscription delivery channel: email, slack, or teams.
+ * @nullable
+ */
+ destination_type?: string | null
+ /**
+ * Subscription recipients, Slack channels, or safe webhook host.
+ * @nullable
+ */
+ destination?: string | null
/** Whether all active public links require a password. */
password_protected: boolean
/**
diff --git a/products/subscriptions/backend/facade/organization_offboarding.py b/products/subscriptions/backend/facade/organization_offboarding.py
new file mode 100644
index 000000000000..8439d9669240
--- /dev/null
+++ b/products/subscriptions/backend/facade/organization_offboarding.py
@@ -0,0 +1,7 @@
+from posthog.organization_offboarding_types import OffboardingResource
+
+from products.subscriptions.backend.logic.organization_offboarding import SubscriptionOffboarding
+
+
+def list_member_offboarding_resources(organization_id: str, user_id: int) -> list[OffboardingResource]:
+ return SubscriptionOffboarding(organization_id, user_id).resources()
diff --git a/products/subscriptions/backend/logic/organization_offboarding.py b/products/subscriptions/backend/logic/organization_offboarding.py
new file mode 100644
index 000000000000..db17e5593905
--- /dev/null
+++ b/products/subscriptions/backend/logic/organization_offboarding.py
@@ -0,0 +1,37 @@
+from django.db.models import QuerySet
+
+from posthog.organization_offboarding_types import OffboardingResource
+
+from products.subscriptions.backend.models.subscription import Subscription
+
+
+class SubscriptionOffboarding:
+ def __init__(self, organization_id: str, user_id: int) -> None:
+ self.organization_id = organization_id
+ self.user_id = user_id
+
+ def _subscriptions(self) -> QuerySet[Subscription]:
+ return (
+ Subscription.objects.filter(team__organization_id=self.organization_id, deleted=False)
+ .exclude(dashboard__deleted=True)
+ .exclude(insight__deleted=True)
+ )
+
+ def resources(self) -> list[OffboardingResource]:
+ return [
+ OffboardingResource(
+ id=f"subscription:{subscription.pk}",
+ resource_id=str(subscription.pk),
+ kind="subscription",
+ name=subscription.title or subscription.display_name,
+ team_id=subscription.team_id,
+ project_name=subscription.team.name,
+ created_at=subscription.created_at,
+ destination_type=subscription.target_type,
+ destination=subscription.recipient_label,
+ url=f"/project/{subscription.team_id}/subscriptions/{subscription.pk}",
+ )
+ for subscription in self._subscriptions()
+ .filter(created_by_id=self.user_id, enabled=True)
+ .select_related("team", "dashboard", "insight")
+ ]
diff --git a/products/subscriptions/backend/logic/subscription_writes.py b/products/subscriptions/backend/logic/subscription_writes.py
index 8e8a95bc037a..26b1b61daa5f 100644
--- a/products/subscriptions/backend/logic/subscription_writes.py
+++ b/products/subscriptions/backend/logic/subscription_writes.py
@@ -481,7 +481,9 @@ class _SubscriptionWrite:
raise SubscriptionRequestInvalidError({"start_date": [f"{base}."]})
raise SubscriptionRequestInvalidError(f"{base}.")
- if target_type == Subscription.SubscriptionTarget.TEAMS:
+ destination_changed = bool({"target_type", "target_value", "integration_id", "delivery_config"} & attrs.keys())
+ validate_destination = existing is None or not turning_off or destination_changed
+ if target_type == Subscription.SubscriptionTarget.TEAMS and validate_destination:
submitted = (attrs.get("target_value") or "").strip()
if self.instance and submitted and submitted == self.instance.recipient_label:
raise SubscriptionRequestInvalidError({"target_value": [TEAMS_WEBHOOK_URL_MASKED_ERROR]})
@@ -489,7 +491,7 @@ class _SubscriptionWrite:
if not is_microsoft_teams_webhook_url(target_value):
raise SubscriptionRequestInvalidError({"target_value": [TEAMS_WEBHOOK_URL_ERROR]})
- if target_type == Subscription.SubscriptionTarget.SLACK:
+ if target_type == Subscription.SubscriptionTarget.SLACK and validate_destination:
if not integration_id:
raise SubscriptionRequestInvalidError(
{"integration_id": ["A Slack integration is required for Slack subscriptions."]}
diff --git a/products/subscriptions/backend/models/subscription.py b/products/subscriptions/backend/models/subscription.py
index 17006e495e7d..3e664f58a5b1 100644
--- a/products/subscriptions/backend/models/subscription.py
+++ b/products/subscriptions/backend/models/subscription.py
@@ -481,7 +481,7 @@ class Subscription(ModelActivityMixin, models.Model):
case self.ResourceType.INSIGHT if self.insight:
return SubscriptionResource(
"Insight",
- f"{self.insight.name or self.insight.derived_name}",
+ self.insight.name or self.insight.derived_name or "Untitled insight",
self.insight.url,
)
case self.ResourceType.DASHBOARD if self.dashboard:
diff --git a/products/subscriptions/backend/tests/test_organization_offboarding.py b/products/subscriptions/backend/tests/test_organization_offboarding.py
new file mode 100644
index 000000000000..97ba00024013
--- /dev/null
+++ b/products/subscriptions/backend/tests/test_organization_offboarding.py
@@ -0,0 +1,166 @@
+from posthog.test.base import APIBaseTest
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Organization, OrganizationMembership, Team, User
+
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.facade.models import Insight
+from products.subscriptions.backend.models.subscription import Subscription
+
+
+class TestSubscriptionOffboarding(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.departing = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.url = f"/api/organizations/@current/members/{self.departing.uuid}/"
+
+ def subscription(self, *, creator: User, recipients: str) -> Subscription:
+ return Subscription.objects.create(
+ team=self.team,
+ created_by=creator,
+ dashboard=Dashboard.objects.create(team=self.team, created_by=creator),
+ title="Weekly report",
+ target_type="email",
+ target_value=recipients,
+ frequency="daily",
+ interval=1,
+ start_date=timezone.now(),
+ )
+
+ def test_preview_lists_created_subscriptions_and_removal_preserves_them(self) -> None:
+ own = self.subscription(creator=self.departing, recipients="[email protected]")
+ others = self.subscription(creator=self.user, recipients="[email protected]")
+ recipient = self.subscription(creator=self.user, recipients="[email protected],[email protected]")
+ only_recipient = self.subscription(creator=self.user, recipients=self.departing.email)
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert [item["id"] for item in response.json()] == [f"subscription:{own.pk}"]
+ assert response.json()[0]["url"] == f"/project/{self.team.pk}/subscriptions/{own.pk}"
+ assert response.json()[0]["created_at"] is not None
+ response = self.client.delete(self.url)
+ assert response.status_code == 204
+ for subscription in (own, others, recipient, only_recipient):
+ subscription.refresh_from_db()
+ assert own.enabled
+ assert others.enabled
+ assert recipient.enabled and recipient.target_value == "[email protected],[email protected]"
+ assert only_recipient.enabled and only_recipient.target_value == self.departing.email
+
+ @parameterized.expand([("dashboard",), ("insight",)])
+ def test_preview_excludes_subscriptions_with_deleted_resources(self, kind: str) -> None:
+ subscription = self.subscription(creator=self.departing, recipients="[email protected]")
+ if kind == "insight":
+ subscription.dashboard = None
+ subscription.insight = Insight.objects.create(team=self.team, created_by=self.departing)
+ subscription.save(update_fields=["dashboard", "insight"])
+ resource = subscription.dashboard if kind == "dashboard" else subscription.insight
+ assert resource is not None
+ assert [item["id"] for item in self.client.get(self.url + "offboarding_preview/").json()] == [
+ f"subscription:{subscription.pk}"
+ ]
+
+ resource.deleted = True
+ resource.save(update_fields=["deleted"])
+
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert response.json() == []
+ subscription.refresh_from_db()
+ assert subscription.enabled
+
+ def test_untitled_subscriptions_use_the_resource_name(self) -> None:
+ subscription = self.subscription(creator=self.departing, recipients="[email protected]")
+ subscription.title = ""
+ subscription.save(update_fields=["title"])
+ assert subscription.dashboard is not None
+ subscription.dashboard.name = "Weekly product usage"
+ subscription.dashboard.save(update_fields=["name"])
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert response.json()[0]["name"] == "Weekly product usage"
+
+ @parameterized.expand(
+ [
+ ("slack", "C123|#reports", "C123|#reports"),
+ ("teams", "https://example.com/webhook/fake-secret", "example.com"),
+ ]
+ )
+ def test_subscription_destinations_exclude_webhook_credentials(
+ self, target_type: str, target_value: str, expected: str
+ ) -> None:
+ subscription = self.subscription(creator=self.departing, recipients=target_value)
+ subscription.target_type = target_type
+ subscription.save(update_fields=["target_type"])
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert response.json()[0]["destination_type"] == target_type
+ assert response.json()[0]["destination"] == expected
+ assert "fake-secret" not in response.content.decode()
+
+ def test_kept_subscriptions_preserve_recipients(self) -> None:
+ kept = self.subscription(creator=self.departing, recipients=f"{self.departing.email},[email protected]")
+ disabled = self.subscription(creator=self.departing, recipients="[email protected]")
+ response = self.client.patch(
+ f"/api/projects/{self.team.pk}/subscriptions/{disabled.pk}/",
+ {"enabled": False},
+ format="json",
+ )
+ assert response.status_code == 200
+ kept.refresh_from_db()
+ disabled.refresh_from_db()
+ assert kept.enabled and kept.target_value == f"{self.departing.email},[email protected]"
+ assert not disabled.enabled
+ assert disabled.target_value == "[email protected]"
+
+ def test_offboarding_does_not_change_subscriptions_in_another_organization(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other organization"))
+ subscription = self.subscription(creator=self.departing, recipients=self.departing.email)
+ subscription.team = other_team
+ subscription.save(update_fields=["team"])
+ assert self.client.get(self.url + "offboarding_preview/").json() == []
+ assert self.client.delete(self.url).status_code == 204
+ subscription.refresh_from_db()
+ assert subscription.enabled
+ assert subscription.target_value == self.departing.email
+
+ def test_ai_subscriptions_are_included(self) -> None:
+ subscription = self.subscription(creator=self.departing, recipients="[email protected]")
+ subscription.prompt = "Summarize weekly product usage"
+ subscription.dashboard = None
+ subscription.save(update_fields=["prompt", "dashboard"])
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert [item["id"] for item in response.json()] == [f"subscription:{subscription.pk}"]
+
+ def test_self_leave_preserves_subscriptions_in_other_projects(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+ subscription = self.subscription(creator=self.departing, recipients="[email protected]")
+ subscription.team = other_team
+ subscription.save(update_fields=["team"])
+ self.client.force_login(self.departing)
+ assert self.client.get(self.url + "offboarding_preview/").json() == []
+ assert self.client.delete(self.url).status_code == 204
+ subscription.refresh_from_db()
+ assert subscription.enabled
+
+ def test_subscription_changes_save_before_removal_and_can_be_reversed(self) -> None:
+ subscription = self.subscription(creator=self.departing, recipients="[email protected]")
+ for enabled in (False, True):
+ response = self.client.patch(
+ f"/api/projects/{self.team.pk}/subscriptions/{subscription.pk}/",
+ {"enabled": enabled, "send_test_now": False},
+ format="json",
+ )
+ assert response.status_code == 200, response.json()
+ subscription.refresh_from_db()
+ assert subscription.enabled == enabled
+ assert self.organization.members.filter(pk=self.departing.pk).exists()
+ assert self.client.delete(self.url).status_code == 204
+ subscription.refresh_from_db()
+ assert subscription.enabled
diff --git a/products/subscriptions/backend/tests/test_subscription.py b/products/subscriptions/backend/tests/test_subscription.py
index 7f3ddecf3ac3..0a57281bc925 100644
--- a/products/subscriptions/backend/tests/test_subscription.py
+++ b/products/subscriptions/backend/tests/test_subscription.py
@@ -1048,6 +1048,49 @@ class TestSubscriptionTemporal(APILicensedTest):
assert response.json()["attr"] == "target_value"
assert response.json()["detail"] == TEAMS_WEBHOOK_URL_ERROR
+ @parameterized.expand(
+ [
+ ("slack_disable", "slack", "C123|#reports", {"enabled": False}, 200),
+ ("slack_delete", "slack", "C123|#reports", {"deleted": True}, 200),
+ ("teams_disable", "teams", "https://example.com/expired-webhook", {"enabled": False}, 200),
+ ("teams_delete", "teams", "https://example.com/expired-webhook", {"deleted": True}, 200),
+ (
+ "slack_destination_edit",
+ "slack",
+ "C123|#reports",
+ {"enabled": False, "target_value": "C456|#other"},
+ 400,
+ ),
+ (
+ "teams_destination_edit",
+ "teams",
+ "https://example.com/expired-webhook",
+ {"enabled": False, "target_value": "https://example.com/another-webhook"},
+ 400,
+ ),
+ ]
+ )
+ def test_turning_off_invalid_destination_only_skips_validation_for_unchanged_destination(
+ self, _name: str, target_type: str, target_value: str, payload: dict[str, bool | str], expected_status: int
+ ) -> None:
+ subscription = Subscription.objects.create(
+ team=self.team,
+ created_by=self.user,
+ insight=self.insight,
+ target_type=target_type,
+ target_value=target_value,
+ frequency="daily",
+ start_date=timezone.now(),
+ )
+ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}", payload)
+ assert response.status_code == expected_status, response.json()
+ subscription.refresh_from_db()
+ if expected_status == status.HTTP_200_OK:
+ assert not subscription.enabled or subscription.deleted
+ else:
+ assert subscription.enabled and not subscription.deleted
+ self.mock_temporal_client.start_workflow.assert_not_called()
+
def test_patch_enabled_true_rejected_when_slack_integration_missing(self):
"""Re-enabling a disabled Slack subscription whose integration is gone must be
rejected up front — otherwise the next delivery would auto-disable it again
diff --git a/products/subscriptions/backend/tests/test_subscription_activity_log.py b/products/subscriptions/backend/tests/test_subscription_activity_log.py
index db50446653e9..403e4d2d4560 100644
--- a/products/subscriptions/backend/tests/test_subscription_activity_log.py
+++ b/products/subscriptions/backend/tests/test_subscription_activity_log.py
@@ -158,6 +158,11 @@ class TestSubscriptionActivityLog(BaseTest):
),
"Signups by week",
),
+ (
+ "unnamed_insight_uses_fallback",
+ lambda self: self._unsaved_subscription(insight=Insight.objects.create(team=self.team)),
+ "Untitled insight",
+ ),
(
"dashboard_uses_dashboard_name",
lambda self: self._unsaved_subscription(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9eb31f6407cf..2d65388b0e57 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64706,6 +64706,8 @@ export namespace Schemas {
* * `insight` - Insight
* * `notebook` - Notebook
* * `recording` - Session recording
+ * * `subscription` - Subscription
+ * * `alert` - Alert
*/
export type MemberOffboardingResourceKindEnum = typeof MemberOffboardingResourceKindEnum[keyof typeof MemberOffboardingResourceKindEnum];
@@ -64715,6 +64717,8 @@ export namespace Schemas {
Insight: 'insight',
Notebook: 'notebook',
Recording: 'recording',
+ Subscription: 'subscription',
+ Alert: 'alert',
} as const;
export interface MemberOffboardingResource {
@@ -64727,7 +64731,9 @@ export namespace Schemas {
* * `dashboard` - Dashboard
* * `insight` - Insight
* * `notebook` - Notebook
- * * `recording` - Session recording */
+ * * `recording` - Session recording
+ * * `subscription` - Subscription
+ * * `alert` - Alert */
kind: MemberOffboardingResourceKindEnum;
/** The resource's display name. */
name: string;
@@ -64735,6 +64741,21 @@ export namespace Schemas {
team_id: number;
/** Name of the project containing the resource. */
project_name: string;
+ /**
+ * When the subscription was created, if applicable.
+ * @nullable
+ */
+ created_at: string | null;
+ /**
+ * Subscription delivery channel: email, slack, or teams.
+ * @nullable
+ */
+ destination_type?: string | null;
+ /**
+ * Subscription recipients, Slack channels, or safe webhook host.
+ * @nullable
+ */
+ destination?: string | null;
/** Whether all active public links require a password. */
password_protected: boolean;
/**