: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
feat(dashboards): copy tile groups between dashboards (#123177)
posthog[bot]c02ab89eb7c3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 018b57363256..36e0245620a6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7285,9 +7285,9 @@ snapshots:products-dashboards-tiles-tile-decorations--winner-with-group-title--light:hash: v1.k794b7964.7b86b194158108c532550809ba0e7708df82e3e8d4a16a6580dfe614465f196d.oZ1nrnPhkV45bWhAMbGzhCXOtaVPBzhX6dDs2k8x1Twproducts-dashboards-tiles-tile-group--long-title-in-narrow-scene--dark:- hash: v1.k794b7964.27638afc84fe3f23808339cda8d42c7e464411aad854363184e963f50a9e8986.0953slExphaNxMyTtkUtSNL5zeDWGAmuH1eVdua6IqA+ hash: v1.k794b7964.7520c13b8a344d6d667fac6f402e2418b65f07e8479c9ab7c5764b9908409b64.IqQ8q-w1XqU52kZ4cA8mei_LdAEcvGXHuODmviYTbPUproducts-dashboards-tiles-tile-group--long-title-in-narrow-scene--light:- hash: v1.k794b7964.e2516d3990cbce5642887f30e4c2fb5185203e189527684c2226936c5d8f9b7b.ZCRE43avr2zzsh5jn7IDs-xe1JwPcaIFoOk_nfhvLp4+ hash: v1.k794b7964.a12a7ea7501e57d64e33b9b2f2d8c3877af396a7fdd34492b9cf74c40604bd10.pThN8_C9JqaiQgLQAjHWnFb94JOknMJkqjDJByKiKOkproducts-dashboards-tiles-tile-group--styles--dark:hash: v1.k794b7964.be0395b6c09a3c0380edd0b5bb22cfe61482fa0c977f51b144dab5fdd77f6ce8.-KKnKUn0dUiBlAtuIOzPRIVfjImLj8UbTWHpPj1r6zYproducts-dashboards-tiles-tile-group--styles--light:diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsxindex f95ac1ed668e..343a9b5a6e05 100644--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx@@ -289,6 +289,7 @@ describe('DashboardItems', () => {refreshDashboardWidgets: jest.fn(),moveToDashboard: jest.fn(),copyToDashboard: jest.fn(),+ copyGroupToDashboard: jest.fn(),setTileOverride: jest.fn(),setDashboardMode: jest.fn(),moveTileToSection: mockMoveTileToSection,@@ -693,7 +694,10 @@ describe('DashboardItems', () => {const showBands = (overrides: Record<string, unknown> = {}, streamedTileIds: number[] = []): void => {const defaultValues = mockedUseValues.getMockImplementation()!mockedUseValues.mockImplementation((logic) => {- const values = { ...defaultValues(logic), ...(logic === dashboardLogic ? overrides : {}) }+ if (logic !== dashboardLogic) {+ return defaultValues(logic)+ }+ const values = { ...defaultValues(logic), ...overrides }const tiles = [...values.tiles,...streamedTileIds.map((id) => ({ id, insight: { id: 100 + id, short_id: `tile${id}` } })),@@ -704,26 +708,24 @@ describe('DashboardItems', () => {...streamedTileIds.map((id) => ({ i: String(id), x: 6, y: 0, w: 6, h: 5 })),],}- return logic === dashboardLogic- ? {- ...values,- tiles,- layouts,- tileGroupSections: [- {- kind: 'group',- key: 'group-plans',- groupKey: 'plans',- group: { title: 'Plans' },- tiles,- },- ],- tileGroupSectionLayouts: [layouts],- collapsedTileGroupKeys: [],- tileGroupMoveOptions: {},- ...overrides,- }- : values+ return {+ ...values,+ tiles,+ layouts,+ tileGroupSections: [+ {+ kind: 'group',+ key: 'group-plans',+ groupKey: 'plans',+ group: { title: 'Plans' },+ tiles,+ },+ ],+ tileGroupSectionLayouts: [layouts],+ collapsedTileGroupKeys: [],+ tileGroupMoveOptions: {},+ ...overrides,+ }})}@@ -750,6 +752,19 @@ describe('DashboardItems', () => {expect(mockUpdateContainerWidth).toHaveBeenCalledWith(1200, 12)})+ it.each([+ { layout: 'bands', overrides: {} },+ { layout: 'tabs', overrides: { activeTileGroupTab: 'plans' } },+ ])('shows group copy only to dashboard editors in $layout', ({ overrides }) => {+ showBands(overrides)+ const { container, rerender } = render(<DashboardItems />)+ expect(container.querySelector('[data-attr="dashboard-tile-group-menu"]')).toBeInTheDocument()++ canEditDashboard = false+ rerender(<DashboardItems />)+ expect(container.querySelector('[data-attr="dashboard-tile-group-menu"]')).not.toBeInTheDocument()+ })+it('keeps a band grid mounted when a tile streams into the band', () => {const defaultValues = mockedUseValues.getMockImplementation()!showBands()diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex 87178912ee08..a4612fc2d309 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -12,6 +12,7 @@ import { DashboardWidgetItem } from '@posthog/products-dashboards/frontend/compoimport { getDashboardWidgetFetchDisplayError } from '@posthog/products-dashboards/frontend/widgets/constants'import { ApiError } from 'lib/api'+import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'import { EditModeEdge, useResizeHandleScrollbarPassThrough } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'import { TileDecorations } from 'lib/components/TileDecorations/TileDecorations'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'@@ -116,6 +117,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPeffectiveBreakdownColors,dataColorThemeId,canEditDashboard,+ copyGroupToDashboardLoading,widgetResultsByTileId,widgetRefreshStatus,scrollToBottomSignal,@@ -140,6 +142,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPapplyWidgetIssueMetadataChange,moveToDashboard,copyToDashboard,+ copyGroupToDashboard,setDashboardEditing,toggleTileGroup,selectTileGroupTab,@@ -147,6 +150,11 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPmoveTileToSection,} = useActions(dashboardLogic)const { updateWidgetTile } = useAsyncActions(dashboardLogic)+ // dashboard_tiles is empty because this selector covers a whole group, not one tile; the+ // backend still rejects a destination that already has one of the group's tiles.+ const { copyToDestinations } = useValues(+ dashboardWidgetMenusLogic({ instanceKey: 'dashboard-groups', dashboardId: dashboard?.id, dashboard_tiles: [] })+ )const { push } = useActions(router)const { data: surveyLinkedInsights, loading: surveyLinkedInsightsLoading } = useSurveyLinkedInsights({// Dashboard pages hide the survey suggestion in compact headers; notebook embeds also use this component and can show it.@@ -257,6 +265,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst canEnterEditModeFromEdge =!!dashboard && canEditDashboard && !layoutEditMode && !isMobileView && isEditablePlacement+ const onCopyGroupToDashboard = canEditDashboard && isEditablePlacement ? copyGroupToDashboard : undefined+const isLayoutZoomToggled = layoutEditMode && layoutZoom !== 1const effectiveZoom = layoutEditMode ? layoutZoom : 1@@ -828,6 +838,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPisDropTarget={dropTargetKey === section.key}collapsedTileGroupKeys={collapsedTileGroupKeys}onToggleTileGroup={toggleTileGroup}+ copyToDestinations={copyToDestinations}+ onCopyGroupToDashboard={onCopyGroupToDashboard}+ copyLoading={copyGroupToDashboardLoading}>{renderSectionGrid(section, index)}</DashboardTileSectionBand>@@ -847,6 +860,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPsections={tileGroupSections}activeSectionKey={tileGroupSections[activeTabIndex].key}onSelect={selectTileGroupTab}+ copyToDestinations={copyToDestinations}+ onCopyGroupToDashboard={onCopyGroupToDashboard}+ copyLoading={copyGroupToDashboardLoading}>{renderSectionGrid(tileGroupSections[activeTabIndex], activeTabIndex)}</DashboardTileGroupTabs>diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 9742f3b7c474..d61540d9f175 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -9,6 +9,7 @@ import posthog from 'posthog-js'import type { Layout } from 'react-grid-layout'import { LemonDialog, lemonToast } from '@posthog/lemon-ui'+import * as dashboardGeneratedApi from '@posthog/products-dashboards/frontend/generated/api'import * as dashboardWidgetUtils from '@posthog/products-dashboards/frontend/utils'import { DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE } from '@posthog/products-dashboards/frontend/widgets/constants'@@ -6557,5 +6558,57 @@ describe('dashboardLogic', () => {tileId: WIDGET_TILE.id,})})++ it('copies a group once and records the completed action', async () => {+ const copyGroup = jest+ .spyOn(dashboardGeneratedApi, 'dashboardsCopyGroupCreate')+ .mockResolvedValueOnce(+ {} as Awaited<ReturnType<typeof dashboardGeneratedApi.dashboardsCopyGroupCreate>>+ )++ logic = dashboardLogic({ id: 5 })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const [firstTile, secondTile] = logic.values.tiles+ logic.actions.setTileProperty(firstTile.id, { group_key: 'plans' })+ logic.actions.setTileProperty(secondTile.id, { group_key: 'plans' })++ await expectLogic(logic, () => {+ logic.actions.copyGroupToDashboard('plans', 8, 'Target dashboard')+ })+ .toDispatchActions(['copyGroupToDashboardFinished'])+ .toFinishAllListeners()+ .toMatchValues({ copyGroupToDashboardLoading: false })++ expect(copyGroup).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 8, {+ fromDashboardId: 5,+ groupKey: 'plans',+ })+ expect(posthog.capture).toHaveBeenCalledWith('dashboard tile group copied to other dashboard', {+ from_dashboard_id: 5,+ to_dashboard_id: 8,+ tile_count: 2,+ })+ })++ it('resets loading and shows an error toast when the copy fails', async () => {+ jest.spyOn(dashboardGeneratedApi, 'dashboardsCopyGroupCreate').mockRejectedValueOnce(+ new Error('network down')+ )+ const errorToast = jest.spyOn(lemonToast, 'error')++ logic = dashboardLogic({ id: 5 })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.copyGroupToDashboard('plans', 8, 'Target dashboard')+ })+ .toDispatchActions(['copyGroupToDashboardFinished'])+ .toFinishAllListeners()+ .toMatchValues({ copyGroupToDashboardLoading: false })++ expect(errorToast).toHaveBeenCalledWith(expect.stringContaining('Could not copy group to dashboard'))+ })})})diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 1818e541e9af..6b4c6e194426 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -25,6 +25,7 @@ import { ResponsiveLayouts } from 'react-grid-layout'import type { Layout } from 'react-grid-layout'import { LemonButton, LemonDialog, lemonToast } from '@posthog/lemon-ui'+import { dashboardsCopyGroupCreate } from '@posthog/products-dashboards/frontend/generated/api'import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'import { isWidgetConfigValidationError, updateDashboardWidgetTile } from '@posthog/products-dashboards/frontend/utils'import { DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE } from '@posthog/products-dashboards/frontend/widgets/constants'@@ -697,6 +698,7 @@ export interface dashboardLogicValues {collapsedTileIds: Set<number>columns: number | nullcontainerWidth: number | null+ copyGroupToDashboardLoading: booleancurrentDashboardSettings: DashboardSettingscurrentDashboardVariables: Record<string, HogQLVariable>currentLayoutSize: 'sm' | 'xs'@@ -905,6 +907,18 @@ export interface dashboardLogicActions {closeTileModal: () => {value: true}+ copyGroupToDashboard: (+ groupKey: string,+ toDashboard: number,+ toDashboardName: string+ ) => {+ groupKey: string+ toDashboard: number+ toDashboardName: string+ }+ copyGroupToDashboardFinished: () => {+ value: true+ }copyToDashboard: (tile: DashboardTile,fromDashboard: number,@@ -2185,6 +2199,12 @@ export const dashboardLogic = kea<dashboardLogicType>([toDashboard,toDashboardName,}),+ copyGroupToDashboard: (groupKey: string, toDashboard: number, toDashboardName: string) => ({+ groupKey,+ toDashboard,+ toDashboardName,+ }),+ copyGroupToDashboardFinished: true,setTextTileId: (textTileId: DashboardTileIdOrNew) => ({ textTileId }),setButtonTileId: (buttonTileId: DashboardTileIdOrNew) => ({ buttonTileId }),openAddInsightModal: true,@@ -2659,6 +2679,13 @@ export const dashboardLogic = kea<dashboardLogicType>([],})),reducers(({ props }) => ({+ copyGroupToDashboardLoading: [+ false,+ {+ copyGroupToDashboard: () => true,+ copyGroupToDashboardFinished: () => false,+ },+ ],dashboardLoading: [false,{@@ -4485,6 +4512,28 @@ export const dashboardLogic = kea<dashboardLogicType>([},})),listeners(({ actions, values, cache, props, sharedListeners }) => ({+ copyGroupToDashboard: async ({ groupKey, toDashboard, toDashboardName }) => {+ try {+ await dashboardsCopyGroupCreate(String(teamLogic.values.currentTeamId), toDashboard, {+ fromDashboardId: props.id,+ groupKey,+ })+ posthog.capture('dashboard tile group copied to other dashboard', {+ from_dashboard_id: props.id,+ to_dashboard_id: toDashboard,+ tile_count: values.tiles.filter((tile) => tile.group_key === groupKey).length,+ })+ lemonToast.success(+ <>+ Group copied to <Link to={urls.dashboard(toDashboard)}>{toDashboardName}</Link>+ </>+ )+ } catch (error) {+ lemonToast.error(`Could not copy group to dashboard: ${String(error)}`)+ } finally {+ actions.copyGroupToDashboardFinished()+ }+ },revealHighlightedInsight: () => {const insightId = values.highlightedInsightIdconst tile = values.tiles.find((tile) => insightId && tile.insight?.short_id === insightId)diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 21128c48a868..c5af91445e74 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -143,6 +143,7 @@ from products.dashboards.backend.api.widget_openapi_serializers import ()from products.dashboards.backend.constants import (DASHBOARD_GRID_COLUMN_COUNT,+ MAX_GROUP_KEY_LENGTH,MAX_GROUP_TITLE_LENGTH,MAX_GROUPS,MAX_TEXT_TILE_AGENT_CONTEXT_LENGTH,@@ -153,6 +154,7 @@ from products.dashboards.backend.constants import ()from products.dashboards.backend.customization import (normalize_dashboard_customization,+ normalized_group_key,stored_customization,stored_groups,validate_template_groups,@@ -646,6 +648,11 @@ class CopyDashboardTileRequestSerializer(serializers.Serializer):tileId = serializers.IntegerField(help_text="Dashboard tile id to copy.")+class CopyDashboardGroupRequestSerializer(serializers.Serializer):+ fromDashboardId = serializers.IntegerField(help_text="Dashboard id the group currently belongs to.")+ groupKey = serializers.CharField(max_length=MAX_GROUP_KEY_LENGTH, help_text="Key of the tile group to copy.")++class TileLayoutBoxSerializer(serializers.Serializer):x = serializers.IntegerField(required=False, help_text="Column position in the dashboard grid (0-indexed).")y = serializers.IntegerField(required=False, help_text="Row position in the dashboard grid (0-indexed).")@@ -3574,6 +3581,116 @@ class DashboardsViewSet().data)+ def _copy_group_tiles(self, request: Request, destination: Dashboard, source_id: int, group_key: str) -> None:+ if source_id == destination.pk:+ raise exceptions.ValidationError("Destination must be a different dashboard than the source.")++ source = get_object_or_404(Dashboard, id=source_id, team__project_id=self.team.project_id, deleted=False)+ access = UserAccessControl(user=cast(User, request.user), team=self.team)+ if not access.check_access_level_for_object(source, "viewer"):+ raise exceptions.PermissionDenied("You don't have permission to view the source dashboard.")+ tiles = list(+ DashboardTile.objects.filter(dashboard=source, group_key=group_key).select_related("insight", "widget")+ )+ if not tiles:+ raise exceptions.NotFound("Tile group not found.")++ new_key = uuid.uuid4().hex+ for tile in tiles:+ if tile.widget_id:+ if tile.widget is None:+ raise exceptions.ValidationError("Widget tile is missing its widget.")+ DashboardSerializer._check_widget_tile_product_access(tile.widget, access)+ elif tile.insight_id:+ insight = tile.insight+ if insight is None:+ raise exceptions.ValidationError("Insight tile is missing its insight.")+ if not access.check_access_level_for_object(insight, "viewer"):+ raise exceptions.PermissionDenied("You don't have permission to view an insight in this group.")+ if DashboardTile.objects.filter(dashboard=destination, insight_id=tile.insight_id).exists():+ raise exceptions.ValidationError(+ "An insight in this group is already on the destination dashboard."+ )+ check_can_add_insight_to_dashboard(cast(User, request.user), destination, insight.query, access)+ elif tile.text_id:+ if DashboardTile.objects.filter(dashboard=destination, text_id=tile.text_id).exists():+ raise exceptions.ValidationError(+ "A text card in this group is already on the destination dashboard."+ )+ elif tile.button_tile_id:+ if DashboardTile.objects.filter(dashboard=destination, button_tile_id=tile.button_tile_id).exists():+ raise exceptions.ValidationError("A button in this group is already on the destination dashboard.")+ else:+ raise exceptions.ValidationError("This group contains an empty tile.")++ source_tops = {+ size: min(tile.layouts[size].get("y", 0) for tile in tiles if size in tile.layouts)+ for size in ("sm", "xs")+ if any(size in tile.layouts for tile in tiles)+ }+ try:+ with transaction.atomic():+ # Without this lock, two copies into the same dashboard would overwrite each other's groups.+ try:+ destination.refresh_from_db(+ fields=["customization"], from_queryset=Dashboard.objects.select_for_update(no_key=True)+ )+ except Dashboard.DoesNotExist:+ raise exceptions.NotFound()+ groups = stored_groups(destination.customization)+ if len(groups) >= MAX_GROUPS:+ raise exceptions.ValidationError({"groups": f"A dashboard can have at most {MAX_GROUPS} groups."})+ destination_tiles = list(DashboardTile.objects.filter(dashboard=destination).only("layouts"))+ destination_bottoms = {+ size: max(+ (+ tile.layouts[size].get("y", 0) + tile.layouts[size].get("h", 0)+ for tile in destination_tiles+ if size in tile.layouts+ ),+ default=0,+ )+ for size in source_tops+ }+ for tile in tiles:+ if tile.widget_id:+ copied = DashboardSerializer._clone_widget_tile_to_dashboard(+ tile, destination, cast(User, request.user), keep_group_key=False+ )+ copied.group_key = new_key+ else:+ copied = tile.copy_to_dashboard(destination, keep_group_key=False)+ copied.group_key = new_key+ copied.layouts = {+ size: {**layout, "y": layout.get("y", 0) - source_tops[size] + destination_bottoms[size]}+ if size in source_tops+ else layout+ for size, layout in tile.layouts.items()+ }+ copied.save(update_fields=["group_key", "layouts"])+ groups[new_key] = stored_groups(source.customization).get(group_key, {})+ destination.customization = _with_groups(+ normalize_dashboard_customization(destination.customization), groups+ )+ destination.save(update_fields=["customization"])+ except (DjangoValidationError, IntegrityError):+ raise exceptions.ValidationError("Unable to copy this group to the destination dashboard.")++ @extend_schema(request=CopyDashboardGroupRequestSerializer, responses={200: DashboardSerializer})+ @action(methods=["POST"], detail=True, required_scopes=["dashboard:write"])+ def copy_group(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Copy a group of tiles and its settings to another dashboard."""+ destination = self.get_object()+ if destination.deleted:+ raise exceptions.NotFound()+ serializer = CopyDashboardGroupRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ source_id = serializer.validated_data["fromDashboardId"]+ group_key = normalized_group_key(serializer.validated_data["groupKey"])+ self._copy_group_tiles(request, destination, source_id, group_key)++ return Response(DashboardSerializer(destination, context=self.get_serializer_context()).data)+@extend_schema(request=ReorderTilesRequestSerializer, responses={200: DashboardSerializer})@action(methods=["POST"], detail=True, required_scopes=["dashboard:write"])def reorder_tiles(self, request: Request, *args: Any, **kwargs: Any) -> Response:diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.pyindex 1be89001832f..90e29076f58c 100644--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py@@ -18,8 +18,8 @@ from posthog.models.team import Teamfrom posthog.scopes import APIScopeObjectfrom products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl-from products.dashboards.backend.api.dashboard import DashboardTileSerializer-from products.dashboards.backend.constants import DEFAULT_WIDGET_LIST_LIMIT+from products.dashboards.backend.api.dashboard import DashboardsViewSet, DashboardTileSerializer+from products.dashboards.backend.constants import DEFAULT_WIDGET_LIST_LIMIT, MAX_GROUPSfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_templates import DashboardTemplatefrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -500,6 +500,258 @@ class TestDashboardWidgets(APIBaseTest):assert source_dashboard["tiles"][0]["group_key"] == "plans"assert (dest_dashboard["tiles"][0]["group_key"], dest_dashboard["tiles"][0]["badge"]) == (None, "winner")+ @override_settings(IN_UNIT_TESTING=True)+ def test_copy_group_copies_tiles_settings_and_relative_layout(self) -> None:+ source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})+ dest_id, _ = self.dashboard_api.create_dashboard({"name": "dest"})+ self.dashboard_api.create_text_tile(+ dest_id,+ extra_data={"layouts": {"sm": {"x": 0, "y": 0, "w": 6, "h": 3}, "xs": {"x": 0, "y": 0, "w": 1, "h": 2}}},+ )+ _, source = self.dashboard_api.create_widget_tile(source_id)+ widget_id = source["tiles"][0]["id"]+ _, source = self.dashboard_api.create_text_tile(source_id)+ text_id = next(tile["id"] for tile in source["tiles"] if tile["text"])+ insight_id, _ = self.dashboard_api.create_insight({"name": "Activation"})+ self.dashboard_api.add_insight_to_dashboard([source_id], insight_id)+ source = self.dashboard_api.get_dashboard(source_id)+ insight_tile_id = next(tile["id"] for tile in source["tiles"] if tile["insight"])+ self.dashboard_api.update_dashboard(+ source_id,+ {+ "groups": {"plans": {"title": "Plans", "color": "green", "collapsed": True}},+ "tiles": [+ {+ "id": widget_id,+ "group_key": "plans",+ "layouts": {"sm": {"x": 0, "y": 4, "w": 6, "h": 3}, "xs": {"x": 0, "y": 7, "w": 1, "h": 2}},+ },+ {+ "id": text_id,+ "group_key": "plans",+ "layouts": {"sm": {"x": 6, "y": 5, "w": 6, "h": 2}, "xs": {"x": 0, "y": 9, "w": 1, "h": 2}},+ },+ {+ "id": insight_tile_id,+ "group_key": "plans",+ "layouts": {"sm": {"x": 0, "y": 6, "w": 6, "h": 2}, "xs": {"x": 0, "y": 11, "w": 1, "h": 2}},+ },+ ],+ },+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_group",+ {"fromDashboardId": source_id, "groupKey": "plans"},+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ copied = [tile for tile in response.json()["tiles"] if tile["group_key"]]+ assert len(copied) == 3+ new_key = copied[0]["group_key"]+ assert new_key != "plans"+ assert all(tile["group_key"] == new_key for tile in copied)+ assert next(tile["insight"]["id"] for tile in copied if tile["insight"]) == insight_id+ assert next(tile["widget"]["id"] for tile in copied if tile["widget"]) != next(+ tile["widget"]["id"] for tile in source["tiles"] if tile["widget"]+ )+ assert response.json()["customization"]["groups"][new_key] == {+ "title": "Plans",+ "color": "green",+ "collapsed": True,+ }+ assert sorted(tile["layouts"]["sm"]["y"] for tile in copied) == [3, 4, 5]+ assert sorted(tile["layouts"]["xs"]["y"] for tile in copied) == [2, 4, 6]+ assert self.dashboard_api.get_dashboard(source_id)["customization"]["groups"]["plans"]["title"] == "Plans"++ def test_copy_group_rejects_existing_tile_without_partial_copy(self) -> None:+ source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})+ dest_id, _ = self.dashboard_api.create_dashboard({"name": "dest"})+ _, source = self.dashboard_api.create_text_tile(source_id, extra_data={"group_key": "plans"})+ self.dashboard_api.create_text_tile(dest_id, text="I AM TEXT!")+ source_tile = source["tiles"][0]+ self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_tile",+ {"fromDashboardId": source_id, "tileId": source_tile["id"]},+ )+ before = self.dashboard_api.get_dashboard(dest_id)++ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_group",+ {"fromDashboardId": source_id, "groupKey": "plans"},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert self.dashboard_api.get_dashboard(dest_id)["tiles"] == before["tiles"]++ def test_copy_group_rejects_same_dashboard_as_source(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})+ self.dashboard_api.create_text_tile(dashboard_id, extra_data={"group_key": "plans"})++ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/copy_group",+ {"fromDashboardId": dashboard_id, "groupKey": "plans"},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand(+ [+ ("source_dashboard", True, False),+ ("insight_in_group", False, True),+ ]+ )+ def test_copy_group_denies_without_viewer_access(+ self, _name: str, deny_source_dashboard: bool, deny_insight: bool+ ) -> None:+ source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})+ dest_id, _ = self.dashboard_api.create_dashboard({"name": "dest"})+ insight_id, _ = self.dashboard_api.create_insight({"name": "Activation"})+ self.dashboard_api.add_insight_to_dashboard([source_id], insight_id)+ source = self.dashboard_api.get_dashboard(source_id)+ insight_tile_id = next(tile["id"] for tile in source["tiles"] if tile["insight"])+ self.dashboard_api.update_dashboard(source_id, {"tiles": [{"id": insight_tile_id, "group_key": "plans"}]})++ real_check = UserAccessControl.check_access_level_for_object++ def deny_selectively(+ user_access_control: UserAccessControl,+ obj: Dashboard | Insight,+ required_level: AccessControlLevel,+ explicit: bool = False,+ ) -> bool:+ if deny_source_dashboard and isinstance(obj, Dashboard) and obj.pk == source_id:+ return False+ if deny_insight and isinstance(obj, Insight) and obj.pk == insight_id:+ return False+ return real_check(user_access_control, obj, required_level, explicit=explicit)++ with patch.object(+ UserAccessControl, "check_access_level_for_object", autospec=True, side_effect=deny_selectively+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_group",+ {"fromDashboardId": source_id, "groupKey": "plans"},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand(+ [+ ("duplicate_insight_tile", status.HTTP_400_BAD_REQUEST),+ ("widget_tile_denied_product_access", status.HTTP_403_FORBIDDEN),+ ]+ )+ @override_settings(IN_UNIT_TESTING=True)+ def test_copy_group_rolls_back_whole_group_on_validation_failure(+ self, failure_mode: str, expected_status: int+ ) -> None:+ source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})+ dest_id, _ = self.dashboard_api.create_dashboard({"name": "dest"})+ _, source = self.dashboard_api.create_widget_tile(source_id)+ widget_tile_id = source["tiles"][0]["id"]+ _, source = self.dashboard_api.create_text_tile(source_id)+ text_tile_id = next(tile["id"] for tile in source["tiles"] if tile["text"])+ insight_id, _ = self.dashboard_api.create_insight({"name": "Activation"})+ self.dashboard_api.add_insight_to_dashboard([source_id], insight_id)+ source = self.dashboard_api.get_dashboard(source_id)+ insight_tile_id = next(tile["id"] for tile in source["tiles"] if tile["insight"])+ self.dashboard_api.update_dashboard(+ source_id,+ {+ "tiles": [+ {"id": widget_tile_id, "group_key": "plans"},+ {"id": text_tile_id, "group_key": "plans"},+ {"id": insight_tile_id, "group_key": "plans"},+ ],+ },+ )++ if failure_mode == "duplicate_insight_tile":+ self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_tile",+ {"fromDashboardId": source_id, "tileId": insight_tile_id},+ )++ before = self.dashboard_api.get_dashboard(dest_id)["tiles"]++ real_check = UserAccessControl.check_access_level_for_resource++ def deny_error_tracking_only(+ user_access_control: UserAccessControl,+ resource: APIScopeObject,+ required_level: AccessControlLevel = "viewer",+ ) -> bool:+ if failure_mode == "widget_tile_denied_product_access" and resource == "error_tracking":+ return False+ return real_check(user_access_control, resource, required_level)++ with patch.object(+ UserAccessControl, "check_access_level_for_resource", autospec=True, side_effect=deny_error_tracking_only+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_group",+ {"fromDashboardId": source_id, "groupKey": "plans"},+ )++ assert response.status_code == expected_status+ assert self.dashboard_api.get_dashboard(dest_id)["tiles"] == before++ @parameterized.expand(+ [+ ("below_limit", MAX_GROUPS - 1, status.HTTP_200_OK),+ ("at_limit", MAX_GROUPS, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_copy_group_enforces_max_groups_on_destination(+ self, _name: str, existing_group_count: int, expected_status: int+ ) -> None:+ source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})+ dest_id, _ = self.dashboard_api.create_dashboard({"name": "dest"})+ self.dashboard_api.create_text_tile(source_id, extra_data={"group_key": "plans"})+ Dashboard.objects.filter(id=dest_id).update(+ customization={"groups": {f"group-{i}": {"title": f"group {i}"} for i in range(existing_group_count)}}+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_group",+ {"fromDashboardId": source_id, "groupKey": "plans"},+ )++ assert response.status_code == expected_status++ @parameterized.expand(+ [+ ("keeps_concurrent_group", 1, status.HTTP_200_OK),+ ("counts_concurrent_groups_against_limit", MAX_GROUPS, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_copy_group_reads_destination_groups_written_after_the_request_loaded_it(+ self, _name: str, concurrent_group_count: int, expected_status: int+ ) -> None:+ source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})+ dest_id, _ = self.dashboard_api.create_dashboard({"name": "dest"})+ self.dashboard_api.create_text_tile(source_id, extra_data={"group_key": "plans"})+ concurrent_groups = {f"group-{i}": {"title": f"group {i}"} for i in range(concurrent_group_count)}+ load_destination = DashboardsViewSet.get_object++ def load_destination_then_write_groups_concurrently(viewset: DashboardsViewSet) -> Dashboard:+ destination = load_destination(viewset)+ Dashboard.objects.filter(id=destination.id).update(customization={"groups": concurrent_groups})+ return destination++ with (+ patch.object(DashboardsViewSet, "get_object", load_destination_then_write_groups_concurrently),+ CaptureQueriesContext(connection) as queries,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dest_id}/copy_group",+ {"fromDashboardId": source_id, "groupKey": "plans"},+ )++ assert response.status_code == expected_status+ assert any("FOR NO KEY UPDATE" in query["sql"] for query in queries.captured_queries)+ stored_group_keys = set(Dashboard.objects.get(id=dest_id).customization["groups"])+ assert set(concurrent_groups) <= stored_group_keys+ assert len(stored_group_keys) == concurrent_group_count + (expected_status == status.HTTP_200_OK)+@override_settings(IN_UNIT_TESTING=True)def test_move_tile_moves_widget_tile(self) -> None:source_id, _ = self.dashboard_api.create_dashboard({"name": "source"})diff --git a/products/dashboards/backend/models/dashboard_tile.py b/products/dashboards/backend/models/dashboard_tile.pyindex a8111f868e4b..6da8e2808700 100644--- a/products/dashboards/backend/models/dashboard_tile.py+++ b/products/dashboards/backend/models/dashboard_tile.py@@ -227,7 +227,7 @@ class DashboardTile(models.Model):raise ValidationError("This content is already on the destination dashboard.")stale.delete()- def copy_to_dashboard(self, dashboard: Dashboard, *, keep_group_key: bool = True) -> None:+ def copy_to_dashboard(self, dashboard: Dashboard, *, keep_group_key: bool = True) -> "DashboardTile":"""Place this tile's content on another dashboard: create a new row, or undelete a soft-deletedrow for the same insight, text, or button (unique constraint would block a second insert otherwise).@@ -275,9 +275,9 @@ class DashboardTile(models.Model):existing.badge = self.badgeexisting.filters_overrides = self.filters_overridesexisting.save()- return+ return existing- DashboardTile.objects.create(+ return DashboardTile.objects.create(dashboard=dashboard,team_id=dashboard.team_id,insight=self.insight,diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsxindex 9a0116e2ff06..637e34a175e1 100644--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsx+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsx@@ -1,5 +1,7 @@import type { Meta, StoryObj } from '@storybook/react'+import type { DashboardBasicType } from '~/types'+import type { DashboardTileGroupApi } from '../../generated/api.schemas'import { DashboardTileGroup } from './DashboardTileGroup'@@ -33,6 +35,8 @@ export const LongTitleInNarrowScene: StoryObj = {tileCount={12}collapsedonToggle={() => {}}+ copyToDestinations={[{ dashboard: { id: 42, name: 'Example dashboard' } as DashboardBasicType }]}+ onCopyToDashboard={() => {}}><FakeTile /></DashboardTileGroup>diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsxindex 2e4a6bd9c5d6..71cfe15fad89 100644--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx@@ -2,10 +2,12 @@ import clsx from 'clsx'import { IconChevronRight } from '@posthog/icons'+import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { pluralize } from 'lib/utils/strings'import type { DashboardTileGroupApi } from '../../generated/api.schemas'+import { DashboardTileGroupCopyMenu } from './DashboardTileGroupCopyMenu'import { TileGroupColorDot } from './TileGroupColorDot'interface DashboardTileGroupProps {@@ -13,6 +15,9 @@ interface DashboardTileGroupProps {tileCount: numbercollapsed: booleanonToggle: () => void+ copyToDestinations?: DashboardWidgetPlacementDestination[]+ onCopyToDashboard?: (dashboardId: number, dashboardName: string) => void+ copyLoading?: booleanchildren: React.ReactNode}@@ -21,6 +26,9 @@ export function DashboardTileGroup({tileCount,collapsed,onToggle,+ copyToDestinations,+ onCopyToDashboard,+ copyLoading,children,}: DashboardTileGroupProps): JSX.Element {const tileCountLabel = pluralize(tileCount, 'tile')@@ -51,6 +59,14 @@ export function DashboardTileGroup({</LemonButton>{group.title && collapsed && <span className="shrink-0 text-secondary text-xs">{tileCountLabel}</span>}<div className="min-w-4 flex-1 border-t border-primary" />+ {onCopyToDashboard && (+ <DashboardTileGroupCopyMenu+ label="Copy group to dashboard"+ destinations={copyToDestinations ?? []}+ onCopyToDashboard={onCopyToDashboard}+ loading={copyLoading}+ />+ )}</div>{!collapsed && children}</section>diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupCopyMenu.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupCopyMenu.tsxnew file mode 100644index 000000000000..e85fb58dfd65--- /dev/null+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupCopyMenu.tsx@@ -0,0 +1,42 @@+import { useActions } from 'kea'++import { DashboardWidgetPlacementMenu } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'+import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'+import { More } from 'lib/lemon-ui/LemonButton/More'++import { dashboardsModel } from '~/models/dashboardsModel'++interface DashboardTileGroupCopyMenuProps {+ label: string+ destinations: DashboardWidgetPlacementDestination[]+ onCopyToDashboard: (dashboardId: number, dashboardName: string) => void+ loading?: boolean+}++export function DashboardTileGroupCopyMenu({+ label,+ destinations,+ onCopyToDashboard,+ loading,+}: DashboardTileGroupCopyMenuProps): JSX.Element {+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)++ return (+ <More+ data-attr="dashboard-tile-group-menu"+ tooltip="Group actions"+ loading={loading}+ disabledReason={loading ? 'Copying group' : undefined}+ dropdown={{ onVisibilityChange: (visible) => visible && loadDashboardsIfNeeded() }}+ overlay={+ <div className="min-w-48 p-1">+ <DashboardWidgetPlacementMenu+ label={label}+ destinations={destinations}+ onSelect={({ id, name }) => onCopyToDashboard(id, name || 'Untitled')}+ />+ </div>+ }+ />+ )+}diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsxindex 31637137cdee..e5001b1b0374 100644--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx@@ -1,12 +1,17 @@+import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { type DashboardSection, getTileGroupLabel } from '../../dashboardTileSections'+import { DashboardTileGroupCopyMenu } from './DashboardTileGroupCopyMenu'import { TileGroupColorDot } from './TileGroupColorDot'interface DashboardTileGroupTabsProps {sections: DashboardSection[]activeSectionKey: stringonSelect: (sectionKey: string) => void+ copyToDestinations?: DashboardWidgetPlacementDestination[]+ onCopyGroupToDashboard?: (groupKey: string, dashboardId: number, dashboardName: string) => void+ copyLoading?: booleanchildren: React.ReactNode}@@ -14,8 +19,13 @@ export function DashboardTileGroupTabs({sections,activeSectionKey,onSelect,+ copyToDestinations,+ onCopyGroupToDashboard,+ copyLoading,children,}: DashboardTileGroupTabsProps): JSX.Element {+ const activeSection = sections.find((section) => section.key === activeSectionKey)+return (<section data-attr="dashboard-tile-group-tabs"><LemonTabs@@ -33,6 +43,19 @@ export function DashboardTileGroupTabs({'Overview'),}))}+ rightSlot={+ activeSection?.kind === 'group' &&+ onCopyGroupToDashboard && (+ <DashboardTileGroupCopyMenu+ label="Copy tab to dashboard"+ destinations={copyToDestinations ?? []}+ onCopyToDashboard={(dashboardId, dashboardName) =>+ onCopyGroupToDashboard(activeSection.groupKey, dashboardId, dashboardName)+ }+ loading={copyLoading}+ />+ )+ }/>{children}</section>diff --git a/products/dashboards/frontend/components/DashboardTileSectionBand.tsx b/products/dashboards/frontend/components/DashboardTileSectionBand.tsxindex 971d985f88b7..02315657c6f8 100644--- a/products/dashboards/frontend/components/DashboardTileSectionBand.tsx+++ b/products/dashboards/frontend/components/DashboardTileSectionBand.tsx@@ -1,5 +1,6 @@import clsx from 'clsx'+import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import type { DashboardSection } from '../dashboardTileSections'@@ -11,6 +12,9 @@ interface DashboardTileSectionBandProps {isDropTarget: booleancollapsedTileGroupKeys: string[]onToggleTileGroup: (groupKey: string) => void+ copyToDestinations?: DashboardWidgetPlacementDestination[]+ onCopyGroupToDashboard?: (groupKey: string, dashboardId: number, dashboardName: string) => void+ copyLoading?: booleanchildren: React.ReactNode}@@ -20,6 +24,9 @@ export function DashboardTileSectionBand({isDropTarget,collapsedTileGroupKeys,onToggleTileGroup,+ copyToDestinations,+ onCopyGroupToDashboard,+ copyLoading,children,}: DashboardTileSectionBandProps): JSX.Element {return (@@ -36,6 +43,14 @@ export function DashboardTileSectionBand({tileCount={section.tiles.length}collapsed={collapsedTileGroupKeys.includes(section.groupKey)}onToggle={() => onToggleTileGroup(section.groupKey)}+ copyToDestinations={copyToDestinations}+ onCopyToDashboard={+ onCopyGroupToDashboard+ ? (dashboardId, dashboardName) =>+ onCopyGroupToDashboard(section.groupKey, dashboardId, dashboardName)+ : undefined+ }+ copyLoading={copyLoading}>{children}</DashboardTileGroup>diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 062ab3124ae3..d22513adeedc 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1379,6 +1379,16 @@ export interface PatchedPatchedDashboardOpenApiApi {delete_insights?: boolean}+export interface CopyDashboardGroupRequestApi {+ /** Dashboard id the group currently belongs to. */+ fromDashboardId: number+ /**+ * Key of the tile group to copy.+ * @maxLength 100+ */+ groupKey: string+}+export interface CopyDashboardTileRequestApi {/** Dashboard id the tile currently belongs to. */fromDashboardId: number@@ -10941,6 +10951,18 @@ export const DashboardsDestroyFormat = {Txt: 'txt',} as const+export type DashboardsCopyGroupCreateParams = {+ format?: DashboardsCopyGroupCreateFormat+}++export type DashboardsCopyGroupCreateFormat =+ (typeof DashboardsCopyGroupCreateFormat)[keyof typeof DashboardsCopyGroupCreateFormat]++export const DashboardsCopyGroupCreateFormat = {+ Json: 'json',+ Txt: 'txt',+} as const+export type DashboardsCopyTileCreateParams = {format?: DashboardsCopyTileCreateFormat}diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.tsindex ed9b1844ca86..7bc7c6ef587d 100644--- a/products/dashboards/frontend/generated/api.ts+++ b/products/dashboards/frontend/generated/api.ts@@ -13,6 +13,7 @@ import type {AddDashboardWidgetsBatchResponseApi,BulkUpdateTagsRequestApi,BulkUpdateTagsResponseApi,+ CopyDashboardGroupRequestApi,CopyDashboardTemplateApi,CopyDashboardTileRequestApi,CreateTextTileRequestApi,@@ -24,6 +25,7 @@ import type {DashboardTemplatesListParams,DashboardTileApi,DashboardsBulkUpdateTagsCreateParams,+ DashboardsCopyGroupCreateParams,DashboardsCopyTileCreateParams,DashboardsCreateFromTemplateJsonCreateParams,DashboardsCreateParams,@@ -410,6 +412,44 @@ export const dashboardsDestroy = async (})}+export const getDashboardsCopyGroupCreateUrl = (+ projectId: string,+ id: number,+ params?: DashboardsCopyGroupCreateParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/dashboards/${id}/copy_group/?${stringifiedParams}`+ : `/api/projects/${projectId}/dashboards/${id}/copy_group/`+}++/**+ * Copy a group of tiles and its settings to another dashboard.+ */+export const dashboardsCopyGroupCreate = async (+ projectId: string,+ id: number,+ copyDashboardGroupRequestApi: CopyDashboardGroupRequestApi,+ params?: DashboardsCopyGroupCreateParams,+ options?: RequestInit+): Promise<DashboardApi> => {+ return apiMutator<DashboardApi>(getDashboardsCopyGroupCreateUrl(projectId, id, params), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(copyDashboardGroupRequestApi),+ })+}+export const getDashboardsCopyTileCreateUrl = (projectId: string,id: number,diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex f1cfb8c5beb5..535d54115639 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -1907,6 +1907,16 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod'OpenAPI-only PATCH body for dashboards (agents\/MCP).\n\nMust be a superset of ``dashboard_patch_runtime_openapi_field_names()`` — ``extend_schema(request=...)``\nreplaces the inferred schema entirely. Contract: ``test_dashboard_openapi.py``.')+/**+ * Copy a group of tiles and its settings to another dashboard.+ */+export const dashboardsCopyGroupCreateBodyGroupKeyMax = 100++export const DashboardsCopyGroupCreateBody = /* @__PURE__ */ zod.object({+ fromDashboardId: zod.number().describe('Dashboard id the group currently belongs to.'),+ groupKey: zod.string().max(dashboardsCopyGroupCreateBodyGroupKeyMax).describe('Key of the tile group to copy.'),+})+/*** Copy an existing dashboard tile to another dashboard (insight, text card, or widget tile).*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 786937887b82..032c00362ff0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27249,6 +27249,16 @@ export namespace Schemas {Number2: 2,} as const;+ export interface CopyDashboardGroupRequest {+ /** Dashboard id the group currently belongs to. */+ fromDashboardId: number;+ /**+ * Key of the tile group to copy.+ * @maxLength 100+ */+ groupKey: string;+ }+export interface CopyDashboardTemplate {/** UUID of a team-scoped template in the same organization. Global and feature-flag templates cannot be copied with this endpoint. */source_template_id: string;@@ -130604,6 +130614,18 @@ export namespace Schemas {Txt: 'txt',} as const;+ export type DashboardsCopyGroupCreateParams = {+ format?: DashboardsCopyGroupCreateFormat;+ };++ export type DashboardsCopyGroupCreateFormat = typeof DashboardsCopyGroupCreateFormat[keyof typeof DashboardsCopyGroupCreateFormat];+++ export const DashboardsCopyGroupCreateFormat = {+ Json: 'json',+ Txt: 'txt',+ } as const;+export type DashboardsCopyTileCreateParams = {format?: DashboardsCopyTileCreateFormat;};