: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(subscriptions): let users correct unavailable insight selections (#120324)
Matt Pua19a556220c73
diff --git a/products/subscriptions/frontend/components/Subscriptions/InsightSelector.test.tsx b/products/subscriptions/frontend/components/Subscriptions/InsightSelector.test.tsxindex 32869db2eba8..63c641ddef6d 100644--- a/products/subscriptions/frontend/components/Subscriptions/InsightSelector.test.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/InsightSelector.test.tsx@@ -115,18 +115,41 @@ describe('InsightSelector', () => {expect(onDefaultsApplied).toHaveBeenCalledWith([101, 102, 103])})- it('filters out stale IDs that no longer exist in tiles', () => {+ it.each([[[101, 999, 102]], [[998, 999]]])('preserves unavailable selections on open: %j', (ids) => {const onChange = jest.fn()+ renderInsightSelector({+ tiles: createMockTiles() as DashboardTile[],+ selectedInsightIds: ids,+ onChange,+ })++ expect(screen.getByText(/selected insights? (?:is|are) no longer on this dashboard/)).toBeInTheDocument()+ expect(onChange).not.toHaveBeenCalled()+ const labels = screen.getAllByRole('checkbox').map((input) => input.nextElementSibling?.textContent)+ expect(labels).toEqual(['Pageviews', 'Sessions', 'Users'])+ expect(screen.queryByText(/ID:/)).not.toBeInTheDocument()+ })- // Selected IDs include 999 which doesn't exist in tiles+ it('keeps unavailable insights when selecting a replacement', async () => {+ const onChange = jest.fn()renderInsightSelector({tiles: createMockTiles() as DashboardTile[],- selectedInsightIds: [101, 999, 102],+ selectedInsightIds: [999],onChange,})- // Should call onChange to remove the stale ID- expect(onChange).toHaveBeenCalledWith([101, 102])+ await userEvent.click(screen.getByText('Sessions'))+ expect(onChange).toHaveBeenLastCalledWith([999, 102])+ })++ it('shows unavailable selections even when the dashboard is empty', () => {+ renderInsightSelector({ tiles: [], selectedInsightIds: [999], onChange: jest.fn() })+ expect(screen.getByText(/selected insights? (?:is|are) no longer on this dashboard/)).toBeInTheDocument()+ expect(+ screen.getByText(+ '1 selected insight is no longer on this dashboard. It will be removed from this subscription when you save.'+ )+ ).toBeInTheDocument()})it('shows max limit message when at capacity', () => {@@ -180,7 +203,9 @@ describe('InsightSelector', () => {onChange: jest.fn(),})- expect(screen.getByText('No insights found in this dashboard.')).toBeInTheDocument()+ expect(+ screen.getByText('No insights found in this dashboard. Add an insight before saving.')+ ).toBeInTheDocument()})it('uses derived_name when name is not available', () => {diff --git a/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsx b/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsxindex ed0083ae2444..b39049d55eb3 100644--- a/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { useEffect, useMemo } from 'react'+import { useEffect } from 'react'import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'import { LemonInput } from 'lib/lemon-ui/LemonInput'@@ -21,37 +21,27 @@ export function InsightSelector({onChange,onDefaultsApplied,}: InsightSelectorProps): JSX.Element {- const logic = insightSelectorLogic({ tiles })- const { filteredTiles, insightTiles, showSearch, searchTerm, userHasInteracted } = useValues(logic)+ const logic = insightSelectorLogic({ tiles, selectedInsightIds })+ const {+ filteredTiles,+ insightTiles,+ showSearch,+ searchTerm,+ userHasInteracted,+ validSelectedIds,+ unavailableSelectedIds,+ } = useValues(logic)const { setSearchTerm, setUserHasInteracted } = useActions(logic)- // Filter out stale IDs that no longer exist in current tiles- const validSelectedIds = useMemo(() => {- const currentInsightIds = new Set(insightTiles.map((tile) => tile.insight!.id))- return selectedInsightIds.filter((id) => currentInsightIds.has(id))- }, [insightTiles, selectedInsightIds])-- // If there are stale IDs, update the form state to remove them- useEffect(() => {- if (validSelectedIds.length < selectedInsightIds.length) {- onChange(validSelectedIds)- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [validSelectedIds, selectedInsightIds])-useEffect(() => {// Auto-select the first N insights for new subscriptions (when nothing is selected yet)- if (insightTiles.length > 0 && validSelectedIds.length === 0 && !userHasInteracted) {+ if (insightTiles.length > 0 && selectedInsightIds.length === 0 && !userHasInteracted) {const defaultSelection = insightTiles.slice(0, MAX_INSIGHTS).map((tile) => tile.insight!.id)onChange(defaultSelection)onDefaultsApplied?.(defaultSelection)}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [insightTiles, validSelectedIds, userHasInteracted])-- if (insightTiles.length === 0) {- return <div className="text-secondary text-sm">No insights found in this dashboard.</div>- }+ }, [insightTiles, selectedInsightIds, userHasInteracted])const selectedCount = validSelectedIds.lengthconst selectableCount = Math.min(insightTiles.length, MAX_INSIGHTS)@@ -60,56 +50,71 @@ export function InsightSelector({const toggleInsight = (insightId: number): void => {setUserHasInteracted()if (validSelectedIds.includes(insightId)) {- const newIds = validSelectedIds.filter((id) => id !== insightId)+ const newIds = selectedInsightIds.filter((id) => id !== insightId)onChange(newIds)} else if (!atMaxLimit) {- onChange([...validSelectedIds, insightId])+ onChange([...selectedInsightIds, insightId])}}return (- <div className="border rounded p-2 space-y-2">- <div className="flex justify-between items-center text-sm">- <span className="font-medium">- {selectedCount} of {selectableCount} insights selected- </span>- {selectedCount === 0 && <span className="text-danger">Select at least one insight</span>}- </div>- {showSearch && (- <LemonInput- type="search"- placeholder="Search insights..."- value={searchTerm}- onChange={setSearchTerm}- fullWidth- />- )}- <div className="border-t pt-2 space-y-1 max-h-[200px] overflow-y-auto">- {filteredTiles.length === 0 ? (- <div className="text-secondary text-sm py-2">No insights match your search.</div>- ) : (- filteredTiles.map((tile) => {- const insight = tile.insight!- const isChecked = validSelectedIds.includes(insight.id)- const isDisabled = !isChecked && atMaxLimit- return (- <LemonCheckbox- key={tile.id}- checked={isChecked}- onChange={() => toggleInsight(insight.id)}- label={insight.name || insight.derived_name || 'Untitled insight'}- disabledReason={- isDisabled && 'Maximum number of insights selected. Deselect one to add another.'- }- />- )- })+ <div className="space-y-2">+ <div className="border rounded p-2 space-y-2">+ {insightTiles.length === 0 && (+ <p className="text-secondary text-sm">+ No insights found in this dashboard. Add an insight before saving.+ </p>)}- </div>- {atMaxLimit && (- <div className="text-xs text-secondary">- Maximum {MAX_INSIGHTS} insights. Deselect one to add another.+ <div className="flex flex-wrap justify-between items-center gap-2 text-sm">+ <span className="font-medium">+ {selectedCount} of {selectableCount} insights selected+ </span>+ {selectedCount === 0 && <span className="text-danger">Select at least one insight</span>}</div>+ {showSearch && (+ <LemonInput+ type="search"+ placeholder="Search insights..."+ value={searchTerm}+ onChange={setSearchTerm}+ fullWidth+ />+ )}+ <div className="border-t pt-2 space-y-1 max-h-[200px] overflow-y-auto">+ {filteredTiles.length === 0 && insightTiles.length > 0 ? (+ <div className="text-secondary text-sm py-2">No insights match your search.</div>+ ) : (+ filteredTiles.map((tile) => {+ const insight = tile.insight!+ const isChecked = validSelectedIds.includes(insight.id)+ const isDisabled = !isChecked && atMaxLimit+ return (+ <LemonCheckbox+ key={tile.id}+ checked={isChecked}+ onChange={() => toggleInsight(insight.id)}+ label={insight.name || insight.derived_name || 'Untitled insight'}+ disabledReason={+ isDisabled &&+ 'Maximum number of insights selected. Deselect one to add another.'+ }+ />+ )+ })+ )}+ </div>+ {atMaxLimit && (+ <div className="text-xs text-secondary">+ Maximum {MAX_INSIGHTS} insights. Deselect one to add another.+ </div>+ )}+ </div>+ {unavailableSelectedIds.length > 0 && (+ <p className="mb-0 text-sm text-danger">+ {unavailableSelectedIds.length === 1+ ? '1 selected insight is no longer on this dashboard. It will be removed from this subscription when you save.'+ : `${unavailableSelectedIds.length} selected insights are no longer on this dashboard. They will be removed from this subscription when you save.`}+ </p>)}</div>)diff --git a/products/subscriptions/frontend/components/Subscriptions/insightSelectorLogic.ts b/products/subscriptions/frontend/components/Subscriptions/insightSelectorLogic.tsindex 5257b8556ba1..370e0fc27f3f 100644--- a/products/subscriptions/frontend/components/Subscriptions/insightSelectorLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/insightSelectorLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, path, props, propsChanged, reducers, selectors } from 'kea'import { DashboardTile } from '~/types'@@ -7,6 +7,7 @@ export const MAX_INSIGHTS = 20export interface InsightSelectorLogicProps {tiles: DashboardTile[]+ selectedInsightIds?: number[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -14,8 +15,12 @@ export interface insightSelectorLogicValues {filteredTiles: DashboardTile[]insightTiles: DashboardTile[]searchTerm: string+ selectedInsightIds: number[]showSearch: boolean+ tiles: DashboardTile[]+ unavailableSelectedIds: number[]userHasInteracted: boolean+ validSelectedIds: number[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -23,6 +28,13 @@ export interface insightSelectorLogicActions {setSearchTerm: (searchTerm: string) => {searchTerm: string}+ setSelectionInputs: (+ tiles: DashboardTile[],+ ids: number[]+ ) => {+ ids: number[]+ tiles: DashboardTile[]+ }setUserHasInteracted: () => {value: true}@@ -31,6 +43,8 @@ export interface insightSelectorLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface insightSelectorLogicMeta {__keaTypeGenInternalSelectorTypes: {+ validSelectedIds: (insightTiles: DashboardTile[], selectedInsightIds: number[]) => number[]+ unavailableSelectedIds: (validSelectedIds: number[], selectedInsightIds: number[]) => number[]insightTiles: (tiles: DashboardTile[]) => DashboardTile[]filteredTiles: (insightTiles: DashboardTile[], searchTerm: string) => DashboardTile[]showSearch: (insightTiles: DashboardTile[]) => boolean@@ -51,16 +65,36 @@ export const insightSelectorLogic = kea<insightSelectorLogicType>([actions({setSearchTerm: (searchTerm: string) => ({ searchTerm }),setUserHasInteracted: true,+ setSelectionInputs: (tiles: DashboardTile[], ids: number[]) => ({ tiles, ids }),}),- reducers({+ reducers(({ props }) => ({+ tiles: [props.tiles, { setSelectionInputs: (_, { tiles }) => tiles }],+ selectedInsightIds: [props.selectedInsightIds ?? [], { setSelectionInputs: (_, { ids }) => ids }],searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],userHasInteracted: [false, { setUserHasInteracted: () => true }],+ })),+ propsChanged(({ actions, props }, previousProps) => {+ if (props.selectedInsightIds !== previousProps.selectedInsightIds || props.tiles !== previousProps.tiles) {+ actions.setSelectionInputs(props.tiles, props.selectedInsightIds ?? [])+ }}),selectors({+ validSelectedIds: [+ (s) => [s.insightTiles, s.selectedInsightIds],+ (tiles: DashboardTile[], selectedIds: number[] = []): number[] => {+ const availableIds = new Set(tiles.map((tile) => tile.insight!.id))+ return selectedIds.filter((id) => availableIds.has(id))+ },+ ],+ unavailableSelectedIds: [+ (s) => [s.validSelectedIds, s.selectedInsightIds],+ (validIds: number[], selectedIds: number[] = []): number[] =>+ selectedIds.filter((id) => !validIds.includes(id)),+ ],insightTiles: [- (_, p) => [p.tiles],+ (s) => [s.tiles],(tiles: DashboardTile[]): DashboardTile[] =>((tiles || []) as DashboardTile[]).filter((tile): tile is DashboardTile => !!tile.insight && !tile.deleted && !tile.insight.deleted)diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex d916a52acc78..1768fcf622b1 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -1,4 +1,17 @@-import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers } from 'kea'+import {+ MakeLogicType,+ actions,+ connect,+ events,+ kea,+ key,+ listeners,+ path,+ props,+ propsChanged,+ reducers,+ selectors,+} from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'@@ -19,7 +32,7 @@ import { getInsightId } from 'scenes/insights/utils'import { organizationLogic } from 'scenes/organizationLogic'import { userLogic } from 'scenes/userLogic'-import { ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'+import { DashboardTile, ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'import {subscriptionsDeliveriesList,@@ -178,14 +191,30 @@ function validateTargetValue(return undefined}+function availableDashboardInsightIds(selectedIds: number[], dashboardTiles?: DashboardTile[]): number[] {+ if (!dashboardTiles) {+ return selectedIds+ }+ const availableIds = new Set(+ dashboardTiles+ .filter((tile) => !tile.deleted && tile.insight && !tile.insight.deleted)+ .map((tile) => tile.insight!.id)+ )+ return selectedIds.filter((id) => availableIds.has(id))+}+function validateDashboardExportInsights(subscription: Partial<SubscriptionType>,- dashboardId: number | undefined+ dashboardId: number | undefined,+ dashboardTiles?: DashboardTile[]): any {if (subscription.resource_type === SubscriptionResourceTypes.AiPrompt || !dashboardId) {return undefined}- return subscription.dashboard_export_insights?.length ? undefined : 'Select at least one insight'+ if (!availableDashboardInsightIds(subscription.dashboard_export_insights ?? [], dashboardTiles).length) {+ return 'Select at least one insight'+ }+ return undefined}function validateWeekdaySchedule(subscription: Partial<SubscriptionType>): string | null {@@ -298,6 +327,7 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {export interface SubscriptionLogicProps extends SubscriptionBaseProps {id: number | 'new'+ dashboardTiles?: DashboardTile[]/** Used to build the prefilled title when the form is opened via the subscribe-nudge notification. */dashboardName?: string | nullinsightName?: string@@ -307,6 +337,8 @@ export interface SubscriptionLogicProps extends SubscriptionBaseProps {export interface subscriptionLogicValues {currentOrganization: OrganizationType | null // organizationLogicuser: UserType | null // userLogic+ dashboardTiles: DashboardTile[] | undefined+ hasUnavailableInsights: booleanisSubscriptionSubmitting: booleanisSubscriptionValid: booleanlastDelivery: SubscriptionDeliveryApi | null@@ -490,6 +522,9 @@ export interface subscriptionLogicActions {sendTestDeliverySuccess: () => {value: true}+ setDashboardTiles: (tiles: DashboardTile[] | undefined) => {+ tiles: DashboardTile[] | undefined+ }setPreviewAsset: (asset: ExportedAssetType | null) => {asset: ExportedAssetType | null}@@ -539,6 +574,9 @@ export interface subscriptionLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface subscriptionLogicMeta {key: string+ __keaTypeGenInternalSelectorTypes: {+ hasUnavailableInsights: (subscription: SubscriptionType, dashboardTiles: DashboardTile[] | undefined) => boolean+ }}export type subscriptionLogicType = MakeLogicType<@@ -566,6 +604,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([setPreviewLoading: (loading: boolean) => ({ loading }),setPreviewError: (error: string | null) => ({ error }),setPreviewImageUrl: (url: string | null) => ({ url }),+ setDashboardTiles: (tiles: DashboardTile[] | undefined) => ({ tiles }),applyDefaultSelectedInsights: (selectedIds: number[]) => ({ selectedIds }),applyDefaultIntegration: (integrationId: number) => ({ integrationId }),replaceTeamsWebhook: true,@@ -577,7 +616,8 @@ export const subscriptionLogic = kea<subscriptionLogicType>([selectAiAnalysisWindow: (mode: AIWindowConfigApi['mode']) => ({ mode }),}),- reducers({+ reducers(({ props }) => ({+ dashboardTiles: [props.dashboardTiles, { setDashboardTiles: (_, { tiles }) => tiles }],// The host the API returned for a saved Teams subscription. Null once the user chooses to// replace the URL, which is what puts the input back on screen and the validation back on.storedTeamsWebhookHost: [@@ -636,8 +676,13 @@ export const subscriptionLogic = kea<subscriptionLogicType>([loadSubscriptionSuccess: () => true,},],- }),+ })),+ propsChanged(({ actions, props }, previousProps) => {+ if (props.dashboardTiles !== previousProps.dashboardTiles) {+ actions.setDashboardTiles(props.dashboardTiles)+ }+ }),loaders(({ props }) => ({lastDelivery: {__default: null as SubscriptionDeliveryApi | null,@@ -691,26 +736,51 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),+ selectors({+ hasUnavailableInsights: [+ (s) => [s.subscription, s.dashboardTiles],+ (subscription: SubscriptionType, dashboardTiles?: DashboardTile[]): boolean => {+ if (subscription.resource_type === SubscriptionResourceTypes.AiPrompt) {+ return false+ }+ const selectedIds = subscription.dashboard_export_insights ?? []+ return availableDashboardInsightIds(selectedIds, dashboardTiles).length < selectedIds.length+ },+ ],+ }),forms(({ props, actions, cache, values }) => ({subscription: {defaults: { enabled: NEW_SUBSCRIPTION.enabled } as unknown as SubscriptionType,- errors: (subscription) => ({- frequency: validateFrequency(subscription),- title: !subscription.title ? 'You need to give your subscription a name' : undefined,- interval: !subscription.interval ? 'You need to set an interval' : undefined,- start_date: !subscription.start_date ? 'You need to set a delivery time' : undefined,- // The destination select cannot produce an unknown value, but a `target_type`- // search param can.- target_type: isSupportedTargetType(subscription.target_type) ? undefined : 'Unsupported target type',- prompt: validatePrompt(subscription.resource_type, subscription.prompt),- ...validateAiWindow(subscription),- target_value: validateTargetValue(- subscription.target_type,- subscription.target_value,- isTeamsWebhookKept(subscription.target_type, values.storedTeamsWebhookHost)- ),- dashboard_export_insights: validateDashboardExportInsights(subscription, props.dashboardId),- }),+ errors: [+ (s) => [s.subscription, s.dashboardTiles, s.storedTeamsWebhookHost],+ (+ subscription: SubscriptionType,+ dashboardTiles: DashboardTile[] | undefined,+ storedTeamsWebhookHost: string | null+ ) => ({+ frequency: validateFrequency(subscription),+ title: !subscription.title ? 'You need to give your subscription a name' : undefined,+ interval: !subscription.interval ? 'You need to set an interval' : undefined,+ start_date: !subscription.start_date ? 'You need to set a delivery time' : undefined,+ // The destination select cannot produce an unknown value, but a `target_type`+ // search param can.+ target_type: isSupportedTargetType(subscription.target_type)+ ? undefined+ : 'Unsupported target type',+ prompt: validatePrompt(subscription.resource_type, subscription.prompt),+ ...validateAiWindow(subscription),+ target_value: validateTargetValue(+ subscription.target_type,+ subscription.target_value,+ isTeamsWebhookKept(subscription.target_type, storedTeamsWebhookHost)+ ),+ dashboard_export_insights: validateDashboardExportInsights(+ subscription,+ props.dashboardId,+ dashboardTiles+ ),+ }),+ ],submit: async (subscription, breakpoint) => {const isAi = subscription.resource_type === SubscriptionResourceTypes.AiPromptconst insightId = !isAi && props.insightShortId ? await getInsightId(props.insightShortId) : undefined@@ -730,7 +800,12 @@ export const subscriptionLogic = kea<subscriptionLogicType>([dashboard: isAi ? undefined : props.dashboardId,// AI subscriptions have no dashboard, so a carried-over insight selection would// trip the backend's "insights without a dashboard" guard. Clear it.- dashboard_export_insights: isAi ? [] : subscription.dashboard_export_insights,+ dashboard_export_insights: isAi+ ? []+ : availableDashboardInsightIds(+ subscription.dashboard_export_insights ?? [],+ values.dashboardTiles+ ),// Only AI subscriptions carry a prompt; a stale one on a non-AI sub (e.g. after// toggling resource_type back) would be rejected by the backend, so drop it.prompt: isAi ? subscription.prompt?.trim() : undefined,diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex e20775d99bd5..79e0b6a818ca 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -239,6 +239,7 @@ export function EditSubscription({insightShortId,dashboardId,dashboardName: dashboard?.name,+ dashboardTiles: dashboard?.tiles,}const logic = subscriptionLogic(logicProps)const subscriptionslogic = subscriptionsLogic({@@ -254,6 +255,7 @@ export function EditSubscription({subscriptionErrors,isSubscriptionSubmitting,subscriptionChanged,+ hasUnavailableInsights,lastDelivery,lastDeliveryLoadFailed,lastDeliveryLoading,@@ -317,7 +319,7 @@ export function EditSubscription({let saveDisabledReason: string | undefined = undefinedif (aiGate.submitBlocked) {saveDisabledReason = AI_NOT_ALLOWED_REASON- } else if (!subscriptionChanged) {+ } else if (!subscriptionChanged && !hasUnavailableInsights) {saveDisabledReason = 'No changes to save'}diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsxindex 6852686eb70d..85c44d8f84b4 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsx@@ -108,6 +108,85 @@ describe('EditSubscription unsaved changes', () => {expect(await screen.findByText('Not found')).toBeInTheDocument()})+ it.each([+ { selectedIds: [998, 999], removeTileAfterOpen: false },+ { selectedIds: [11, 999], removeTileAfterOpen: false },+ { selectedIds: [11], removeTileAfterOpen: true },+ ])(+ 'removes unavailable selections on save: %j',+ async ({ selectedIds, removeTileAfterOpen }) => {+ const subscription = subscriptionFixture({+ target_type: 'email',+ target_value: '[email protected]',+ dashboard_export_insights: selectedIds,+ })+ let savedIds: number[] | undefined+ const patch = jest.fn(async ({ request }) => {+ const body = await request.json()+ savedIds = body.dashboard_export_insights+ return [200, { ...subscription, ...body }]+ })+ useMocks({+ get: {+ '/_preflight/': { ...preflightJson, email_service_available: true },+ '/api/environments/:team/subscriptions/1': subscription,+ '/api/environments/:team/subscriptions': { count: 0, results: [] },+ '/api/projects/:team/subscriptions/1/deliveries/': { next: null, previous: null, results: [] },+ '/api/projects/:team/integrations': { count: 1, results: [SLACK_INTEGRATION] },+ '/api/environments/:team/subscriptions/summary_quota': {+ active_count: 0,+ limit: null,+ at_limit: false,+ },+ '/api/organizations/@current/': MOCK_DEFAULT_ORGANIZATION,+ '/api/organizations/@current/members/': { count: 0, results: [] },+ },+ patch: { '/api/environments/:team/subscriptions/1': patch },+ })+ initKeaTests()+ userLogic.mount()+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)+ router.actions.push('/dashboard/5/subscriptions/1')+ const { rerender } = render(+ <Provider>+ <EditSubscription id={1} dashboard={DASHBOARD} onCancel={jest.fn()} onDelete={jest.fn()} />+ </Provider>+ )++ if (removeTileAfterOpen) {+ await screen.findByDisplayValue(subscription.title)+ expect(isClean()).toBe(true)+ rerender(+ <Provider>+ <EditSubscription+ id={1}+ dashboard={{ ...DASHBOARD, tiles: DASHBOARD.tiles.slice(1) }}+ onCancel={jest.fn()}+ onDelete={jest.fn()}+ />+ </Provider>+ )+ }+ await screen.findByText(/selected insights? (?:is|are) no longer on this dashboard/, {}, { timeout: 10000 })+ expect(isClean()).toBe(false)+ expect(screen.queryByText('Remove all missing insights')).not.toBeInTheDocument()+ if (selectedIds.includes(998) || removeTileAfterOpen) {+ await userEvent.click(saveButton())+ expect(await screen.findAllByText('Select at least one insight')).not.toHaveLength(0)+ expect(patch).not.toHaveBeenCalled()+ await userEvent.click(screen.getByText(removeTileAfterOpen ? 'Sessions' : 'Pageviews'))+ }+ await userEvent.click(saveButton())+ await waitFor(() => expect(patch).toHaveBeenCalledTimes(1))+ expect(savedIds).toEqual([removeTileAfterOpen ? 12 : 11])+ await waitFor(() => expect(isClean()).toBe(true))+ expect(+ screen.queryByText(/selected insights? (?:is|are) no longer on this dashboard/)+ ).not.toBeInTheDocument()+ },+ 30000+ )+it.each([['an email destination',