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.

chore(approvals): extract approvals into its own product (#66197)

Paul D'Ambraca94a6c45544
diff --git a/.github/CODEOWNERS-soft b/.github/CODEOWNERS-soft
index 3574f801b6d8..1a110a2b99c8 100644
--- a/.github/CODEOWNERS-soft
+++ b/.github/CODEOWNERS-soft
@@ -142,7 +142,6 @@ frontend/src/scenes/audit-logs/ @PostHog/team-platform-features
frontend/src/scenes/activity/ @PostHog/team-platform-features
posthog/models/activity_logging/ @PostHog/team-platform-features
frontend/src/scenes/approvals/ @PostHog/team-platform-features
-posthog/approvals/ @PostHog/team-platform-features
frontend/src/scenes/resource-transfer/ @PostHog/team-platform-features
posthog/api/resource_transfer.py @PostHog/team-platform-features
posthog/models/resource_transfer/ @PostHog/team-platform-features
diff --git a/.semgrep/rules/idor-team-scoped-models.py b/.semgrep/rules/idor-team-scoped-models.py
index 7b40a86c196f..1b917f903bf9 100644
--- a/.semgrep/rules/idor-team-scoped-models.py
+++ b/.semgrep/rules/idor-team-scoped-models.py
@@ -1,5 +1,6 @@
from django.shortcuts import get_object_or_404
-from posthog.models import ChangeRequest, Notebook
+from posthog.models import Notebook
+from products.approvals.backend.models import ChangeRequest
from products.cohorts.backend.models.cohort import Cohort
from products.product_analytics.backend.models.insight import Insight
from products.actions.backend.models.action import Action
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 24033dda2915..d10d356f16c8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2696,6 +2696,8 @@ importers:
products/annotations: {}
+ products/approvals: {}
+
products/batch_exports: {}
products/business_knowledge:
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 0e5dd64442b8..5ebabf3a08d9 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -15,7 +15,6 @@ from posthog.api.query_performance_proxy import QueryPerformanceProxyViewSet
from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry
from posthog.api.sdk_health import SdkHealthViewSet
from posthog.api.wizard import http as wizard
-from posthog.approvals import api as approval_api
from posthog.settings import EE_AVAILABLE
from ee.api.quota_limits import QuotaLimitsViewSet
@@ -598,20 +597,6 @@ register_legacy_dual_route_team_nested_viewset(
projects_router.register(r"js-snippet", JsSnippetViewSet, "project_js_snippet", ["team_id"])
-register_legacy_dual_route_team_nested_viewset(
- r"change_requests",
- approval_api.ChangeRequestViewSet,
- "project_change_requests",
- ["team_id"],
-)
-
-register_legacy_dual_route_team_nested_viewset(
- r"approval_policies",
- approval_api.ApprovalPolicyViewSet,
- "project_approval_policies",
- ["team_id"],
-)
-
register_legacy_dual_route_team_nested_viewset(
r"core_events",
CoreEventViewSet,
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index cb96bafd78f1..3cd25f9b8091 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -821,7 +821,7 @@ class TestPersonalAPIKeysWithApprovalsScope(PersonalAPIKeysBaseTest):
assert response.json()["detail"] == "API key missing required scope 'approvals:read'"
def _create_change_request(self):
- from posthog.approvals.models import ChangeRequest, ChangeRequestState
+ from products.approvals.backend.models import ChangeRequest, ChangeRequestState
return ChangeRequest.objects.create(
team=self.team,
diff --git a/posthog/migrations/1239_migrate_approvals_models.py b/posthog/migrations/1239_migrate_approvals_models.py
new file mode 100644
index 000000000000..580eba27da76
--- /dev/null
+++ b/posthog/migrations/1239_migrate_approvals_models.py
@@ -0,0 +1,95 @@
+from django.db import migrations
+
+MODELS_TO_MOVE = ("changerequest", "approvalpolicy", "approval")
+
+
+def _move_content_types(apps, schema_editor, from_label, to_label):
+ """Move ContentTypes between apps, handling duplicates idempotently."""
+ db_alias = schema_editor.connection.alias
+ ContentType = apps.get_model("contenttypes", "ContentType")
+ Permission = apps.get_model("auth", "Permission")
+
+ for model_name in MODELS_TO_MOVE:
+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()
+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()
+
+ if source and target:
+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)
+ source.delete(using=db_alias)
+ elif source:
+ source.app_label = to_label
+ source.save(using=db_alias)
+
+
+def update_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "posthog", "approvals")
+
+
+def reverse_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "approvals", "posthog")
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("approvals", "0001_migrate_approvals_models"),
+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),
+ ]
+
+ # State-only move: the approval models now live in the `approvals` app
+ # (products/approvals/backend). database_operations is empty — the physical tables are
+ # untouched; products/approvals/backend/migrations/0001_migrate_approvals_models.py
+ # recreates them in ORM state under the `approvals` app. The RunPython below repoints
+ # existing django_content_type / auth_permission rows from the posthog label to approvals.
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterUniqueTogether(
+ name="approvalpolicy",
+ unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="approvalpolicy",
+ name="bypass_roles",
+ ),
+ migrations.RemoveField(
+ model_name="approvalpolicy",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="approvalpolicy",
+ name="organization",
+ ),
+ migrations.RemoveField(
+ model_name="approvalpolicy",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="changerequest",
+ name="applied_by",
+ ),
+ migrations.RemoveField(
+ model_name="changerequest",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="changerequest",
+ name="organization",
+ ),
+ migrations.RemoveField(
+ model_name="changerequest",
+ name="team",
+ ),
+ migrations.DeleteModel(
+ name="Approval",
+ ),
+ migrations.DeleteModel(
+ name="ApprovalPolicy",
+ ),
+ migrations.DeleteModel(
+ name="ChangeRequest",
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(update_content_types, reverse_content_types),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 664ecbdbfbed..379e354ae555 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1238_ducklakebackfill_earliest_event_date
+1239_migrate_approvals_models
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index f3ea3c5f075f..07dc14d23531 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -85,12 +85,7 @@ from .oauth import (
OAuthRefreshToken,
)
-from ..approvals.models import Approval, ApprovalPolicy, ChangeRequest
-
__all__ = [
- "Approval",
- "ApprovalPolicy",
- "ChangeRequest",
"ActivityLog",
"AsyncDeletion",
"AsyncMigration",
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 195575fccbb1..09f0780ac6ad 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -95,6 +95,7 @@ PRODUCTS_APPS = [
"products.cohorts.backend.apps.CohortsConfig",
"products.growth.backend.apps.GrowthConfig",
"products.reminders.backend.apps.RemindersConfig",
+ "products.approvals.backend.apps.ApprovalsConfig",
]
INSTALLED_APPS = [
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index b713c9c9e23d..9c56c57e2644 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -7,7 +7,6 @@ from celery import Celery
from celery.canvas import Signature
from celery.schedules import crontab
-from posthog.approvals.tasks import expire_old_change_requests, validate_pending_change_requests
from posthog.caching.warming import schedule_warming_for_teams_task
from posthog.clickhouse.client.execute_async import QueryStatusManager
from posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports
@@ -73,6 +72,7 @@ from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_p
from posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entries
from posthog.utils import get_crontab, get_instance_region
+from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requests
from products.conversations.backend.tasks import (
flush_pending_email_replies,
poll_teams_shared_channels,
diff --git a/posthog/approvals/__init__.py b/products/approvals/__init__.py
similarity index 100%
rename from posthog/approvals/__init__.py
rename to products/approvals/__init__.py
diff --git a/posthog/approvals/tests/__init__.py b/products/approvals/backend/__init__.py
similarity index 100%
rename from posthog/approvals/tests/__init__.py
rename to products/approvals/backend/__init__.py
diff --git a/posthog/approvals/actions/__init__.py b/products/approvals/backend/actions/__init__.py
similarity index 100%
rename from posthog/approvals/actions/__init__.py
rename to products/approvals/backend/actions/__init__.py
diff --git a/posthog/approvals/actions/base.py b/products/approvals/backend/actions/base.py
similarity index 100%
rename from posthog/approvals/actions/base.py
rename to products/approvals/backend/actions/base.py
diff --git a/posthog/approvals/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.py
similarity index 99%
rename from posthog/approvals/actions/feature_flags.py
rename to products/approvals/backend/actions/feature_flags.py
index 49e5f44716b4..3bd6a9d02e99 100644
--- a/posthog/approvals/actions/feature_flags.py
+++ b/products/approvals/backend/actions/feature_flags.py
@@ -3,9 +3,8 @@ from typing import Any, Optional
from django.db import transaction
-from posthog.approvals.actions.base import BaseAction
-from posthog.approvals.exceptions import ApplyFailed, PreconditionFailed
-
+from products.approvals.backend.actions.base import BaseAction
+from products.approvals.backend.exceptions import ApplyFailed, PreconditionFailed
from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
from products.feature_flags.backend.models.feature_flag import FeatureFlag
diff --git a/posthog/approvals/actions/registry.py b/products/approvals/backend/actions/registry.py
similarity index 82%
rename from posthog/approvals/actions/registry.py
rename to products/approvals/backend/actions/registry.py
index acfc9572ff87..e5612a413df5 100644
--- a/posthog/approvals/actions/registry.py
+++ b/products/approvals/backend/actions/registry.py
@@ -1,12 +1,12 @@
from typing import Optional
-from posthog.approvals.actions.base import BaseAction
+from products.approvals.backend.actions.base import BaseAction
ACTION_REGISTRY: dict[str, type[BaseAction]] = {}
def register_actions():
- from posthog.approvals.actions.feature_flags import (
+ from products.approvals.backend.actions.feature_flags import (
DisableFeatureFlagAction,
EnableFeatureFlagAction,
UpdateFeatureFlagAction,
diff --git a/posthog/approvals/api.py b/products/approvals/backend/api.py
similarity index 95%
rename from posthog/approvals/api.py
rename to products/approvals/backend/api.py
index 2185b80a3021..906b4b28b307 100644
--- a/posthog/approvals/api.py
+++ b/products/approvals/backend/api.py
@@ -13,11 +13,6 @@ from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.approvals.exceptions import AlreadyVotedError, InvalidStateError, ReasonRequiredError
-from posthog.approvals.models import ApprovalPolicy, ChangeRequest
-from posthog.approvals.permissions import CanApprove, CanCancel
-from posthog.approvals.serializers import ApprovalPolicySerializer, ChangeRequestSerializer
-from posthog.approvals.services import ChangeRequestService
from posthog.constants import AvailableFeature
from posthog.models import User
from posthog.permissions import (
@@ -26,6 +21,12 @@ from posthog.permissions import (
PremiumFeaturePermission,
)
+from products.approvals.backend.exceptions import AlreadyVotedError, InvalidStateError, ReasonRequiredError
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
+from products.approvals.backend.permissions import CanApprove, CanCancel
+from products.approvals.backend.serializers import ApprovalPolicySerializer, ChangeRequestSerializer
+from products.approvals.backend.services import ChangeRequestService
+
logger = logging.getLogger(__name__)
diff --git a/products/approvals/backend/apps.py b/products/approvals/backend/apps.py
new file mode 100644
index 000000000000..7c57c4cc1646
--- /dev/null
+++ b/products/approvals/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class ApprovalsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.approvals.backend"
+ label = "approvals"
diff --git a/posthog/approvals/decorators.py b/products/approvals/backend/decorators.py
similarity index 97%
rename from posthog/approvals/decorators.py
rename to products/approvals/backend/decorators.py
index 49d38e615bad..08b6a4801652 100644
--- a/posthog/approvals/decorators.py
+++ b/products/approvals/backend/decorators.py
@@ -10,15 +10,16 @@ from rest_framework import status
from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
from rest_framework.response import Response
-from posthog.approvals.actions.registry import get_action
-from posthog.approvals.exceptions import ApprovalRequired
-from posthog.approvals.models import ChangeRequest, ChangeRequestState
-from posthog.approvals.notifications import send_approval_requested_notification
-from posthog.approvals.policies import PolicyDecision, PolicyEngine
-from posthog.approvals.serializers import ChangeRequestSerializer
from posthog.constants import AvailableFeature
from posthog.event_usage import report_user_action
+from products.approvals.backend.actions.registry import get_action
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.models import ChangeRequest, ChangeRequestState
+from products.approvals.backend.notifications import send_approval_requested_notification
+from products.approvals.backend.policies import PolicyDecision, PolicyEngine
+from products.approvals.backend.serializers import ChangeRequestSerializer
+
logger = logging.getLogger(__name__)
diff --git a/posthog/approvals/exceptions.py b/products/approvals/backend/exceptions.py
similarity index 100%
rename from posthog/approvals/exceptions.py
rename to products/approvals/backend/exceptions.py
diff --git a/products/approvals/backend/migrations/0001_migrate_approvals_models.py b/products/approvals/backend/migrations/0001_migrate_approvals_models.py
new file mode 100644
index 000000000000..90446ce96643
--- /dev/null
+++ b/products/approvals/backend/migrations/0001_migrate_approvals_models.py
@@ -0,0 +1,230 @@
+# Generated by Django 5.2.14 on 2026-06-25 17:18
+
+import datetime
+from typing import Any
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("ee", "0050_migrate_replay_models"),
+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ # State-only move from the `posthog` app. The physical tables already exist
+ # (created under the posthog app), so database_operations is empty — this migration
+ # only recreates the models in ORM state under the `approvals` app.
+ database_operations: list[Any] = []
+
+ state_operations = [
+ migrations.CreateModel(
+ name="ChangeRequest",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("action_key", models.CharField(max_length=128)),
+ ("action_version", models.IntegerField(default=1)),
+ ("resource_type", models.CharField(max_length=64)),
+ ("resource_id", models.CharField(blank=True, max_length=128, null=True)),
+ ("intent", models.JSONField()),
+ ("intent_display", models.JSONField()),
+ ("policy_snapshot", models.JSONField()),
+ (
+ "validation_status",
+ models.CharField(
+ choices=[
+ ("valid", "Valid"),
+ ("invalid", "Invalid"),
+ ("expired", "Expired"),
+ ("stale", "Stale (resource changed)"),
+ ],
+ default="valid",
+ max_length=16,
+ ),
+ ),
+ ("validation_errors", models.JSONField(blank=True, null=True)),
+ ("validated_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("approved", "Approved (awaiting application)"),
+ ("applied", "Applied"),
+ ("rejected", "Rejected"),
+ ("expired", "Expired"),
+ ("failed", "Failed to apply"),
+ ],
+ default="pending",
+ max_length=16,
+ ),
+ ),
+ ("expires_at", models.DateTimeField()),
+ ("applied_at", models.DateTimeField(blank=True, null=True)),
+ ("apply_error", models.TextField(blank=True)),
+ ("result_data", models.JSONField(blank=True, null=True)),
+ (
+ "applied_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="change_requests_applied",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.organization"),
+ ),
+ ("team", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team")),
+ ],
+ options={
+ "db_table": "posthog_changerequest",
+ "ordering": ["-created_at"],
+ },
+ ),
+ migrations.CreateModel(
+ name="Approval",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ (
+ "decision",
+ models.CharField(choices=[("approved", "Approved"), ("rejected", "Rejected")], max_length=16),
+ ),
+ ("reason", models.TextField(blank=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL
+ ),
+ ),
+ (
+ "change_request",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="approvals",
+ to="approvals.changerequest",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_approval",
+ },
+ ),
+ migrations.CreateModel(
+ name="ApprovalPolicy",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("action_key", models.CharField(max_length=128)),
+ ("conditions", models.JSONField(default=dict)),
+ ("approver_config", models.JSONField()),
+ ("allow_self_approve", models.BooleanField(default=False)),
+ ("bypass_org_membership_levels", models.JSONField(default=list)),
+ (
+ "expires_after",
+ models.DurationField(
+ default=datetime.timedelta(days=14), help_text="Auto-expire change requests after this duration"
+ ),
+ ),
+ ("enabled", models.BooleanField(default=True)),
+ (
+ "bypass_roles",
+ models.ManyToManyField(
+ blank=True,
+ db_table="posthog_approvalpolicy_bypass_roles",
+ related_name="bypass_policies",
+ to="ee.role",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.organization"),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"
+ ),
+ ),
+ ],
+ options={
+ "verbose_name_plural": "Approval policies",
+ "db_table": "posthog_approvalpolicy",
+ "indexes": [
+ models.Index(fields=["action_key", "enabled"], name="posthog_app_action__871059_idx"),
+ models.Index(fields=["organization", "enabled"], name="posthog_app_organiz_36e124_idx"),
+ models.Index(fields=["team", "enabled"], name="posthog_app_team_id_9f077f_idx"),
+ ],
+ "unique_together": {("organization", "team", "action_key")},
+ },
+ ),
+ migrations.AddIndex(
+ model_name="changerequest",
+ index=models.Index(fields=["team", "state"], name="posthog_cha_team_id_0a5974_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="changerequest",
+ index=models.Index(fields=["action_key", "state"], name="posthog_cha_action__2d384d_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="changerequest",
+ index=models.Index(fields=["expires_at"], name="posthog_cha_expires_0a6444_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="changerequest",
+ index=models.Index(fields=["validation_status", "state"], name="posthog_cha_validat_24672f_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="approval",
+ index=models.Index(fields=["change_request", "decision"], name="posthog_app_change__5af5e4_idx"),
+ ),
+ migrations.AlterUniqueTogether(
+ name="approval",
+ unique_together={("change_request", "created_by")},
+ ),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(database_operations=database_operations, state_operations=state_operations)
+ ]
diff --git a/products/approvals/backend/migrations/__init__.py b/products/approvals/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/approvals/backend/migrations/max_migration.txt b/products/approvals/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..21e2fe39a8a9
--- /dev/null
+++ b/products/approvals/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_approvals_models
diff --git a/posthog/approvals/mixins.py b/products/approvals/backend/mixins.py
similarity index 89%
rename from posthog/approvals/mixins.py
rename to products/approvals/backend/mixins.py
index ceb458f10408..bc8766c9f3d1 100644
--- a/posthog/approvals/mixins.py
+++ b/products/approvals/backend/mixins.py
@@ -1,8 +1,8 @@
from rest_framework import status
from rest_framework.response import Response
-from posthog.approvals.exceptions import ApprovalRequired
-from posthog.approvals.serializers import ChangeRequestSerializer
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.serializers import ChangeRequestSerializer
class ApprovalHandlingMixin:
diff --git a/posthog/approvals/models.py b/products/approvals/backend/models.py
similarity index 91%
rename from posthog/approvals/models.py
rename to products/approvals/backend/models.py
index 64e8def99bf5..c993b8bbb3ee 100644
--- a/posthog/approvals/models.py
+++ b/products/approvals/backend/models.py
@@ -6,8 +6,8 @@ from django.db import models
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
if TYPE_CHECKING:
- from posthog.approvals.actions.base import BaseAction
- from posthog.approvals.models import ApprovalPolicy as ApprovalPolicyType
+ from products.approvals.backend.actions.base import BaseAction
+ from products.approvals.backend.models import ApprovalPolicy as ApprovalPolicyType
class ChangeRequestState(models.TextChoices):
@@ -71,7 +71,7 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
result_data = models.JSONField(null=True, blank=True)
class Meta:
- app_label = "posthog"
+ db_table = "posthog_changerequest" # pinned to pre-move physical table name, do not rename
indexes = [
models.Index(fields=["team", "state"]),
models.Index(fields=["action_key", "state"]),
@@ -85,7 +85,7 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
def get_policy(self) -> Optional["ApprovalPolicyType"]:
"""Get the matching approval policy for this change request."""
- from posthog.approvals.policies import PolicyEngine
+ from products.approvals.backend.policies import PolicyEngine
return PolicyEngine().get_policy(self.action_key, self.team, self.organization)
@@ -100,7 +100,7 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
def get_action_class(self) -> Optional[type["BaseAction"]]:
"""Get the action class for this change request from the registry."""
- from posthog.approvals.actions.registry import get_action
+ from products.approvals.backend.actions.registry import get_action
return get_action(self.action_key)
@@ -126,7 +126,7 @@ class Approval(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
reason = models.TextField(blank=True)
class Meta:
- app_label = "posthog"
+ db_table = "posthog_approval" # pinned to pre-move physical table name, do not rename
unique_together = [["change_request", "created_by"]]
indexes = [
models.Index(fields=["change_request", "decision"]),
@@ -170,6 +170,7 @@ class ApprovalPolicy(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
"ee.Role",
blank=True,
related_name="bypass_policies",
+ db_table="posthog_approvalpolicy_bypass_roles", # pinned to pre-move physical M2M table name, do not rename
)
expires_after = models.DurationField(
@@ -182,7 +183,7 @@ class ApprovalPolicy(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
objects = ApprovalPolicyManager()
class Meta:
- app_label = "posthog"
+ db_table = "posthog_approvalpolicy" # pinned to pre-move physical table name, do not rename
unique_together = [["organization", "team", "action_key"]]
indexes = [
models.Index(fields=["action_key", "enabled"]),
diff --git a/posthog/approvals/notifications.py b/products/approvals/backend/notifications.py
similarity index 99%
rename from posthog/approvals/notifications.py
rename to products/approvals/backend/notifications.py
index 027d04b64611..f4e331e37fee 100644
--- a/posthog/approvals/notifications.py
+++ b/products/approvals/backend/notifications.py
@@ -16,7 +16,7 @@ from products.notifications.backend.facade.api import (
from products.notifications.backend.facade.enums import NotificationOnlyResourceType
if TYPE_CHECKING:
- from posthog.approvals.models import Approval, ChangeRequest
+ from products.approvals.backend.models import Approval, ChangeRequest
logger = get_logger(__name__)
diff --git a/posthog/approvals/permissions.py b/products/approvals/backend/permissions.py
similarity index 97%
rename from posthog/approvals/permissions.py
rename to products/approvals/backend/permissions.py
index d36cc5854757..c084875f541f 100644
--- a/posthog/approvals/permissions.py
+++ b/products/approvals/backend/permissions.py
@@ -11,7 +11,7 @@ class CanApprove(permissions.BasePermission):
message = "You do not have permission to approve this change request"
def has_object_permission(self, request, view, obj):
- from posthog.approvals.models import ChangeRequestState
+ from products.approvals.backend.models import ChangeRequestState
if obj.state != ChangeRequestState.PENDING:
self.message = "Only pending change requests can be approved"
diff --git a/posthog/approvals/policies.py b/products/approvals/backend/policies.py
similarity index 98%
rename from posthog/approvals/policies.py
rename to products/approvals/backend/policies.py
index d71265c15159..3cd3440c8c6b 100644
--- a/posthog/approvals/policies.py
+++ b/products/approvals/backend/policies.py
@@ -33,7 +33,7 @@ class PolicyEngine:
1. Team-level policy (if team provided)
2. Org-level policy
"""
- from posthog.approvals.models import ApprovalPolicy
+ from products.approvals.backend.models import ApprovalPolicy
policy = None
@@ -66,7 +66,7 @@ class PolicyEngine:
Get all active policies for an action that match the given intent.
Used for conflict detection.
"""
- from posthog.approvals.models import ApprovalPolicy
+ from products.approvals.backend.models import ApprovalPolicy
policies = []
diff --git a/products/approvals/backend/routes.py b/products/approvals/backend/routes.py
new file mode 100644
index 000000000000..f06f4df038e8
--- /dev/null
+++ b/products/approvals/backend/routes.py
@@ -0,0 +1,18 @@
+from posthog.api.routing import RouterRegistry
+
+from products.approvals.backend import api as approval_api
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.register_legacy_dual_route(
+ r"change_requests",
+ approval_api.ChangeRequestViewSet,
+ "project_change_requests",
+ ["team_id"],
+ )
+ routers.register_legacy_dual_route(
+ r"approval_policies",
+ approval_api.ApprovalPolicyViewSet,
+ "project_approval_policies",
+ ["team_id"],
+ )
diff --git a/posthog/approvals/serializers.py b/products/approvals/backend/serializers.py
similarity index 98%
rename from posthog/approvals/serializers.py
rename to products/approvals/backend/serializers.py
index ab573afb0552..893e63509475 100644
--- a/posthog/approvals/serializers.py
+++ b/products/approvals/backend/serializers.py
@@ -2,7 +2,8 @@ from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from posthog.api.shared import UserBasicSerializer
-from posthog.approvals.models import Approval, ApprovalPolicy, ChangeRequest
+
+from products.approvals.backend.models import Approval, ApprovalPolicy, ChangeRequest
class ChangeRequestSerializer(serializers.ModelSerializer):
diff --git a/posthog/approvals/services.py b/products/approvals/backend/services.py
similarity index 97%
rename from posthog/approvals/services.py
rename to products/approvals/backend/services.py
index 3d317ebe2c21..4e75ca84fbc4 100644
--- a/posthog/approvals/services.py
+++ b/products/approvals/backend/services.py
@@ -5,18 +5,22 @@ from typing import Any, Optional
from django.db import transaction
from django.utils import timezone
-from posthog.approvals.actions.registry import get_action
-from posthog.approvals.exceptions import (
+from posthog.event_usage import report_user_action
+from posthog.models import User
+
+from products.approvals.backend.actions.registry import get_action
+from products.approvals.backend.exceptions import (
AlreadyVotedError,
ApplyFailed,
InvalidStateError,
PreconditionFailed,
ReasonRequiredError,
)
-from posthog.approvals.models import Approval, ApprovalDecision, ChangeRequest, ChangeRequestState
-from posthog.approvals.notifications import send_approval_applied_notification, send_approval_decision_notification
-from posthog.event_usage import report_user_action
-from posthog.models import User
+from products.approvals.backend.models import Approval, ApprovalDecision, ChangeRequest, ChangeRequestState
+from products.approvals.backend.notifications import (
+ send_approval_applied_notification,
+ send_approval_decision_notification,
+)
logger = logging.getLogger(__name__)
diff --git a/posthog/approvals/tasks.py b/products/approvals/backend/tasks.py
similarity index 90%
rename from posthog/approvals/tasks.py
rename to products/approvals/backend/tasks.py
index 1795b4983955..2e71c6ae3f3e 100644
--- a/posthog/approvals/tasks.py
+++ b/products/approvals/backend/tasks.py
@@ -6,14 +6,17 @@ from django.utils import timezone
from celery import shared_task
from structlog import get_logger
-from posthog.approvals.models import ChangeRequest, ChangeRequestState, ValidationStatus
-from posthog.approvals.notifications import send_approval_expired_notification
from posthog.scoping_audit import skip_team_scope_audit
+from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus
+from products.approvals.backend.notifications import send_approval_expired_notification
+
logger = get_logger(__name__)
-@shared_task(ignore_result=True)
+# Pin the task name to its pre-move path so the beat schedule and any in-flight
+# messages keep routing after the module moved out of posthog/approvals.
+@shared_task(ignore_result=True, name="posthog.approvals.tasks.validate_pending_change_requests")
@skip_team_scope_audit
def validate_pending_change_requests() -> dict[str, Any]:
"""
@@ -83,7 +86,7 @@ def validate_pending_change_requests() -> dict[str, Any]:
return result
-@shared_task(ignore_result=True)
+@shared_task(ignore_result=True, name="posthog.approvals.tasks.expire_old_change_requests")
@skip_team_scope_audit
def expire_old_change_requests() -> dict[str, Any]:
"""
diff --git a/products/approvals/backend/tests/__init__.py b/products/approvals/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/approvals/tests/test_approvals_api.py b/products/approvals/backend/tests/test_approvals_api.py
similarity index 99%
rename from posthog/approvals/tests/test_approvals_api.py
rename to products/approvals/backend/tests/test_approvals_api.py
index 285677214619..33d719daef6d 100644
--- a/posthog/approvals/tests/test_approvals_api.py
+++ b/products/approvals/backend/tests/test_approvals_api.py
@@ -8,7 +8,10 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.approvals.models import (
+from posthog.constants import AvailableFeature
+from posthog.models import User
+
+from products.approvals.backend.models import (
Approval,
ApprovalDecision,
ApprovalPolicy,
@@ -16,9 +19,6 @@ from posthog.approvals.models import (
ChangeRequestState,
ValidationStatus,
)
-from posthog.constants import AvailableFeature
-from posthog.models import User
-
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -204,7 +204,7 @@ class TestChangeRequestViewSet(APIBaseTest):
assert response.json()["id"] == str(cr.id)
assert response.json()["action_key"] == "feature_flag.enable"
- @patch("posthog.approvals.services.apply_change_request")
+ @patch("products.approvals.backend.services.apply_change_request")
def test_approve_success(self, mock_apply):
mock_apply.return_value = type("obj", (object,), {"id": 123, "version": 1})()
cr = self._create_change_request()
@@ -382,7 +382,7 @@ class TestChangeRequestViewSet(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["can_approve"] is False
- @patch("posthog.approvals.services.apply_change_request")
+ @patch("products.approvals.backend.services.apply_change_request")
def test_approve_succeeds_when_user_in_approver_role(self, mock_apply):
from ee.models.rbac.role import Role, RoleMembership
diff --git a/posthog/approvals/tests/test_notifications.py b/products/approvals/backend/tests/test_notifications.py
similarity index 84%
rename from posthog/approvals/tests/test_notifications.py
rename to products/approvals/backend/tests/test_notifications.py
index 56464cddc050..3b811a73b2d7 100644
--- a/posthog/approvals/tests/test_notifications.py
+++ b/products/approvals/backend/tests/test_notifications.py
@@ -5,8 +5,17 @@ from unittest.mock import MagicMock, patch
from django.utils import timezone
-from posthog.approvals.models import Approval, ApprovalDecision, ApprovalPolicy, ChangeRequest, ChangeRequestState
-from posthog.approvals.notifications import (
+from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP
+from posthog.models.instance_setting import override_instance_config
+
+from products.approvals.backend.models import (
+ Approval,
+ ApprovalDecision,
+ ApprovalPolicy,
+ ChangeRequest,
+ ChangeRequestState,
+)
+from products.approvals.backend.notifications import (
_build_change_request_url,
_send_approval_email,
send_approval_applied_notification,
@@ -14,8 +23,6 @@ from posthog.approvals.notifications import (
send_approval_expired_notification,
send_approval_requested_notification,
)
-from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP
-from posthog.models.instance_setting import override_instance_config
class TestApprovalNotifications(BaseTest):
@@ -92,8 +99,8 @@ class TestBuildChangeRequestUrl(TestApprovalNotifications):
class TestSendApprovalEmail(TestApprovalNotifications):
- @patch("posthog.approvals.notifications.EmailMessage")
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.EmailMessage")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_sends_email_when_available(self, mock_is_email_available, mock_email_message):
mock_is_email_available.return_value = True
mock_message_instance = MagicMock()
@@ -116,7 +123,7 @@ class TestSendApprovalEmail(TestApprovalNotifications):
mock_message_instance.add_user_recipient.assert_called_once_with(self.approver)
mock_message_instance.send.assert_called_once_with(send_async=True)
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_skips_when_email_not_available(self, mock_is_email_available):
mock_is_email_available.return_value = False
@@ -141,7 +148,7 @@ class TestSendApprovalEmail(TestApprovalNotifications):
class TestSendApprovalRequestedNotification(TestApprovalNotifications):
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_sends_to_all_approvers(self, mock_send_email):
send_approval_requested_notification(self.change_request)
@@ -152,7 +159,7 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):
self.assertIn(self.approver, recipients)
self.assertIn(self.approver2, recipients)
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_skips_when_no_policy(self, mock_send_email):
self.policy.delete()
@@ -160,7 +167,7 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):
mock_send_email.assert_not_called()
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_uses_correct_template(self, mock_send_email):
send_approval_requested_notification(self.change_request)
@@ -168,7 +175,7 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):
self.assertEqual(call_kwargs["template_name"], "approval_requested")
self.assertIn("needs your sign-off", call_kwargs["subject"])
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_continues_on_individual_email_failure(self, mock_send_email):
mock_send_email.side_effect = [Exception("Email failed"), None]
@@ -178,8 +185,8 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):
class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_dispatches_one_realtime_per_approver(self, _mock_email, mock_create_notification):
send_approval_requested_notification(self.change_request)
@@ -199,8 +206,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
expected_url = f"/project/{self.change_request.team.project_id}/approvals/{self.change_request.id}"
self.assertEqual(first_data.source_url, expected_url)
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_body_falls_back_to_action_key_when_no_description(self, _mock_email, mock_create_notification):
self.change_request.intent_display = {}
self.change_request.save()
@@ -210,8 +217,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
first_data = mock_create_notification.call_args_list[0].args[0]
self.assertEqual(first_data.body, self.change_request.action_key)
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_no_realtime_dispatch_when_no_policy(self, _mock_email, mock_create_notification):
self.policy.delete()
@@ -219,14 +226,14 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
mock_create_notification.assert_not_called()
- @patch("posthog.approvals.notifications.create_notification", side_effect=RuntimeError("boom"))
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification", side_effect=RuntimeError("boom"))
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_realtime_failure_is_swallowed(self, _mock_email, _mock_create):
# Should not raise — failure is logged and swallowed so email path is not impacted.
send_approval_requested_notification(self.change_request)
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_failure_for_one_approver_does_not_block_others(self, _mock_email, mock_create_notification):
mock_create_notification.side_effect = [RuntimeError("boom"), None]
@@ -236,8 +243,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
target_ids = [call.args[0].target_id for call in mock_create_notification.call_args_list]
self.assertEqual(set(target_ids), {str(self.approver.id), str(self.approver2.id)})
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_no_realtime_dispatch_when_no_approvers(self, _mock_email, mock_create_notification):
self.policy.approver_config = {"users": [], "quorum": 1}
self.policy.save()
@@ -246,8 +253,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
mock_create_notification.assert_not_called()
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_email_failure_does_not_block_realtime(self, mock_email, mock_create_notification):
mock_email.side_effect = RuntimeError("smtp down")
@@ -257,7 +264,7 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):
class TestSendApprovalDecisionNotification(TestApprovalNotifications):
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_sends_approval_notification(self, mock_send_email):
approval = Approval.objects.create(
change_request=self.change_request,
@@ -274,7 +281,7 @@ class TestSendApprovalDecisionNotification(TestApprovalNotifications):
self.assertEqual(call_kwargs["template_name"], "approval_approved")
self.assertIn("approved your change", call_kwargs["subject"])
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_sends_rejection_notification(self, mock_send_email):
approval = Approval.objects.create(
change_request=self.change_request,
@@ -290,7 +297,7 @@ class TestSendApprovalDecisionNotification(TestApprovalNotifications):
self.assertEqual(call_kwargs["template_name"], "approval_rejected")
self.assertEqual(call_kwargs["subject"], "Your change request was declined")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_skips_when_no_requester(self, mock_send_email):
self.change_request.created_by = None
self.change_request.save()
@@ -307,7 +314,7 @@ class TestSendApprovalDecisionNotification(TestApprovalNotifications):
class TestSendApprovalExpiredNotification(TestApprovalNotifications):
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_sends_expired_notification(self, mock_send_email):
send_approval_expired_notification(self.change_request)
@@ -317,7 +324,7 @@ class TestSendApprovalExpiredNotification(TestApprovalNotifications):
self.assertEqual(call_kwargs["template_name"], "approval_expired")
self.assertEqual(call_kwargs["subject"], "Your change request timed out")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_skips_when_no_requester(self, mock_send_email):
self.change_request.created_by = None
self.change_request.save()
@@ -328,7 +335,7 @@ class TestSendApprovalExpiredNotification(TestApprovalNotifications):
class TestSendApprovalAppliedNotification(TestApprovalNotifications):
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_sends_applied_notification(self, mock_send_email):
send_approval_applied_notification(self.change_request)
@@ -338,7 +345,7 @@ class TestSendApprovalAppliedNotification(TestApprovalNotifications):
self.assertEqual(call_kwargs["template_name"], "approval_applied")
self.assertEqual(call_kwargs["subject"], "Your change is live! 🎉")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_skips_when_no_requester(self, mock_send_email):
self.change_request.created_by = None
self.change_request.save()
@@ -349,7 +356,7 @@ class TestSendApprovalAppliedNotification(TestApprovalNotifications):
class TestEmailTemplateRendering(TestApprovalNotifications):
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_approval_requested_template_renders(self, mock_is_email_available):
mock_is_email_available.return_value = True
@@ -370,7 +377,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):
self.assertIn("needs your sign-off", message.html_body)
self.assertIn("Test Team", message.html_body)
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_approval_approved_template_renders(self, mock_is_email_available):
mock_is_email_available.return_value = True
@@ -391,7 +398,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):
self.assertIn("approved your change", message.html_body)
self.assertIn("Test Team", message.html_body)
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_approval_rejected_template_renders(self, mock_is_email_available):
mock_is_email_available.return_value = True
@@ -412,7 +419,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):
self.assertIn("wasn't approved", message.html_body)
self.assertIn("Test Team", message.html_body)
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_approval_expired_template_renders(self, mock_is_email_available):
mock_is_email_available.return_value = True
@@ -432,7 +439,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):
self.assertIn("expired", message.html_body)
self.assertIn("Test Team", message.html_body)
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_approval_applied_template_renders(self, mock_is_email_available):
mock_is_email_available.return_value = True
@@ -452,7 +459,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):
self.assertIn("is live", message.html_body)
self.assertIn("Test Team", message.html_body)
- @patch("posthog.approvals.notifications.is_email_available")
+ @patch("products.approvals.backend.notifications.is_email_available")
def test_templates_contain_cta_button(self, mock_is_email_available):
mock_is_email_available.return_value = True
templates_with_cta = {
@@ -484,8 +491,8 @@ class TestEmailTemplateRendering(TestApprovalNotifications):
class TestRealtimeDispatchOnResolve(TestApprovalNotifications):
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_decision_approved_dispatches_realtime(self, _mock_email, mock_create_notification):
approval = self._create_approval(self.change_request, decision="approved")
@@ -498,8 +505,8 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):
assert data.resource_type.value == "approval"
assert data.source_url == f"/project/{self.team.project_id}/approvals/{self.change_request.id}"
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_decision_rejected_dispatches_realtime(self, _mock_email, mock_create_notification):
approval = self._create_approval(self.change_request, decision="rejected")
@@ -508,24 +515,24 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):
data = mock_create_notification.call_args.args[0]
assert "declined" in data.title.lower()
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_applied_dispatches_realtime(self, _mock_email, mock_create_notification):
send_approval_applied_notification(self.change_request)
data = mock_create_notification.call_args.args[0]
assert "live" in data.title.lower()
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_expired_dispatches_realtime(self, _mock_email, mock_create_notification):
send_approval_expired_notification(self.change_request)
data = mock_create_notification.call_args.args[0]
assert "expired" in data.title.lower()
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_skips_realtime_when_no_requester(self, _mock_email, mock_create_notification):
self.change_request.created_by = None
self.change_request.save()
@@ -535,8 +542,8 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):
mock_create_notification.assert_not_called()
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_email_failure_does_not_block_realtime(self, mock_email, mock_create_notification):
mock_email.side_effect = RuntimeError("smtp down")
@@ -544,16 +551,16 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):
mock_create_notification.assert_called_once()
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_body_uses_intent_display_description(self, _mock_email, mock_create_notification):
send_approval_applied_notification(self.change_request)
data = mock_create_notification.call_args.args[0]
assert data.body == "Update rollout to 50%"
- @patch("posthog.approvals.notifications.create_notification")
- @patch("posthog.approvals.notifications._send_approval_email")
+ @patch("products.approvals.backend.notifications.create_notification")
+ @patch("products.approvals.backend.notifications._send_approval_email")
def test_body_falls_back_to_action_key_when_no_description(self, _mock_email, mock_create_notification):
self.change_request.intent_display = {}
self.change_request.save()
diff --git a/posthog/approvals/tests/test_policy_engine.py b/products/approvals/backend/tests/test_policy_engine.py
similarity index 99%
rename from posthog/approvals/tests/test_policy_engine.py
rename to products/approvals/backend/tests/test_policy_engine.py
index 6d6b2bd87d1c..1c28a4583b7e 100644
--- a/posthog/approvals/tests/test_policy_engine.py
+++ b/products/approvals/backend/tests/test_policy_engine.py
@@ -4,10 +4,11 @@ from posthog.test.base import APIBaseTest
from parameterized import parameterized
-from posthog.approvals.models import ApprovalPolicy
-from posthog.approvals.policies import PolicyEngine
from posthog.models.organization import OrganizationMembership
+from products.approvals.backend.models import ApprovalPolicy
+from products.approvals.backend.policies import PolicyEngine
+
class TestPolicyEngineBypass(APIBaseTest):
def _create_policy(
diff --git a/posthog/approvals/tests/test_services.py b/products/approvals/backend/tests/test_services.py
similarity index 89%
rename from posthog/approvals/tests/test_services.py
rename to products/approvals/backend/tests/test_services.py
index b0d43f73b2d2..b4a54e3d3a9c 100644
--- a/posthog/approvals/tests/test_services.py
+++ b/products/approvals/backend/tests/test_services.py
@@ -7,9 +7,9 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.approvals.exceptions import InvalidStateError
-from posthog.approvals.models import ChangeRequest, ChangeRequestState
-from posthog.approvals.services import ChangeRequestService
+from products.approvals.backend.exceptions import InvalidStateError
+from products.approvals.backend.models import ChangeRequest, ChangeRequestState
+from products.approvals.backend.services import ChangeRequestService
class TestApproveRejectRaceCondition(BaseTest):
diff --git a/posthog/approvals/tests/test_tasks.py b/products/approvals/backend/tests/test_tasks.py
similarity index 91%
rename from posthog/approvals/tests/test_tasks.py
rename to products/approvals/backend/tests/test_tasks.py
index 31ab902ea133..c9e0c5a0fef6 100644
--- a/posthog/approvals/tests/test_tasks.py
+++ b/products/approvals/backend/tests/test_tasks.py
@@ -7,8 +7,8 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.approvals.models import ChangeRequest
-from posthog.approvals.tasks import expire_old_change_requests, validate_pending_change_requests
+from products.approvals.backend.models import ChangeRequest
+from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requests
class TestValidatePendingChangeRequests(BaseTest):
@@ -49,7 +49,7 @@ class TestValidatePendingChangeRequests(BaseTest):
self.assertEqual(result["checked_count"], 0)
self.assertEqual(result["stale_count"], 0)
- @patch("posthog.approvals.tasks.ChangeRequest.get_action_class")
+ @patch("products.approvals.backend.tasks.ChangeRequest.get_action_class")
def test_marks_stale_when_resource_changed(self, mock_get_action):
mock_action = mock_get_action.return_value
mock_action.prepare_context.return_value = {}
@@ -63,7 +63,7 @@ class TestValidatePendingChangeRequests(BaseTest):
self.assertIsNotNone(self.change_request.validation_errors)
self.assertIsNotNone(self.change_request.validated_at)
- @patch("posthog.approvals.tasks.ChangeRequest.get_action_class")
+ @patch("products.approvals.backend.tasks.ChangeRequest.get_action_class")
def test_leaves_unchanged_when_not_stale(self, mock_get_action):
mock_action = mock_get_action.return_value
mock_action.prepare_context.return_value = {}
@@ -124,7 +124,7 @@ class TestExpireOldChangeRequests(BaseTest):
self.expired_request.refresh_from_db()
self.assertEqual(self.expired_request.state, expected_state)
- @patch("posthog.approvals.tasks.send_approval_expired_notification")
+ @patch("products.approvals.backend.tasks.send_approval_expired_notification")
def test_expire_task_sends_notifications(self, mock_notification):
expire_old_change_requests()
diff --git a/posthog/approvals/tests/test_update_feature_flag_action.py b/products/approvals/backend/tests/test_update_feature_flag_action.py
similarity index 94%
rename from posthog/approvals/tests/test_update_feature_flag_action.py
rename to products/approvals/backend/tests/test_update_feature_flag_action.py
index 3f062ad3d0c3..d3aa5592c807 100644
--- a/posthog/approvals/tests/test_update_feature_flag_action.py
+++ b/products/approvals/backend/tests/test_update_feature_flag_action.py
@@ -5,10 +5,9 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from posthog.approvals.actions.feature_flags import UpdateFeatureFlagAction
-from posthog.approvals.models import ApprovalPolicy, ChangeRequest
-from posthog.approvals.policies import PolicyEngine
-
+from products.approvals.backend.actions.feature_flags import UpdateFeatureFlagAction
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
+from products.approvals.backend.policies import PolicyEngine
from products.feature_flags.backend.models.feature_flag import FeatureFlag
SINGLE_DICT_PATHS = {"holdout"}
@@ -199,14 +198,14 @@ class TestCheckStaleness(APIBaseTest):
intent = {"preconditions": {"version": stored_version}}
context = {"instance": flag}
- from posthog.approvals.actions.feature_flags import EnableFeatureFlagAction
+ from products.approvals.backend.actions.feature_flags import EnableFeatureFlagAction
result = EnableFeatureFlagAction.check_staleness(intent, context)
assert result is expected_stale
def test_stale_when_no_instance_in_context(self):
- from posthog.approvals.actions.feature_flags import EnableFeatureFlagAction
+ from products.approvals.backend.actions.feature_flags import EnableFeatureFlagAction
intent = {"preconditions": {"version": 1}}
result = EnableFeatureFlagAction.check_staleness(intent, {})
@@ -214,7 +213,7 @@ class TestCheckStaleness(APIBaseTest):
assert result is True
def test_not_stale_when_no_stored_version(self):
- from posthog.approvals.actions.feature_flags import EnableFeatureFlagAction
+ from products.approvals.backend.actions.feature_flags import EnableFeatureFlagAction
flag = self._create_flag()
intent: dict[str, Any] = {"preconditions": {}}
@@ -248,7 +247,7 @@ class TestCheckStaleness(APIBaseTest):
assert result is True
def test_base_action_check_staleness_always_returns_false(self):
- from posthog.approvals.actions.base import BaseAction
+ from products.approvals.backend.actions.base import BaseAction
result = BaseAction.check_staleness({"preconditions": {"version": 1}}, {})
@@ -387,7 +386,7 @@ class TestMultiPolicyConflictDetection(APIBaseTest):
created_by=self.user,
)
- @patch("posthog.approvals.decorators._is_approvals_enabled", return_value=True)
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
def test_single_policy_match_returns_normal_approval_flow(self, mock_enabled):
flag = self._create_flag()
self._create_policy(
@@ -402,7 +401,7 @@ class TestMultiPolicyConflictDetection(APIBaseTest):
assert response.status_code in [200, 409]
- @patch("posthog.approvals.decorators._is_approvals_enabled", return_value=True)
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
def test_matching_policy_returns_http_400(self, mock_enabled):
flag = self._create_flag()
self._create_policy(
@@ -423,7 +422,7 @@ class TestMultiPolicyConflictDetection(APIBaseTest):
class TestActionRegistrationAndIntegration(APIBaseTest):
def test_update_feature_flag_action_registered_in_registry(self):
- from posthog.approvals.actions.registry import ACTION_REGISTRY, register_actions
+ from products.approvals.backend.actions.registry import ACTION_REGISTRY, register_actions
register_actions()
@@ -431,7 +430,7 @@ class TestActionRegistrationAndIntegration(APIBaseTest):
assert ACTION_REGISTRY["feature_flag.update"] == UpdateFeatureFlagAction
def test_action_coexists_with_enable_disable_actions(self):
- from posthog.approvals.actions.registry import ACTION_REGISTRY, register_actions
+ from products.approvals.backend.actions.registry import ACTION_REGISTRY, register_actions
register_actions()
@@ -439,7 +438,7 @@ class TestActionRegistrationAndIntegration(APIBaseTest):
assert "feature_flag.disable" in ACTION_REGISTRY
assert "feature_flag.update" in ACTION_REGISTRY
- @patch("posthog.approvals.decorators._is_approvals_enabled", return_value=True)
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
def test_enable_disable_detected_before_update(self, mock_enabled):
flag = FeatureFlag.objects.create(
team=self.team,
diff --git a/products/approvals/package.json b/products/approvals/package.json
new file mode 100644
index 000000000000..29e5f52a6291
--- /dev/null
+++ b/products/approvals/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-approvals",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend"
+ }
+}
diff --git a/products/approvals/product.yaml b/products/approvals/product.yaml
new file mode 100644
index 000000000000..eb73b6aaceb4
--- /dev/null
+++ b/products/approvals/product.yaml
@@ -0,0 +1,3 @@
+name: Approvals
+owners:
+ - team-feature-flags
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 3b2ccd0e798f..df83e032d20b 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -27,7 +27,6 @@ from posthog.schema import (
)
from posthog.api.cohort import CohortSerializer
-from posthog.approvals.policies import PolicyEngine
from posthog.event_usage import EventSource, report_user_action
from posthog.models.filters.filter import Filter
from posthog.models.signals import mute_selected_signals
@@ -38,6 +37,7 @@ from posthog.rbac.user_access_control import UserAccessControl
from posthog.utils import str_to_bool
from products.actions.backend.models.action import Action
+from products.approvals.backend.policies import PolicyEngine
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 4f946e96a4ae..729f1ac524f1 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -28,7 +28,6 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
-from posthog.approvals.mixins import ApprovalHandlingMixin
from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.models.filters.filter import Filter
from posthog.models.organization import OrganizationMembership
@@ -40,6 +39,7 @@ from posthog.temporal.common.client import sync_connect
from posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputs
from posthog.user_permissions import UserPermissions
+from products.approvals.backend.mixins import ApprovalHandlingMixin
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.llm_metric_templates import build_template, list_templates
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 75ad6f19c118..a6874419ddcc 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -36,8 +36,6 @@ from posthog.api.services.flags_service import get_flags_from_service
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action
-from posthog.approvals.decorators import approval_gate
-from posthog.approvals.mixins import ApprovalHandlingMixin
from posthog.auth import (
IDJagAccessTokenAuthentication,
OAuthAccessTokenAuthentication,
@@ -69,6 +67,8 @@ from posthog.settings.feature_flags import REMOTE_CONFIG_RATE_LIMITS
from posthog.utils import is_valid_regex
from posthog.views import format_bytes
+from products.approvals.backend.decorators import approval_gate
+from products.approvals.backend.mixins import ApprovalHandlingMixin
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.util import get_all_cohort_dependencies
from products.dashboards.backend.api.dashboard import Dashboard
diff --git a/products/ruff.toml b/products/ruff.toml
index 31677da02c9d..3b09f70990a7 100644
--- a/products/ruff.toml
+++ b/products/ruff.toml
@@ -21,6 +21,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
"actions/backend/**" = ["ANN"]
"alerts/backend/**" = ["ANN"]
"annotations/backend/**" = ["ANN"]
+"approvals/backend/**" = ["ANN"]
"batch_exports/backend/**" = ["ANN"]
"cdp/backend/**" = ["ANN"]
"cohorts/backend/**" = ["ANN"]
@@ -60,6 +61,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
"alerts/**" = ["PLC0415"]
"analytics_platform/**" = ["PLC0415"]
"annotations/**" = ["PLC0415"]
+"approvals/**" = ["PLC0415"]
"batch_exports/**" = ["PLC0415"]
"business_knowledge/**" = ["PLC0415"]
"cdp/**" = ["PLC0415"]
diff --git a/tach.toml b/tach.toml
index 1fdcabab3840..ec1f0ba12cfe 100644
--- a/tach.toml
+++ b/tach.toml
@@ -71,6 +71,7 @@ depends_on = [
"ee",
"products.access_control",
"products.analytics_platform",
+ "products.approvals",
"products.batch_exports",
"products.business_knowledge",
"products.cdp",
@@ -159,6 +160,16 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.approvals"
+depends_on = [
+ "ee",
+ "posthog",
+ "products.feature_flags",
+ "products.notifications",
+]
+layer = "modules"
+
[[modules]]
path = "products.batch_exports"
depends_on = [
@@ -307,6 +318,7 @@ depends_on = [
"ee",
"posthog",
"products.actions",
+ "products.approvals",
"products.ai_observability",
"products.analytics_platform",
"products.data_tools",
@@ -325,6 +337,7 @@ depends_on = [
"products.cohorts",
"ee",
"posthog",
+ "products.approvals",
"products.dashboards",
"products.early_access_features",
"products.experiments",