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(insights): Add an option to apply internal and test account filter to all existing insights (#83116)

Daniel Parker319b598c5dc9
diff --git a/docs/published/docs/data/test-accounts.mdx b/docs/published/docs/data/test-accounts.mdx
new file mode 100644
index 000000000000..48df0a43b055
--- /dev/null
+++ b/docs/published/docs/data/test-accounts.mdx
@@ -0,0 +1,116 @@
+---
+title: Internal and test users
+sidebar: Docs
+showTitle: true
+---
+
+Your own team's traffic skews your data.
+Developers on localhost, staff accounts, contractors, and QA runs all get captured alongside real users.
+
+PostHog lets you define who counts as internal for a project, then filter those people out of your analytics.
+
+For a step-by-step walkthrough of setting up your first filter, see [how to filter out internal users](/tutorials/filter-internal-users).
+
+## Defining who counts as internal
+
+Go to **Settings → Project → Filter out internal and test users**.
+You need to be a project admin to change these settings.
+
+The filters you add here describe the people you want to exclude.
+Each entry is a property filter, and you can add as many as you need.
+An event or person is treated as internal if it matches any of them.
+
+Three kinds of entry are supported:
+
+| Kind | Example | Notes |
+| --------------- | --------------------------------------- | --------------------------------------------------------------- |
+| Person property | `email` does not contain `@example.com` | Works everywhere, including CDP destinations |
+| Event property | `$host` does not contain `localhost` | Useful for excluding local development traffic |
+| Cohort | `id` not in `Internal team` | See [using cohorts as filters](#using-cohorts-as-filters) below |
+
+Available operators include `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`, `gt`, `lt`, `gte`, `lte`, `is_set`, `is_not_set`, `in`, and `not_in`.
+
+These settings are per project.
+If you use more than one project, set them up in each one.
+
+## Where the filter applies
+
+Once defined, the same filter list is used by product analytics insights, web analytics, revenue analytics, session replay, and [CDP destinations](/docs/cdp).
+
+Defining the filters does not switch them on by itself.
+For insights, filtering is a per-insight setting, so you control which insights use it.
+
+## Turning the filter on for insights
+
+There are three controls, and they do different things.
+
+### On a single insight
+
+Every insight has a **Filter out internal and test users** toggle in its filter panel.
+This is the setting the other two controls write to.
+
+### As the default for new insights
+
+**Enable this filter on all new insights** in project settings sets the starting value for insights created from then on.
+It does not change insights that already exist.
+
+### On the insights you already have
+
+Under **Existing insights** in project settings, **Turn on for existing insights** and **Turn off for existing insights** apply your choice across every insight in the project.
+
+Use this after setting up your filters for the first time, so your existing dashboards and insights stop counting internal traffic.
+
+Some insights are left as they are:
+
+- **SQL insights**, which have no such toggle. Write the exclusion into the query itself if you need it.
+- **Insights you can't edit.** An organization admin can run it to cover those, or you can ask for edit access to them. See [access control](/docs/settings/access-control).
+- **Insights saved in an older format.** These keep whatever they were set to. Open one and save it to convert it, then run this again.
+
+After each run you get a summary of how many insights were changed, how many already matched, and how many were left alone.
+
+Dashboards show whatever their insights are set to.
+The exception is a dashboard with its own override for this filter, which keeps that override and ignores the change to the underlying insight.
+
+### Getting a previous setting back
+
+There is no bulk undo.
+Running it the other way sets every insight to the opposite value, rather than restoring the mix that was there before.
+
+To recover a single insight, open its activity log.
+Each change is recorded with the insight's previous query, so you can see what it was set to and put it back by hand.
+
+## Using cohorts as filters
+
+Inline person property filters work on every surface, including real-time CDP destinations.
+
+Cohorts work for analytics queries such as insights and dashboards.
+In CDP destinations they only work if the cohort is built exclusively from person property filters.
+A cohort that uses behavioral filters, or has no properties defined, causes CDP destinations to error.
+
+If you need one filter list that works everywhere, use inline person property filters.
+
+Cohort filters have also been reported to exclude anonymous users along with the cohort members.
+See [issue #39835](https://github.com/PostHog/posthog/issues/39835) for the current status.
+
+## API
+
+You can apply the filter to existing insights over the API:
+
+```bash
+curl -X POST 'https://us.posthog.com/api/projects/:project_id/insights/bulk_set_test_account_filter/' \
+ -H 'Authorization: Bearer <POSTHOG_PERSONAL_API_KEY>' \
+ -H 'Content-Type: application/json' \
+ -d '{"enabled": true}'
+```
+
+The key needs the `insight:write` scope, and its owner has to be a project admin, the same as in the UI.
+The response counts the outcomes:
+
+```json
+{ "updated": 42, "unchanged": 3, "unsupported": 2, "skipped": 0, "legacy": 0 }
+```
+
+Insights are updated in batches, so a request that fails part way through leaves the finished batches applied.
+Running it again is safe and picks up the rest.
+
+See the [API reference](/docs/api) for more.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c1c55192eb3a..66986a928901 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6591,7 +6591,7 @@ snapshots:
scenes-app-inbox-scene--empty-control--dark:
hash: v1.k794b7964.99ffca71975a423bd8ef679c361fd0bf4b9a1f6be6d4f4dfe82b69a9637184af.NwEat2sZEU9_PcNSbsxCt1SZBzTzyQJbewP-ZpJZOM4
scenes-app-inbox-scene--empty-control--light:
- hash: v1.k794b7964.0bd8154cc24c9f19aef821da27d873001473634e8c8e4868d414d9204b35c58f.ATQvLBhDOPKTDa3bKkfGKcPytCuMGpk_mBtOdv-f3WQ
+ hash: v1.k794b7964.897cfada57cb1060860335179b5f5d10d33399f095e30ffa6a5902e188905977.VxZJrOI1PpjGafyt7ExIH6RjhtapLZ36twmDzUMFcts
scenes-app-inbox-scene--empty-with-many-scouts--dark:
hash: v1.k794b7964.32ea8aa91e71baa9a72b403c44731aa97bff8282b6bd9d5041b4537a50825060.G9RYZ-ZdAGxc4hcvryNgiAmH5xsqtHIj8mjKeXCZpJI
scenes-app-inbox-scene--empty-with-many-scouts--light:
@@ -7569,9 +7569,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-csp-reporting--light:
hash: v1.k794b7964.fd469d98fbaae429c7a81f49593b7f5723a4e068f3ceb03ed5f047b0535e227c.NLE5KInsuUjiK_nTGOj4Pgh43vBGeZXEgKsn6Rw5hXQ
scenes-app-settings-environment--settings-environment-customization--dark:
- hash: v1.k794b7964.62c21cd085915d104c92416ee218f9f12159066791fb833f576912ead2a809b7.OUqBSu9xrfAvA_NO2eN6cmVREwKJxJrx3vlevIwQD3g
+ hash: v1.k794b7964.b2b538c8df6d6b783d47c2be8817bb2f861b008fa847c50d5c99af59cbfa4cac.i6X_OHC5u_KV0XlPvyAcdu8QrZ93MD0OrVZQmaPcgMI
scenes-app-settings-environment--settings-environment-customization--light:
- hash: v1.k794b7964.e94d97fff18d5bff78eb6d25f0b56ecc7d8ca86ff3f05eca2186eb6696465d9d.h-lAqKJZMVq-VXGOL4mnrcH_f4ExzGTdGzUCaGg7N7Y
+ hash: v1.k794b7964.a393b6bb989d93d6b36362c11e1d6dfb4019d8d631c0d250ec0cc295301e2b96.Hn0smGMdrsefh679kAsc4_NCm7DZwG063H7cj1I5iiM
scenes-app-settings-environment--settings-environment-danger-zone--dark:
hash: v1.k794b7964.b2709895d612381724c2275aeaa291853ad3460c7a70f82f44f9b68b53d48da7.5LGiSsDKJB9hs5AsxbeWNNMpCqNP39jEiu5P91ZXcGY
scenes-app-settings-environment--settings-environment-danger-zone--light:
diff --git a/frontend/src/scenes/settings/environment/ApplyTestAccountFilterToExistingInsights.tsx b/frontend/src/scenes/settings/environment/ApplyTestAccountFilterToExistingInsights.tsx
new file mode 100644
index 000000000000..69486b3aa0f3
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/ApplyTestAccountFilterToExistingInsights.tsx
@@ -0,0 +1,95 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, Link } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { applyTestAccountFilterLogic } from './applyTestAccountFilterLogic'
+
+export function ApplyTestAccountFilterToExistingInsights(): JSX.Element {
+ const { applyToExistingInsights } = useActions(applyTestAccountFilterLogic)
+ const { pendingEnabled, bulkSetResponseLoading } = useValues(applyTestAccountFilterLogic)
+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ const noFiltersReason = currentTeam?.test_account_filters?.length ? null : 'Add at least one filter above first'
+ const inFlightReason = bulkSetResponseLoading ? 'Applying your last change' : null
+
+ const confirm = (enabled: boolean): void => {
+ LemonDialog.open({
+ title: `Turn the internal and test user filter ${enabled ? 'on' : 'off'} for every insight in this project?`,
+ width: 560,
+ content: (
+ <div className="flex flex-col gap-3">
+ <p className="mb-0">
+ Every insight in this project will {enabled ? 'start' : 'stop'} filtering out internal and test
+ users, including insights other people created. This replaces whatever each insight is set to
+ now.
+ </p>
+ <div>
+ <p className="mb-1">Left as they are:</p>
+ <ul className="list-disc pl-5 mb-0">
+ <li>SQL insights, which have no such filter</li>
+ <li>
+ Insights you can't edit. An organization admin can run this to cover those, or you can
+ ask for edit access to them.{' '}
+ <Link to="https://posthog.com/docs/settings/access-control">About access control</Link>
+ </li>
+ <li>
+ Insights saved in an older format. Open and save one to convert it, then run this again.
+ </li>
+ </ul>
+ </div>
+ <p className="mb-0">
+ Dashboards follow their insights, unless a dashboard sets its own override. The default for new
+ insights doesn't change.
+ </p>
+ <LemonBanner type="warning">
+ There's no bulk undo. Running it the other way later would set every insight to{' '}
+ {enabled ? 'off' : 'on'}, not restore what each one had before. To get a single insight back,
+ check its activity log for the previous setting.
+ </LemonBanner>
+ </div>
+ ),
+ primaryButton: {
+ children: `Turn the filter ${enabled ? 'on' : 'off'}`,
+ onClick: () => applyToExistingInsights(enabled),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ return (
+ <div>
+ {/* Sized below the settings section's own h2, so this reads as part of it rather than a sibling. */}
+ <h3 className="text-sm font-semibold mb-1">Existing insights</h3>
+ <p className="text-secondary text-sm">
+ Turn the internal and test user filter on or off for every insight in this project. This doesn't change
+ the default for new insights.
+ </p>
+ <div className="flex gap-2">
+ {[true, false].map((enabled) => (
+ <LemonButton
+ key={String(enabled)}
+ type="secondary"
+ size="small"
+ data-attr={`apply-test-account-filter-to-existing-insights-${enabled ? 'on' : 'off'}`}
+ loading={bulkSetResponseLoading && pendingEnabled === enabled}
+ disabled={currentTeamLoading}
+ disabledReason={restrictedReason ?? noFiltersReason ?? inFlightReason}
+ onClick={() => confirm(enabled)}
+ >
+ {enabled ? 'Turn on for existing insights' : 'Turn off for existing insights'}
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/environment/TestAccountFiltersConfig.tsx b/frontend/src/scenes/settings/environment/TestAccountFiltersConfig.tsx
index ebdfa4614ae4..831de16b1d45 100644
--- a/frontend/src/scenes/settings/environment/TestAccountFiltersConfig.tsx
+++ b/frontend/src/scenes/settings/environment/TestAccountFiltersConfig.tsx
@@ -18,6 +18,7 @@ import { AnyPropertyFilter, type CohortType, PropertyOperator, type TeamPublicTy
import { revenueAnalyticsSettingsLogic } from 'products/revenue_analytics/frontend/settings/revenueAnalyticsSettingsLogic'
+import { ApplyTestAccountFilterToExistingInsights } from './ApplyTestAccountFilterToExistingInsights'
import { filterTestAccountsDefaultsLogic } from './filterTestAccountDefaultsLogic'
function createTestAccountFilterWarningLabels(
@@ -155,6 +156,7 @@ function TestAccountFiltersConfig(): JSX.Element {
label="Filter out internal and test users from revenue analytics"
bordered
/>
+ <ApplyTestAccountFilterToExistingInsights />
</div>
)
}
diff --git a/frontend/src/scenes/settings/environment/applyTestAccountFilterLogic.test.ts b/frontend/src/scenes/settings/environment/applyTestAccountFilterLogic.test.ts
new file mode 100644
index 000000000000..d0320be99950
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/applyTestAccountFilterLogic.test.ts
@@ -0,0 +1,48 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { initKeaTests } from '~/test/init'
+
+import { insightsBulkSetTestAccountFilterCreate } from 'products/product_analytics/frontend/generated/api'
+
+import { applyTestAccountFilterLogic } from './applyTestAccountFilterLogic'
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: { success: jest.fn(), info: jest.fn(), error: jest.fn() },
+}))
+jest.mock('products/product_analytics/frontend/generated/api', () => ({
+ insightsBulkSetTestAccountFilterCreate: jest.fn(),
+}))
+
+const mockedApi = insightsBulkSetTestAccountFilterCreate as jest.Mock
+const mockedToast = lemonToast as jest.Mocked<typeof lemonToast>
+
+describe('applyTestAccountFilterLogic', () => {
+ let logic: ReturnType<typeof applyTestAccountFilterLogic.build>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ logic = applyTestAccountFilterLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ // A project of only legacy insights leaves every other count at zero, so without `legacy` in the
+ // summary the run reports that nothing needed changing while those insights still filter the other way.
+ it('names insights held back for their storage format rather than reporting nothing to do', async () => {
+ mockedApi.mockResolvedValue({ updated: 0, unchanged: 0, unsupported: 0, skipped: 0, legacy: 3 })
+
+ logic.actions.applyToExistingInsights(true)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockedToast.success).not.toHaveBeenCalled()
+ const [message] = mockedToast.info.mock.calls[0]
+ expect(message).toContain('No insights changed.')
+ expect(message).toContain('3 saved in an older format')
+ })
+})
diff --git a/frontend/src/scenes/settings/environment/applyTestAccountFilterLogic.ts b/frontend/src/scenes/settings/environment/applyTestAccountFilterLogic.ts
new file mode 100644
index 000000000000..87f15687ac1e
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/applyTestAccountFilterLogic.ts
@@ -0,0 +1,105 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { insightsBulkSetTestAccountFilterCreate } from 'products/product_analytics/frontend/generated/api'
+import { InsightBulkSetTestAccountFilterResponseApi } from 'products/product_analytics/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface applyTestAccountFilterLogicValues {
+ currentProjectId: number | string // teamLogic
+ bulkSetResponse: InsightBulkSetTestAccountFilterResponseApi | null
+ bulkSetResponseLoading: boolean
+ pendingEnabled: boolean | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface applyTestAccountFilterLogicActions {
+ applyToExistingInsights: (enabled: boolean) => {
+ enabled: boolean
+ }
+ applyToExistingInsightsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ applyToExistingInsightsSuccess: (
+ bulkSetResponse: InsightBulkSetTestAccountFilterResponseApi,
+ payload?: {
+ enabled: boolean
+ }
+ ) => {
+ bulkSetResponse: InsightBulkSetTestAccountFilterResponseApi
+ payload?: {
+ enabled: boolean
+ }
+ }
+}
+
+export type applyTestAccountFilterLogicType = MakeLogicType<
+ applyTestAccountFilterLogicValues,
+ applyTestAccountFilterLogicActions
+>
+
+export const applyTestAccountFilterLogic = kea<applyTestAccountFilterLogicType>([
+ path(['scenes', 'settings', 'environment', 'applyTestAccountFilterLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+ actions({
+ applyToExistingInsights: (enabled: boolean) => ({ enabled }),
+ }),
+ reducers({
+ pendingEnabled: [
+ null as boolean | null,
+ {
+ applyToExistingInsights: (_, { enabled }) => enabled,
+ applyToExistingInsightsSuccess: () => null,
+ applyToExistingInsightsFailure: () => null,
+ },
+ ],
+ }),
+ loaders(({ values }) => ({
+ bulkSetResponse: [
+ null as InsightBulkSetTestAccountFilterResponseApi | null,
+ {
+ applyToExistingInsights: async ({ enabled }: { enabled: boolean }) => {
+ return await insightsBulkSetTestAccountFilterCreate((values.currentProjectId ?? '').toString(), {
+ enabled,
+ })
+ },
+ },
+ ],
+ })),
+ listeners(() => ({
+ applyToExistingInsightsSuccess: ({ bulkSetResponse, payload }) => {
+ if (!bulkSetResponse) {
+ return
+ }
+ const { updated, unsupported, skipped, legacy } = bulkSetResponse
+ const direction = payload?.enabled ? 'on' : 'off'
+ const noun = updated === 1 ? 'insight' : 'insights'
+ const extras = [
+ unsupported > 0 ? `${unsupported} with no such filter, like SQL insights` : null,
+ // The two with a next step say what it is. Nothing can put the toggle on a SQL insight.
+ skipped > 0 ? `${skipped} you can't edit (an organization admin can apply it to those)` : null,
+ legacy > 0 ? `${legacy} saved in an older format (open and save one to convert it)` : null,
+ ].filter(Boolean)
+ const leftAlone = extras.length > 0 ? ` Left alone: ${extras.join(', ')}.` : ''
+ if (updated > 0) {
+ lemonToast.success(`Turned the filter ${direction} for ${updated} ${noun}.${leftAlone}`)
+ } else {
+ // "Needed changing" would be a lie when insights were held back rather than already correct.
+ const nothing = extras.length > 0 ? 'No insights changed.' : 'No insights needed changing.'
+ lemonToast.info(`${nothing}${leftAlone}`)
+ }
+ },
+ applyToExistingInsightsFailure: () => {
+ lemonToast.error('Could not update your existing insights. Try again in a moment.')
+ },
+ })),
+])
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 2642b48a1b61..ddb5ef99f180 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -110,6 +110,7 @@ from posthog.models.filters.utils import get_filter
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
+from posthog.permissions import TeamMemberStrictManagementPermission
from posthog.ph_client import feature_enabled_or_false
from posthog.query_cache import QueryCache
from posthog.rate_limit import (
@@ -156,6 +157,7 @@ from products.product_analytics.backend.api.insight_metadata import (
generate_insight_metadata,
)
from products.product_analytics.backend.api.insight_suggestions import get_insight_analysis, get_insight_suggestions
+from products.product_analytics.backend.insight_test_account_filters import plan_test_account_filter_update
from products.product_analytics.backend.logic import map_stale_to_latest
from products.product_analytics.backend.models.insight import Insight, InsightViewed
from products.product_analytics.backend.models.insight_variable import InsightVariable
@@ -1623,6 +1625,31 @@ class InsightBulkRestoreResponseSerializer(serializers.Serializer):
)
+INSIGHT_BULK_TEST_ACCOUNT_FILTER_BATCH_SIZE = 500
+
+
+class InsightBulkSetTestAccountFilterRequestSerializer(serializers.Serializer):
+ enabled = serializers.BooleanField(
+ help_text="Whether every existing insight should filter out internal and test users."
+ )
+
+
+class InsightBulkSetTestAccountFilterResponseSerializer(serializers.Serializer):
+ updated = serializers.IntegerField(help_text="Number of insights whose test account filter was changed.")
+ unchanged = serializers.IntegerField(help_text="Number of insights that already had the requested value.")
+ unsupported = serializers.IntegerField(
+ help_text="Number of insights with no test account filter to set, such as SQL insights."
+ )
+ skipped = serializers.IntegerField(help_text="Number of insights the requester cannot edit.")
+ legacy = serializers.IntegerField(
+ help_text=(
+ "Number of insights left as they are because they still store legacy `filters` rather than a query. "
+ "They keep whatever value they already had. Opening and saving one converts it, after which this "
+ "endpoint covers it."
+ )
+ )
+
+
@extend_schema(extensions={"x-product": ProductKey.PRODUCT_ANALYTICS})
@extend_schema_view(
list=extend_schema(
@@ -2739,6 +2766,155 @@ When set, the specified dashboard's filters and date range override will be appl
return Response({"restored": restored, "skipped": skipped})
+ @validated_request(
+ request_serializer=InsightBulkSetTestAccountFilterRequestSerializer,
+ responses={200: OpenApiResponse(response=InsightBulkSetTestAccountFilterResponseSerializer)},
+ description=(
+ "Turn 'filter out internal and test users' on or off for every existing insight in the project. "
+ "Requires project admin, matching the settings UI that fronts it. The setting of the same name only "
+ "decides the default for new insights; this applies it to the insights that already exist. Only "
+ "insights that store a query are changed; insights still holding legacy `filters` are counted in "
+ "`legacy` and left as they are. Insights with nowhere to put the toggle, such as SQL insights, are "
+ "left alone, as are insights the requester cannot edit. Dashboards follow their insights unless the "
+ "dashboard sets its own override. Insights are updated in batches, so a failure part way through "
+ "leaves the finished batches applied. Retrying is safe and picks up the rest."
+ ),
+ )
+ @action(
+ methods=["POST"],
+ detail=False,
+ required_scopes=["insight:write"],
+ # Layered onto the viewset's chain rather than replacing it: `TeamAndOrgViewSetMixin.get_permissions`
+ # builds its own list and extends it with `self.permission_classes`, which is what this sets.
+ permission_classes=[TeamMemberStrictManagementPermission],
+ )
+ def bulk_set_test_account_filter(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ enabled: bool = request.validated_data["enabled"]
+ # Project-scoped to match `dangerously_get_queryset`, since insights are project-level even though they
+ # are served under /environments/. The per-insight access check below resolves rows team-scoped, which is
+ # equivalent today because team_id == project_id, and asymmetric only under the deprecated
+ # multi-team-per-project path being removed. Same trade-off as the feature flag bulk endpoint.
+ saved_insights = Insight.objects.filter(team__project_id=self.team.project_id, saved=True)
+ # Counted rather than silently dropped: these still carry the toggle through `filter_to_query`, so a run
+ # that leaves them behind has to say so instead of reporting that nothing needed changing.
+ legacy_count = saved_insights.filter(query__isnull=True).count()
+
+ totals = {"updated": 0, "unchanged": 0, "unsupported": 0, "skipped": 0, "legacy": legacy_count}
+ considered = legacy_count
+ # Keyset pagination, so each batch scans forward from the previous batch's last id rather than re-walking
+ # the index from the start, and no project's whole insight list has to sit in memory. The writes below
+ # never touch `id`, so the cursor can't skip or repeat a row.
+ cursor = 0
+ while True:
+ batch = list(
+ saved_insights.filter(query__isnull=False, id__gt=cursor).order_by("id")[
+ :INSIGHT_BULK_TEST_ACCOUNT_FILTER_BATCH_SIZE
+ ]
+ )
+ if not batch:
+ break
+ cursor = batch[-1].id
+ considered += len(batch)
+ for key, count in self._set_test_account_filter_on_batch(batch, enabled=enabled).items():
+ totals[key] += count
+
+ if totals["updated"]:
+ self.user_permissions.reset_insights_dashboard_cached_results()
+
+ # Reported even when nothing changed: a run that finds no insights to flip still tells us
+ # someone reached for this, and the no-op rate is the signal for whether it's discoverable.
+ report_user_action(
+ request.user,
+ "insights bulk test account filter set",
+ {
+ "enabled": enabled,
+ # Includes the legacy rows so the outcome counts still add up to what was considered.
+ "insights_considered": considered,
+ **{f"insights_{outcome}": count for outcome, count in totals.items()},
+ },
+ team=self.team,
+ request=request,
+ )
+
+ return Response(totals)
+
+ # Annotated as Sequence rather than list because this viewset defines a `list` action, which shadows the
+ # builtin inside the class body: `list[Insight]` here raises TypeError at import.
+ def _editable_insights(self, insights: Sequence[Insight]) -> tuple[Sequence[Insight], int]:
+ """The insights from this batch the caller may edit, and how many were held back.
+
+ Access has to be resolved one insight at a time. `filter_queryset_by_access_level` answers whether an
+ insight is visible rather than whether it can be edited, so filtering in the query would let insights
+ the caller only has `viewer` on through to the write.
+
+ EE's `CanEditInsight` needs no counterpart here. It refuses insights on dashboards the caller can only
+ view, but `can_edit` short-circuits for anyone who `can_restrict`, which is every project admin, and the
+ action already requires project admin. Relaxing that requirement would have to bring the check back.
+ """
+ if not self.user_access_control:
+ return insights, 0
+
+ self.user_access_control.preload_object_access_controls(cast(list, list(insights)))
+ editable = [
+ insight
+ for insight in insights
+ if (level := self.user_access_control.get_user_access_level(insight))
+ and access_level_satisfied_for_resource("insight", level, "editor")
+ ]
+ return editable, len(insights) - len(editable)
+
+ def _set_test_account_filter_on_batch(self, insights: Sequence[Insight], *, enabled: bool) -> dict[str, int]:
+ editable, skipped = self._editable_insights(insights)
+ counts = {"updated": 0, "unchanged": 0, "unsupported": 0, "skipped": skipped}
+
+ current_user = cast(User, self.request.user)
+ was_impersonated = is_impersonated(self.request)
+ organization_id = current_user.current_organization_id
+ modified_at = now()
+
+ to_update: list[Insight] = []
+ activity_log_entries: list[LogActivityEntry] = []
+ for insight in editable:
+ update = plan_test_account_filter_update(insight.query, enabled=enabled)
+ if not update.supported:
+ counts["unsupported"] += 1
+ continue
+ if not update.changed:
+ counts["unchanged"] += 1
+ continue
+
+ change = Change(type="Insight", field="query", action="changed", before=insight.query, after=update.query)
+ insight.query = update.query
+ insight.last_modified_at = modified_at
+ insight.last_modified_by = current_user
+ to_update.append(insight)
+ counts["updated"] += 1
+
+ insight_name = insight.name or insight.derived_name
+ # The experiments feature creates unnamed insights; the single-update path skips logging those.
+ if insight_name:
+ activity_log_entries.append(
+ LogActivityEntry(
+ organization_id=organization_id,
+ team_id=self.team_id,
+ user=current_user,
+ was_impersonated=was_impersonated,
+ item_id=insight.id,
+ scope="Insight",
+ activity="updated",
+ detail=Detail(name=insight_name, short_id=insight.short_id, changes=[change]),
+ )
+ )
+
+ if to_update:
+ with transaction.atomic():
+ # `query_metadata` is derived from the query's entities, which this toggle doesn't touch, so it
+ # stays valid even though bulk_update skips the regeneration in `Insight.save`.
+ Insight.objects.bulk_update(to_update, ["query", "last_modified_at", "last_modified_by"])
+ bulk_log_activity(activity_log_entries)
+
+ return counts
+
@extend_schema(
operation_id="insights_all_activity_retrieve",
parameters=[
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index 7deab17e9293..9b95cb7df15b 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -5299,3 +5299,174 @@ class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest)
self.assertFalse(Insight.objects_including_soft_deleted.get(id=insight.id).deleted)
# The insight comes back, but its tile on a dashboard the user can only view stays hidden.
self.assertTrue(DashboardTile.objects_including_soft_deleted.get(id=tile.id).deleted)
+
+
+class TestInsightBulkSetTestAccountFilter(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The action is project-admin only, so the caller in the rest of these tests has to be one.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def _create_query_insight(self, *, name: str = "Trend", filter_test_accounts: bool | None = None) -> Insight:
+ source: dict[str, Any] = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}
+ if filter_test_accounts is not None:
+ source["filterTestAccounts"] = filter_test_accounts
+ return Insight.objects.create(
+ team=self.team,
+ name=name,
+ saved=True,
+ created_by=self.user,
+ query={"kind": "InsightVizNode", "source": source},
+ )
+
+ def _reloaded_source(self, insight: Insight) -> dict[str, Any]:
+ insight.refresh_from_db()
+ assert insight.query is not None
+ return insight.query["source"]
+
+ def _bulk_set(self, enabled: bool) -> Any:
+ return self.client.post(
+ f"/api/environments/{self.team.id}/insights/bulk_set_test_account_filter/",
+ {"enabled": enabled},
+ format="json",
+ )
+
+ @parameterized.expand([("turn on", True), ("turn off", False)])
+ def test_sets_the_filter_on_every_query_insight(self, _name: str, enabled: bool) -> None:
+ needs_change = self._create_query_insight(filter_test_accounts=not enabled)
+ already_set = self._create_query_insight(name="Already set", filter_test_accounts=enabled)
+
+ response = self._bulk_set(enabled)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(response.json(), {"updated": 1, "unchanged": 1, "unsupported": 0, "skipped": 0, "legacy": 0})
+ self.assertEqual(self._reloaded_source(needs_change)["filterTestAccounts"], enabled)
+ self.assertEqual(self._reloaded_source(already_set)["filterTestAccounts"], enabled)
+
+ @patch("products.product_analytics.backend.api.insight.INSIGHT_BULK_TEST_ACCOUNT_FILTER_BATCH_SIZE", 2)
+ def test_covers_every_insight_across_several_batches(self) -> None:
+ insights = [self._create_query_insight(name=f"Trend {n}", filter_test_accounts=False) for n in range(5)]
+
+ response = self._bulk_set(True)
+
+ # A cursor that doesn't advance reprocesses rows, one that advances too far leaves the tail untouched.
+ # Both are invisible while every insight fits in a single batch, which is every other case here.
+ self.assertEqual(response.json(), {"updated": 5, "unchanged": 0, "unsupported": 0, "skipped": 0, "legacy": 0})
+ for insight in insights:
+ self.assertTrue(self._reloaded_source(insight)["filterTestAccounts"])
+
+ def test_treats_a_missing_filter_as_off(self) -> None:
+ insight = self._create_query_insight()
+
+ self.assertEqual(self._bulk_set(False).json()["unchanged"], 1)
+ self.assertEqual(self._bulk_set(True).json()["updated"], 1)
+
+ self.assertTrue(self._reloaded_source(insight)["filterTestAccounts"])
+
+ def test_leaves_sql_insights_alone(self) -> None:
+ sql_insight = Insight.objects.create(
+ team=self.team,
+ name="SQL",
+ saved=True,
+ query={"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},
+ )
+
+ response = self._bulk_set(True)
+
+ self.assertEqual(response.json(), {"updated": 0, "unchanged": 0, "unsupported": 1, "skipped": 0, "legacy": 0})
+ self.assertNotIn("filterTestAccounts", self._reloaded_source(sql_insight))
+
+ def test_reports_insights_that_only_have_legacy_filters_rather_than_changing_them(self) -> None:
+ mine = self._create_query_insight(filter_test_accounts=False)
+ legacy = Insight.objects.create(
+ team=self.team, name="Legacy", saved=True, filters={"insight": "TRENDS", "events": [{"id": "$pageview"}]}
+ )
+
+ response = self._bulk_set(True)
+
+ # `legacy: 1` rather than `unsupported: 1`: these carry the toggle and have their own remedy, so the
+ # caller has to be able to tell them apart from a SQL insight that can never have one.
+ self.assertEqual(response.json(), {"updated": 1, "unchanged": 0, "unsupported": 0, "skipped": 0, "legacy": 1})
+ self.assertTrue(self._reloaded_source(mine)["filterTestAccounts"])
+ legacy.refresh_from_db()
+ self.assertNotIn("filter_test_accounts", legacy.filters)
+
+ def test_leaves_insights_in_other_projects_alone(self) -> None:
+ mine = self._create_query_insight(filter_test_accounts=False)
+ _, other_team = Project.objects.create_with_team(organization=self.organization, initiating_user=self.user)
+ theirs = Insight.objects.create(
+ team=other_team,
+ name="Theirs",
+ saved=True,
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "filterTestAccounts": False,
+ },
+ },
+ )
+
+ response = self._bulk_set(True)
+
+ self.assertEqual(response.json(), {"updated": 1, "unchanged": 0, "unsupported": 0, "skipped": 0, "legacy": 0})
+ self.assertTrue(self._reloaded_source(mine)["filterTestAccounts"])
+ self.assertFalse(self._reloaded_source(theirs)["filterTestAccounts"])
+
+ def test_refuses_a_member_who_could_otherwise_edit_every_insight(self) -> None:
+ insight = self._create_query_insight(filter_test_accounts=False)
+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+
+ self.client.force_login(member)
+ response = self._bulk_set(True)
+
+ # The per-insight check would let this through: insights default to editor access, which is how the
+ # settings UI hiding the button from non-admins ended up being the only thing stopping them.
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(self._reloaded_source(insight)["filterTestAccounts"])
+
+ def test_records_the_change_in_the_activity_log(self) -> None:
+ insight = self._create_query_insight()
+
+ self._bulk_set(True)
+
+ response = self.client.get(f"/api/environments/{self.team.id}/insights/{insight.id}/activity/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ activities = response.json()["results"]
+ self.assertEqual(activities[0]["activity"], "updated")
+ self.assertEqual([change["field"] for change in activities[0]["detail"]["changes"]], ["query"])
+
+ @parameterized.expand(
+ [
+ ("a run that flips insights", False, {"insights_updated": 1, "insights_unchanged": 0}),
+ ("a run that flips nothing", True, {"insights_updated": 0, "insights_unchanged": 1}),
+ ]
+ )
+ @patch("products.product_analytics.backend.api.insight.report_user_action")
+ def test_reports_the_run_for_analytics(
+ self,
+ _name: str,
+ already_enabled: bool,
+ expected_counts: dict[str, int],
+ mock_report_user_action: mock.Mock,
+ ) -> None:
+ self._create_query_insight(filter_test_accounts=already_enabled)
+
+ self._bulk_set(True)
+
+ mock_report_user_action.assert_any_call(
+ self.user,
+ "insights bulk test account filter set",
+ {
+ "enabled": True,
+ "insights_considered": 1,
+ "insights_unsupported": 0,
+ "insights_skipped": 0,
+ "insights_legacy": 0,
+ **expected_counts,
+ },
+ team=ANY,
+ request=ANY,
+ )
diff --git a/products/product_analytics/backend/insight_test_account_filters.py b/products/product_analytics/backend/insight_test_account_filters.py
new file mode 100644
index 000000000000..df5a7964f537
--- /dev/null
+++ b/products/product_analytics/backend/insight_test_account_filters.py
@@ -0,0 +1,70 @@
+import copy
+from typing import Any
+
+from pydantic import BaseModel
+
+from posthog import schema
+from posthog.dataclasses import frozen
+from posthog.hogql_queries.apply_dashboard_filters import WRAPPER_NODE_KINDS
+
+_WRAPPER_KINDS = {kind.value for kind in WRAPPER_NODE_KINDS}
+
+
+def _kinds_supporting_test_account_filter() -> frozenset[str]:
+ """Read the query kinds that carry `filterTestAccounts` off the generated schema, so a kind that gains
+ the field is covered without anyone remembering to update a hardcoded list."""
+ kinds: set[str] = set()
+ for candidate in vars(schema).values():
+ if not (isinstance(candidate, type) and issubclass(candidate, BaseModel)):
+ continue
+ fields = candidate.model_fields
+ if "filterTestAccounts" not in fields or "kind" not in fields:
+ continue
+ kind = getattr(fields["kind"].default, "value", fields["kind"].default)
+ if isinstance(kind, str):
+ kinds.add(kind)
+ return frozenset(kinds)
+
+
+KINDS_SUPPORTING_TEST_ACCOUNT_FILTER = _kinds_supporting_test_account_filter()
+
+
+@frozen
+class TestAccountFilterUpdate:
+ """What setting the test account filter to a given value would do to one insight."""
+
+ supported: bool
+ query: dict[str, Any] | None = None
+
+ @property
+ def changed(self) -> bool:
+ return self.query is not None
+
+
+UNSUPPORTED = TestAccountFilterUpdate(supported=False)
+ALREADY_SET = TestAccountFilterUpdate(supported=True)
+
+
+def plan_test_account_filter_update(query: Any, *, enabled: bool) -> TestAccountFilterUpdate:
+ """Work out how to set the test account filter on an insight, without touching the stored query.
+
+ `supported` is False for insights with nowhere to put the toggle, such as SQL insights. When it is True
+ but nothing changed, the insight already had this value.
+ """
+ if not isinstance(query, dict):
+ return UNSUPPORTED
+
+ node = query
+ while node.get("kind") in _WRAPPER_KINDS and isinstance(node.get("source"), dict):
+ node = node["source"]
+ if node.get("kind") not in KINDS_SUPPORTING_TEST_ACCOUNT_FILTER:
+ return UNSUPPORTED
+ if bool(node.get("filterTestAccounts")) == enabled:
+ return ALREADY_SET
+
+ updated = copy.deepcopy(query)
+ target = updated
+ while target.get("kind") in _WRAPPER_KINDS and isinstance(target.get("source"), dict):
+ target = target["source"]
+ target["filterTestAccounts"] = enabled
+ return TestAccountFilterUpdate(supported=True, query=updated)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 31ad1c03b59a..e955352c8147 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8403,6 +8403,24 @@ export interface InsightBulkRestoreResponseApi {
skipped: InsightBulkOperationSkippedApi[]
}
+export interface InsightBulkSetTestAccountFilterRequestApi {
+ /** Whether every existing insight should filter out internal and test users. */
+ enabled: boolean
+}
+
+export interface InsightBulkSetTestAccountFilterResponseApi {
+ /** Number of insights whose test account filter was changed. */
+ updated: number
+ /** Number of insights that already had the requested value. */
+ unchanged: number
+ /** Number of insights with no test account filter to set, such as SQL insights. */
+ unsupported: number
+ /** Number of insights the requester cannot edit. */
+ skipped: number
+ /** Number of insights left as they are because they still store legacy `filters` rather than a query. They keep whatever value they already had. Opening and saving one converts it, after which this endpoint covers it. */
+ legacy: number
+}
+
/**
* * `add` - add
* * `remove` - remove
@@ -8941,6 +8959,18 @@ export const InsightsBulkRestoreCreateFormat = {
Json: 'json',
} as const
+export type InsightsBulkSetTestAccountFilterCreateParams = {
+ format?: InsightsBulkSetTestAccountFilterCreateFormat
+}
+
+export type InsightsBulkSetTestAccountFilterCreateFormat =
+ (typeof InsightsBulkSetTestAccountFilterCreateFormat)[keyof typeof InsightsBulkSetTestAccountFilterCreateFormat]
+
+export const InsightsBulkSetTestAccountFilterCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+} as const
+
export type InsightsBulkUpdateTagsCreateParams = {
format?: InsightsBulkUpdateTagsCreateFormat
}
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index 55ea28796d74..029c79090536 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -24,12 +24,15 @@ import type {
InsightBulkDeleteRequestApi,
InsightBulkDeleteResponseApi,
InsightBulkRestoreResponseApi,
+ InsightBulkSetTestAccountFilterRequestApi,
+ InsightBulkSetTestAccountFilterResponseApi,
InsightViewedRequestApi,
InsightsActivityRetrieveParams,
InsightsAllActivityRetrieveParams,
InsightsAnalyzeRetrieveParams,
InsightsBulkDeleteCreateParams,
InsightsBulkRestoreCreateParams,
+ InsightsBulkSetTestAccountFilterCreateParams,
InsightsBulkUpdateTagsCreateParams,
InsightsCancelCreateParams,
InsightsCreateParams,
@@ -819,6 +822,45 @@ export const insightsBulkRestoreCreate = async (
})
}
+export const getInsightsBulkSetTestAccountFilterCreateUrl = (
+ projectId: string,
+ params?: InsightsBulkSetTestAccountFilterCreateParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/insights/bulk_set_test_account_filter/?${stringifiedParams}`
+ : `/api/projects/${projectId}/insights/bulk_set_test_account_filter/`
+}
+
+/**
+ * Turn 'filter out internal and test users' on or off for every existing insight in the project. Requires project admin, matching the settings UI that fronts it. The setting of the same name only decides the default for new insights; this applies it to the insights that already exist. Only insights that store a query are changed; insights still holding legacy `filters` are counted in `legacy` and left as they are. Insights with nowhere to put the toggle, such as SQL insights, are left alone, as are insights the requester cannot edit. Dashboards follow their insights unless the dashboard sets its own override. Insights are updated in batches, so a failure part way through leaves the finished batches applied. Retrying is safe and picks up the rest.
+ */
+export const insightsBulkSetTestAccountFilterCreate = async (
+ projectId: string,
+ insightBulkSetTestAccountFilterRequestApi: InsightBulkSetTestAccountFilterRequestApi,
+ params?: InsightsBulkSetTestAccountFilterCreateParams,
+ options?: RequestInit
+): Promise<InsightBulkSetTestAccountFilterResponseApi> => {
+ return apiMutator<InsightBulkSetTestAccountFilterResponseApi>(
+ getInsightsBulkSetTestAccountFilterCreateUrl(projectId, params),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(insightBulkSetTestAccountFilterRequestApi),
+ }
+ )
+}
+
export const getInsightsBulkUpdateTagsCreateUrl = (projectId: string, params?: InsightsBulkUpdateTagsCreateParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index 0b15893e2020..9a213d9965cf 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -269,6 +269,13 @@ export const InsightsBulkRestoreCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Turn 'filter out internal and test users' on or off for every existing insight in the project. Requires project admin, matching the settings UI that fronts it. The setting of the same name only decides the default for new insights; this applies it to the insights that already exist. Only insights that store a query are changed; insights still holding legacy `filters` are counted in `legacy` and left as they are. Insights with nowhere to put the toggle, such as SQL insights, are left alone, as are insights the requester cannot edit. Dashboards follow their insights unless the dashboard sets its own override. Insights are updated in batches, so a failure part way through leaves the finished batches applied. Retrying is safe and picks up the rest.
+ */
+export const InsightsBulkSetTestAccountFilterCreateBody = /* @__PURE__ */ zod.object({
+ enabled: zod.boolean().describe('Whether every existing insight should filter out internal and test users.'),
+})
+
/**
* Bulk update tags on multiple objects.
*
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index 4bda8efc8909..a6e0b18eb3ae 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -274,6 +274,9 @@ tools:
insights-bulk-restore-create:
operation: insights_bulk_restore_create
enabled: false
+ insights-bulk-set-test-account-filter-create:
+ operation: insights_bulk_set_test_account_filter_create
+ enabled: false
insights-bulk-update-tags-create:
operation: insights_bulk_update_tags_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9599b3b1c21a..dc3a6e5094c6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43133,6 +43133,24 @@ export namespace Schemas {
skipped: InsightBulkOperationSkipped[];
}
+ export interface InsightBulkSetTestAccountFilterRequest {
+ /** Whether every existing insight should filter out internal and test users. */
+ enabled: boolean;
+ }
+
+ export interface InsightBulkSetTestAccountFilterResponse {
+ /** Number of insights whose test account filter was changed. */
+ updated: number;
+ /** Number of insights that already had the requested value. */
+ unchanged: number;
+ /** Number of insights with no test account filter to set, such as SQL insights. */
+ unsupported: number;
+ /** Number of insights the requester cannot edit. */
+ skipped: number;
+ /** Number of insights left as they are because they still store legacy `filters` rather than a query. They keep whatever value they already had. Opening and saving one converts it, after which this endpoint covers it. */
+ legacy: number;
+ }
+
/**
* * `trends` - trends
* * `funnel` - funnel
@@ -89443,6 +89461,18 @@ export namespace Schemas {
Json: 'json',
} as const;
+ export type InsightsBulkSetTestAccountFilterCreateParams = {
+ format?: InsightsBulkSetTestAccountFilterCreateFormat;
+ };
+
+ export type InsightsBulkSetTestAccountFilterCreateFormat = typeof InsightsBulkSetTestAccountFilterCreateFormat[keyof typeof InsightsBulkSetTestAccountFilterCreateFormat];
+
+
+ export const InsightsBulkSetTestAccountFilterCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+ } as const;
+
export type InsightsBulkUpdateTagsCreateParams = {
format?: InsightsBulkUpdateTagsCreateFormat;
};