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(flags): replace auto-created usage dashboards with inline charts (#79288)

Phil Haackb7992440e7a7
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a55b0cbf0577..0e15fe0d47bc 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -330,7 +330,6 @@ export const FEATURE_FLAGS = {
FEATURE_FLAG_DRAG_DROP_CONDITIONS: 'feature-flag-drag-drop-conditions', // owner: @gustavo #team-feature-flags
FEATURE_FLAG_EARLY_EXIT: 'feature-flag-early-exit', // owner: @gustavo #team-feature-flags
FEATURE_FLAG_NOTIFICATIONS: 'feature-flag-notifications', // owner: @reecejones #team-platform-features
- FEATURE_FLAG_USAGE_DASHBOARD_CHECKBOX: 'feature-flag-usage-dashboard-checkbox', // owner: #team-feature-flags, globally disabled, enables opt-out of auto dashboard creation
FIELD_NOTES: 'field-notes', // owner: @adamleith
FLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flags
FLAGGED_FEATURE_INDICATOR: 'flagged-feature-indicator', // owner: @benjackwhite
diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
index 88c54c67075c..33399a3f4c5b 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
@@ -35,7 +35,6 @@ import { PendingChangeRequestBanner } from 'scenes/approvals/PendingChangeReques
import { ChunkLoadErrorBoundary } from 'scenes/ChunkLoadErrorBoundary'
import { Dashboard } from 'scenes/dashboard/Dashboard'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { EmptyDashboardComponent } from 'scenes/dashboard/EmptyDashboardComponent'
import { FeatureFlagPermissions } from 'scenes/FeatureFlagPermissions'
import { NotebookNodeType } from 'scenes/notebooks/types'
import { SceneExport } from 'scenes/sceneTypes'
@@ -91,6 +90,7 @@ import FeatureFlagProjects from './FeatureFlagProjects'
import FeatureFlagSchedule from './FeatureFlagSchedule'
import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'
import { FeatureFlagTestingTab } from './FeatureFlagTestingTab'
+import { FeatureFlagUsageMetrics } from './FeatureFlagUsageMetrics'
const RESOURCE_TYPE = 'feature_flag'
@@ -639,11 +639,12 @@ function ConnectedUsageDashboard({
dashboardId: number
hasEnrichedAnalytics: boolean | undefined
}): JSX.Element | null {
- const { dashboard } = useValues(dashboardLogic({ id: dashboardId, placement: DashboardPlacement.FeatureFlag })) as {
+ const { dashboard, error404 } = useValues(
+ dashboardLogic({ id: dashboardId, placement: DashboardPlacement.FeatureFlag })
+ ) as {
dashboard: DashboardType<QueryBasedInsightModel> | null
+ error404: boolean
}
- const { enrichAnalyticsNoticeAcknowledged } = useValues(featureFlagsLogic)
- const { closeEnrichAnalyticsNotice } = useActions(featureFlagsLogic)
const { enrichUsageDashboard } = useActions(featureFlagLogic)
useEffect(() => {
@@ -656,26 +657,23 @@ function ConnectedUsageDashboard({
}
}, [dashboard, hasEnrichedAnalytics, enrichUsageDashboard])
+ // The dashboard FK survives a soft delete (SET_NULL only fires on a hard delete), so a
+ // deleted dashboard still looks linked here. Fall back to the same inline charts a
+ // dashboardless flag gets instead of an unrecoverable skeleton.
+ if (error404) {
+ return <FeatureFlagUsageMetrics id={featureFlag.id!} />
+ }
+
if (!dashboard) {
return <LemonSkeleton className="h-60" />
}
return (
- <>
- {!hasEnrichedAnalytics && !enrichAnalyticsNoticeAcknowledged && (
- <LemonBanner type="info" className="mb-3" onClose={() => closeEnrichAnalyticsNotice()}>
- Get richer insights automatically by{' '}
- <Link to="https://posthog.com/docs/libraries/js/features#enriched-flag-analytics" target="_blank">
- enabling enriched analytics for flags{' '}
- </Link>
- </LemonBanner>
- )}
- <Dashboard
- id={dashboardId.toString()}
- placement={DashboardPlacement.FeatureFlag}
- backTo={{ url: urls.featureFlag(featureFlag.id!), name: featureFlag.key }}
- />
- </>
+ <Dashboard
+ id={dashboardId.toString()}
+ placement={DashboardPlacement.FeatureFlag}
+ backTo={{ url: urls.featureFlag(featureFlag.id!), name: featureFlag.key }}
+ />
)
}
@@ -685,8 +683,8 @@ function UsageTab({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Elemen
usage_dashboard: dashboardId,
has_enriched_analytics: hasEnrichedAnalytics,
} = featureFlag
- const { generateUsageDashboard } = useActions(featureFlagLogic)
- const { featureFlagLoading } = useValues(featureFlagLogic)
+ const { enrichAnalyticsNoticeAcknowledged } = useValues(featureFlagsLogic)
+ const { closeEnrichAnalyticsNotice } = useActions(featureFlagsLogic)
const propertyFilter: AnyPropertyFilter[] = [
{
@@ -707,28 +705,23 @@ function UsageTab({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Elemen
return (
<div data-attr="feature-flag-usage-container">
+ {!hasEnrichedAnalytics && !enrichAnalyticsNoticeAcknowledged && (
+ <LemonBanner type="info" className="mb-3" onClose={() => closeEnrichAnalyticsNotice()}>
+ Get richer insights automatically by{' '}
+ <Link to="https://posthog.com/docs/libraries/js/features#enriched-flag-analytics" target="_blank">
+ enabling enriched analytics for flags
+ </Link>
+ </LemonBanner>
+ )}
{dashboardId ? (
<ConnectedUsageDashboard
featureFlag={featureFlag}
dashboardId={dashboardId}
hasEnrichedAnalytics={hasEnrichedAnalytics}
/>
- ) : (
- <div>
- <b>Dashboard</b>
- <div className="text-secondary mb-2">
- There is currently no connected dashboard to this feature flag. If there was previously a
- connected dashboard, it may have been deleted.
- </div>
- {featureFlagLoading ? (
- <EmptyDashboardComponent loading={true} canEdit={false} />
- ) : (
- <LemonButton type="primary" onClick={() => generateUsageDashboard()}>
- Generate Usage Dashboard
- </LemonButton>
- )}
- </div>
- )}
+ ) : featureFlag.id ? (
+ <FeatureFlagUsageMetrics id={featureFlag.id} />
+ ) : null}
<div className="mt-4 mb-4">
<b>Log</b>
<div className="text-secondary">{`Feature flag calls for "${featureFlagKey}" will appear here`}</div>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx b/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
new file mode 100644
index 000000000000..8273994bc2ae
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
@@ -0,0 +1,35 @@
+import { useActions, useValues } from 'kea'
+
+import { QueryCard } from 'lib/components/Cards/InsightCard/QueryCard'
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+
+import { featureFlagUsageLogic } from './featureFlagUsageLogic'
+
+export function FeatureFlagUsageMetrics({ id }: { id: number }): JSX.Element {
+ const logic = featureFlagUsageLogic({ id })
+ const { dateRange, usageCharts } = useValues(logic)
+ const { setDates } = useActions(logic)
+
+ return (
+ <div className="flex flex-col gap-4" data-attr="feature-flag-usage-inline">
+ <div>
+ <DateFilter
+ dateFrom={dateRange.date_from ?? null}
+ dateTo={dateRange.date_to ?? null}
+ onChange={(fromDate, toDate) => setDates(fromDate, toDate)}
+ />
+ </div>
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ {usageCharts.map((chart) => (
+ <QueryCard
+ key={chart.key}
+ uniqueKey={`feature-flag-usage-${id}-${chart.key}`}
+ title={chart.title}
+ description={chart.description}
+ query={chart.query}
+ />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
index 274a7693e3d7..69aa2bc829a7 100644
--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx
+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
@@ -397,7 +397,6 @@ const featureFlagActionsMapping: Record<
last_called_at: () => null,
is_used_in_replay_settings: () => null,
_create_in_folder: () => null,
- _should_create_usage_dashboard: () => null,
}
const getActorName = (logItem: ActivityLogItem): JSX.Element => {
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index 00e39c08be9b..b4b8e2e99e80 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -384,7 +384,6 @@ export const NEW_FLAG: FeatureFlagType = {
last_modified_by: null,
evaluation_runtime: FeatureFlagEvaluationRuntime.ALL,
bucketing_identifier: null,
- _should_create_usage_dashboard: true,
}
const NEW_VARIANT = {
key: '',
@@ -745,7 +744,6 @@ export interface featureFlagLogicValues {
featureFlagErrors: DeepPartialMap<
{
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -779,7 +777,7 @@ export interface featureFlagLogicValues {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
},
@@ -797,7 +795,6 @@ export interface featureFlagLogicValues {
featureFlagValidationErrors: DeepPartialMap<
{
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -831,7 +828,7 @@ export interface featureFlagLogicValues {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
},
@@ -1071,9 +1068,6 @@ export interface featureFlagLogicActions {
enrichUsageDashboard: () => {
value: true
}
- generateUsageDashboard: () => {
- value: true
- }
loadCopyDependencyRequirements: () => {
value: true
}
@@ -1244,7 +1238,6 @@ export interface featureFlagLogicActions {
resetEncryptedPayload: () => {}
resetFeatureFlag: (values?: {
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1278,13 +1271,12 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}) => {
values?: {
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1318,7 +1310,7 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}
@@ -1422,7 +1414,6 @@ export interface featureFlagLogicActions {
setFeatureFlagValues: (
values: DeepPartial<{
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1456,14 +1447,13 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}>
) => {
values: DeepPartial<{
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1497,7 +1487,7 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}>
@@ -1592,7 +1582,6 @@ export interface featureFlagLogicActions {
}
submitFeatureFlagRequest: (featureFlag: {
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1626,13 +1615,12 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}) => {
featureFlag: {
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1666,14 +1654,13 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}
}
submitFeatureFlagSuccess: (featureFlag: {
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1707,13 +1694,12 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}) => {
featureFlag: {
_create_in_folder?: string | null | undefined
- _should_create_usage_dashboard?: boolean | undefined
active: boolean
archived: boolean
bucketing_identifier?: FeatureFlagBucketingIdentifier | null | undefined
@@ -1747,7 +1733,7 @@ export interface featureFlagLogicActions {
surveys: Survey[] | null
tags: string[]
updated_at: string | null
- usage_dashboard?: number | undefined
+ usage_dashboard?: number | null | undefined
user_access_level: AccessControlLevel
version: number | null
}
@@ -2011,7 +1997,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
expandAdvanced: options?.expandAdvanced ?? false,
}),
distributeVariantsEqually: true,
- generateUsageDashboard: true,
enrichUsageDashboard: true,
setCopyDestinationProject: (id: number | null) => ({ id }),
setCopySchedule: (copySchedule: boolean) => ({ copySchedule }),
@@ -2783,7 +2768,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
let baseFlagConfig: typeof NEW_FLAG = {
...NEW_FLAG,
ensure_experience_continuity: values.currentTeam?.flags_persistence_default ?? false,
- _should_create_usage_dashboard: true,
}
if (flagType !== 'remote_config') {
@@ -2856,7 +2840,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
return {
...NEW_FLAG,
ensure_experience_continuity: values.currentTeam?.flags_persistence_default ?? false,
- _should_create_usage_dashboard: true,
}
},
saveFeatureFlag: async (updatedFlag: Partial<FeatureFlagType>) => {
@@ -3444,12 +3427,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
eventUsageLogic.actions.reportFeatureFlagScheduleSuccess()
},
showDependentFlagsConfirmation: sharedListeners.showDependentFlagsConfirmation,
- generateUsageDashboard: async () => {
- if (props.id) {
- await api.create(`api/projects/${values.currentProjectId}/feature_flags/${props.id}/dashboard`)
- actions.loadFeatureFlag()
- }
- },
enrichUsageDashboard: async (_, breakpoint) => {
if (props.id) {
await breakpoint(1000) // in ms
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts
new file mode 100644
index 000000000000..8161e66ea830
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts
@@ -0,0 +1,112 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { urls } from 'scenes/urls'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { FeatureFlagType } from '~/types'
+
+import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'
+import { featureFlagUsageLogic } from './featureFlagUsageLogic'
+import { DEFAULT_USAGE_DATE_RANGE } from './featureFlagUsageQueries'
+
+const FLAG_ID = 1
+
+function flag(overrides: Partial<FeatureFlagType> = {}): FeatureFlagType {
+ return {
+ ...NEW_FLAG,
+ id: FLAG_ID,
+ key: 'alpha-feature',
+ has_enriched_analytics: false,
+ ...overrides,
+ }
+}
+
+describe('featureFlagUsageLogic', () => {
+ let logic: ReturnType<typeof featureFlagUsageLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ [`/api/projects/:team/feature_flags/${FLAG_ID}/`]: () => [200, flag()],
+ },
+ })
+ initKeaTests()
+ featureFlagLogic({ id: FLAG_ID }).mount()
+ logic = featureFlagUsageLogic({ id: FLAG_ID })
+ logic.mount()
+ })
+
+ it.each([
+ [false, ['total-volume', 'unique-callers']],
+ [true, ['total-volume', 'unique-callers', 'feature-view', 'feature-interaction']],
+ ])('renders the enriched charts only when has_enriched_analytics is %s', (hasEnriched, expectedKeys) => {
+ featureFlagLogic({ id: FLAG_ID }).actions.loadFeatureFlagSuccess(flag({ has_enriched_analytics: hasEnriched }))
+
+ expect(logic.values.usageCharts.map((chart) => chart.key)).toEqual(expectedKeys)
+ })
+
+ it('rebuilds every chart against the selected date range', async () => {
+ featureFlagLogic({ id: FLAG_ID }).actions.loadFeatureFlagSuccess(flag({ has_enriched_analytics: true }))
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-24h', null)
+ }).toMatchValues({ dateRange: { date_from: '-24h', date_to: null } })
+
+ expect(logic.values.usageCharts).toHaveLength(4)
+ for (const chart of logic.values.usageCharts) {
+ expect(chart.query.source.dateRange).toEqual({ date_from: '-24h', date_to: null })
+ expect(chart.query.source.interval).toEqual('hour')
+ }
+ })
+
+ it('carries the flag key into every chart query', () => {
+ featureFlagLogic({ id: FLAG_ID }).actions.loadFeatureFlagSuccess(flag({ key: 'renamed-feature' }))
+
+ for (const chart of logic.values.usageCharts) {
+ expect(chart.query.source.properties).toEqual([expect.objectContaining({ value: 'renamed-feature' })])
+ }
+ })
+
+ it('writes the selected range to the URL without pushing a history entry', async () => {
+ router.actions.push(urls.featureFlag(FLAG_ID))
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({ date_from: '-7d' })
+ expect(router.values.searchParams.date_to).toBeUndefined()
+ // A push here would make featureFlagLogic reload the flag on every date change.
+ expect(router.values.lastMethod).toEqual('REPLACE')
+ })
+
+ it('restores the range from the URL', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push(urls.featureFlag(FLAG_ID), { date_from: '-24h' })
+ }).toMatchValues({ dateRange: { date_from: '-24h', date_to: null } })
+ })
+
+ it('treats a URL with only date_to as an explicit range, not the default', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push(urls.featureFlag(FLAG_ID), { date_to: '2024-01-01' })
+ }).toMatchValues({ dateRange: { date_from: null, date_to: '2024-01-01' } })
+ })
+
+ it('keeps the default range when the URL carries no date params', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push(urls.featureFlag(FLAG_ID), { edit: 'true' })
+ }).toMatchValues({ dateRange: DEFAULT_USAGE_DATE_RANGE })
+ })
+
+ it('resets a custom range back to default when navigating to a bare URL', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toMatchValues({ dateRange: { date_from: '-7d', date_to: null } })
+
+ await expectLogic(logic, () => {
+ router.actions.push(urls.featureFlag(FLAG_ID))
+ }).toMatchValues({ dateRange: DEFAULT_USAGE_DATE_RANGE })
+ })
+})
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
new file mode 100644
index 000000000000..5ff66f3bdf34
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
@@ -0,0 +1,158 @@
+import { LogicWrapper, MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { actionToUrl, router, urlToAction } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { Noun, groupsModel } from '~/models/groupsModel'
+import { DateRange } from '~/queries/schema/schema-general'
+import { FeatureFlagType } from '~/types'
+
+import { featureFlagLogic } from './featureFlagLogic'
+import {
+ DEFAULT_USAGE_DATE_RANGE,
+ FlagUsageChart,
+ FlagUsageQueryOptions,
+ buildEnrichedUsageCharts,
+ buildFlagCalledTotalVolumeChart,
+ buildFlagCalledUniqueCallersChart,
+} from './featureFlagUsageQueries'
+
+// The Usage tab only renders for persisted flags, so unlike featureFlagLogic this
+// logic never mounts for 'new'/'link' ids.
+export interface FeatureFlagUsageLogicProps {
+ id: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagUsageLogicValues {
+ featureFlag: FeatureFlagType // featureFlagLogic
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
+ aggregationGroupTypeIndex: number | null | undefined
+ dateRange: DateRange
+ flagKey: string
+ hasEnrichedAnalytics: boolean | undefined
+ usageCharts: FlagUsageChart[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagUsageLogicActions {
+ setDates: (
+ dateFrom: string | null,
+ dateTo: string | null
+ ) => {
+ dateFrom: string | null
+ dateTo: string | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagUsageLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ flagKey: (featureFlag: FeatureFlagType) => string
+ aggregationGroupTypeIndex: (featureFlag: FeatureFlagType) => number | null | undefined
+ hasEnrichedAnalytics: (featureFlag: FeatureFlagType) => boolean | undefined
+ usageCharts: (
+ flagKey: string,
+ aggregationGroupTypeIndex: number | null | undefined,
+ hasEnrichedAnalytics: boolean | undefined,
+ dateRange: DateRange,
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
+ ) => FlagUsageChart[]
+ }
+}
+
+export type featureFlagUsageLogicType = MakeLogicType<
+ featureFlagUsageLogicValues,
+ featureFlagUsageLogicActions,
+ FeatureFlagUsageLogicProps,
+ featureFlagUsageLogicMeta
+>
+
+export const featureFlagUsageLogic: LogicWrapper<featureFlagUsageLogicType> = kea<featureFlagUsageLogicType>([
+ props({} as FeatureFlagUsageLogicProps),
+ key(({ id }) => id),
+ path((key) => ['scenes', 'feature-flags', 'featureFlagUsageLogic', key]),
+ connect((props: FeatureFlagUsageLogicProps) => ({
+ values: [featureFlagLogic(props), ['featureFlag'], groupsModel, ['aggregationLabel']],
+ })),
+ actions({
+ setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ }),
+ reducers({
+ dateRange: [
+ DEFAULT_USAGE_DATE_RANGE,
+ {
+ setDates: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),
+ },
+ ],
+ }),
+ selectors({
+ // Split out of `featureFlag` so a reload that only touches an unrelated field (name,
+ // description, ...) doesn't change these inputs and cascade into rebuilding every chart.
+ flagKey: [(s) => [s.featureFlag], (featureFlag: FeatureFlagType): string => featureFlag.key],
+ aggregationGroupTypeIndex: [
+ (s) => [s.featureFlag],
+ (featureFlag: FeatureFlagType): number | null | undefined =>
+ featureFlag.filters?.aggregation_group_type_index,
+ ],
+ hasEnrichedAnalytics: [
+ (s) => [s.featureFlag],
+ (featureFlag: FeatureFlagType): boolean | undefined => featureFlag.has_enriched_analytics,
+ ],
+ usageCharts: [
+ (s) => [s.flagKey, s.aggregationGroupTypeIndex, s.hasEnrichedAnalytics, s.dateRange, s.aggregationLabel],
+ (
+ flagKey: string,
+ aggregationGroupTypeIndex: number | null | undefined,
+ hasEnrichedAnalytics: boolean | undefined,
+ dateRange: DateRange,
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
+ ): FlagUsageChart[] => {
+ const options: FlagUsageQueryOptions = {
+ flagKey,
+ aggregationGroupTypeIndex,
+ callerNoun: aggregationLabel(aggregationGroupTypeIndex, true),
+ dateRange,
+ }
+ const charts = [buildFlagCalledTotalVolumeChart(options), buildFlagCalledUniqueCallersChart(options)]
+ if (hasEnrichedAnalytics) {
+ charts.push(...buildEnrichedUsageCharts(options))
+ }
+ return charts
+ },
+ ],
+ }),
+ actionToUrl(({ values }) => ({
+ setDates: () => {
+ const searchParams = { ...router.values.searchParams }
+ for (const [param, value] of [
+ ['date_from', values.dateRange.date_from],
+ ['date_to', values.dateRange.date_to],
+ ] as const) {
+ if (value) {
+ searchParams[param] = value
+ } else {
+ delete searchParams[param]
+ }
+ }
+ // Replace rather than push: featureFlagLogic reloads the flag on a PUSH to this pathname.
+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
+ },
+ })),
+ urlToAction(({ actions, props, values }) => ({
+ [urls.featureFlag(props.id)]: (_, searchParams) => {
+ // Absent params mean "use the default range", not "clear the range". A range is only
+ // read off the URL when at least one of the two params is present; otherwise both
+ // fall back to the default, matching the DateRange convention of a null date_to.
+ const useDefaultRange = !searchParams.date_from && !searchParams.date_to
+ const dateFrom = useDefaultRange
+ ? (DEFAULT_USAGE_DATE_RANGE.date_from ?? null)
+ : (searchParams.date_from ?? null)
+ const dateTo = useDefaultRange ? (DEFAULT_USAGE_DATE_RANGE.date_to ?? null) : (searchParams.date_to ?? null)
+ if (dateFrom !== values.dateRange.date_from || dateTo !== values.dateRange.date_to) {
+ actions.setDates(dateFrom, dateTo)
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
new file mode 100644
index 000000000000..034b0ad9a0d0
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
@@ -0,0 +1,148 @@
+import { Noun } from '~/models/groupsModel'
+import { DateRange } from '~/queries/schema/schema-general'
+
+import {
+ buildEnrichedUsageCharts,
+ buildFlagCalledTotalVolumeChart,
+ buildFlagCalledUniqueCallersChart,
+ FlagUsageChart,
+ FlagUsageQueryOptions,
+} from './featureFlagUsageQueries'
+
+const dateRange: DateRange = { date_from: '-30d', date_to: null }
+const userNoun: Noun = { singular: 'user', plural: 'users' }
+
+const personFlagOptions: FlagUsageQueryOptions = {
+ flagKey: 'alpha-feature',
+ aggregationGroupTypeIndex: null,
+ callerNoun: userNoun,
+ dateRange,
+}
+
+const groupFlagOptions: FlagUsageQueryOptions = {
+ flagKey: 'group-feature',
+ aggregationGroupTypeIndex: 0,
+ callerNoun: { singular: 'organization', plural: 'organizations' },
+ dateRange,
+}
+
+describe('featureFlagUsageQueries', () => {
+ it.each([
+ ['buildFlagCalledTotalVolumeChart', (): FlagUsageChart => buildFlagCalledTotalVolumeChart(personFlagOptions)],
+ [
+ 'buildFlagCalledUniqueCallersChart',
+ (): FlagUsageChart => buildFlagCalledUniqueCallersChart(personFlagOptions),
+ ],
+ ['buildEnrichedUsageCharts', (): FlagUsageChart => buildEnrichedUsageCharts(personFlagOptions)[0]],
+ ])('%s builds an unsaved TrendsQuery with the shared envelope', (_name, build) => {
+ const { query } = build()
+
+ expect(query.kind).toEqual('InsightVizNode')
+ expect(query.source.kind).toEqual('TrendsQuery')
+ expect(query.source.version).not.toBeUndefined()
+ expect(query.source.filterTestAccounts).toBe(false)
+ expect(query.source.dateRange).toEqual(dateRange)
+ })
+
+ it.each([
+ ['-30d', 'day'],
+ ['-24h', 'hour'],
+ ['-180d', 'month'],
+ ])('derives the interval for %s from the date range', (date_from, expected) => {
+ const { query } = buildFlagCalledTotalVolumeChart({
+ ...personFlagOptions,
+ dateRange: { date_from, date_to: null },
+ })
+
+ expect(query.source.interval).toEqual(expected)
+ })
+
+ it('buildFlagCalledTotalVolumeChart targets $feature_flag_called with no math and the feature-flag-response breakdown', () => {
+ const { query } = buildFlagCalledTotalVolumeChart(personFlagOptions)
+
+ expect(query.source.series).toMatchObject([
+ { kind: 'EventsNode', event: '$feature_flag_called', name: '$feature_flag_called' },
+ ])
+ expect(query.source.series[0]).not.toHaveProperty('math')
+ expect(query.source.breakdownFilter).toEqual({
+ breakdown: '$feature_flag_response',
+ breakdown_type: 'event',
+ })
+ expect(query.source.trendsFilter).toMatchObject({
+ display: 'ActionsLineGraph',
+ aggregationAxisFormat: 'numeric',
+ })
+ })
+
+ it.each([
+ [
+ 'buildFlagCalledTotalVolumeChart',
+ (options: FlagUsageQueryOptions): FlagUsageChart => buildFlagCalledTotalVolumeChart(options),
+ ],
+ [
+ 'buildFlagCalledUniqueCallersChart',
+ (options: FlagUsageQueryOptions): FlagUsageChart => buildFlagCalledUniqueCallersChart(options),
+ ],
+ ])('%s filters on $feature_flag, adding a $group_N is_set filter only for group flags', (_name, build) => {
+ expect(build(personFlagOptions).query.source.properties).toEqual([
+ { key: '$feature_flag', type: 'event', operator: 'exact', value: 'alpha-feature' },
+ ])
+ expect(build(groupFlagOptions).query.source.properties).toEqual([
+ { key: '$feature_flag', type: 'event', operator: 'exact', value: 'group-feature' },
+ { key: '$group_0', type: 'event', operator: 'is_set', value: 'is_set' },
+ ])
+ })
+
+ it('buildFlagCalledUniqueCallersChart uses dau math and an ActionsTable display for a person flag', () => {
+ const { title, query } = buildFlagCalledUniqueCallersChart(personFlagOptions)
+
+ expect(title).toEqual('Feature flag calls made by unique users per variant')
+ expect(query.source.series).toMatchObject([
+ { kind: 'EventsNode', event: '$feature_flag_called', name: '$feature_flag_called', math: 'dau' },
+ ])
+ expect(query.source.trendsFilter).toMatchObject({ display: 'ActionsTable' })
+ })
+
+ it('buildFlagCalledUniqueCallersChart uses unique_group math and the group noun for a group flag', () => {
+ const { title, query } = buildFlagCalledUniqueCallersChart(groupFlagOptions)
+
+ expect(title).toEqual('Feature flag calls made by unique organizations per variant')
+ expect(query.source.series).toMatchObject([
+ {
+ kind: 'EventsNode',
+ event: '$feature_flag_called',
+ name: '$feature_flag_called',
+ math: 'unique_group',
+ math_group_type_index: 0,
+ },
+ ])
+ })
+
+ it('buildEnrichedUsageCharts builds total and unique-user series for feature view and interaction events', () => {
+ const [featureView, featureInteraction] = buildEnrichedUsageCharts(personFlagOptions)
+
+ expect(featureView.query.source.series).toMatchObject([
+ { kind: 'EventsNode', event: '$feature_view', name: 'Feature view - Total' },
+ { kind: 'EventsNode', event: '$feature_view', name: 'Feature view - Unique users', math: 'dau' },
+ ])
+ expect(featureInteraction.query.source.series).toMatchObject([
+ { kind: 'EventsNode', event: '$feature_interaction', name: 'Feature interaction - Total' },
+ {
+ kind: 'EventsNode',
+ event: '$feature_interaction',
+ name: 'Feature interaction - Unique users',
+ math: 'dau',
+ },
+ ])
+ })
+
+ it('buildEnrichedUsageCharts filters on the bare feature_flag property key with no breakdown', () => {
+ // A wrong property key here silently produces an empty chart, so pin the exact key.
+ for (const chart of buildEnrichedUsageCharts(personFlagOptions)) {
+ expect(chart.query.source.properties).toEqual([
+ { key: 'feature_flag', type: 'event', operator: 'exact', value: 'alpha-feature' },
+ ])
+ expect(chart.query.source.breakdownFilter).toBeUndefined()
+ }
+ })
+})
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
new file mode 100644
index 000000000000..dca7b0f97d69
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
@@ -0,0 +1,185 @@
+// The Usage tab renders these charts inline for flags without a usage dashboard. Event names,
+// property keys, breakdown, and math must stay identical to the saved-dashboard insight definitions
+// in posthog/helpers/dashboard_templates.py (create_feature_flag_dashboard and
+// add_enriched_insights_to_feature_flag_dashboard), so both surfaces report the same numbers.
+// Titles differ on purpose: update_feature_flag_dashboard looks tiles up by name, so the Python
+// names are pinned, while these use sentence case. The interval here follows the user's date range
+// rather than the template's fixed "day".
+import { getDefaultInterval } from 'lib/utils/dateFilters'
+
+import { Noun } from '~/models/groupsModel'
+import {
+ DateRange,
+ EventsNode,
+ InsightVizNode,
+ NodeKind,
+ ProductKey,
+ TrendsQuery,
+} from '~/queries/schema/schema-general'
+import { setLatestVersionsOnQuery } from '~/queries/utils'
+import {
+ AnyPropertyFilter,
+ BaseMathType,
+ ChartDisplayType,
+ GroupMathType,
+ GroupTypeIndex,
+ PropertyFilterType,
+ PropertyOperator,
+} from '~/types'
+
+export interface FlagUsageQueryOptions {
+ flagKey: string
+ aggregationGroupTypeIndex: number | null | undefined
+ /** Noun matching aggregationGroupTypeIndex, e.g. from groupsModel's aggregationLabel(index, true). */
+ callerNoun: Noun
+ dateRange: DateRange
+}
+
+export const DEFAULT_USAGE_DATE_RANGE: DateRange = { date_from: '-30d', date_to: null }
+
+export interface FlagUsageChart {
+ key: string
+ title: string
+ description: string
+ query: InsightVizNode<TrendsQuery>
+}
+
+function flagCalledProperties({ flagKey, aggregationGroupTypeIndex }: FlagUsageQueryOptions): AnyPropertyFilter[] {
+ const properties: AnyPropertyFilter[] = [
+ {
+ key: '$feature_flag',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: flagKey,
+ },
+ ]
+ if (aggregationGroupTypeIndex != null) {
+ properties.push({
+ key: `$group_${aggregationGroupTypeIndex}`,
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.IsSet,
+ value: 'is_set',
+ })
+ }
+ return properties
+}
+
+function buildUsageQuery(
+ dateRange: DateRange,
+ source: Pick<TrendsQuery, 'series' | 'properties' | 'breakdownFilter'>,
+ display: ChartDisplayType
+): InsightVizNode<TrendsQuery> {
+ return setLatestVersionsOnQuery({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ ...source,
+ dateRange,
+ interval: getDefaultInterval(dateRange.date_from ?? null, dateRange.date_to ?? null),
+ filterTestAccounts: false,
+ trendsFilter: { display, aggregationAxisFormat: 'numeric' },
+ tags: { productKey: ProductKey.FEATURE_FLAGS },
+ },
+ })
+}
+
+export function buildFlagCalledTotalVolumeChart(options: FlagUsageQueryOptions): FlagUsageChart {
+ return {
+ key: 'total-volume',
+ title: 'Feature flag called total volume',
+ description: `Shows the number of total calls made on feature flag with key: ${options.flagKey}`,
+ query: buildUsageQuery(
+ options.dateRange,
+ {
+ series: [{ kind: NodeKind.EventsNode, event: '$feature_flag_called', name: '$feature_flag_called' }],
+ breakdownFilter: { breakdown: '$feature_flag_response', breakdown_type: 'event' },
+ properties: flagCalledProperties(options),
+ },
+ ChartDisplayType.ActionsLineGraph
+ ),
+ }
+}
+
+export function buildFlagCalledUniqueCallersChart(options: FlagUsageQueryOptions): FlagUsageChart {
+ const mathProperties: Pick<EventsNode, 'math' | 'math_group_type_index'> =
+ options.aggregationGroupTypeIndex != null
+ ? {
+ math: GroupMathType.UniqueGroup,
+ math_group_type_index: options.aggregationGroupTypeIndex as GroupTypeIndex,
+ }
+ : { math: BaseMathType.UniqueUsers }
+ return {
+ key: 'unique-callers',
+ title: `Feature flag calls made by unique ${options.callerNoun.plural} per variant`,
+ description: `Shows the number of unique ${options.callerNoun.singular} calls made on feature flag per variant with key: ${options.flagKey}`,
+ query: buildUsageQuery(
+ options.dateRange,
+ {
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: '$feature_flag_called',
+ name: '$feature_flag_called',
+ ...mathProperties,
+ },
+ ],
+ breakdownFilter: { breakdown: '$feature_flag_response', breakdown_type: 'event' },
+ properties: flagCalledProperties(options),
+ },
+ ChartDisplayType.ActionsTable
+ ),
+ }
+}
+
+export function buildEnrichedUsageCharts(
+ options: Pick<FlagUsageQueryOptions, 'flagKey' | 'dateRange'>
+): FlagUsageChart[] {
+ return [
+ {
+ key: 'feature-view',
+ title: 'Feature viewed total volume',
+ description: 'Shows the total number of times this feature was viewed',
+ query: buildUsageQuery(
+ options.dateRange,
+ {
+ series: enrichedSeries('$feature_view', 'Feature view'),
+ properties: enrichedProperties(options.flagKey),
+ },
+ ChartDisplayType.ActionsLineGraph
+ ),
+ },
+ {
+ key: 'feature-interaction',
+ title: 'Feature interaction total volume',
+ description: 'Shows the total number of times this feature was interacted with',
+ query: buildUsageQuery(
+ options.dateRange,
+ {
+ series: enrichedSeries('$feature_interaction', 'Feature interaction'),
+ properties: enrichedProperties(options.flagKey),
+ },
+ ChartDisplayType.ActionsLineGraph
+ ),
+ },
+ ]
+}
+
+function enrichedSeries(event: '$feature_view' | '$feature_interaction', seriesLabel: string): EventsNode[] {
+ return [
+ { kind: NodeKind.EventsNode, event, name: `${seriesLabel} - Total` },
+ { kind: NodeKind.EventsNode, event, name: `${seriesLabel} - Unique users`, math: BaseMathType.UniqueUsers },
+ ]
+}
+
+// Enriched analytics events carry the flag key in the bare `feature_flag` property,
+// unlike $feature_flag_called which uses `$feature_flag`.
+function enrichedProperties(flagKey: string): AnyPropertyFilter[] {
+ return [
+ {
+ key: 'feature_flag',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: flagKey,
+ },
+ ]
+}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 60fe086bba5c..aafd05725ee4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4365,7 +4365,7 @@ export interface FeatureFlagType extends Omit<FeatureFlagBasicType, 'id' | 'team
can_edit: boolean
tags: string[]
evaluation_contexts: string[]
- usage_dashboard?: number
+ usage_dashboard?: number | null
has_enriched_analytics?: boolean
is_remote_configuration: boolean
has_encrypted_payloads: boolean
@@ -4373,7 +4373,6 @@ export interface FeatureFlagType extends Omit<FeatureFlagBasicType, 'id' | 'team
_create_in_folder?: string | null
evaluation_runtime: FeatureFlagEvaluationRuntime
bucketing_identifier?: FeatureFlagBucketingIdentifier | null
- _should_create_usage_dashboard?: boolean
last_called_at?: string | null
is_used_in_replay_settings?: boolean
}
diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.py
index 007ac26c6f9a..3a9ab6914de6 100644
--- a/posthog/api/test/test_activity_log.py
+++ b/posthog/api/test/test_activity_log.py
@@ -193,7 +193,7 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):
res = self.client.get(f"/api/projects/{self.team.id}/activity_log")
assert res.status_code == status.HTTP_200_OK
- assert len(res.json()["results"]) == 46
+ assert len(res.json()["results"]) == 39
def test_can_list_all_activity_filtered_by_scope(self) -> None:
res = self.client.get(f"/api/projects/{self.team.id}/activity_log?scope=FeatureFlag")
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.py
index 2ab651a4f079..1ed9bfe41b48 100644
--- a/posthog/helpers/dashboard_templates.py
+++ b/posthog/helpers/dashboard_templates.py
@@ -779,6 +779,8 @@ def _get_feature_flag_unique_calls_insight_name(feature_flag) -> str:
return f"Feature Flag calls made by unique {plural} per variant"
+# The feature flag Usage tab renders these same charts inline for flags without a usage dashboard —
+# keep frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts in sync with this template.
def create_feature_flag_dashboard(feature_flag, dashboard: Dashboard, user) -> None:
dashboard.filters = {"date_from": "-30d"}
tag, _ = Tag.objects.get_or_create(
@@ -1191,6 +1193,8 @@ def _update_tile_with_new_key(
insight.save()
+# The feature flag Usage tab renders these same charts inline for flags without a usage dashboard —
+# keep frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts in sync with this template.
def add_enriched_insights_to_feature_flag_dashboard(feature_flag, dashboard: Dashboard) -> None:
# 1 row
_create_tile_for_insight(
diff --git a/posthog/tasks/update_survey_iteration.py b/posthog/tasks/update_survey_iteration.py
index 663e499b65bb..5922e6100088 100644
--- a/posthog/tasks/update_survey_iteration.py
+++ b/posthog/tasks/update_survey_iteration.py
@@ -114,7 +114,6 @@ def _get_targeting_flag(survey: Survey) -> FeatureFlag:
"active": True,
"filters": {"groups": user_submitted_dismissed_groups},
"creation_context": "surveys",
- "_should_create_usage_dashboard": False,
},
team=survey.team,
user=None,
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index a46eea7b70df..5930c1b1fa58 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -938,7 +938,15 @@ class FeatureFlagSerializer(
experiment_set_metadata = serializers.SerializerMethodField()
surveys: serializers.SerializerMethodField = serializers.SerializerMethodField()
features: serializers.SerializerMethodField = serializers.SerializerMethodField()
- usage_dashboard: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField(read_only=True) # ty: ignore[invalid-assignment]
+ usage_dashboard: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Dashboard of saved usage insights for this flag, or null if it has none. "
+ "Flags do not get one on creation; create it with "
+ "POST /api/projects/{project_id}/feature_flags/{id}/dashboard/."
+ ),
+ )
analytics_dashboards = TeamScopedPrimaryKeyRelatedField(
many=True,
required=False,
@@ -965,7 +973,6 @@ class FeatureFlagSerializer(
help_text="Indicates the origin product of the feature flag. Choices: 'feature_flags', 'experiments', 'surveys', 'early_access_features', 'web_experiments', 'product_tours'.",
)
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
- _should_create_usage_dashboard = serializers.BooleanField(required=False, write_only=True, default=True)
class Meta:
model = FeatureFlag
@@ -1002,7 +1009,6 @@ class FeatureFlagSerializer(
"bucketing_identifier",
"last_called_at",
"_create_in_folder",
- "_should_create_usage_dashboard",
"is_used_in_replay_settings",
"is_eligible_for_experiment",
]
@@ -1822,7 +1828,6 @@ class FeatureFlagSerializer(
"creation_context", "feature_flags"
) # default to "feature_flags" if an alternative value is not provided
- should_create_usage_dashboard = validated_data.pop("_should_create_usage_dashboard")
self._update_filters(validated_data)
# Safety net: validate() already materialized this for gated creates, but keep it here for
@@ -1844,9 +1849,6 @@ class FeatureFlagSerializer(
self._attempt_set_tags(tags, instance)
self._attempt_set_evaluation_contexts(evaluation_contexts, instance)
- if should_create_usage_dashboard:
- _create_usage_dashboard(instance, request.user)
-
if analytics_dashboards is not None:
for dashboard in analytics_dashboards:
# nosemgrep: idor-lookup-without-team -- dashboard objects validated via get_fields() queryset restriction
@@ -3089,11 +3091,27 @@ class FeatureFlagViewSet(
return response
+ # No UI surface calls this, since the Usage tab renders its charts inline. It exists for API
+ # users who want a saved usage dashboard.
+ @extend_schema(request=None)
@action(methods=["POST"], detail=True)
def dashboard(self, request: request.Request, **kwargs):
+ from products.dashboards.backend.models.dashboard import Dashboard
+
feature_flag: FeatureFlag = self.get_object()
try:
- usage_dashboard = _create_usage_dashboard(feature_flag, request.user)
+ # The FK on the flag isn't cleared by a dashboard soft-delete, so look the id up
+ # through the manager that excludes deleted rows rather than via the FK accessor,
+ # which would happily return a deleted dashboard and skip regenerating it.
+ usage_dashboard = (
+ Dashboard.objects.filter(
+ id=feature_flag.usage_dashboard_id, team__project_id=self.team.project_id
+ ).first()
+ if feature_flag.usage_dashboard_id
+ else None
+ )
+ if usage_dashboard is None:
+ usage_dashboard = _create_usage_dashboard(feature_flag, request.user)
if feature_flag.has_enriched_analytics and not feature_flag.usage_dashboard_has_enriched_insights:
add_enriched_insights_to_feature_flag_dashboard(feature_flag, usage_dashboard)
@@ -3110,6 +3128,7 @@ class FeatureFlagViewSet(
return Response({"success": True}, status=200)
+ @extend_schema(request=None)
@action(methods=["POST"], detail=True)
def enrich_usage_dashboard(self, request: request.Request, **kwargs):
feature_flag: FeatureFlag = self.get_object()
@@ -3119,7 +3138,10 @@ class FeatureFlagViewSet(
return Response(
{
"success": False,
- "error": f"Usage dashboard not found",
+ "error": (
+ "Usage dashboard not found. Create one first with "
+ "POST /api/projects/{project_id}/feature_flags/{id}/dashboard/"
+ ),
},
status=400,
)
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index 9e7e2e96e0a9..db9984d6581e 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -680,1243 +680,6 @@
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'dashboard')
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23
- '''
- SELECT "posthog_tag"."id",
- "posthog_tag"."name",
- "posthog_tag"."team_id"
- FROM "posthog_tag"
- INNER JOIN "posthog_team" ON ("posthog_tag"."team_id" = "posthog_team"."id")
- WHERE (("posthog_tag"."team_id" =
- (SELECT U0."parent_team_id" AS "parent_team_id"
- FROM "posthog_team" U0
- WHERE U0."id" = 99999
- LIMIT 1)
- OR ("posthog_team"."parent_team_id" IS NULL
- AND "posthog_tag"."team_id" = 99999))
- AND "posthog_tag"."name" = 'feature flags')
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24
- '''
- SELECT "posthog_team"."id",
- "posthog_team"."uuid",
- "posthog_team"."organization_id",
- "posthog_team"."parent_team_id",
- "posthog_team"."project_id",
- "posthog_team"."api_token",
- "posthog_team"."app_urls",
- "posthog_team"."name",
- "posthog_team"."slack_incoming_webhook",
- "posthog_team"."created_at",
- "posthog_team"."updated_at",
- "posthog_team"."anonymize_ips",
- "posthog_team"."completed_snippet_onboarding",
- "posthog_team"."has_completed_onboarding_for",
- "posthog_team"."onboarding_tasks",
- "posthog_team"."ingested_event",
- "posthog_team"."ingested_production_event",
- "posthog_team"."ingested_production_event_last_checked_at",
- "posthog_team"."person_processing_opt_out",
- "posthog_team"."secret_api_token",
- "posthog_team"."secret_api_token_backup",
- "posthog_team"."session_recording_opt_in",
- "posthog_team"."session_recording_sample_rate",
- "posthog_team"."session_recording_minimum_duration_milliseconds",
- "posthog_team"."session_recording_linked_flag",
- "posthog_team"."session_recording_network_payload_capture_config",
- "posthog_team"."session_recording_masking_config",
- "posthog_team"."session_recording_url_trigger_config",
- "posthog_team"."session_recording_url_blocklist_config",
- "posthog_team"."session_recording_event_trigger_config",
- "posthog_team"."session_recording_trigger_match_type_config",
- "posthog_team"."session_recording_trigger_groups",
- "posthog_team"."session_replay_config",
- "posthog_team"."session_recording_retention_period",
- "posthog_team"."event_retention_months",
- "posthog_team"."conversations_enabled",
- "posthog_team"."conversations_settings",
- "posthog_team"."proactive_tasks_enabled",
- "posthog_team"."survey_config",
- "posthog_team"."surveys_opt_in",
- "posthog_team"."product_tours_opt_in",
- "posthog_team"."capture_console_log_opt_in",
- "posthog_team"."capture_performance_opt_in",
- "posthog_team"."capture_dead_clicks",
- "posthog_team"."autocapture_opt_out",
- "posthog_team"."autocapture_web_vitals_opt_in",
- "posthog_team"."autocapture_web_vitals_allowed_metrics",
- "posthog_team"."autocapture_exceptions_opt_in",
- "posthog_team"."autocapture_exceptions_errors_to_ignore",
- "posthog_team"."logs_settings",
- "posthog_team"."llm_gateway_enabled_at",
- "posthog_team"."llm_gateway_revoked_at",
- "posthog_team"."llm_gateway_overspend_allowance_usd",
- "posthog_team"."heatmaps_opt_in",
- "posthog_team"."receive_org_level_activity_logs",
- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
- "posthog_team"."web_analytics_pre_aggregated_tables_version",
- "posthog_team"."flags_persistence_default",
- "posthog_team"."feature_flag_confirmation_enabled",
- "posthog_team"."feature_flag_confirmation_message",
- "posthog_team"."default_evaluation_environments_enabled",
- "posthog_team"."require_evaluation_environment_tags",
- "posthog_team"."default_evaluation_contexts_enabled",
- "posthog_team"."require_evaluation_contexts",
- "posthog_team"."session_recording_version",
- "posthog_team"."signup_token",
- "posthog_team"."is_demo",
- "posthog_team"."access_control",
- "posthog_team"."week_start_day",
- "posthog_team"."inject_web_apps",
- "posthog_team"."test_account_filters",
- "posthog_team"."test_account_filters_default_checked",
- "posthog_team"."path_cleaning_filters",
- "posthog_team"."timezone",
- "posthog_team"."data_attributes",
- "posthog_team"."person_display_name_properties",
- "posthog_team"."live_events_columns",
- "posthog_team"."recording_domains",
- "posthog_team"."human_friendly_comparison_periods",
- "posthog_team"."cookieless_server_hash_mode",
- "posthog_team"."primary_dashboard_id",
- "posthog_team"."default_data_theme",
- "posthog_team"."extra_settings",
- "posthog_team"."modifiers",
- "posthog_team"."correlation_config",
- "posthog_team"."session_recording_retention_period_days",
- "posthog_team"."external_data_workspace_id",
- "posthog_team"."external_data_workspace_last_synced_at",
- "posthog_team"."api_query_rate_limit",
- "posthog_team"."drop_events_older_than",
- "posthog_team"."base_currency",
- "posthog_team"."experiment_recalculation_time",
- "posthog_team"."default_experiment_confidence_level",
- "posthog_team"."default_experiment_stats_method",
- "posthog_team"."business_model"
- FROM "posthog_team"
- WHERE "posthog_team"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25
- '''
- SELECT 1 AS "a"
- FROM "posthog_tag"
- WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26
- '''
- SELECT 1 AS "a"
- FROM "posthog_dashboard"
- WHERE "posthog_dashboard"."id" = 99999
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27
- '''
- SELECT 1 AS "a"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."id" = '00000000000000000000000000000000'::uuid
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28
- '''
- SELECT 1 AS "_check"
- WHERE COALESCE((EXISTS
- (SELECT 1 AS "a"
- FROM "posthog_taggeditem" U0
- WHERE (U0."dashboard_id" = 99999
- AND U0."tag_id" = '00000000000000000000000000000000'::uuid
- AND U0."dashboard_id" IS NOT NULL)
- LIMIT 1)), true)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29
- '''
- SELECT 1 AS "_check"
- WHERE COALESCE(true, true)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3
- '''
- SELECT 1 AS "a"
- FROM "posthog_organizationmembership"
- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
- AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30
- '''
- SELECT "posthog_tag"."id",
- "posthog_tag"."name",
- "posthog_tag"."team_id"
- FROM "posthog_tag"
- WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31
- '''
- SELECT "posthog_team"."id",
- "posthog_team"."uuid",
- "posthog_team"."organization_id",
- "posthog_team"."parent_team_id",
- "posthog_team"."project_id",
- "posthog_team"."api_token",
- "posthog_team"."app_urls",
- "posthog_team"."name",
- "posthog_team"."slack_incoming_webhook",
- "posthog_team"."created_at",
- "posthog_team"."updated_at",
- "posthog_team"."anonymize_ips",
- "posthog_team"."completed_snippet_onboarding",
- "posthog_team"."has_completed_onboarding_for",
- "posthog_team"."onboarding_tasks",
- "posthog_team"."ingested_event",
- "posthog_team"."ingested_production_event",
- "posthog_team"."ingested_production_event_last_checked_at",
- "posthog_team"."person_processing_opt_out",
- "posthog_team"."secret_api_token",
- "posthog_team"."secret_api_token_backup",
- "posthog_team"."session_recording_opt_in",
- "posthog_team"."session_recording_sample_rate",
- "posthog_team"."session_recording_minimum_duration_milliseconds",
- "posthog_team"."session_recording_linked_flag",
- "posthog_team"."session_recording_network_payload_capture_config",
- "posthog_team"."session_recording_masking_config",
- "posthog_team"."session_recording_url_trigger_config",
- "posthog_team"."session_recording_url_blocklist_config",
- "posthog_team"."session_recording_event_trigger_config",
- "posthog_team"."session_recording_trigger_match_type_config",
- "posthog_team"."session_recording_trigger_groups",
- "posthog_team"."session_replay_config",
- "posthog_team"."session_recording_retention_period",
- "posthog_team"."event_retention_months",
- "posthog_team"."conversations_enabled",
- "posthog_team"."conversations_settings",
- "posthog_team"."proactive_tasks_enabled",
- "posthog_team"."survey_config",
- "posthog_team"."surveys_opt_in",
- "posthog_team"."product_tours_opt_in",
- "posthog_team"."capture_console_log_opt_in",
- "posthog_team"."capture_performance_opt_in",
- "posthog_team"."capture_dead_clicks",
- "posthog_team"."autocapture_opt_out",
- "posthog_team"."autocapture_web_vitals_opt_in",
- "posthog_team"."autocapture_web_vitals_allowed_metrics",
- "posthog_team"."autocapture_exceptions_opt_in",
- "posthog_team"."autocapture_exceptions_errors_to_ignore",
- "posthog_team"."logs_settings",
- "posthog_team"."llm_gateway_enabled_at",
- "posthog_team"."llm_gateway_revoked_at",
- "posthog_team"."llm_gateway_overspend_allowance_usd",
- "posthog_team"."heatmaps_opt_in",
- "posthog_team"."receive_org_level_activity_logs",
- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
- "posthog_team"."web_analytics_pre_aggregated_tables_version",
- "posthog_team"."flags_persistence_default",
- "posthog_team"."feature_flag_confirmation_enabled",
- "posthog_team"."feature_flag_confirmation_message",
- "posthog_team"."default_evaluation_environments_enabled",
- "posthog_team"."require_evaluation_environment_tags",
- "posthog_team"."default_evaluation_contexts_enabled",
- "posthog_team"."require_evaluation_contexts",
- "posthog_team"."session_recording_version",
- "posthog_team"."signup_token",
- "posthog_team"."is_demo",
- "posthog_team"."access_control",
- "posthog_team"."week_start_day",
- "posthog_team"."inject_web_apps",
- "posthog_team"."test_account_filters",
- "posthog_team"."test_account_filters_default_checked",
- "posthog_team"."path_cleaning_filters",
- "posthog_team"."timezone",
- "posthog_team"."data_attributes",
- "posthog_team"."person_display_name_properties",
- "posthog_team"."live_events_columns",
- "posthog_team"."recording_domains",
- "posthog_team"."human_friendly_comparison_periods",
- "posthog_team"."cookieless_server_hash_mode",
- "posthog_team"."primary_dashboard_id",
- "posthog_team"."default_data_theme",
- "posthog_team"."extra_settings",
- "posthog_team"."modifiers",
- "posthog_team"."correlation_config",
- "posthog_team"."session_recording_retention_period_days",
- "posthog_team"."external_data_workspace_id",
- "posthog_team"."external_data_workspace_last_synced_at",
- "posthog_team"."api_query_rate_limit",
- "posthog_team"."drop_events_older_than",
- "posthog_team"."base_currency",
- "posthog_team"."experiment_recalculation_time",
- "posthog_team"."default_experiment_confidence_level",
- "posthog_team"."default_experiment_stats_method",
- "posthog_team"."business_model"
- FROM "posthog_team"
- WHERE "posthog_team"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32
- '''
- SELECT "posthog_dashboard"."id",
- "posthog_dashboard"."name",
- "posthog_dashboard"."description",
- "posthog_dashboard"."team_id",
- "posthog_dashboard"."pinned",
- "posthog_dashboard"."created_at",
- "posthog_dashboard"."created_by_id",
- "posthog_dashboard"."deleted",
- "posthog_dashboard"."last_accessed_at",
- "posthog_dashboard"."last_refresh",
- "posthog_dashboard"."filters",
- "posthog_dashboard"."variables",
- "posthog_dashboard"."breakdown_colors",
- "posthog_dashboard"."data_color_theme_id",
- "posthog_dashboard"."creation_mode",
- "posthog_dashboard"."restriction_level",
- "posthog_dashboard"."quick_filter_ids",
- "posthog_dashboard"."deprecated_tags",
- "posthog_dashboard"."tags",
- "posthog_dashboard"."share_token",
- "posthog_dashboard"."is_shared"
- FROM "posthog_dashboard"
- WHERE (NOT ("posthog_dashboard"."deleted")
- AND "posthog_dashboard"."id" = 99999)
- ORDER BY "posthog_dashboard"."id" ASC
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'dashboard')
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34
- '''
- SELECT "posthog_team"."id",
- "posthog_team"."uuid",
- "posthog_team"."organization_id",
- "posthog_team"."parent_team_id",
- "posthog_team"."project_id",
- "posthog_team"."api_token",
- "posthog_team"."app_urls",
- "posthog_team"."name",
- "posthog_team"."slack_incoming_webhook",
- "posthog_team"."created_at",
- "posthog_team"."updated_at",
- "posthog_team"."anonymize_ips",
- "posthog_team"."completed_snippet_onboarding",
- "posthog_team"."has_completed_onboarding_for",
- "posthog_team"."onboarding_tasks",
- "posthog_team"."ingested_event",
- "posthog_team"."ingested_production_event",
- "posthog_team"."ingested_production_event_last_checked_at",
- "posthog_team"."person_processing_opt_out",
- "posthog_team"."secret_api_token",
- "posthog_team"."secret_api_token_backup",
- "posthog_team"."session_recording_opt_in",
- "posthog_team"."session_recording_sample_rate",
- "posthog_team"."session_recording_minimum_duration_milliseconds",
- "posthog_team"."session_recording_linked_flag",
- "posthog_team"."session_recording_network_payload_capture_config",
- "posthog_team"."session_recording_masking_config",
- "posthog_team"."session_recording_url_trigger_config",
- "posthog_team"."session_recording_url_blocklist_config",
- "posthog_team"."session_recording_event_trigger_config",
- "posthog_team"."session_recording_trigger_match_type_config",
- "posthog_team"."session_recording_trigger_groups",
- "posthog_team"."session_replay_config",
- "posthog_team"."session_recording_retention_period",
- "posthog_team"."event_retention_months",
- "posthog_team"."conversations_enabled",
- "posthog_team"."conversations_settings",
- "posthog_team"."proactive_tasks_enabled",
- "posthog_team"."survey_config",
- "posthog_team"."surveys_opt_in",
- "posthog_team"."product_tours_opt_in",
- "posthog_team"."capture_console_log_opt_in",
- "posthog_team"."capture_performance_opt_in",
- "posthog_team"."capture_dead_clicks",
- "posthog_team"."autocapture_opt_out",
- "posthog_team"."autocapture_web_vitals_opt_in",
- "posthog_team"."autocapture_web_vitals_allowed_metrics",
- "posthog_team"."autocapture_exceptions_opt_in",
- "posthog_team"."autocapture_exceptions_errors_to_ignore",
- "posthog_team"."logs_settings",
- "posthog_team"."llm_gateway_enabled_at",
- "posthog_team"."llm_gateway_revoked_at",
- "posthog_team"."llm_gateway_overspend_allowance_usd",
- "posthog_team"."heatmaps_opt_in",
- "posthog_team"."receive_org_level_activity_logs",
- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
- "posthog_team"."web_analytics_pre_aggregated_tables_version",
- "posthog_team"."flags_persistence_default",
- "posthog_team"."feature_flag_confirmation_enabled",
- "posthog_team"."feature_flag_confirmation_message",
- "posthog_team"."default_evaluation_environments_enabled",
- "posthog_team"."require_evaluation_environment_tags",
- "posthog_team"."default_evaluation_contexts_enabled",
- "posthog_team"."require_evaluation_contexts",
- "posthog_team"."session_recording_version",
- "posthog_team"."signup_token",
- "posthog_team"."is_demo",
- "posthog_team"."access_control",
- "posthog_team"."week_start_day",
- "posthog_team"."inject_web_apps",
- "posthog_team"."test_account_filters",
- "posthog_team"."test_account_filters_default_checked",
- "posthog_team"."path_cleaning_filters",
- "posthog_team"."timezone",
- "posthog_team"."data_attributes",
- "posthog_team"."person_display_name_properties",
- "posthog_team"."live_events_columns",
- "posthog_team"."recording_domains",
- "posthog_team"."human_friendly_comparison_periods",
- "posthog_team"."cookieless_server_hash_mode",
- "posthog_team"."primary_dashboard_id",
- "posthog_team"."default_data_theme",
- "posthog_team"."extra_settings",
- "posthog_team"."modifiers",
- "posthog_team"."correlation_config",
- "posthog_team"."session_recording_retention_period_days",
- "posthog_team"."external_data_workspace_id",
- "posthog_team"."external_data_workspace_last_synced_at",
- "posthog_team"."api_query_rate_limit",
- "posthog_team"."drop_events_older_than",
- "posthog_team"."base_currency",
- "posthog_team"."experiment_recalculation_time",
- "posthog_team"."default_experiment_confidence_level",
- "posthog_team"."default_experiment_stats_method",
- "posthog_team"."business_model"
- FROM "posthog_team"
- WHERE "posthog_team"."primary_dashboard_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35
- '''
- SELECT "posthog_team"."id",
- "posthog_team"."uuid",
- "posthog_team"."organization_id",
- "posthog_team"."parent_team_id",
- "posthog_team"."project_id",
- "posthog_team"."api_token",
- "posthog_team"."app_urls",
- "posthog_team"."name",
- "posthog_team"."slack_incoming_webhook",
- "posthog_team"."created_at",
- "posthog_team"."updated_at",
- "posthog_team"."anonymize_ips",
- "posthog_team"."completed_snippet_onboarding",
- "posthog_team"."has_completed_onboarding_for",
- "posthog_team"."onboarding_tasks",
- "posthog_team"."ingested_event",
- "posthog_team"."ingested_production_event",
- "posthog_team"."ingested_production_event_last_checked_at",
- "posthog_team"."person_processing_opt_out",
- "posthog_team"."secret_api_token",
- "posthog_team"."secret_api_token_backup",
- "posthog_team"."session_recording_opt_in",
- "posthog_team"."session_recording_sample_rate",
- "posthog_team"."session_recording_minimum_duration_milliseconds",
- "posthog_team"."session_recording_linked_flag",
- "posthog_team"."session_recording_network_payload_capture_config",
- "posthog_team"."session_recording_masking_config",
- "posthog_team"."session_recording_url_trigger_config",
- "posthog_team"."session_recording_url_blocklist_config",
- "posthog_team"."session_recording_event_trigger_config",
- "posthog_team"."session_recording_trigger_match_type_config",
- "posthog_team"."session_recording_trigger_groups",
- "posthog_team"."session_replay_config",
- "posthog_team"."session_recording_retention_period",
- "posthog_team"."event_retention_months",
- "posthog_team"."conversations_enabled",
- "posthog_team"."conversations_settings",
- "posthog_team"."proactive_tasks_enabled",
- "posthog_team"."survey_config",
- "posthog_team"."surveys_opt_in",
- "posthog_team"."product_tours_opt_in",
- "posthog_team"."capture_console_log_opt_in",
- "posthog_team"."capture_performance_opt_in",
- "posthog_team"."capture_dead_clicks",
- "posthog_team"."autocapture_opt_out",
- "posthog_team"."autocapture_web_vitals_opt_in",
- "posthog_team"."autocapture_web_vitals_allowed_metrics",
- "posthog_team"."autocapture_exceptions_opt_in",
- "posthog_team"."autocapture_exceptions_errors_to_ignore",
- "posthog_team"."logs_settings",
- "posthog_team"."llm_gateway_enabled_at",
- "posthog_team"."llm_gateway_revoked_at",
- "posthog_team"."llm_gateway_overspend_allowance_usd",
- "posthog_team"."heatmaps_opt_in",
- "posthog_team"."receive_org_level_activity_logs",
- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
- "posthog_team"."web_analytics_pre_aggregated_tables_version",
- "posthog_team"."flags_persistence_default",
- "posthog_team"."feature_flag_confirmation_enabled",
- "posthog_team"."feature_flag_confirmation_message",
- "posthog_team"."default_evaluation_environments_enabled",
- "posthog_team"."require_evaluation_environment_tags",
- "posthog_team"."default_evaluation_contexts_enabled",
- "posthog_team"."require_evaluation_contexts",
- "posthog_team"."session_recording_version",
- "posthog_team"."signup_token",
- "posthog_team"."is_demo",
- "posthog_team"."access_control",
- "posthog_team"."week_start_day",
- "posthog_team"."inject_web_apps",
- "posthog_team"."test_account_filters",
- "posthog_team"."test_account_filters_default_checked",
- "posthog_team"."path_cleaning_filters",
- "posthog_team"."timezone",
- "posthog_team"."data_attributes",
- "posthog_team"."person_display_name_properties",
- "posthog_team"."live_events_columns",
- "posthog_team"."recording_domains",
- "posthog_team"."human_friendly_comparison_periods",
- "posthog_team"."cookieless_server_hash_mode",
- "posthog_team"."primary_dashboard_id",
- "posthog_team"."default_data_theme",
- "posthog_team"."extra_settings",
- "posthog_team"."modifiers",
- "posthog_team"."correlation_config",
- "posthog_team"."session_recording_retention_period_days",
- "posthog_team"."external_data_workspace_id",
- "posthog_team"."external_data_workspace_last_synced_at",
- "posthog_team"."api_query_rate_limit",
- "posthog_team"."drop_events_older_than",
- "posthog_team"."base_currency",
- "posthog_team"."experiment_recalculation_time",
- "posthog_team"."default_experiment_confidence_level",
- "posthog_team"."default_experiment_stats_method",
- "posthog_team"."business_model"
- FROM "posthog_team"
- WHERE "posthog_team"."primary_dashboard_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."dashboard_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37
- '''
- SELECT "posthog_tag"."id",
- "posthog_tag"."name",
- "posthog_tag"."team_id"
- FROM "posthog_tag"
- WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.38
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."dashboard_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.39
- '''
- SELECT "posthog_tag"."id",
- "posthog_tag"."name",
- "posthog_tag"."team_id"
- FROM "posthog_tag"
- WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.4
- '''
- SELECT "posthog_organizationmembership"."id",
- "posthog_organizationmembership"."organization_id",
- "posthog_organizationmembership"."user_id",
- "posthog_organizationmembership"."level",
- "posthog_organizationmembership"."joined_at",
- "posthog_organizationmembership"."updated_at",
- "posthog_organizationmembership"."invited_by_id",
- "posthog_organization"."id",
- "posthog_organization"."name",
- "posthog_organization"."slug",
- "posthog_organization"."logo_media_id",
- "posthog_organization"."created_at",
- "posthog_organization"."updated_at",
- "posthog_organization"."is_active",
- "posthog_organization"."is_not_active_reason",
- "posthog_organization"."session_cookie_age",
- "posthog_organization"."is_member_join_email_enabled",
- "posthog_organization"."is_ai_data_processing_approved",
- "posthog_organization"."is_ai_training_opted_in",
- "posthog_organization"."is_ai_training_locked",
- "posthog_organization"."is_ai_training_cta_shown",
- "posthog_organization"."enforce_2fa",
- "posthog_organization"."enforce_verified_domains",
- "posthog_organization"."members_can_invite",
- "posthog_organization"."members_can_create_projects",
- "posthog_organization"."members_can_use_personal_api_keys",
- "posthog_organization"."members_can_see_org_members",
- "posthog_organization"."allow_publicly_shared_resources",
- "posthog_organization"."default_role_id",
- "posthog_organization"."plugins_access_level",
- "posthog_organization"."for_internal_metrics",
- "posthog_organization"."default_experiment_stats_method",
- "posthog_organization"."default_anonymize_ips",
- "posthog_organization"."is_hipaa",
- "posthog_organization"."is_pending_deletion",
- "posthog_organization"."customer_id",
- "posthog_organization"."available_product_features",
- "posthog_organization"."usage",
- "posthog_organization"."never_drop_data",
- "posthog_organization"."customer_trust_scores",
- "posthog_organization"."setup_section_2_completed",
- "posthog_organization"."personalization",
- "posthog_organization"."domain_whitelist",
- "posthog_organization"."is_platform"
- FROM "posthog_organizationmembership"
- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
- WHERE "posthog_organizationmembership"."user_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.40
- '''
- SELECT "posthog_dashboardtile"."id",
- "posthog_dashboardtile"."dashboard_id",
- "posthog_dashboardtile"."insight_id",
- "posthog_dashboardtile"."text_id",
- "posthog_dashboardtile"."button_tile_id",
- "posthog_dashboardtile"."widget_id",
- "posthog_dashboardtile"."team_id",
- "posthog_dashboardtile"."layouts",
- "posthog_dashboardtile"."color",
- "posthog_dashboardtile"."filters_hash",
- "posthog_dashboardtile"."last_refresh",
- "posthog_dashboardtile"."refreshing",
- "posthog_dashboardtile"."refresh_attempt",
- "posthog_dashboardtile"."filters_overrides",
- "posthog_dashboardtile"."show_description",
- "posthog_dashboardtile"."transparent_background",
- "posthog_dashboardtile"."deleted"
- FROM "posthog_dashboardtile"
- INNER JOIN "posthog_dashboard" ON ("posthog_dashboardtile"."dashboard_id" = "posthog_dashboard"."id")
- WHERE (NOT ("posthog_dashboardtile"."deleted"
- AND "posthog_dashboardtile"."deleted" IS NOT NULL)
- AND NOT ("posthog_dashboard"."deleted")
- AND "posthog_dashboardtile"."dashboard_id" = 99999)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41
- '''
- SELECT "posthog_dashboardtile"."id",
- "posthog_dashboardtile"."dashboard_id",
- "posthog_dashboardtile"."insight_id",
- "posthog_dashboardtile"."text_id",
- "posthog_dashboardtile"."button_tile_id",
- "posthog_dashboardtile"."widget_id",
- "posthog_dashboardtile"."team_id",
- "posthog_dashboardtile"."layouts",
- "posthog_dashboardtile"."color",
- "posthog_dashboardtile"."filters_hash",
- "posthog_dashboardtile"."last_refresh",
- "posthog_dashboardtile"."refreshing",
- "posthog_dashboardtile"."refresh_attempt",
- "posthog_dashboardtile"."filters_overrides",
- "posthog_dashboardtile"."show_description",
- "posthog_dashboardtile"."transparent_background",
- "posthog_dashboardtile"."deleted"
- FROM "posthog_dashboardtile"
- INNER JOIN "posthog_dashboard" ON ("posthog_dashboardtile"."dashboard_id" = "posthog_dashboard"."id")
- WHERE (NOT ("posthog_dashboardtile"."deleted"
- AND "posthog_dashboardtile"."deleted" IS NOT NULL)
- AND NOT ("posthog_dashboard"."deleted")
- AND "posthog_dashboardtile"."dashboard_id" = 99999)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.42
- '''
- SELECT "posthog_dashboarditem"."id",
- "posthog_dashboarditem"."name",
- "posthog_dashboarditem"."derived_name",
- "posthog_dashboarditem"."description",
- "posthog_dashboarditem"."team_id",
- "posthog_dashboarditem"."filters",
- "posthog_dashboarditem"."filters_hash",
- "posthog_dashboarditem"."query",
- "posthog_dashboarditem"."query_metadata",
- "posthog_dashboarditem"."order",
- "posthog_dashboarditem"."deleted",
- "posthog_dashboarditem"."saved",
- "posthog_dashboarditem"."created_at",
- "posthog_dashboarditem"."refreshing",
- "posthog_dashboarditem"."created_by_id",
- "posthog_dashboarditem"."is_sample",
- "posthog_dashboarditem"."short_id",
- "posthog_dashboarditem"."favorited",
- "posthog_dashboarditem"."refresh_attempt",
- "posthog_dashboarditem"."last_modified_at",
- "posthog_dashboarditem"."last_modified_by_id",
- "posthog_dashboarditem"."dashboard_id",
- "posthog_dashboarditem"."last_refresh",
- "posthog_dashboarditem"."layouts",
- "posthog_dashboarditem"."color",
- "posthog_dashboarditem"."dive_dashboard_id",
- "posthog_dashboarditem"."updated_at",
- "posthog_dashboarditem"."deprecated_tags",
- "posthog_dashboarditem"."tags"
- FROM "posthog_dashboarditem"
- WHERE (NOT ("posthog_dashboarditem"."deleted")
- AND "posthog_dashboarditem"."dashboard_id" = 99999)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.43
- '''
- SELECT "posthog_dashboarditem"."id",
- "posthog_dashboarditem"."name",
- "posthog_dashboarditem"."derived_name",
- "posthog_dashboarditem"."description",
- "posthog_dashboarditem"."team_id",
- "posthog_dashboarditem"."filters",
- "posthog_dashboarditem"."filters_hash",
- "posthog_dashboarditem"."query",
- "posthog_dashboarditem"."query_metadata",
- "posthog_dashboarditem"."order",
- "posthog_dashboarditem"."deleted",
- "posthog_dashboarditem"."saved",
- "posthog_dashboarditem"."created_at",
- "posthog_dashboarditem"."refreshing",
- "posthog_dashboarditem"."created_by_id",
- "posthog_dashboarditem"."is_sample",
- "posthog_dashboarditem"."short_id",
- "posthog_dashboarditem"."favorited",
- "posthog_dashboarditem"."refresh_attempt",
- "posthog_dashboarditem"."last_modified_at",
- "posthog_dashboarditem"."last_modified_by_id",
- "posthog_dashboarditem"."dashboard_id",
- "posthog_dashboarditem"."last_refresh",
- "posthog_dashboarditem"."layouts",
- "posthog_dashboarditem"."color",
- "posthog_dashboarditem"."dive_dashboard_id",
- "posthog_dashboarditem"."updated_at",
- "posthog_dashboarditem"."deprecated_tags",
- "posthog_dashboarditem"."tags"
- FROM "posthog_dashboarditem"
- WHERE (NOT ("posthog_dashboarditem"."deleted")
- AND "posthog_dashboarditem"."dashboard_id" = 99999)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.44
- '''
- SELECT "posthog_dashboarditem"."id",
- "posthog_dashboarditem"."name",
- "posthog_dashboarditem"."derived_name",
- "posthog_dashboarditem"."description",
- "posthog_dashboarditem"."team_id",
- "posthog_dashboarditem"."filters",
- "posthog_dashboarditem"."filters_hash",
- "posthog_dashboarditem"."query",
- "posthog_dashboarditem"."query_metadata",
- "posthog_dashboarditem"."order",
- "posthog_dashboarditem"."deleted",
- "posthog_dashboarditem"."saved",
- "posthog_dashboarditem"."created_at",
- "posthog_dashboarditem"."refreshing",
- "posthog_dashboarditem"."created_by_id",
- "posthog_dashboarditem"."is_sample",
- "posthog_dashboarditem"."short_id",
- "posthog_dashboarditem"."favorited",
- "posthog_dashboarditem"."refresh_attempt",
- "posthog_dashboarditem"."last_modified_at",
- "posthog_dashboarditem"."last_modified_by_id",
- "posthog_dashboarditem"."dashboard_id",
- "posthog_dashboarditem"."last_refresh",
- "posthog_dashboarditem"."layouts",
- "posthog_dashboarditem"."color",
- "posthog_dashboarditem"."dive_dashboard_id",
- "posthog_dashboarditem"."updated_at",
- "posthog_dashboarditem"."deprecated_tags",
- "posthog_dashboarditem"."tags"
- FROM "posthog_dashboarditem"
- INNER JOIN "posthog_dashboardtile" ON ("posthog_dashboarditem"."id" = "posthog_dashboardtile"."insight_id")
- WHERE (NOT ("posthog_dashboarditem"."deleted")
- AND "posthog_dashboardtile"."dashboard_id" = 99999)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.45
- '''
- SELECT "posthog_dashboarditem"."id",
- "posthog_dashboarditem"."name",
- "posthog_dashboarditem"."derived_name",
- "posthog_dashboarditem"."description",
- "posthog_dashboarditem"."team_id",
- "posthog_dashboarditem"."filters",
- "posthog_dashboarditem"."filters_hash",
- "posthog_dashboarditem"."query",
- "posthog_dashboarditem"."query_metadata",
- "posthog_dashboarditem"."order",
- "posthog_dashboarditem"."deleted",
- "posthog_dashboarditem"."saved",
- "posthog_dashboarditem"."created_at",
- "posthog_dashboarditem"."refreshing",
- "posthog_dashboarditem"."created_by_id",
- "posthog_dashboarditem"."is_sample",
- "posthog_dashboarditem"."short_id",
- "posthog_dashboarditem"."favorited",
- "posthog_dashboarditem"."refresh_attempt",
- "posthog_dashboarditem"."last_modified_at",
- "posthog_dashboarditem"."last_modified_by_id",
- "posthog_dashboarditem"."dashboard_id",
- "posthog_dashboarditem"."last_refresh",
- "posthog_dashboarditem"."layouts",
- "posthog_dashboarditem"."color",
- "posthog_dashboarditem"."dive_dashboard_id",
- "posthog_dashboarditem"."updated_at",
- "posthog_dashboarditem"."deprecated_tags",
- "posthog_dashboarditem"."tags"
- FROM "posthog_dashboarditem"
- INNER JOIN "posthog_dashboardtile" ON ("posthog_dashboarditem"."id" = "posthog_dashboardtile"."insight_id")
- WHERE (NOT ("posthog_dashboarditem"."deleted")
- AND "posthog_dashboardtile"."dashboard_id" = 99999)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.46
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'insight'
- AND NOT ("posthog_filesystem"."shortcut"
- AND "posthog_filesystem"."shortcut" IS NOT NULL))
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.47
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'insight'
- AND NOT ("posthog_filesystem"."shortcut"
- AND "posthog_filesystem"."shortcut" IS NOT NULL))
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.48
- '''
- SELECT "posthog_featureflag"."id",
- "posthog_featureflag"."key",
- "posthog_featureflag"."name",
- "posthog_featureflag"."filters",
- "posthog_featureflag"."team_id",
- "posthog_featureflag"."created_by_id",
- "posthog_featureflag"."created_at",
- "posthog_featureflag"."updated_at",
- "posthog_featureflag"."deleted",
- "posthog_featureflag"."active",
- "posthog_featureflag"."archived",
- "posthog_featureflag"."version",
- "posthog_featureflag"."last_modified_by_id",
- "posthog_featureflag"."ensure_experience_continuity",
- "posthog_featureflag"."usage_dashboard_id",
- "posthog_featureflag"."has_enriched_analytics",
- "posthog_featureflag"."is_remote_configuration",
- "posthog_featureflag"."has_encrypted_payloads",
- "posthog_featureflag"."evaluation_runtime",
- "posthog_featureflag"."bucketing_identifier",
- "posthog_featureflag"."last_called_at"
- FROM "posthog_featureflag"
- WHERE (NOT ("posthog_featureflag"."deleted")
- AND "posthog_featureflag"."id" = 99999)
- ORDER BY "posthog_featureflag"."id" ASC
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.49
- '''
- SELECT "posthog_featureflag"."active" AS "active",
- "posthog_featureflag"."deleted" AS "deleted",
- "posthog_featureflag"."filters" AS "filters",
- "posthog_featureflag"."key" AS "key"
- FROM "posthog_featureflag"
- WHERE "posthog_featureflag"."id" = 99999
- ORDER BY "posthog_featureflag"."id" ASC
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5
- '''
- SELECT "posthog_team"."id",
- "posthog_team"."organization_id"
- FROM "posthog_team"
- WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.50
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'feature_flag'
- AND NOT ("posthog_filesystem"."shortcut"
- AND "posthog_filesystem"."shortcut" IS NOT NULL))
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51
- '''
- SELECT "posthog_filesystemshortcut"."id",
- "posthog_filesystemshortcut"."team_id",
- "posthog_filesystemshortcut"."user_id",
- "posthog_filesystemshortcut"."path",
- "posthog_filesystemshortcut"."type",
- "posthog_filesystemshortcut"."ref",
- "posthog_filesystemshortcut"."href",
- "posthog_filesystemshortcut"."order",
- "posthog_filesystemshortcut"."created_at",
- "posthog_filesystemshortcut"."surface"
- FROM "posthog_filesystemshortcut"
- WHERE (("posthog_filesystemshortcut"."surface" IS NULL
- OR "posthog_filesystemshortcut"."surface" = 'web')
- AND "posthog_filesystemshortcut"."ref" = '0001'
- AND "posthog_filesystemshortcut"."team_id" = 99999
- AND "posthog_filesystemshortcut"."type" = 'feature_flag'
- AND NOT ("posthog_filesystemshortcut"."path" = 'copied-flag-key'
- AND "posthog_filesystemshortcut"."href" = '__skipped__'
- AND "posthog_filesystemshortcut"."href" IS NOT NULL))
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52
- '''
- SELECT "posthog_integration"."id",
- "posthog_integration"."team_id",
- "posthog_integration"."kind",
- "posthog_integration"."integration_id",
- "posthog_integration"."config",
- "posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
- "posthog_integration"."errors",
- "posthog_integration"."created_at",
- "posthog_integration"."created_by_id"
- FROM "posthog_integration"
- WHERE ("posthog_integration"."kind" = 'vercel'
- AND "posthog_integration"."team_id" = 99999)
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53
- '''
- SELECT "posthog_organizationintegration"."id",
- "posthog_organizationintegration"."organization_id",
- "posthog_organizationintegration"."kind",
- "posthog_organizationintegration"."integration_id",
- "posthog_organizationintegration"."config",
- "posthog_organizationintegration"."sensitive_config",
- "posthog_organizationintegration"."created_by_id",
- "posthog_organizationintegration"."created_at",
- "posthog_organizationintegration"."updated_at"
- FROM "posthog_organizationintegration"
- WHERE ("posthog_organizationintegration"."kind" = 'vercel'
- AND "posthog_organizationintegration"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."feature_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."feature_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56
- '''
- SELECT "posthog_survey"."id",
- "posthog_survey"."team_id",
- "posthog_survey"."name",
- "posthog_survey"."description",
- "posthog_survey"."linked_flag_id",
- "posthog_survey"."targeting_flag_id",
- "posthog_survey"."linked_insight_id",
- "posthog_survey"."internal_targeting_flag_id",
- "posthog_survey"."internal_response_sampling_flag_id",
- "posthog_survey"."type",
- "posthog_survey"."conditions",
- "posthog_survey"."questions",
- "posthog_survey"."appearance",
- "posthog_survey"."created_at",
- "posthog_survey"."created_by_id",
- "posthog_survey"."start_date",
- "posthog_survey"."end_date",
- "posthog_survey"."updated_at",
- "posthog_survey"."archived",
- "posthog_survey"."responses_limit",
- "posthog_survey"."response_sampling_start_date",
- "posthog_survey"."response_sampling_interval_type",
- "posthog_survey"."response_sampling_interval",
- "posthog_survey"."response_sampling_limit",
- "posthog_survey"."response_sampling_daily_limits",
- "posthog_survey"."iteration_count",
- "posthog_survey"."iteration_frequency_days",
- "posthog_survey"."iteration_start_dates",
- "posthog_survey"."current_iteration",
- "posthog_survey"."current_iteration_start_date",
- "posthog_survey"."schedule",
- "posthog_survey"."enable_partial_responses",
- "posthog_survey"."enable_iframe_embedding",
- "posthog_survey"."headline_summary",
- "posthog_survey"."headline_response_count",
- "posthog_survey"."question_summaries",
- "posthog_survey"."form_content",
- "posthog_survey"."base_language",
- "posthog_survey"."translations"
- FROM "posthog_survey"
- WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57
- '''
- SELECT "posthog_survey"."id",
- "posthog_survey"."team_id",
- "posthog_survey"."name",
- "posthog_survey"."description",
- "posthog_survey"."linked_flag_id",
- "posthog_survey"."targeting_flag_id",
- "posthog_survey"."linked_insight_id",
- "posthog_survey"."internal_targeting_flag_id",
- "posthog_survey"."internal_response_sampling_flag_id",
- "posthog_survey"."type",
- "posthog_survey"."conditions",
- "posthog_survey"."questions",
- "posthog_survey"."appearance",
- "posthog_survey"."created_at",
- "posthog_survey"."created_by_id",
- "posthog_survey"."start_date",
- "posthog_survey"."end_date",
- "posthog_survey"."updated_at",
- "posthog_survey"."archived",
- "posthog_survey"."responses_limit",
- "posthog_survey"."response_sampling_start_date",
- "posthog_survey"."response_sampling_interval_type",
- "posthog_survey"."response_sampling_interval",
- "posthog_survey"."response_sampling_limit",
- "posthog_survey"."response_sampling_daily_limits",
- "posthog_survey"."iteration_count",
- "posthog_survey"."iteration_frequency_days",
- "posthog_survey"."iteration_start_dates",
- "posthog_survey"."current_iteration",
- "posthog_survey"."current_iteration_start_date",
- "posthog_survey"."schedule",
- "posthog_survey"."enable_partial_responses",
- "posthog_survey"."enable_iframe_embedding",
- "posthog_survey"."headline_summary",
- "posthog_survey"."headline_response_count",
- "posthog_survey"."question_summaries",
- "posthog_survey"."form_content",
- "posthog_survey"."base_language",
- "posthog_survey"."translations"
- FROM "posthog_survey"
- WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58
- '''
- SELECT "ee_featureflagroleaccess"."id",
- "ee_featureflagroleaccess"."feature_flag_id",
- "ee_featureflagroleaccess"."role_id",
- "ee_featureflagroleaccess"."added_at",
- "ee_featureflagroleaccess"."updated_at"
- FROM "ee_featureflagroleaccess"
- WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59
- '''
- SELECT "ee_featureflagroleaccess"."id",
- "ee_featureflagroleaccess"."feature_flag_id",
- "ee_featureflagroleaccess"."role_id",
- "ee_featureflagroleaccess"."added_at",
- "ee_featureflagroleaccess"."updated_at"
- FROM "ee_featureflagroleaccess"
- WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6
- '''
- SELECT "posthog_featureflag"."id",
- "posthog_featureflag"."key",
- "posthog_featureflag"."name",
- "posthog_featureflag"."filters",
- "posthog_featureflag"."team_id",
- "posthog_featureflag"."created_by_id",
- "posthog_featureflag"."created_at",
- "posthog_featureflag"."updated_at",
- "posthog_featureflag"."deleted",
- "posthog_featureflag"."active",
- "posthog_featureflag"."archived",
- "posthog_featureflag"."version",
- "posthog_featureflag"."last_modified_by_id",
- "posthog_featureflag"."ensure_experience_continuity",
- "posthog_featureflag"."usage_dashboard_id",
- "posthog_featureflag"."has_enriched_analytics",
- "posthog_featureflag"."is_remote_configuration",
- "posthog_featureflag"."has_encrypted_payloads",
- "posthog_featureflag"."evaluation_runtime",
- "posthog_featureflag"."bucketing_identifier",
- "posthog_featureflag"."last_called_at"
- FROM "posthog_featureflag"
- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")
- WHERE (NOT ("posthog_featureflag"."deleted")
- AND "posthog_featureflag"."key" = 'copied-flag-key'
- AND "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
- AND "posthog_team"."project_id" = 99999
- AND "posthog_featureflag"."team_id" IN (1,
- 2,
- 3,
- 4,
- 5 /* ... */))
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.60
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -1959,7 +722,7 @@
AND NOT "posthog_experiment"."deleted")
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.61
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -2002,7 +765,7 @@
AND NOT "posthog_experiment"."deleted")
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -2047,7 +810,7 @@
WHERE "posthog_survey"."linked_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25
'''
SELECT "posthog_earlyaccessfeature"."id",
"posthog_earlyaccessfeature"."team_id",
@@ -2065,7 +828,7 @@
WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -2118,7 +881,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27
'''
SELECT "posthog_dashboard"."id",
"posthog_dashboard"."name",
@@ -2147,7 +910,7 @@
AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -2200,7 +963,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29
'''
SELECT 1 AS "a"
FROM "posthog_team"
@@ -2209,7 +972,16 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3
+ '''
+ SELECT 1 AS "a"
+ FROM "posthog_organizationmembership"
+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
+ AND "posthog_organizationmembership"."user_id" = 99999)
+ LIMIT 1
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30
'''
SELECT "posthog_featureflagevaluationcontext"."id",
"posthog_featureflagevaluationcontext"."feature_flag_id",
@@ -2225,7 +997,7 @@
WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.69
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31
'''
SELECT "posthog_tag"."name" AS "tag__name"
FROM "posthog_taggeditem"
@@ -2233,6 +1005,102 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.4
+ '''
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
+ WHERE "posthog_organizationmembership"."user_id" = 99999
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5
+ '''
+ SELECT "posthog_team"."id",
+ "posthog_team"."organization_id"
+ FROM "posthog_team"
+ WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6
+ '''
+ SELECT "posthog_featureflag"."id",
+ "posthog_featureflag"."key",
+ "posthog_featureflag"."name",
+ "posthog_featureflag"."filters",
+ "posthog_featureflag"."team_id",
+ "posthog_featureflag"."created_by_id",
+ "posthog_featureflag"."created_at",
+ "posthog_featureflag"."updated_at",
+ "posthog_featureflag"."deleted",
+ "posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
+ "posthog_featureflag"."version",
+ "posthog_featureflag"."last_modified_by_id",
+ "posthog_featureflag"."ensure_experience_continuity",
+ "posthog_featureflag"."usage_dashboard_id",
+ "posthog_featureflag"."has_enriched_analytics",
+ "posthog_featureflag"."is_remote_configuration",
+ "posthog_featureflag"."has_encrypted_payloads",
+ "posthog_featureflag"."evaluation_runtime",
+ "posthog_featureflag"."bucketing_identifier",
+ "posthog_featureflag"."last_called_at"
+ FROM "posthog_featureflag"
+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")
+ WHERE (NOT ("posthog_featureflag"."deleted")
+ AND "posthog_featureflag"."key" = 'copied-flag-key'
+ AND "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
+ AND "posthog_team"."project_id" = 99999
+ AND "posthog_featureflag"."team_id" IN (1,
+ 2,
+ 3,
+ 4,
+ 5 /* ... */))
+ LIMIT 21
+ '''
+# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.7
'''
SELECT "posthog_team"."id",
diff --git a/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py b/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py
index 17b8db9c5f60..31b97c63fb6a 100644
--- a/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py
+++ b/products/feature_flags/backend/api/test/feature_flag_openapi_test_helpers.py
@@ -12,7 +12,6 @@ from products.feature_flags.backend.api.feature_flag import FeatureFlagSerialize
FEATURE_FLAG_REQUEST_SCHEMA_EXCLUDED_RUNTIME_FIELDS: frozenset[str] = frozenset(
{
"_create_in_folder", # create-only write_only helper for folder placement
- "_should_create_usage_dashboard", # create-only write_only internal toggle
"analytics_dashboards", # relational link managed via dashboards, not the flag create/update surface
"created_at", # server-managed timestamp, not agent-facing
"creation_context", # write_only origin-product marker set by internal callers
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index d6293d7a5d22..53aee37cfaf4 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -114,6 +114,10 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
query = cast(dict[str, Any], insight.query)
return query["source"]["properties"]["values"][0]["values"][0]["value"]
+ def _generate_usage_dashboard(self, flag_id: int) -> None:
+ response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/{flag_id}/dashboard")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
def test_cant_create_flag_with_duplicate_key(self):
FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
count = FeatureFlag.objects.count()
@@ -2994,6 +2998,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
frozen_datetime.tick(delta=timedelta(minutes=10))
@@ -3178,6 +3183,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
frozen_datetime.tick(delta=timedelta(minutes=10))
@@ -3267,6 +3273,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
frozen_datetime.tick(delta=timedelta(minutes=10))
@@ -3356,6 +3363,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
frozen_datetime.tick(delta=timedelta(minutes=10))
@@ -4410,7 +4418,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
# (they're survey-specific and filtered out from the main list)
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_create_feature_flag_usage_dashboard(self, mock_report_user_action):
+ def test_generate_usage_dashboard_creates_insights(self, mock_report_user_action):
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{
@@ -4422,6 +4430,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
instance = FeatureFlag.objects.get(id=flag_id)
self.assertEqual(instance.key, "alpha-feature")
@@ -4794,7 +4803,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
]
)
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_create_group_feature_flag_usage_dashboard(
+ def test_generate_group_usage_dashboard_creates_insights(
self, _name, group_type, expected_singular, expected_plural, mock_report_user_action
):
if group_type is not None:
@@ -4831,7 +4840,9 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
format="json",
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- instance = FeatureFlag.objects.get(id=response.json()["id"])
+ flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
+ instance = FeatureFlag.objects.get(id=flag_id)
dashboard = instance.usage_dashboard
assert dashboard is not None
@@ -4893,6 +4904,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(create.status_code, status.HTTP_201_CREATED)
flag_id = create.json()["id"]
+ self._generate_usage_dashboard(flag_id)
response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -4946,6 +4958,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
+ self._generate_usage_dashboard(flag_id)
instance = FeatureFlag.objects.get(id=flag_id)
self.assertEqual(instance.key, "alpha-feature")
@@ -4985,6 +4998,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flag_id = response.json()["id"]
instance = FeatureFlag.objects.get(id=flag_id)
self.assertEqual(instance.key, "alpha-feature")
+ self._generate_usage_dashboard(flag_id)
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}/enrich_usage_dashboard",
@@ -4999,6 +5013,77 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
},
)
+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")
+ def test_dashboard_enrichment_fails_if_no_usage_dashboard(self, mock_report_user_action: MagicMock) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {
+ "name": "Alpha feature",
+ "key": "alpha-feature",
+ "filters": {"groups": [{"rollout_percentage": 50}]},
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ flag_id = response.json()["id"]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/{flag_id}/enrich_usage_dashboard",
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ {
+ "error": (
+ "Usage dashboard not found. Create one first with "
+ "POST /api/projects/{project_id}/feature_flags/{id}/dashboard/"
+ ),
+ "success": False,
+ },
+ )
+
+ def test_dashboard_endpoint_is_idempotent(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"name": "Alpha feature", "key": "alpha-feature", "filters": {"groups": [{"rollout_percentage": 50}]}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ flag_id = response.json()["id"]
+
+ self._generate_usage_dashboard(flag_id)
+ first_dashboard_id = FeatureFlag.objects.get(id=flag_id).usage_dashboard_id
+ assert first_dashboard_id is not None
+
+ self._generate_usage_dashboard(flag_id)
+ instance = FeatureFlag.objects.get(id=flag_id)
+
+ self.assertEqual(instance.usage_dashboard_id, first_dashboard_id)
+ self.assertTrue(Dashboard.objects.filter(id=first_dashboard_id, deleted=False).exists())
+
+ def test_dashboard_endpoint_regenerates_after_dashboard_is_deleted(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"name": "Alpha feature", "key": "alpha-feature", "filters": {"groups": [{"rollout_percentage": 50}]}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ flag_id = response.json()["id"]
+
+ self._generate_usage_dashboard(flag_id)
+ deleted_dashboard_id = FeatureFlag.objects.get(id=flag_id).usage_dashboard_id
+ assert deleted_dashboard_id is not None
+ Dashboard.objects.filter(id=deleted_dashboard_id).update(deleted=True)
+
+ self._generate_usage_dashboard(flag_id)
+ instance = FeatureFlag.objects.get(id=flag_id)
+
+ new_dashboard_id = instance.usage_dashboard_id
+ assert new_dashboard_id is not None
+ self.assertNotEqual(new_dashboard_id, deleted_dashboard_id)
+ self.assertTrue(Dashboard.objects.filter(id=new_dashboard_id, deleted=False).exists())
+
@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
def test_local_evaluation_billing_analytics_for_regular_feature_flag_list(self):
FeatureFlag.objects.all().delete()
@@ -7784,10 +7869,12 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert data["keys"] == {str(flag1.id): "test-flag-1"}
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
- def test_create_feature_flag_without_usage_dashboard(self, mock_report_user_action):
+ def test_create_feature_flag_does_not_create_usage_dashboard(self, mock_report_user_action: MagicMock) -> None:
+ dashboard_count_before = Dashboard.objects.filter(team=self.team).count()
+
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
- {"key": "no-usage-dashboard", "_should_create_usage_dashboard": False},
+ {"key": "no-usage-dashboard"},
format="json",
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
@@ -7797,6 +7884,11 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(instance.key, "no-usage-dashboard")
self.assertEqual(instance.name, "")
assert instance.usage_dashboard is None, "Usage dashboard should not be created"
+ self.assertEqual(
+ Dashboard.objects.filter(team=self.team).count(),
+ dashboard_count_before,
+ "Feature flag creation should not create any dashboard",
+ )
def test_feature_flag_detail_actions_respect_access_control(self) -> None:
self.organization.available_product_features = [
diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
index cd8ae9184515..09b6b824eec8 100644
--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
@@ -828,7 +828,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):
# Linked instances must be overridden for a soft-deleted flag
self.assertEqual(flag_response["experiment_set"], [])
self.assertEqual(flag_response["surveys"], [])
- self.assertNotEqual(flag_response["usage_dashboard"], existing_deleted_flag.usage_dashboard.id)
+ self.assertIsNone(flag_response["usage_dashboard"])
self.assertEqual(flag_response["analytics_dashboards"], [])
# target_project_2 should have failed: soft-deleted flag is still referenced
diff --git a/products/feature_flags/backend/max_tools.py b/products/feature_flags/backend/max_tools.py
index da8582f56009..440c08c45b3d 100644
--- a/products/feature_flags/backend/max_tools.py
+++ b/products/feature_flags/backend/max_tools.py
@@ -267,7 +267,6 @@ class CreateFeatureFlagTool(MaxTool):
"active": flag_schema.active,
"filters": filters,
"tags": flag_schema.tags,
- "_should_create_usage_dashboard": False,
}
# Unspecified (None) falls back to the project defaults; an explicit empty list is left as-is.
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index c795c4b616af..f4d09a6ae6e3 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -498,7 +498,11 @@ export interface FeatureFlagApi {
readonly can_edit: boolean
tags?: unknown[]
evaluation_contexts?: unknown[]
- readonly usage_dashboard: number
+ /**
+ * Dashboard of saved usage insights for this flag, or null if it has none. Flags do not get one on creation; create it with POST /api/projects/{project_id}/feature_flags/{id}/dashboard/.
+ * @nullable
+ */
+ readonly usage_dashboard: number | null
analytics_dashboards?: number[]
/** @nullable */
has_enriched_analytics?: boolean | null
@@ -538,7 +542,6 @@ export interface FeatureFlagApi {
*/
last_called_at?: string | null
_create_in_folder?: string
- _should_create_usage_dashboard?: boolean
/** Check if this feature flag is used in any team's session recording linked flag setting. */
readonly is_used_in_replay_settings: boolean
/** Whether this flag can back an experiment: multivariate with 2 to 20 variants. */
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 34a9efd23f2b..fbe4b114157a 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -767,14 +767,11 @@ export const getFeatureFlagsDashboardCreateUrl = (projectId: string, id: number)
export const featureFlagsDashboardCreate = async (
projectId: string,
id: number,
- featureFlagApi: NonReadonly<FeatureFlagApi>,
options?: RequestInit
): Promise<void> => {
return apiMutator<void>(getFeatureFlagsDashboardCreateUrl(projectId, id), {
...options,
method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(featureFlagApi),
})
}
@@ -808,14 +805,11 @@ export const getFeatureFlagsEnrichUsageDashboardCreateUrl = (projectId: string,
export const featureFlagsEnrichUsageDashboardCreate = async (
projectId: string,
id: number,
- featureFlagApi: NonReadonly<FeatureFlagApi>,
options?: RequestInit
): Promise<void> => {
return apiMutator<void>(getFeatureFlagsEnrichUsageDashboardCreateUrl(projectId, id), {
...options,
method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(featureFlagApi),
})
}
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index e7dc238b977e..277775e0e23b 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -516,7 +516,6 @@ export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({
export const featureFlagsUpdateBodyKeyMax = 400
export const featureFlagsUpdateBodyVersionDefault = 0
-export const featureFlagsUpdateBodyShouldCreateUsageDashboardDefault = true
export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod
.object({
@@ -588,7 +587,6 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod
.nullish()
.describe('Last time this feature flag was called (from $feature_flag_called events)'),
_create_in_folder: zod.string().optional(),
- _should_create_usage_dashboard: zod.boolean().default(featureFlagsUpdateBodyShouldCreateUsageDashboardDefault),
})
.describe('Serializer mixin that handles tags for objects.')
@@ -945,7 +943,6 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({
export const featureFlagsCreateStaticCohortForFlagCreateBodyKeyMax = 400
export const featureFlagsCreateStaticCohortForFlagCreateBodyVersionDefault = 0
-export const featureFlagsCreateStaticCohortForFlagCreateBodyShouldCreateUsageDashboardDefault = true
export const FeatureFlagsCreateStaticCohortForFlagCreateBody = /* @__PURE__ */ zod
.object({
@@ -1017,181 +1014,6 @@ export const FeatureFlagsCreateStaticCohortForFlagCreateBody = /* @__PURE__ */ z
.nullish()
.describe('Last time this feature flag was called (from $feature_flag_called events)'),
_create_in_folder: zod.string().optional(),
- _should_create_usage_dashboard: zod
- .boolean()
- .default(featureFlagsCreateStaticCohortForFlagCreateBodyShouldCreateUsageDashboardDefault),
- })
- .describe('Serializer mixin that handles tags for objects.')
-
-/**
- * Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
- *
- * If you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.
- */
-export const featureFlagsDashboardCreateBodyKeyMax = 400
-
-export const featureFlagsDashboardCreateBodyVersionDefault = 0
-export const featureFlagsDashboardCreateBodyShouldCreateUsageDashboardDefault = true
-
-export const FeatureFlagsDashboardCreateBody = /* @__PURE__ */ zod
- .object({
- name: zod
- .string()
- .optional()
- .describe('contains the description for the flag (field name `name` is kept for backwards-compatibility)'),
- key: zod.string().max(featureFlagsDashboardCreateBodyKeyMax),
- filters: zod.record(zod.string(), zod.unknown()).optional(),
- deleted: zod.boolean().optional(),
- active: zod.boolean().optional(),
- archived: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
- ),
- created_at: zod.iso.datetime({ offset: true }).optional(),
- version: zod.number().default(featureFlagsDashboardCreateBodyVersionDefault),
- ensure_experience_continuity: zod.boolean().nullish(),
- tags: zod.array(zod.unknown()).optional(),
- evaluation_contexts: zod.array(zod.unknown()).optional(),
- analytics_dashboards: zod.array(zod.number()).optional(),
- has_enriched_analytics: zod.boolean().nullish(),
- creation_context: zod
- .enum([
- 'feature_flags',
- 'experiments',
- 'surveys',
- 'early_access_features',
- 'web_experiments',
- 'product_tours',
- ])
- .describe(
- '\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours'
- )
- .optional()
- .describe(
- "Indicates the origin product of the feature flag. Choices: 'feature_flags', 'experiments', 'surveys', 'early_access_features', 'web_experiments', 'product_tours'.\n\n\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours"
- ),
- is_remote_configuration: zod.boolean().nullish(),
- has_encrypted_payloads: zod.boolean().nullish(),
- evaluation_runtime: zod
- .union([
- zod
- .enum(['server', 'client', 'all'])
- .describe('\* `server` - Server\n\* `client` - Client\n\* `all` - All'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Specifies where this feature flag should be evaluated\n\n\* `server` - Server\n\* `client` - Client\n\* `all` - All'
- ),
- bucketing_identifier: zod
- .union([
- zod
- .enum(['distinct_id', 'device_id'])
- .describe('\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Identifier used for bucketing users into rollout and variants\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'
- ),
- last_called_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Last time this feature flag was called (from $feature_flag_called events)'),
- _create_in_folder: zod.string().optional(),
- _should_create_usage_dashboard: zod
- .boolean()
- .default(featureFlagsDashboardCreateBodyShouldCreateUsageDashboardDefault),
- })
- .describe('Serializer mixin that handles tags for objects.')
-
-/**
- * Create, read, update and delete feature flags. [See docs](https://posthog.com/docs/feature-flags) for more information on feature flags.
- *
- * If you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.
- */
-export const featureFlagsEnrichUsageDashboardCreateBodyKeyMax = 400
-
-export const featureFlagsEnrichUsageDashboardCreateBodyVersionDefault = 0
-export const featureFlagsEnrichUsageDashboardCreateBodyShouldCreateUsageDashboardDefault = true
-
-export const FeatureFlagsEnrichUsageDashboardCreateBody = /* @__PURE__ */ zod
- .object({
- name: zod
- .string()
- .optional()
- .describe('contains the description for the flag (field name `name` is kept for backwards-compatibility)'),
- key: zod.string().max(featureFlagsEnrichUsageDashboardCreateBodyKeyMax),
- filters: zod.record(zod.string(), zod.unknown()).optional(),
- deleted: zod.boolean().optional(),
- active: zod.boolean().optional(),
- archived: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'
- ),
- created_at: zod.iso.datetime({ offset: true }).optional(),
- version: zod.number().default(featureFlagsEnrichUsageDashboardCreateBodyVersionDefault),
- ensure_experience_continuity: zod.boolean().nullish(),
- tags: zod.array(zod.unknown()).optional(),
- evaluation_contexts: zod.array(zod.unknown()).optional(),
- analytics_dashboards: zod.array(zod.number()).optional(),
- has_enriched_analytics: zod.boolean().nullish(),
- creation_context: zod
- .enum([
- 'feature_flags',
- 'experiments',
- 'surveys',
- 'early_access_features',
- 'web_experiments',
- 'product_tours',
- ])
- .describe(
- '\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours'
- )
- .optional()
- .describe(
- "Indicates the origin product of the feature flag. Choices: 'feature_flags', 'experiments', 'surveys', 'early_access_features', 'web_experiments', 'product_tours'.\n\n\* `feature_flags` - feature_flags\n\* `experiments` - experiments\n\* `surveys` - surveys\n\* `early_access_features` - early_access_features\n\* `web_experiments` - web_experiments\n\* `product_tours` - product_tours"
- ),
- is_remote_configuration: zod.boolean().nullish(),
- has_encrypted_payloads: zod.boolean().nullish(),
- evaluation_runtime: zod
- .union([
- zod
- .enum(['server', 'client', 'all'])
- .describe('\* `server` - Server\n\* `client` - Client\n\* `all` - All'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Specifies where this feature flag should be evaluated\n\n\* `server` - Server\n\* `client` - Client\n\* `all` - All'
- ),
- bucketing_identifier: zod
- .union([
- zod
- .enum(['distinct_id', 'device_id'])
- .describe('\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Identifier used for bucketing users into rollout and variants\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'
- ),
- last_called_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Last time this feature flag was called (from $feature_flag_called events)'),
- _create_in_folder: zod.string().optional(),
- _should_create_usage_dashboard: zod
- .boolean()
- .default(featureFlagsEnrichUsageDashboardCreateBodyShouldCreateUsageDashboardDefault),
})
.describe('Serializer mixin that handles tags for objects.')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 14ae4030a60e..12f1928f8c71 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34600,7 +34600,11 @@ export namespace Schemas {
readonly can_edit: boolean;
tags?: unknown[];
evaluation_contexts?: unknown[];
- readonly usage_dashboard: number;
+ /**
+ * Dashboard of saved usage insights for this flag, or null if it has none. Flags do not get one on creation; create it with POST /api/projects/{project_id}/feature_flags/{id}/dashboard/.
+ * @nullable
+ */
+ readonly usage_dashboard: number | null;
analytics_dashboards?: number[];
/** @nullable */
has_enriched_analytics?: boolean | null;
@@ -34640,7 +34644,6 @@ export namespace Schemas {
*/
last_called_at?: string | null;
_create_in_folder?: string;
- _should_create_usage_dashboard?: boolean;
/** Check if this feature flag is used in any team's session recording linked flag setting. */
readonly is_used_in_replay_settings: boolean;
/** Whether this flag can back an experiment: multivariate with 2 to 20 variants. */