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(ingestion): show tokens and restriction shortcut on tophog dashboard (#69769)

Paweł Ledwoń4c6923ba332c
diff --git a/ee/urls.py b/ee/urls.py
index a53ce8d233c0..fac83e2dea07 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -123,7 +123,7 @@ if settings.ADMIN_PORTAL_ENABLED:
from posthog.admin.admins.radar_bypass_admin import RadarBypassViewSet, radar_bypass_view
from posthog.admin.admins.realtime_cohort_calculation_admin import analyze_realtime_cohort_calculation_view
from posthog.admin.admins.resave_cohorts_admin import resave_cohorts_view
- from posthog.admin.admins.tophog_admin import tophog_dashboard_view
+ from posthog.admin.admins.tophog_admin import tophog_dashboard_view, tophog_restrictions_view
admin_urlpatterns = [
# APPEND_SLASH is disabled globally, so redirect /admin to /admin/ explicitly
@@ -199,6 +199,11 @@ if settings.ADMIN_PORTAL_ENABLED:
admin.site.admin_view(tophog_dashboard_view),
name="tophog-dashboard",
),
+ path(
+ "admin/tophog/restrictions/",
+ admin.site.admin_view(tophog_restrictions_view),
+ name="tophog-restrictions",
+ ),
path(
"admin/health-checks/",
admin.site.admin_view(health_check_list_view),
diff --git a/posthog/admin/admins/event_ingestion_restriction_config.py b/posthog/admin/admins/event_ingestion_restriction_config.py
index 62cca456895e..408b4551379b 100644
--- a/posthog/admin/admins/event_ingestion_restriction_config.py
+++ b/posthog/admin/admins/event_ingestion_restriction_config.py
@@ -141,6 +141,15 @@ class EventIngestionRestrictionConfigAdmin(admin.ModelAdmin):
def has_event_uuids(self, obj):
return bool(obj.event_uuids)
+ def get_changeform_initial_data(self, request):
+ initial = super().get_changeform_initial_data(request)
+ # Allow prefilling the pipelines checkboxes from a comma-separated GET param
+ # (used by the tophog restrictions page)
+ pipelines = initial.get("pipelines")
+ if isinstance(pipelines, str):
+ initial["pipelines"] = [p for p in pipelines.split(",") if p]
+ return initial
+
def get_form(self, request, obj=None, change=False, **kwargs):
form = super().get_form(request, obj, change, **kwargs)
restriction_type_field = form.base_fields.get("restriction_type")
diff --git a/posthog/admin/admins/tophog_admin.py b/posthog/admin/admins/tophog_admin.py
index 4214d7316c12..bfdb6a5a04a9 100644
--- a/posthog/admin/admins/tophog_admin.py
+++ b/posthog/admin/admins/tophog_admin.py
@@ -3,14 +3,36 @@ from collections import OrderedDict, defaultdict
from datetime import UTC, datetime, timedelta
from urllib.parse import urlencode
-from django.contrib import admin
+from django.contrib import admin, messages
from django.core.exceptions import PermissionDenied
+from django.http import HttpResponseRedirect
from django.shortcuts import render
+from django.urls import reverse
+from posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig
+from posthog.models.team.team import Team
from posthog.models.tophog.queries import query_tophog_filter_options, query_tophog_metrics
logger = logging.getLogger(__name__)
+# Maps tophog key fields to EventIngestionRestrictionConfig filter fields, used both for
+# matching existing restrictions against a tophog entry and for prefilling the add form
+RESTRICTION_FILTER_FIELDS = {
+ "distinct_id": "distinct_ids",
+ "session_id": "session_ids",
+ "event_name": "event_names",
+ "event_uuid": "event_uuids",
+}
+
+# Maps tophog pipeline names (INGESTION_PIPELINE deployment values) to
+# EventIngestionRestrictionConfig pipeline values until the naming is unified
+TOPHOG_TO_RESTRICTION_PIPELINE = {
+ "analytics": "analytics",
+ "sessionreplay": "session_recordings",
+ "errortracking": "errortracking",
+ "clientwarnings": "clientwarnings",
+}
+
PRESETS = OrderedDict(
[
("5m", 5),
@@ -53,6 +75,96 @@ def _format_key(key: dict[str, str]) -> str:
return ", ".join(f"{k}: {v}" for k, v in key.items())
+def _resolve_team_tokens(keys: list[dict[str, str]]) -> dict[str, str]:
+ """Map team_id (as it appears in tophog keys) to the team's API token."""
+ team_ids = {key["team_id"] for key in keys if key.get("team_id", "").isdigit()}
+ if not team_ids:
+ return {}
+ teams = Team.objects.filter(id__in=[int(team_id) for team_id in team_ids]).values_list("id", "api_token")
+ return {str(team_id): api_token for team_id, api_token in teams}
+
+
+def _key_token(key: dict[str, str], tokens_by_team_id: dict[str, str]) -> str:
+ token = key.get("token", "")
+ if token and token != "unknown":
+ return token
+ return tokens_by_team_id.get(key.get("team_id", ""), "")
+
+
+def _map_pipelines(tophog_pipelines: list[str]) -> list[str]:
+ return sorted({TOPHOG_TO_RESTRICTION_PIPELINE[p] for p in tophog_pipelines if p in TOPHOG_TO_RESTRICTION_PIPELINE})
+
+
+def _restrictions_page_url(token: str, key: dict[str, str], tophog_pipelines: list[str]) -> str:
+ """Link to the restrictions page for a tophog entry, carrying the full key for search and prefill."""
+ params = {"token": token, **{k: v for k, v in key.items() if k != "token"}}
+ if tophog_pipelines:
+ params["pipelines"] = ",".join(tophog_pipelines)
+ return reverse("tophog-restrictions") + "?" + urlencode(params)
+
+
+def _create_restriction_url(token: str, key: dict[str, str], restriction_pipelines: list[str]) -> str:
+ """Link to the event ingestion restriction add form, prefilled from a tophog key."""
+ params = {"token": token}
+ for key_field, config_field in RESTRICTION_FILTER_FIELDS.items():
+ value = key.get(key_field)
+ if value:
+ params[config_field] = value
+ if restriction_pipelines:
+ params["pipelines"] = ",".join(restriction_pipelines)
+ return reverse("admin:posthog_eventingestionrestrictionconfig_add") + "?" + urlencode(params)
+
+
+def _restriction_matches(
+ restriction: EventIngestionRestrictionConfig, key: dict[str, str], tophog_pipelines: list[str]
+) -> bool:
+ """Whether an existing restriction already covers the tophog entry described by key and pipelines.
+
+ Mirrors the ingestion matching semantics: an empty filter list matches everything,
+ a non-empty list matches if it contains the entry's value (fields combine with AND).
+ Key fields absent from the tophog entry don't disqualify a restriction.
+
+ Pipelines require full coverage: every one of the entry's pipelines must map to a
+ restriction pipeline the restriction applies to. Unmapped pipelines (e.g. ai, heatmaps)
+ can't be restricted at all, so an entry that includes one is never covered.
+ """
+ if _extendable_fields(restriction, key):
+ return False
+ if tophog_pipelines:
+ mapped = [TOPHOG_TO_RESTRICTION_PIPELINE.get(p) for p in tophog_pipelines]
+ if None in mapped:
+ return False
+ if restriction.pipelines and not set(mapped) <= set(restriction.pipelines):
+ return False
+ return True
+
+
+def _extendable_fields(restriction: EventIngestionRestrictionConfig, key: dict[str, str]) -> list[str]:
+ """Filter fields whose configured values exclude the tophog entry's value.
+
+ Only non-empty lists qualify: appending to an empty list would narrow a
+ match-everything filter down to a single value instead of extending it.
+ """
+ extendable = []
+ for key_field, config_field in RESTRICTION_FILTER_FIELDS.items():
+ value = key.get(key_field)
+ configured = getattr(restriction, config_field) or []
+ if value and configured and value not in configured:
+ extendable.append(config_field)
+ return extendable
+
+
+def _extend_restriction(restriction: EventIngestionRestrictionConfig, key: dict[str, str]) -> list[str]:
+ """Append the tophog entry's key values to the restriction's filter lists; returns changed fields."""
+ changed = _extendable_fields(restriction, key)
+ for key_field, config_field in RESTRICTION_FILTER_FIELDS.items():
+ if config_field in changed:
+ setattr(restriction, config_field, [*getattr(restriction, config_field), key[key_field]])
+ if changed:
+ restriction.save()
+ return changed
+
+
def tophog_dashboard_view(request):
if not request.user.is_staff:
raise PermissionDenied
@@ -80,8 +192,11 @@ def tophog_dashboard_view(request):
lane=selected_lane or None,
)
+ tokens_by_team_id = _resolve_team_tokens([row["key"] for row in rows])
+
for row in rows:
table_name = f"{row['metric']} ({row['type']})"
+ token = _key_token(row["key"], tokens_by_team_id)
metrics[table_name].append(
{
"key": _format_key(row["key"]),
@@ -89,6 +204,8 @@ def tophog_dashboard_view(request):
"count": row["obs"],
"pipeline": ", ".join(row["pipelines"]),
"lane": ", ".join(row["lanes"]),
+ "token": token,
+ "restrictions_url": (_restrictions_page_url(token, row["key"], row["pipelines"]) if token else ""),
}
)
except Exception as e:
@@ -124,3 +241,60 @@ def tophog_dashboard_view(request):
"filter_qs": filter_qs,
}
return render(request, "admin/tophog.html", context)
+
+
+def tophog_restrictions_view(request):
+ if not request.user.is_staff:
+ raise PermissionDenied
+
+ token = request.GET.get("token", "")
+ key = {k: v for k, v in request.GET.items() if k not in ("token", "pipelines") and v}
+ tophog_pipelines = [p for p in request.GET.get("pipelines", "").split(",") if p]
+ restriction_pipelines = _map_pipelines(tophog_pipelines)
+
+ if request.method == "POST":
+ restriction = EventIngestionRestrictionConfig.objects.filter(
+ pk=request.POST.get("restriction_id"), token=token
+ ).first()
+ if restriction is None:
+ messages.error(request, "Restriction not found for this token.")
+ else:
+ changed = _extend_restriction(restriction, key)
+ if changed:
+ messages.success(
+ request,
+ f"Extended {restriction.get_restriction_type_display()} restriction: {', '.join(changed)}.",
+ )
+ else:
+ messages.info(request, "Nothing to add — restriction unchanged.")
+ # Rebuild the URL from parsed values instead of echoing request data (open-redirect hygiene)
+ return HttpResponseRedirect(_restrictions_page_url(token, key, tophog_pipelines))
+
+ restrictions = (
+ EventIngestionRestrictionConfig.objects.filter(token=token).order_by("restriction_type") if token else []
+ )
+ entries = [
+ {
+ "restriction": restriction,
+ "matches": _restriction_matches(restriction, key, tophog_pipelines),
+ "extendable_fields": _extendable_fields(restriction, key),
+ "edit_url": reverse("admin:posthog_eventingestionrestrictionconfig_change", args=[restriction.pk]),
+ }
+ for restriction in restrictions
+ ]
+
+ unmapped_pipelines = [p for p in tophog_pipelines if p not in TOPHOG_TO_RESTRICTION_PIPELINE]
+
+ context = {
+ **admin.site.each_context(request),
+ "title": "TopHog Restrictions",
+ "token": token,
+ "key": key,
+ "tophog_pipelines": tophog_pipelines,
+ "restriction_pipelines": restriction_pipelines,
+ "unmapped_pipelines": unmapped_pipelines,
+ "entries": entries,
+ "create_url": _create_restriction_url(token, key, restriction_pipelines) if token else "",
+ "dashboard_url": reverse("tophog-dashboard"),
+ }
+ return render(request, "admin/tophog_restrictions.html", context)
diff --git a/posthog/admin/test_tophog_admin.py b/posthog/admin/test_tophog_admin.py
new file mode 100644
index 000000000000..fbabb9928eec
--- /dev/null
+++ b/posthog/admin/test_tophog_admin.py
@@ -0,0 +1,178 @@
+from urllib.parse import parse_qs, urlparse
+
+from posthog.test.base import BaseTest
+
+from django.contrib import admin
+from django.test import RequestFactory
+from django.urls import reverse
+
+from parameterized import parameterized
+
+from posthog.admin.admins.event_ingestion_restriction_config import (
+ EventIngestionRestrictionConfigAdmin,
+ EventIngestionRestrictionConfigForm,
+)
+from posthog.admin.admins.tophog_admin import (
+ RESTRICTION_FILTER_FIELDS,
+ _create_restriction_url,
+ _extend_restriction,
+ _key_token,
+ _map_pipelines,
+ _resolve_team_tokens,
+ _restriction_matches,
+ _restrictions_page_url,
+)
+from posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig, RestrictionType
+
+
+class TestTopHogAdminHelpers(BaseTest):
+ def test_resolve_team_tokens_maps_team_id_to_api_token(self):
+ tokens = _resolve_team_tokens(
+ [
+ {"team_id": str(self.team.id), "distinct_id": "did"},
+ {"team_id": "not-a-number"},
+ {"fn": "process"},
+ ]
+ )
+ self.assertEqual(tokens, {str(self.team.id): self.team.api_token})
+
+ @parameterized.expand(
+ [
+ ("explicit_token", {"token": "phc_abc", "team_id": "1"}, "phc_abc"),
+ ("unknown_placeholder_falls_back_to_team_id", {"token": "unknown", "team_id": "1"}, "resolved"),
+ ("team_id_lookup", {"team_id": "1"}, "resolved"),
+ ("unresolvable_team_id", {"team_id": "2"}, ""),
+ ("no_token_or_team_id", {"fn": "process"}, ""),
+ ]
+ )
+ def test_key_token(self, _name, key, expected):
+ self.assertEqual(_key_token(key, {"1": "resolved"}), expected)
+
+ def test_restrictions_page_url_carries_full_key_and_pipelines(self):
+ url = _restrictions_page_url(
+ "phc_abc",
+ {"team_id": "1", "distinct_id": "did", "partition": "3", "token": "unknown"},
+ ["analytics", "heatmaps"],
+ )
+ parsed = urlparse(url)
+ self.assertEqual(parsed.path, reverse("tophog-restrictions"))
+ self.assertEqual(
+ parse_qs(parsed.query),
+ {
+ "token": ["phc_abc"],
+ "team_id": ["1"],
+ "distinct_id": ["did"],
+ "partition": ["3"],
+ "pipelines": ["analytics,heatmaps"],
+ },
+ )
+
+ def test_create_restriction_url_prefills_add_form_from_key(self):
+ url = _create_restriction_url(
+ "phc_abc",
+ {"team_id": "1", "distinct_id": "did", "session_id": "sid", "partition": "3"},
+ ["analytics", "session_recordings"],
+ )
+ parsed = urlparse(url)
+ self.assertEqual(parsed.path, reverse("admin:posthog_eventingestionrestrictionconfig_add"))
+ self.assertEqual(
+ parse_qs(parsed.query),
+ {
+ "token": ["phc_abc"],
+ "distinct_ids": ["did"],
+ "session_ids": ["sid"],
+ "pipelines": ["analytics,session_recordings"],
+ },
+ )
+
+ def test_prefill_params_are_restriction_form_fields(self):
+ form_fields = EventIngestionRestrictionConfigForm().fields
+ for form_field in ["token", "pipelines", *RESTRICTION_FILTER_FIELDS.values()]:
+ self.assertIn(form_field, form_fields)
+
+ @parameterized.expand(
+ [
+ ("known_names_mapped", ["sessionreplay", "analytics"], ["analytics", "session_recordings"]),
+ ("unknown_names_dropped", ["heatmaps", "ai"], []),
+ ]
+ )
+ def test_map_pipelines(self, _name, tophog_pipelines, expected):
+ self.assertEqual(_map_pipelines(tophog_pipelines), expected)
+
+ @parameterized.expand(
+ [
+ ("empty_filters_cover_everything", {}, {"distinct_id": "d1"}, [], True),
+ ("value_in_list", {"distinct_ids": ["d1", "d2"]}, {"distinct_id": "d1"}, [], True),
+ ("value_not_in_list", {"distinct_ids": ["d2"]}, {"distinct_id": "d1"}, [], False),
+ (
+ "all_fields_must_cover",
+ {"distinct_ids": ["d1"], "session_ids": ["s2"]},
+ {"distinct_id": "d1", "session_id": "s1"},
+ [],
+ False,
+ ),
+ ("pipeline_covered", {}, {}, ["analytics"], True),
+ ("pipeline_disjoint", {"pipelines": ["errortracking"]}, {}, ["analytics"], False),
+ ("unmapped_pipeline_never_covered", {}, {}, ["ai"], False),
+ ("partially_unmapped_never_covered", {}, {}, ["analytics", "ai"], False),
+ ("partial_pipeline_coverage_not_covered", {}, {}, ["analytics", "sessionreplay"], False),
+ (
+ "full_pipeline_coverage",
+ {"pipelines": ["analytics", "session_recordings"]},
+ {},
+ ["analytics", "sessionreplay"],
+ True,
+ ),
+ ]
+ )
+ def test_restriction_matches(self, _name, config_kwargs, key, tophog_pipelines, expected):
+ restriction = EventIngestionRestrictionConfig(
+ token="phc_abc",
+ restriction_type=RestrictionType.DROP_EVENT_FROM_INGESTION,
+ **{"pipelines": ["analytics"], **config_kwargs},
+ )
+ self.assertEqual(_restriction_matches(restriction, key, tophog_pipelines), expected)
+
+ def test_extend_restriction_appends_only_to_nonempty_lists(self):
+ restriction = EventIngestionRestrictionConfig.objects.create(
+ token="phc_extend",
+ restriction_type=RestrictionType.DROP_EVENT_FROM_INGESTION,
+ distinct_ids=["existing"],
+ )
+ changed = _extend_restriction(restriction, {"distinct_id": "new-id", "session_id": "s1"})
+ self.assertEqual(changed, ["distinct_ids"])
+ restriction.refresh_from_db()
+ self.assertEqual(restriction.distinct_ids, ["existing", "new-id"])
+ self.assertEqual(restriction.session_ids, [])
+
+ def test_extend_restriction_noop_when_already_covered(self):
+ restriction = EventIngestionRestrictionConfig.objects.create(
+ token="phc_noop",
+ restriction_type=RestrictionType.DROP_EVENT_FROM_INGESTION,
+ distinct_ids=["d1"],
+ )
+ self.assertEqual(_extend_restriction(restriction, {"distinct_id": "d1"}), [])
+ restriction.refresh_from_db()
+ self.assertEqual(restriction.distinct_ids, ["d1"])
+
+ def test_pipelines_prefill_split_from_comma_separated_param(self):
+ model_admin = EventIngestionRestrictionConfigAdmin(EventIngestionRestrictionConfig, admin.site)
+ request = RequestFactory().get("/", {"token": "phc_x", "pipelines": "analytics,session_recordings"})
+ initial = model_admin.get_changeform_initial_data(request)
+ self.assertEqual(initial["pipelines"], ["analytics", "session_recordings"])
+ self.assertEqual(initial["token"], "phc_x")
+
+ def test_restrictions_view_extend_post(self):
+ self.user.is_staff = True
+ self.user.save()
+ self.client.force_login(self.user)
+ restriction = EventIngestionRestrictionConfig.objects.create(
+ token="phc_view",
+ restriction_type=RestrictionType.DROP_EVENT_FROM_INGESTION,
+ distinct_ids=["existing"],
+ )
+ url = reverse("tophog-restrictions") + "?token=phc_view&distinct_id=new-id"
+ response = self.client.post(url, {"restriction_id": str(restriction.pk)})
+ self.assertEqual(response.status_code, 302)
+ restriction.refresh_from_db()
+ self.assertEqual(restriction.distinct_ids, ["existing", "new-id"])
diff --git a/posthog/models/tophog/queries.py b/posthog/models/tophog/queries.py
index 0ee8100b12c4..eacb3c3e869d 100644
--- a/posthog/models/tophog/queries.py
+++ b/posthog/models/tophog/queries.py
@@ -1,6 +1,7 @@
from datetime import datetime
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
TOPHOG_QUERY = """
WITH filtered AS (
@@ -60,7 +61,8 @@ def query_tophog_metrics(
params["lane"] = lane
query = TOPHOG_QUERY.format(filters=" ".join(filters))
- rows = sync_execute(query, params)
+ with tags_context(product=Product.INGESTION, feature=Feature.DEBUG_QUERY):
+ rows = sync_execute(query, params)
return [
{
@@ -81,7 +83,8 @@ def query_tophog_filter_options(
date_to: datetime,
) -> tuple[list[str], list[str]]:
params: dict[str, datetime] = {"date_from": date_from, "date_to": date_to}
- rows = sync_execute(FILTER_OPTIONS_QUERY, params)
+ with tags_context(product=Product.INGESTION, feature=Feature.DEBUG_QUERY):
+ rows = sync_execute(FILTER_OPTIONS_QUERY, params)
pipelines = sorted({row[0] for row in rows})
lanes = sorted({row[1] for row in rows})
diff --git a/posthog/templates/admin/tophog.html b/posthog/templates/admin/tophog.html
index d22f454f368c..fa146a7919fc 100644
--- a/posthog/templates/admin/tophog.html
+++ b/posthog/templates/admin/tophog.html
@@ -100,6 +100,20 @@
.filter-form button:hover {
opacity: 0.85;
}
+.restriction-link {
+ display: inline-block;
+ padding: 2px 8px;
+ background: var(--primary);
+ color: var(--header-link-color, #fff);
+ border-radius: 4px;
+ font-size: 11px;
+ text-decoration: none;
+ white-space: nowrap;
+}
+.restriction-link:hover {
+ opacity: 0.85;
+ color: var(--header-link-color, #fff);
+}
</style>
{% endblock %}
@@ -178,10 +192,12 @@
<tr>
<th scope="col">Rank</th>
<th scope="col">Key</th>
+ <th scope="col">Token</th>
<th scope="col">Value</th>
<th scope="col">Count</th>
<th scope="col">Pipeline</th>
<th scope="col">Lane</th>
+ <th scope="col"></th>
</tr>
</thead>
<tbody>
@@ -189,10 +205,16 @@
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ entry.key }}</td>
+ <td>{{ entry.token }}</td>
<td>{{ entry.value }}</td>
<td>{{ entry.count }}</td>
<td>{{ entry.pipeline }}</td>
<td>{{ entry.lane }}</td>
+ <td>
+ {% if entry.restrictions_url %}
+ <a href="{{ entry.restrictions_url }}" class="restriction-link">Restrictions</a>
+ {% endif %}
+ </td>
</tr>
{% endfor %}
</tbody>
diff --git a/posthog/templates/admin/tophog_restrictions.html b/posthog/templates/admin/tophog_restrictions.html
new file mode 100644
index 000000000000..d7dabf3fde40
--- /dev/null
+++ b/posthog/templates/admin/tophog_restrictions.html
@@ -0,0 +1,177 @@
+{% extends "admin/base_site.html" %}
+{% load i18n static %}
+
+{% block extrastyle %}
+{{ block.super }}
+<link rel="stylesheet" href="{% static 'admin/css/changelists.css' %}" />
+<link rel="stylesheet" href="{% static 'admin/css/forms.css' %}" />
+<style>
+.entry-context {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-bottom: 15px;
+}
+.entry-context .chip {
+ display: inline-block;
+ padding: 3px 10px;
+ border: 1px solid var(--border-color);
+ border-radius: 12px;
+ font-size: 12px;
+ background: var(--darkened-bg);
+ color: var(--body-fg);
+ white-space: nowrap;
+}
+.entry-context .chip b {
+ font-weight: 600;
+}
+.match-badge {
+ display: inline-block;
+ padding: 2px 8px;
+ border-radius: 10px;
+ font-size: 11px;
+ font-weight: 600;
+ white-space: nowrap;
+}
+.match-badge.matches {
+ background: var(--message-success-bg, #d1f2d9);
+ color: #0a5c2b;
+}
+.match-badge.no-match {
+ background: var(--darkened-bg);
+ color: var(--body-quiet-color);
+}
+.action-link {
+ display: inline-block;
+ padding: 2px 8px;
+ background: var(--primary);
+ color: var(--header-link-color, #fff);
+ border: none;
+ border-radius: 4px;
+ font-size: 11px;
+ text-decoration: none;
+ white-space: nowrap;
+ cursor: pointer;
+ line-height: 1.5;
+}
+.action-link:hover {
+ opacity: 0.85;
+ color: var(--header-link-color, #fff);
+}
+.actions-cell {
+ white-space: nowrap;
+}
+.actions-cell form {
+ display: inline-block;
+ margin: 0;
+}
+.create-bar {
+ margin-top: 15px;
+}
+.create-bar .action-link {
+ padding: 6px 14px;
+ font-size: 12px;
+}
+.pipeline-note {
+ margin: 10px 0;
+ font-size: 12px;
+ color: var(--body-quiet-color);
+}
+</style>
+{% endblock %}
+
+{% if not is_popup %}
+{% block breadcrumbs %}
+<div class="breadcrumbs">
+ <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a>
+ &rsaquo; <a href="{{ dashboard_url }}">TopHog Dashboard</a>
+ &rsaquo; Restrictions
+</div>
+{% endblock %}
+{% endif %}
+
+{% block content %}
+<div id="content-main">
+ <h2>Restrictions for tophog entry</h2>
+
+ <div class="entry-context">
+ <span class="chip"><b>token:</b> {{ token }}</span>
+ {% for k, v in key.items %}
+ <span class="chip"><b>{{ k }}:</b> {{ v }}</span>
+ {% endfor %}
+ {% if tophog_pipelines %}
+ <span class="chip"><b>pipelines:</b> {{ tophog_pipelines|join:", " }}</span>
+ {% endif %}
+ </div>
+
+ {% if restriction_pipelines %}
+ <p class="pipeline-note">
+ Mapped to restriction pipelines: {{ restriction_pipelines|join:", " }}{% if unmapped_pipelines %}
+ (no restriction pipeline mapping for: {{ unmapped_pipelines|join:", " }}){% endif %}
+ </p>
+ {% elif unmapped_pipelines %}
+ <p class="pipeline-note">No restriction pipeline mapping for: {{ unmapped_pipelines|join:", " }}</p>
+ {% endif %}
+
+ {% if not token %}
+ <p class="errornote">No token given — cannot search restrictions.</p>
+ {% elif entries %}
+ <div class="module">
+ <table style="width: 100%;">
+ <caption>Existing restrictions for this token</caption>
+ <thead>
+ <tr>
+ <th scope="col">Type</th>
+ <th scope="col">Pipelines</th>
+ <th scope="col">Distinct IDs</th>
+ <th scope="col">Session IDs</th>
+ <th scope="col">Event names</th>
+ <th scope="col">Event UUIDs</th>
+ <th scope="col">Note</th>
+ <th scope="col">Covers this entry</th>
+ <th scope="col"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for entry in entries %}
+ <tr>
+ <td>{{ entry.restriction.get_restriction_type_display }}</td>
+ <td>{{ entry.restriction.pipelines|join:", " }}</td>
+ <td>{{ entry.restriction.distinct_ids|join:", "|truncatechars:80|default:"all" }}</td>
+ <td>{{ entry.restriction.session_ids|join:", "|truncatechars:80|default:"all" }}</td>
+ <td>{{ entry.restriction.event_names|join:", "|truncatechars:80|default:"all" }}</td>
+ <td>{{ entry.restriction.event_uuids|join:", "|truncatechars:80|default:"all" }}</td>
+ <td>{{ entry.restriction.note|default:""|truncatechars:80 }}</td>
+ <td>
+ {% if entry.matches %}
+ <span class="match-badge matches">covers</span>
+ {% else %}
+ <span class="match-badge no-match">does not cover</span>
+ {% endif %}
+ </td>
+ <td class="actions-cell">
+ {% if entry.extendable_fields %}
+ <form method="post" action="">
+ {% csrf_token %}
+ <input type="hidden" name="restriction_id" value="{{ entry.restriction.pk }}">
+ <button type="submit" class="action-link" title="Append entry values to: {{ entry.extendable_fields|join:', ' }}">Extend</button>
+ </form>
+ {% endif %}
+ <a href="{{ entry.edit_url }}" class="action-link">Edit</a>
+ </td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+ {% else %}
+ <p>No existing restrictions for this token.</p>
+ {% endif %}
+
+ {% if create_url %}
+ <div class="create-bar">
+ <a href="{{ create_url }}" class="action-link">Create new restriction</a>
+ </div>
+ {% endif %}
+</div>
+{% endblock %}