:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(flags): extract bulk copy logic and reusable button component (#70914)
Phil Haack4e91c975c960
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.mdindex 50a2fcea12f0..d92cc3380e74 100644--- a/docs/internal/feature-flags/django-api-endpoints.md+++ b/docs/internal/feature-flags/django-api-endpoints.md@@ -68,6 +68,9 @@ Standard REST on `/api/projects/{id}/feature_flags/`. Hard `DELETE` is blocked| `GET` | `/api/organizations/{id}/feature_flags/{key}/` | Get a flag by key across all accessible teams || `POST` | `/api/organizations/{id}/feature_flags/copy_flags/` | Copy a flag from one project to target projects |+`copy_flags` requires editor access to `feature_flag` in each target project, not just visibility.+A caller who can see a project but can't edit flags there gets a `failed` entry for that target instead of a copy.+## Key actions in detail### `my_flags` and `evaluation_reasons`diff --git a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.ts b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.tsindex 82db972514f8..6fe28f23a730 100644--- a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.ts+++ b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.ts@@ -1,4 +1,4 @@-import { splitCopiedByOverwrite } from './BulkCopyFlagsModal'+import { splitCopiedByOverwrite } from './flagSelectionLogic'describe('splitCopiedByOverwrite', () => {it('returns no entries when nothing was copied', () => {diff --git a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsxindex 023dcb6dd4b0..00b9a13e95aa 100644--- a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx+++ b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'+import { useMemo } from 'react'-import { IconCheck, IconWarning, IconX } from '@posthog/icons'+import { IconCheck, IconCopy, IconWarning, IconX } from '@posthog/icons'import {LemonBanner,LemonButton,@@ -14,28 +15,32 @@ import {import { pluralize } from 'lib/utils/strings'import { organizationLogic } from 'scenes/organizationLogic'-import {- BULK_COPY_MAX_TARGET_PROJECTS,- BulkCopyFailure,- BulkCopyResult,- flagSelectionLogic,-} from './flagSelectionLogic'+import { BulkCopyFailure, flagSelectionLogic, getBulkCopyDisabledReason } from './flagSelectionLogic'-/** Splits each copied entry's projectIds into freshly created flags vs. overwrites of flags that already existed in the target. */-export function splitCopiedByOverwrite(copied: BulkCopyResult['copied']): {- newCopies: Array<{ key: string; projectIds: number[] }>- overwrites: Array<{ key: string; projectIds: number[] }>-} {- const newCopies = copied- .map((entry) => ({- key: entry.key,- projectIds: entry.projectIds.filter((id) => !entry.updatedProjectIds.includes(id)),- }))- .filter((entry) => entry.projectIds.length > 0)- const overwrites = copied- .map((entry) => ({ key: entry.key, projectIds: entry.updatedProjectIds }))- .filter((entry) => entry.projectIds.length > 0)- return { newCopies, overwrites }+/** "Copy to projects" bulk action button shared by the flags overview table and the projects grid. */+export function BulkCopyToProjectsButton({+ dataAttr,+ selectedCount,+ extraDisabledReason,+ onOpen,+}: {+ dataAttr: string+ selectedCount: number+ extraDisabledReason?: string | null+ onOpen: () => void+}): JSX.Element {+ return (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconCopy />}+ data-attr={dataAttr}+ disabledReason={getBulkCopyDisabledReason(selectedCount, extraDisabledReason)}+ onClick={onOpen}+ >+ Copy to projects+ </LemonButton>+ )}function CopiedFlagsList({@@ -97,6 +102,10 @@ export function BulkCopyFlagsModal(): JSX.Element | null {bulkCopyProgress,bulkCopyResult,bulkCopyFlagCount,+ bulkCopySplitCopied,+ bulkCopyPendingApproval: pendingApproval,+ bulkCopyHardFailures: hardFailures,+ bulkCopySubmitDisabledReason,} = useValues(flagSelectionLogic)const {closeBulkCopyModal,@@ -108,26 +117,31 @@ export function BulkCopyFlagsModal(): JSX.Element | null {} = useActions(flagSelectionLogic)const { currentOrganization } = useValues(organizationLogic)+ // Gate the sort on visibility (rather than skipping the hook) so it doesn't redo this work+ // on every render of the parent scene while the modal is closed.+ const teams = useMemo(+ () =>+ bulkCopyModalVisible+ ? [...(currentOrganization?.teams ?? [])].sort((a, b) => a.name.localeCompare(b.name))+ : [],+ [bulkCopyModalVisible, currentOrganization?.teams]+ )+ const teamNameById = useMemo(() => new Map(teams.map((team) => [team.id, team.name])), [teams])+ const destinationOptions = useMemo(+ () =>+ teams+ .filter((team) => team.id !== bulkCopySourceProjectId)+ .map((team) => ({ key: String(team.id), label: team.name, value: team.id })),+ [teams, bulkCopySourceProjectId]+ )+if (!bulkCopyModalVisible || !bulkCopyParams) {return null}- const teams = [...(currentOrganization?.teams ?? [])].sort((a, b) => a.name.localeCompare(b.name))- const teamNameById = new Map(teams.map((team) => [team.id, team.name]))- const destinationOptions = teams- .filter((team) => team.id !== bulkCopySourceProjectId)- .map((team) => ({ key: String(team.id), label: team.name, value: team.id }))-- const pendingApproval = bulkCopyResult?.failed.filter((failure) => failure.approvalPending) ?? []- const hardFailures = bulkCopyResult?.failed.filter((failure) => !failure.approvalPending) ?? []- const { newCopies, overwrites } = splitCopiedByOverwrite(bulkCopyResult?.copied ?? [])-- const submitDisabledReason =- bulkCopyTargetProjectIds.length === 0- ? 'Select at least one destination project'- : bulkCopyTargetProjectIds.length > BULK_COPY_MAX_TARGET_PROJECTS- ? `Bulk copy supports up to ${BULK_COPY_MAX_TARGET_PROJECTS} destination projects at once`- : undefined+ const { newCopies, overwrites } = bulkCopySplitCopied+ const progressText =+ bulkCopyRunning && bulkCopyProgress ? `Copying ${bulkCopyProgress.done} of ${bulkCopyProgress.total}` : nullreturn (<LemonModal@@ -157,17 +171,13 @@ export function BulkCopyFlagsModal(): JSX.Element | null {type="primary"onClick={bulkCopyFlags}loading={bulkCopyRunning}- disabledReason={submitDisabledReason}+ disabledReason={bulkCopySubmitDisabledReason}data-attr="bulk-copy-flags-submit">- {bulkCopyRunning && bulkCopyProgress- ? `Copying ${bulkCopyProgress.done} of ${bulkCopyProgress.total}…`- : 'Copy flags'}+ {progressText ? `${progressText}…` : 'Copy flags'}</LemonButton><span aria-live="polite" aria-atomic="true" className="sr-only">- {bulkCopyRunning && bulkCopyProgress- ? `Copying ${bulkCopyProgress.done} of ${bulkCopyProgress.total}`- : ''}+ {progressText ?? ''}</span></>)@@ -178,7 +188,7 @@ export function BulkCopyFlagsModal(): JSX.Element | null {{newCopies.length > 0 && (<div className="space-y-2"><div className="flex items-center gap-2 text-success font-medium">- <IconCheck className="text-lg" />+ <IconCheck className="text-lg" aria-hidden="true" /><span>Copied {pluralize(newCopies.length, 'new flag')}</span></div><CopiedFlagsList entries={newCopies} teamNameById={teamNameById} />@@ -187,7 +197,7 @@ export function BulkCopyFlagsModal(): JSX.Element | null {{overwrites.length > 0 && (<div className="space-y-2"><div className="flex items-center gap-2 text-warning font-medium">- <IconWarning className="text-lg" />+ <IconWarning className="text-lg" aria-hidden="true" /><span>Updated {pluralize(overwrites.length, 'existing flag')}</span></div><p className="text-sm text-muted pl-6 mb-0">@@ -200,7 +210,7 @@ export function BulkCopyFlagsModal(): JSX.Element | null {{pendingApproval.length > 0 && (<div className="space-y-2"><div className="flex items-center gap-2 text-warning font-medium">- <IconWarning className="text-lg" />+ <IconWarning className="text-lg" aria-hidden="true" /><span>{pluralize(pendingApproval.length, 'copy', 'copies')} pending approval<LemonTag type="warning" className="ml-2 uppercase">@@ -218,7 +228,7 @@ export function BulkCopyFlagsModal(): JSX.Element | null {{hardFailures.length > 0 && (<div className="space-y-2"><div className="flex items-center gap-2 text-danger font-medium">- <IconX className="text-lg" />+ <IconX className="text-lg" aria-hidden="true" /><span>{pluralize(hardFailures.length, 'copy', 'copies')} failed</span></div><FailureList failures={hardFailures} teamNameById={teamNameById} />diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsxindex b058bfb9953c..d93bc1335b5a 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { combineUrl, router } from 'kea-router'import { useEffect, useRef, useState } from 'react'-import { IconCopy, IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'+import { IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'import { LemonButton, LemonDialog, LemonTag, lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'@@ -58,13 +58,13 @@ import {} from '~/types'import { ApprovalsPromoBanner } from './ApprovalsPromoBanner'-import { BulkCopyFlagsModal } from './BulkCopyFlagsModal'+import { BulkCopyFlagsModal, BulkCopyToProjectsButton } from './BulkCopyFlagsModal'import { BulkDeleteResultsModal } from './BulkDeleteResultsModal'import { openFeatureFlagArchiveDialog } from './featureFlagArchiveDialog'import { openFeatureFlagDeleteDialog } from './featureFlagDeleteDialog'import { FeatureFlagFiltersSection } from './FeatureFlagFilters'import { FLAGS_PER_PAGE, FeatureFlagsTab, featureFlagsLogic, flagMatchesType } from './featureFlagsLogic'-import { BULK_COPY_MAX_FLAGS, flagSelectionLogic } from './flagSelectionLogic'+import { flagSelectionLogic } from './flagSelectionLogic'import { OverlayForNewFeatureFlagMenu } from './NewFeatureFlagMenu'import ProjectsGrid from './projects-grid/ProjectsGrid'@@ -675,19 +675,15 @@ export function OverviewTab({Select all {totalMatchingCount} matching flags</LemonButton>)}- <LemonButton- type="secondary"- size="small"- icon={<IconCopy />}- data-attr="bulk-copy-flags-button"- disabledReason={+ <BulkCopyToProjectsButton+ dataAttr="bulk-copy-flags-button"+ selectedCount={ctx.selectedCount}+ extraDisabledReason={(currentOrganization?.teams?.length ?? 0) <= 1? 'Your organization has only one project'- : ctx.selectedCount > BULK_COPY_MAX_FLAGS- ? `Bulk copy supports up to ${BULK_COPY_MAX_FLAGS} flags at once`- : undefined+ : undefined}- onClick={() => {+ onOpen={() => {if (currentProjectId) {openBulkCopyModal({sourceProjectId: currentProjectId,@@ -695,9 +691,7 @@ export function OverviewTab({})}}}- >- Copy to projects- </LemonButton>+ /><BulkUpdateTagsButtonresource="feature_flags"selectedIds={ctx.selectedKeys}diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.tsindex fa14cfc5635b..b1fead9dbfcc 100644--- a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts@@ -5,11 +5,14 @@ import { beforeUnload } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { pluralize } from 'lib/utils/strings'import { organizationLogic } from 'scenes/organizationLogic'import { projectLogic } from 'scenes/projectLogic'+import type { CopyFlagsResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'+import { featureFlagsLogic } from './featureFlagsLogic'import type { flagSelectionLogicType } from './flagSelectionLogicType'@@ -70,18 +73,25 @@ function summarizeBulkCopy(const pendingApprovalCount = failed.filter((failure) => failure.approvalPending).lengthconst hardFailureCount = failed.length - pendingApprovalCountconst updatedPairCount = copied.reduce((count, entry) => count + entry.updatedProjectIds.length, 0)+ // Omit the "Copied N flags" clause entirely when nothing copied, rather than showing a+ // contradictory "Copied 0 flags ... pending approval" message.const summary =- `Copied ${pluralize(copied.length, 'flag')} to ${pluralize(targetCount, 'project')}` +- (updatedPairCount > 0 ? ` (${pluralize(updatedPairCount, 'existing flag')} overwritten)` : '')+ copied.length > 0+ ? `Copied ${pluralize(copied.length, 'flag')} to ${pluralize(targetCount, 'project')}` ++ (updatedPairCount > 0 ? ` (${pluralize(updatedPairCount, 'existing flag')} overwritten)` : '')+ : nullif (failed.length === 0 && copied.length > 0) {- return { level: 'success', message: summary }+ return { level: 'success', message: summary as string }}if (copied.length > 0 || pendingApprovalCount > 0) {+ const parts = [+ summary,+ pendingApprovalCount > 0 ? `${pluralize(pendingApprovalCount, 'copy', 'copies')} pending approval` : null,+ hardFailureCount > 0 ? `${pluralize(hardFailureCount, 'copy', 'copies')} failed` : null,+ ].filter((part): part is string => part !== null)return {level: 'warning',- message: `${summary}${pendingApprovalCount > 0 ? `, ${pendingApprovalCount} pending approval` : ''}${- hardFailureCount > 0 ? `, ${hardFailureCount} failed` : ''- }`,+ message: parts.join(', '),}}return { level: 'error', message: 'No flags were copied' }@@ -91,17 +101,72 @@ function errorMessageFrom(error: unknown): string {if (typeof error === 'string') {return error}- if (error && typeof error === 'object') {- const { detail, message } = error as { detail?: unknown; message?: unknown }- if (typeof detail === 'string') {- return detail+ if (error instanceof ApiError) {+ return error.detail ?? error.message+ }+ return 'Request failed'+}++/** Turns one key's copy response into the copied/failed/warning entries the bulk-copy listener accumulates. */+function aggregateCopyResponse(+ key: string,+ targetProjectIds: number[],+ response: CopyFlagsResponseApi+): { copied: BulkCopyResult['copied'][number] | null; failed: BulkCopyFailure[]; warnings: string[] } {+ // Copied targets are inferred as requested-minus-failed (robust to success items+ // missing team_id during deploy skew); overwrites come from the per-item flag.+ const failedProjectIds = new Set(response.failed.map((entry) => entry.project_id))+ const copiedProjectIds = targetProjectIds.filter((id) => !failedProjectIds.has(id))+ const updatedProjectIds = response.success+ .filter((item) => item.updated_existing && item.team_id != null)+ .map((item) => item.team_id)+ const failed: BulkCopyFailure[] = response.failed.map((entry) => ({+ key,+ projectId: entry.project_id ?? null,+ errorMessage: errorMessageFrom(entry.error_message || 'Copy failed'),+ approvalPending: entry.approval_pending,+ }))+ const warnings: string[] = []+ for (const successItem of response.success) {+ for (const warning of successItem.flag_dependency_warnings ?? []) {+ warnings.push(`${key}: ${warning}`)}- if (typeof message === 'string') {- return message+ if (successItem.schedule_copy_warning) {+ warnings.push(`${key}: ${successItem.schedule_copy_warning}`)}- return JSON.stringify(error)}- return 'Request failed'+ return {+ copied: copiedProjectIds.length > 0 ? { key, projectIds: copiedProjectIds, updatedProjectIds } : null,+ failed,+ warnings,+ }+}++/** Splits each copied entry's projectIds into freshly created flags vs. overwrites of flags that already existed in the target. */+export function splitCopiedByOverwrite(copied: BulkCopyResult['copied']): {+ newCopies: Array<{ key: string; projectIds: number[] }>+ overwrites: Array<{ key: string; projectIds: number[] }>+} {+ const newCopies = copied+ .map((entry) => ({+ key: entry.key,+ projectIds: entry.projectIds.filter((id) => !entry.updatedProjectIds.includes(id)),+ }))+ .filter((entry) => entry.projectIds.length > 0)+ const overwrites = copied+ .map((entry) => ({ key: entry.key, projectIds: entry.updatedProjectIds }))+ .filter((entry) => entry.projectIds.length > 0)+ return { newCopies, overwrites }+}++export function getBulkCopyDisabledReason(selectedCount: number, extraReason?: string | null): string | undefined {+ if (extraReason) {+ return extraReason+ }+ if (selectedCount > BULK_COPY_MAX_FLAGS) {+ return `Bulk copy supports up to ${BULK_COPY_MAX_FLAGS} flags at once`+ }+ return undefined}export const flagSelectionLogic = kea<flagSelectionLogicType>([@@ -231,6 +296,29 @@ export const flagSelectionLogic = kea<flagSelectionLogicType>([(s) => [s.bulkCopyParams],(params: BulkCopyParams | null): number => params?.flagKeys?.length ?? params?.flagIds?.length ?? 0,],+ bulkCopySplitCopied: [+ (s) => [s.bulkCopyResult],+ (result: BulkCopyResult | null) => splitCopiedByOverwrite(result?.copied ?? []),+ ],+ bulkCopyPendingApproval: [+ (s) => [s.bulkCopyResult],+ (result: BulkCopyResult | null): BulkCopyFailure[] =>+ result?.failed.filter((failure) => failure.approvalPending) ?? [],+ ],+ bulkCopyHardFailures: [+ (s) => [s.bulkCopyResult],+ (result: BulkCopyResult | null): BulkCopyFailure[] =>+ result?.failed.filter((failure) => !failure.approvalPending) ?? [],+ ],+ bulkCopySubmitDisabledReason: [+ (s) => [s.bulkCopyTargetProjectIds],+ (targetProjectIds: number[]): string | undefined =>+ targetProjectIds.length === 0+ ? 'Select at least one destination project'+ : targetProjectIds.length > BULK_COPY_MAX_TARGET_PROJECTS+ ? `Bulk copy supports up to ${BULK_COPY_MAX_TARGET_PROJECTS} destination projects at once`+ : undefined,+ ],}),listeners(({ actions, values }) => ({@@ -292,33 +380,12 @@ export const flagSelectionLogic = kea<flagSelectionLogicType>([copy_schedule: values.bulkCopySchedule,disable_copied_flag: values.bulkCopyDisableCopiedFlag,})- const failedEntries = response.failed- // Copied targets are inferred as requested-minus-failed (robust to success items- // missing team_id during deploy skew); overwrites come from the per-item flag.- const failedProjectIds = new Set(failedEntries.map((entry) => entry.project_id))- const copiedProjectIds = targetProjectIds.filter((id) => !failedProjectIds.has(id))- const updatedProjectIds = response.success- .filter((item) => item.updated_existing && item.team_id != null)- .map((item) => item.team_id)- if (copiedProjectIds.length > 0) {- copied.push({ key, projectIds: copiedProjectIds, updatedProjectIds })- }- for (const entry of failedEntries) {- failed.push({- key,- projectId: entry.project_id ?? null,- errorMessage: errorMessageFrom(entry.error_message ?? 'Copy failed'),- approvalPending: entry.approval_pending,- })- }- for (const successItem of response.success) {- for (const warning of successItem.flag_dependency_warnings ?? []) {- warnings.add(`${key}: ${warning}`)- }- if (successItem.schedule_copy_warning) {- warnings.add(`${key}: ${successItem.schedule_copy_warning}`)- }+ const aggregated = aggregateCopyResponse(key, targetProjectIds, response)+ if (aggregated.copied) {+ copied.push(aggregated.copied)}+ failed.push(...aggregated.failed)+ aggregated.warnings.forEach((warning) => warnings.add(warning))} catch (error) {for (const projectId of targetProjectIds) {failed.push({ key, projectId, errorMessage: errorMessageFrom(error) })diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsxindex 3741ffeffb43..736dd833178e 100644--- a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx@@ -1,8 +1,7 @@import { useActions, useValues } from 'kea'import { useEffect, useMemo, useRef, useState } from 'react'-import { IconCopy } from '@posthog/icons'-import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'+import { LemonSkeleton } from '@posthog/lemon-ui'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'@@ -13,8 +12,8 @@ import { urls } from 'scenes/urls'import { SceneSection } from '~/layout/scenes/components/SceneSection'import { OrganizationFeatureFlag, OrganizationFeatureFlagRow } from '~/types'-import { BulkCopyFlagsModal } from '../BulkCopyFlagsModal'-import { BULK_COPY_MAX_FLAGS, flagSelectionLogic } from '../flagSelectionLogic'+import { BulkCopyFlagsModal, BulkCopyToProjectsButton } from '../BulkCopyFlagsModal'+import { flagSelectionLogic } from '../flagSelectionLogic'import { confirmFlagActiveToggleInProject, flagToggleKey } from '../updateFlagActiveInProject'import { CellState, ProjectsGridCell } from './ProjectsGridCell'import { projectsGridLogic } from './projectsGridLogic'@@ -184,26 +183,17 @@ export function ProjectsGrid(): JSX.Element {noun: ['flag', 'flags'],barPortalTarget: bulkBarTarget,renderActions: (ctx) => (- <LemonButton- type="secondary"- size="small"- icon={<IconCopy />}- data-attr="projects-grid-bulk-copy-button"- disabledReason={- ctx.selectedCount > BULK_COPY_MAX_FLAGS- ? `Bulk copy supports up to ${BULK_COPY_MAX_FLAGS} flags at once`- : undefined- }- onClick={() => {+ <BulkCopyToProjectsButton+ dataAttr="projects-grid-bulk-copy-button"+ selectedCount={ctx.selectedCount}+ onOpen={() =>openBulkCopyModal({sourceProjectId: currentTeamId,flagKeys: ctx.selectedKeys.map(String),sourceSelectable: true,})- }}- >- Copy to projects- </LemonButton>+ }+ />),}}/>