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(metrics): regenerate a generated dashboard template from review (#121328)

Frank Hamand9a33fe137bfc
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 43f118b2f34d..c5198c5e40b9 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -883,6 +883,14 @@ def reject_dashboard_template(*, user: User, template_id: str) -> DashboardTempl
return service.reject(user, template_id)
+def regenerate_dashboard_template(*, user: User, template_id: str) -> DashboardTemplateSummary:
+ from products.metrics.backend.suggested_dashboards import ( # noqa: PLC0415 — keeps the dashboard and export code off the facade import path
+ service,
+ )
+
+ return service.regenerate(user, template_id)
+
+
def dashboard_template_picture(*, template_id: str, round_number: int) -> bytes | None:
"""The PNG that a generation round rendered of the preview dashboard."""
from products.metrics.backend.suggested_dashboards import ( # noqa: PLC0415 — keeps the dashboard and export code off the facade import path
diff --git a/products/metrics/backend/presentation/suggested_dashboards_api.py b/products/metrics/backend/presentation/suggested_dashboards_api.py
index e7d591b287bf..7160de89fac7 100644
--- a/products/metrics/backend/presentation/suggested_dashboards_api.py
+++ b/products/metrics/backend/presentation/suggested_dashboards_api.py
@@ -28,6 +28,7 @@ from products.metrics.backend.facade.api import (
list_dashboard_templates,
list_suggested_dashboards,
open_dashboard_template_preview,
+ regenerate_dashboard_template,
reject_dashboard_template,
)
from products.metrics.backend.facade.contracts import (
@@ -240,6 +241,18 @@ class MetricsDashboardTemplateViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
raise ValidationError(str(error))
return Response(MetricsDashboardTemplateSerializer(asdict(template)).data)
+ @extend_schema(request=None, responses={200: MetricsDashboardTemplateSerializer})
+ @action(detail=True, methods=["POST"])
+ def regenerate(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:
+ """Discard the panels and the preview of a generated template, and generate it again from its metrics."""
+ try:
+ template = regenerate_dashboard_template(user=cast(User, request.user), template_id=str(pk))
+ except SuggestedDashboardNotFound as error:
+ raise NotFound(str(error))
+ except SuggestedDashboardError as error:
+ raise ValidationError(str(error))
+ return Response(MetricsDashboardTemplateSerializer(asdict(template)).data)
+
@extend_schema(
parameters=[OpenApiParameter("round", OpenApiTypes.INT, required=True, description="Check round, from 1.")],
responses={(200, "image/png"): OpenApiResponse(description="The picture of the preview dashboard.")},
@@ -258,7 +271,8 @@ class MetricsDashboardTemplateViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
if content is None:
raise NotFound("This round has no picture.")
response = HttpResponse(content, content_type="image/png")
- response["Cache-Control"] = "private, max-age=3600"
+ # A regeneration reuses the round numbers, so a cached picture could show an older generation.
+ response["Cache-Control"] = "private, no-cache"
return response
@extend_schema(request=None, responses={202: None})
diff --git a/products/metrics/backend/suggested_dashboards/generation.py b/products/metrics/backend/suggested_dashboards/generation.py
index 3bdd6ca45c74..edad7c177a1e 100644
--- a/products/metrics/backend/suggested_dashboards/generation.py
+++ b/products/metrics/backend/suggested_dashboards/generation.py
@@ -129,7 +129,9 @@ def start_generation(team_id: int, request: GenerationRequest) -> str | None:
"status": MetricsDashboardTemplate.Status.GENERATING,
"metric_names": sorted(request.metric_names),
"source_team_id": team_id,
- "generation": GenerationRecord(model=MODEL, requested_name=request.name).model_dump(mode="json"),
+ "generation": GenerationRecord(
+ model=MODEL, requested_name=request.name, requested_metric_names=sorted(request.metric_names)
+ ).model_dump(mode="json"),
},
)
return str(template.id) if created else None
diff --git a/products/metrics/backend/suggested_dashboards/review.py b/products/metrics/backend/suggested_dashboards/review.py
index 9df56befbbdc..829734224cef 100644
--- a/products/metrics/backend/suggested_dashboards/review.py
+++ b/products/metrics/backend/suggested_dashboards/review.py
@@ -31,8 +31,9 @@ from products.metrics.backend.suggested_dashboards.dashboards import (
panels_from_tiles,
referenced_variables,
)
+from products.metrics.backend.suggested_dashboards.llm import MODEL
from products.metrics.backend.suggested_dashboards.matching import template_metric_names
-from products.metrics.backend.suggested_dashboards.spec import TemplatePanel, template_panels
+from products.metrics.backend.suggested_dashboards.spec import GenerationRecord, TemplatePanel, template_panels
class TemplateNotReviewable(Exception):
@@ -209,6 +210,53 @@ def reject(*, template: MetricsDashboardTemplate, user: User) -> MetricsDashboar
return locked
+_REGENERABLE = frozenset(
+ {
+ MetricsDashboardTemplate.Status.PENDING_REVIEW,
+ MetricsDashboardTemplate.Status.REJECTED,
+ MetricsDashboardTemplate.Status.FAILED,
+ }
+)
+
+
+def regenerate(*, template: MetricsDashboardTemplate, user: User) -> MetricsDashboardTemplate:
+ """Discard the panels and the preview of a generated template, and set it to generate again.
+
+ The caller starts the generation. The template keeps its key, so the same metrics never make a second one.
+ """
+ with transaction.atomic():
+ locked = MetricsDashboardTemplate.objects.select_for_update().get(id=template.id)
+ if locked.source != MetricsDashboardTemplate.Source.GENERATED:
+ raise TemplateNotReviewable("Only a generated dashboard can be generated again.")
+ if locked.status not in _REGENERABLE:
+ raise TemplateNotReviewable(
+ "This dashboard is still being generated."
+ if locked.status == MetricsDashboardTemplate.Status.GENERATING
+ else "Reject this dashboard before you generate it again."
+ )
+ source_team = Team.objects.select_related("organization").filter(id=locked.source_team_id).first()
+ if source_team is None:
+ raise TemplateNotReviewable("The project that this dashboard came from no longer exists.")
+ if not source_team.organization.is_ai_data_processing_approved:
+ raise TemplateNotReviewable("The organization of the source project does not allow AI data processing.")
+ record = GenerationRecord.model_validate(locked.generation or {})
+ drop_preview(locked)
+ locked.name = record.requested_name or locked.name
+ locked.metric_names = record.requested_metric_names or locked.metric_names
+ locked.panels = []
+ locked.variables = []
+ locked.generation = GenerationRecord(
+ model=MODEL, requested_name=locked.name, requested_metric_names=locked.metric_names
+ ).model_dump(mode="json")
+ locked.status = MetricsDashboardTemplate.Status.GENERATING
+ locked.reviewed_by = None
+ locked.reviewed_at = None
+ locked.save()
+ MetricsDashboardSuggestion.objects.unscoped().filter(template_id=locked.id, dashboard_id__isnull=True).delete()
+ report_user_action(user, "metrics dashboard template regenerated", {"template_id": str(locked.id)})
+ return locked
+
+
def create_from_suggestion(*, suggestion: MetricsDashboardSuggestion, team: Team, user: User) -> int:
"""Create the suggested dashboard in the team, as the user. A second call opens the same dashboard.
diff --git a/products/metrics/backend/suggested_dashboards/service.py b/products/metrics/backend/suggested_dashboards/service.py
index 4353f6226690..5c43fc85fbd5 100644
--- a/products/metrics/backend/suggested_dashboards/service.py
+++ b/products/metrics/backend/suggested_dashboards/service.py
@@ -2,7 +2,10 @@
from __future__ import annotations
+import datetime as dt
+
from django.db.models import Count, QuerySet
+from django.utils import timezone
import structlog
@@ -19,9 +22,10 @@ from products.metrics.backend.facade.contracts import (
)
from products.metrics.backend.facade.enums import DashboardTemplateSource, DashboardTemplateStatus
from products.metrics.backend.models import MetricsDashboardSuggestion, MetricsDashboardTemplate
-from products.metrics.backend.suggested_dashboards import review
+from products.metrics.backend.suggested_dashboards import generation, review
from products.metrics.backend.suggested_dashboards.spec import GenerationRecord, template_panels
from products.metrics.backend.temporal import schedule
+from products.metrics.backend.temporal.inputs import GenerationRequestInputs
logger = structlog.get_logger(__name__)
@@ -172,6 +176,49 @@ def reject(user: User, template_id: str) -> DashboardTemplateSummary:
return get_template(str(template.id))
+# Allows for a clock difference between this server and Temporal when the run start times are compared.
+_START_CLOCK_MARGIN = dt.timedelta(seconds=5)
+
+
+def regenerate(user: User, template_id: str) -> DashboardTemplateSummary:
+ existing = _get_template(template_id)
+ # A finished generation saves its template before its workflow closes. A new run must wait for that close.
+ if schedule.generation_running(existing.key):
+ raise SuggestedDashboardError("The previous generation is still finishing. Try again in a minute.")
+ started_at = timezone.now() - _START_CLOCK_MARGIN
+ try:
+ template = review.regenerate(template=existing, user=user)
+ except review.TemplateNotReviewable as error:
+ raise SuggestedDashboardError(str(error)) from error
+ assert template.source_team_id is not None
+ try:
+ schedule.start_regeneration(
+ template.source_team_id,
+ str(template.id),
+ GenerationRequestInputs(
+ key=template.key,
+ name=template.name,
+ description=template.description,
+ metric_names=list(template.metric_names),
+ ),
+ )
+ except Exception as error:
+ # Temporal can start the workflow and lose only its answer, so the failure is recorded only when no run
+ # of this regeneration is going. A run that started before it is an earlier generation.
+ running = schedule.generation_running(template.key, started_after=started_at)
+ if running:
+ return get_template(str(template.id))
+ logger.exception("metrics_suggested_dashboards_regeneration_not_started", template_id=str(template.id))
+ if running is None:
+ # The stale generation sweep fails the template when no workflow finishes it.
+ raise SuggestedDashboardError(
+ "Could not confirm that the generation started. Check this dashboard again in a few minutes."
+ ) from error
+ generation.finish_generation(str(template.id), error="The generation could not start.")
+ raise SuggestedDashboardError("The generation could not start. Try again.") from error
+ return get_template(str(template.id))
+
+
def picture(template_id: str, round_number: int) -> bytes | None:
template = _get_template(template_id)
record = GenerationRecord.model_validate(template.generation or {})
diff --git a/products/metrics/backend/suggested_dashboards/spec.py b/products/metrics/backend/suggested_dashboards/spec.py
index 869419e6b2ce..4742fea51b03 100644
--- a/products/metrics/backend/suggested_dashboards/spec.py
+++ b/products/metrics/backend/suggested_dashboards/spec.py
@@ -129,6 +129,8 @@ class GenerationRecord(_Model):
model: str = ""
requested_name: str = ""
+ # A finished template lists only the metrics of its panels, so a regeneration starts again from these.
+ requested_metric_names: list[str] = Field(default_factory=list)
rounds: list[GenerationRound] = Field(default_factory=list)
# The panels in the shape that the model writes, so that a check round can show the model its own panels.
draft_panels: list[DraftPanel] = Field(default_factory=list)
diff --git a/products/metrics/backend/temporal/activities.py b/products/metrics/backend/temporal/activities.py
index cfcc233e8e23..6fae1ee42375 100644
--- a/products/metrics/backend/temporal/activities.py
+++ b/products/metrics/backend/temporal/activities.py
@@ -74,6 +74,8 @@ async def analyze_team_activity(inputs: SuggestInputs) -> SuggestResult:
@temporalio.activity.defn
async def start_generation_activity(inputs: GenerateInputs) -> str | None:
+ if inputs.template_id is not None:
+ return inputs.template_id
request = generation.GenerationRequest(
key=inputs.request.key,
name=inputs.request.name,
diff --git a/products/metrics/backend/temporal/inputs.py b/products/metrics/backend/temporal/inputs.py
index 2a6420969a5c..d9173bb0d1f4 100644
--- a/products/metrics/backend/temporal/inputs.py
+++ b/products/metrics/backend/temporal/inputs.py
@@ -46,6 +46,8 @@ class SuggestResult:
class GenerateInputs:
team_id: int
request: GenerationRequestInputs
+ # Set when a reviewer generates an existing template again. The template is already set to generating.
+ template_id: str | None = None
@dataclasses.dataclass(frozen=True)
diff --git a/products/metrics/backend/temporal/schedule.py b/products/metrics/backend/temporal/schedule.py
index e2ad19ac751b..162b09745723 100644
--- a/products/metrics/backend/temporal/schedule.py
+++ b/products/metrics/backend/temporal/schedule.py
@@ -1,7 +1,7 @@
"""The 5-minute schedule of the dashboard discovery, and the way the API starts one analysis now."""
import asyncio
-from datetime import timedelta
+from datetime import datetime, timedelta
from django.conf import settings
@@ -13,19 +13,25 @@ from temporalio.client import (
ScheduleOverlapPolicy,
SchedulePolicy,
ScheduleSpec,
+ WorkflowExecutionStatus,
)
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
+from temporalio.service import RPCError, RPCStatusCode
from posthog.scheduling.jitter import deterministic_offset
from posthog.temporal.common.client import sync_connect
from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
-from products.metrics.backend.suggested_dashboards.timeouts import SUGGEST_TIMEOUT
+from products.metrics.backend.suggested_dashboards.timeouts import GENERATE_TIMEOUT, SUGGEST_TIMEOUT
from products.metrics.backend.temporal.inputs import (
DISCOVERY_WORKFLOW_NAME,
+ GENERATE_WORKFLOW_NAME,
SUGGEST_WORKFLOW_NAME,
DiscoveryInputs,
+ GenerateInputs,
+ GenerationRequestInputs,
SuggestInputs,
+ generate_workflow_id,
suggest_workflow_id,
)
@@ -71,3 +77,36 @@ def start_team_analysis(team_id: int, *, force: bool) -> None:
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
)
)
+
+
+def start_regeneration(team_id: int, template_id: str, request: GenerationRequestInputs) -> None:
+ """Generate an existing template again. A finished run of the same template is replaced, a running one is not."""
+ client = sync_connect()
+ asyncio.run(
+ client.start_workflow(
+ GENERATE_WORKFLOW_NAME,
+ GenerateInputs(team_id=team_id, request=request, template_id=template_id),
+ id=generate_workflow_id(request.key),
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ execution_timeout=GENERATE_TIMEOUT,
+ id_conflict_policy=WorkflowIDConflictPolicy.FAIL,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ )
+ )
+
+
+def generation_running(key: str, *, started_after: datetime | None = None) -> bool | None:
+ """Whether a generate workflow of the template runs, and started after `started_after` when it is set.
+
+ None when Temporal does not answer.
+ """
+ try:
+ client = sync_connect()
+ description = asyncio.run(client.get_workflow_handle(generate_workflow_id(key)).describe())
+ except RPCError as error:
+ return False if error.status == RPCStatusCode.NOT_FOUND else None
+ except Exception:
+ return None
+ if description.status != WorkflowExecutionStatus.RUNNING:
+ return False
+ return started_after is None or description.start_time >= started_after
diff --git a/products/metrics/backend/tests/test_suggested_dashboards_api.py b/products/metrics/backend/tests/test_suggested_dashboards_api.py
index 619380947f2e..62964552a73c 100644
--- a/products/metrics/backend/tests/test_suggested_dashboards_api.py
+++ b/products/metrics/backend/tests/test_suggested_dashboards_api.py
@@ -313,6 +313,9 @@ class TestSuggestedDashboardsAPI(APIBaseTest):
("rejecting_a_curated_one", "reject", "approved", "curated"),
("rejecting_one_still_generating", "reject", "generating", "generated"),
("approving_a_withdrawn_curated_one", "approve", "rejected", "curated"),
+ ("regenerating_a_curated_one", "regenerate", "rejected", "curated"),
+ ("regenerating_one_still_generating", "regenerate", "generating", "generated"),
+ ("regenerating_an_approved_one", "regenerate", "approved", "generated"),
]
)
def test_a_template_that_cannot_be_reviewed(
@@ -328,6 +331,75 @@ class TestSuggestedDashboardsAPI(APIBaseTest):
template.refresh_from_db()
assert template.status == template_status
+ @parameterized.expand(
+ [
+ ("started", None, None, 200, "generating"),
+ ("not_started", RuntimeError, False, 400, "failed"),
+ ("started_but_the_answer_was_lost", RuntimeError, True, 200, "generating"),
+ ("unknown", RuntimeError, None, 400, "generating"),
+ ]
+ )
+ def test_regenerating_discards_the_panels_and_starts_again_from_the_requested_metrics(
+ self,
+ _name: str,
+ start_error: type[Exception] | None,
+ running: bool | None,
+ expected_code: int,
+ expected_status: str,
+ ) -> None:
+ self.user.is_staff = True
+ self.user.save(update_fields=["is_staff"])
+ preview = Dashboard.objects.create(
+ team=self.team, name="Preview", creation_mode=Dashboard.CreationMode.UNLISTED
+ )
+ template = _template("generated-queue", "rejected", "queue_depth", source="generated")
+ template.source_team_id = self.team.id
+ template.preview_team_id, template.preview_dashboard_id = self.team.id, preview.id
+ template.generation = {"requested_name": "Job queue", "requested_metric_names": QUEUE_METRICS}
+ template.save()
+
+ with (
+ patch("products.metrics.backend.temporal.schedule.start_regeneration", side_effect=start_error) as start,
+ patch(
+ "products.metrics.backend.temporal.schedule.generation_running",
+ side_effect=lambda key, started_after=None: running if started_after else False,
+ ),
+ patch("products.metrics.backend.suggested_dashboards.generation.ph_background_capture"),
+ ):
+ response = self.client.post(f"{self.base_url}/dashboard_templates/{template.id}/regenerate/")
+
+ assert response.status_code == expected_code
+ start.assert_called_once()
+ team_id, template_id, request = start.call_args.args
+ assert (team_id, template_id, request.key, request.metric_names) == (
+ self.team.id,
+ str(template.id),
+ "generated-queue",
+ QUEUE_METRICS,
+ )
+ saved = MetricsDashboardTemplate.objects.get(id=template.id)
+ assert (saved.status, saved.panels, saved.name) == (expected_status, [], "Job queue")
+ assert saved.preview_dashboard_id is None
+ assert not Dashboard.objects.filter(id=preview.id, deleted=False).exists()
+
+ def test_regenerating_waits_for_the_previous_run_to_close(self) -> None:
+ self.user.is_staff = True
+ self.user.save(update_fields=["is_staff"])
+ template = _template("generated-queue", "pending_review", "queue_depth", source="generated")
+ template.source_team_id = self.team.id
+ template.save(update_fields=["source_team_id"])
+
+ with (
+ patch("products.metrics.backend.temporal.schedule.generation_running", return_value=True),
+ patch("products.metrics.backend.temporal.schedule.start_regeneration") as start,
+ ):
+ response = self.client.post(f"{self.base_url}/dashboard_templates/{template.id}/regenerate/")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ start.assert_not_called()
+ template.refresh_from_db()
+ assert (template.status, len(template.panels)) == ("pending_review", 1)
+
def test_a_curated_template_comes_back_with_its_file(self) -> None:
sync_curated_templates()
# An older worker without the file withdrew it during a deploy.
diff --git a/products/metrics/frontend/dashboardReview/DashboardTemplateDetail.tsx b/products/metrics/frontend/dashboardReview/DashboardTemplateDetail.tsx
index 2e922661fbfe..4008c8f51251 100644
--- a/products/metrics/frontend/dashboardReview/DashboardTemplateDetail.tsx
+++ b/products/metrics/frontend/dashboardReview/DashboardTemplateDetail.tsx
@@ -43,10 +43,9 @@ function PreviewDashboard({ dashboardId }: { dashboardId: number }): JSX.Element
}
export function DashboardTemplateDetail(): JSX.Element {
- const { template, templateLoading, previewDashboardId, previewLoading, previewError, reviewable } = useValues(
- metricsDashboardReviewSceneLogic
- )
- const { approveTemplate, rejectTemplate } = useActions(metricsDashboardReviewSceneLogic)
+ const { template, templateLoading, previewDashboardId, previewLoading, previewError, reviewable, regenerable } =
+ useValues(metricsDashboardReviewSceneLogic)
+ const { approveTemplate, rejectTemplate, confirmRegenerate } = useActions(metricsDashboardReviewSceneLogic)
const { openSidePanel } = useActions(sidePanelStateLogic)
const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
@@ -103,6 +102,17 @@ export function DashboardTemplateDetail(): JSX.Element {
Edit with PostHog AI
</span>
</LemonButton>
+ {regenerable && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={confirmRegenerate}
+ loading={templateLoading}
+ data-attr="metrics-dashboard-review-regenerate"
+ >
+ Regenerate
+ </LemonButton>
+ )}
{reviewable && template.status !== 'rejected' && (
<LemonButton
type="secondary"
diff --git a/products/metrics/frontend/dashboardReview/QuillDashboardTemplateDetailActions.tsx b/products/metrics/frontend/dashboardReview/QuillDashboardTemplateDetailActions.tsx
index ed571a7dd0fe..8d96610fe155 100644
--- a/products/metrics/frontend/dashboardReview/QuillDashboardTemplateDetailActions.tsx
+++ b/products/metrics/frontend/dashboardReview/QuillDashboardTemplateDetailActions.tsx
@@ -20,8 +20,8 @@ export function QuillDashboardTemplateDetailActions({
template,
onEditWithAI,
}: QuillDashboardTemplateDetailActionsProps): JSX.Element {
- const { templateLoading, previewDashboardId, reviewable } = useValues(metricsDashboardReviewSceneLogic)
- const { approveTemplate, rejectTemplate } = useActions(metricsDashboardReviewSceneLogic)
+ const { templateLoading, previewDashboardId, reviewable, regenerable } = useValues(metricsDashboardReviewSceneLogic)
+ const { approveTemplate, rejectTemplate, confirmRegenerate } = useActions(metricsDashboardReviewSceneLogic)
const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
return (
@@ -50,6 +50,16 @@ export function QuillDashboardTemplateDetailActions({
Edit with PostHog AI
</span>
</Button>
+ {regenerable && (
+ <Button
+ variant="outline"
+ onClick={confirmRegenerate}
+ loading={templateLoading}
+ data-attr="metrics-dashboard-review-regenerate"
+ >
+ Regenerate
+ </Button>
+ )}
{reviewable && template.status !== 'rejected' && (
<Button
variant="destructive-outline"
diff --git a/products/metrics/frontend/dashboardReview/metricsDashboardReviewSceneLogic.ts b/products/metrics/frontend/dashboardReview/metricsDashboardReviewSceneLogic.ts
index 95bf2d5eefea..1448783e2a4a 100644
--- a/products/metrics/frontend/dashboardReview/metricsDashboardReviewSceneLogic.ts
+++ b/products/metrics/frontend/dashboardReview/metricsDashboardReviewSceneLogic.ts
@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import { ApiError } from 'lib/api-error'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -14,6 +15,7 @@ import {
metricsDashboardTemplatesApproveCreate,
metricsDashboardTemplatesList,
metricsDashboardTemplatesPreviewCreate,
+ metricsDashboardTemplatesRegenerateCreate,
metricsDashboardTemplatesRejectCreate,
metricsDashboardTemplatesRetrieve,
} from 'products/metrics/frontend/generated/api'
@@ -39,6 +41,7 @@ export interface metricsDashboardReviewSceneLogicValues {
previewError: string | null
previewLoading: boolean
previewRequestTemplateId: string | null
+ regenerable: boolean
reviewable: boolean
statusFilter: ReviewStatusFilter
template: MetricsDashboardTemplateApi | null
@@ -80,6 +83,9 @@ export interface metricsDashboardReviewSceneLogicActions {
template: MetricsDashboardTemplateApi | null
payload?: any
}
+ confirmRegenerate: () => {
+ value: true
+ }
loadTemplate: () => any
loadTemplateFailure: (
error: string,
@@ -131,6 +137,21 @@ export interface metricsDashboardReviewSceneLogicActions {
templateId: string
}
}
+ regenerateTemplate: () => any
+ regenerateTemplateFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ regenerateTemplateSuccess: (
+ template: MetricsDashboardTemplateApi | null,
+ payload?: any
+ ) => {
+ template: MetricsDashboardTemplateApi | null
+ payload?: any
+ }
rejectTemplate: () => any
rejectTemplateFailure: (
error: string,
@@ -162,6 +183,7 @@ export interface metricsDashboardReviewSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
previewLoading: (previewRequestTemplateId: string | null, templateId: string | null) => boolean
reviewable: (template: MetricsDashboardTemplateApi | null) => boolean
+ regenerable: (template: MetricsDashboardTemplateApi | null) => boolean
breadcrumbs: (template: MetricsDashboardTemplateApi | null, templateId: string | null) => Breadcrumb[]
}
}
@@ -182,6 +204,7 @@ export const metricsDashboardReviewSceneLogic = kea<metricsDashboardReviewSceneL
setStatusFilter: (statusFilter: ReviewStatusFilter) => ({ statusFilter }),
setTemplateId: (templateId: string | null) => ({ templateId }),
setPreviewError: (previewError: string | null) => ({ previewError }),
+ confirmRegenerate: true,
}),
loaders(({ values }) => ({
templates: [
@@ -227,6 +250,27 @@ export const metricsDashboardReviewSceneLogic = kea<metricsDashboardReviewSceneL
return values.template
}
},
+ regenerateTemplate: async () => {
+ try {
+ const template = await metricsDashboardTemplatesRegenerateCreate(
+ String(values.currentTeamId),
+ values.templateId as string
+ )
+ lemonToast.info(`Regenerating "${template.name}". It is back for review in a few minutes.`)
+ return template
+ } catch (error) {
+ lemonToast.error(errorDetail(error, 'Could not regenerate the dashboard.'))
+ // A failed start can still have reset the template and deleted its preview.
+ try {
+ return await metricsDashboardTemplatesRetrieve(
+ String(values.currentTeamId),
+ values.templateId as string
+ )
+ } catch {
+ return values.template
+ }
+ }
+ },
},
],
analysisStarted: [
@@ -286,6 +330,8 @@ export const metricsDashboardReviewSceneLogic = kea<metricsDashboardReviewSceneL
// A review deletes the preview, so the page stops showing it. A failed review keeps it.
approveTemplateSuccess: (state, { template }) => (template?.status === 'approved' ? null : state),
rejectTemplateSuccess: (state, { template }) => (template?.status === 'rejected' ? null : state),
+ regenerateTemplateSuccess: (state, { template }) =>
+ template && ['pending_review', 'rejected'].includes(template.status) ? state : null,
},
// The template of the preview request in flight. A stale request also ends the loader's own loading state.
previewRequestTemplateId: [
@@ -317,6 +363,13 @@ export const metricsDashboardReviewSceneLogic = kea<metricsDashboardReviewSceneL
(template: MetricsDashboardTemplateApi | null): boolean =>
!!template && ['pending_review', 'rejected'].includes(template.status) && template.source !== 'curated',
],
+ regenerable: [
+ (s) => [s.template],
+ (template: MetricsDashboardTemplateApi | null): boolean =>
+ !!template &&
+ template.source === 'generated' &&
+ ['pending_review', 'rejected', 'failed'].includes(template.status),
+ ],
breadcrumbs: [
(s) => [s.template, s.templateId],
(template: MetricsDashboardTemplateApi | null, templateId: string | null): Breadcrumb[] => [
@@ -356,6 +409,21 @@ export const metricsDashboardReviewSceneLogic = kea<metricsDashboardReviewSceneL
approveTemplateSuccess: () => {
actions.loadTemplates()
},
+ confirmRegenerate: () => {
+ LemonDialog.open({
+ title: 'Regenerate this dashboard?',
+ description: 'The new panels replace the current panels and preview.',
+ primaryButton: {
+ children: 'Regenerate',
+ status: 'danger',
+ onClick: () => actions.regenerateTemplate(),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ regenerateTemplateSuccess: () => {
+ actions.loadTemplates()
+ },
rejectTemplateSuccess: ({ template }) => {
actions.loadTemplates()
// A rejected dashboard can still be approved, so it gets a new preview.
diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.ts
index 83d20941f2e7..095bbba83ff8 100644
--- a/products/metrics/frontend/generated/api.ts
+++ b/products/metrics/frontend/generated/api.ts
@@ -371,6 +371,24 @@ export const metricsDashboardTemplatesPreviewCreate = async (
})
}
+export const getMetricsDashboardTemplatesRegenerateCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/metrics/dashboard_templates/${id}/regenerate/`
+}
+
+/**
+ * Discard the panels and the preview of a generated template, and generate it again from its metrics.
+ */
+export const metricsDashboardTemplatesRegenerateCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<MetricsDashboardTemplateApi> => {
+ return apiMutator<MetricsDashboardTemplateApi>(getMetricsDashboardTemplatesRegenerateCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getMetricsDashboardTemplatesRejectCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/metrics/dashboard_templates/${id}/reject/`
}