adloop 0.44.1__tar.gz → 0.46.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {adloop-0.44.1 → adloop-0.46.0}/PKG-INFO +2 -2
- {adloop-0.44.1 → adloop-0.46.0}/README.md +1 -1
- {adloop-0.44.1 → adloop-0.46.0}/pyproject.toml +1 -1
- {adloop-0.44.1 → adloop-0.46.0}/pyproject.toml.orig +1 -1
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/audiences.py +261 -65
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/merchant/read.py +226 -42
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/adloop.md +2 -2
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/server.py +35 -10
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/__main__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/_mcp_patches.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/ai_max.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/assets.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/audiences.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/brands.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/campaign_settings.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/conversion_actions.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/currency.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/custom_conversion_goals.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/enums.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/forecast.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/gaql.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/image_fetch.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/pmax.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/read.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/recommendation_subscriptions.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/recommendations.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/shopping.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/snippet_headers.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/validate_only.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ads/write.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/auth.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/cli.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/config.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/conversion_setup.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/crossref.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/diagnostics.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/admin.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/annotations.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/attribution.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/audit.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/definitions.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/funnels.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/reports.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/retention.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/suggest.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/tracking.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/ga4/write.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gsc/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gsc/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gsc/reports.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gtm/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gtm/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gtm/entities.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gtm/read.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/gtm/write.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/merchant/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/merchant/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/auth.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/_common.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/ad_groups.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/ads.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/campaigns.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/extensions.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/negatives.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/removal.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/manage/targeting.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/read.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/microsoft_ads/write.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/oauth_redirect.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/pagespeed.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/reddit/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/reddit/auth.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/reddit/client.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/reddit/read.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/reddit/schedule.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/reddit/write.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/commands/analyze-performance.md +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/commands/budget-plan.md +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/commands/create-ad.md +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/commands/create-campaign.md +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/commands/diagnose-tracking.md +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules/commands/optimize-campaign.md +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/rules_install.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/runtime.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/approval.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/approval_card.html +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/audit.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/guards.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/outcomes.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/safety/preview.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/tracking.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/upload_card.html +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/uploads.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/views/__init__.py +0 -0
- {adloop-0.44.1 → adloop-0.46.0}/src/adloop/views/performance.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: adloop
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.46.0
|
|
4
4
|
Summary: Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first.
|
|
5
5
|
Keywords: mcp,mcp-server,google-ads,google-ads-mcp,reddit-ads,google-analytics,ga4,claude,chatgpt,cursor,marketing
|
|
6
6
|
Author: Daniel Klose
|
|
@@ -248,7 +248,7 @@ The Google account also needs **Edit** permission on the container (and **Publis
|
|
|
248
248
|
| Tool | What It Does |
|
|
249
249
|
|------|-------------|
|
|
250
250
|
| `list_merchant_accounts` | Discover accessible Merchant Center accounts |
|
|
251
|
-
| `get_merchant_feed_health` | Feed health — approved/pending/disapproved counts per reporting context, top product issues with docs, account-level issues. Disapprovals silently starve Shopping/PMax. |
|
|
251
|
+
| `get_merchant_feed_health` | Feed health — approved/pending/disapproved counts per reporting context, paid surfaces kept apart from free listings, top product issues with docs, account-level issues. Disapprovals silently starve Shopping/PMax. |
|
|
252
252
|
| `get_merchant_product_issues` | The products behind the feed-health counts: which are disapproved, limited or pending, and each issue with its attribute and affected countries |
|
|
253
253
|
|
|
254
254
|
> **Setup for Merchant Center tools** — Enable the **Merchant API** in your GCP project (the Content API for Shopping is deprecated). The Merchant API has no read-only scope; AdLoop uses it strictly read-only. Upgrading OAuth users re-authorize once.
|
|
@@ -216,7 +216,7 @@ The Google account also needs **Edit** permission on the container (and **Publis
|
|
|
216
216
|
| Tool | What It Does |
|
|
217
217
|
|------|-------------|
|
|
218
218
|
| `list_merchant_accounts` | Discover accessible Merchant Center accounts |
|
|
219
|
-
| `get_merchant_feed_health` | Feed health — approved/pending/disapproved counts per reporting context, top product issues with docs, account-level issues. Disapprovals silently starve Shopping/PMax. |
|
|
219
|
+
| `get_merchant_feed_health` | Feed health — approved/pending/disapproved counts per reporting context, paid surfaces kept apart from free listings, top product issues with docs, account-level issues. Disapprovals silently starve Shopping/PMax. |
|
|
220
220
|
| `get_merchant_product_issues` | The products behind the feed-health counts: which are disapproved, limited or pending, and each issue with its attribute and affected countries |
|
|
221
221
|
|
|
222
222
|
> **Setup for Merchant Center tools** — Enable the **Merchant API** in your GCP project (the Content API for Shopping is deprecated). The Merchant API has no read-only scope; AdLoop uses it strictly read-only. Upgrading OAuth users re-authorize once.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""GA4 audiences: list them, create, rename or archive one.
|
|
2
2
|
|
|
3
|
-
An audience is a group of users defined by what they did
|
|
4
|
-
sent
|
|
3
|
+
An audience is a group of users defined by what they did: the events they
|
|
4
|
+
sent, the pages they viewed, or a sequence of both in order. GA4 shares its audiences with every linked Google Ads account that
|
|
5
5
|
allows personalized advertising, where they show up as remarketing lists
|
|
6
6
|
(get_audience_lists) and can be attached to campaigns
|
|
7
7
|
(draft_audience_attachment). That makes a GA4 audience the way to build a
|
|
@@ -28,6 +28,12 @@ ADS_MIN_ACTIVE_USERS = 100
|
|
|
28
28
|
_EVENT = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,39}$")
|
|
29
29
|
_ACTIONS = ("create", "update", "archive")
|
|
30
30
|
_SCOPE = "AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS"
|
|
31
|
+
# A page condition is a page_view event whose page_location (the full URL)
|
|
32
|
+
# contains the text. GA4 names an event parameter by its plain name here.
|
|
33
|
+
_PAGE_EVENT, _PAGE_FIELD = "page_view", "page_location"
|
|
34
|
+
MAX_PAGE_LENGTH = 100
|
|
35
|
+
MAX_SEQUENCE_STEPS = 10
|
|
36
|
+
_STEP_KEYS = {"event", "page", "directly_followed", "within_minutes"}
|
|
31
37
|
OPERATIONS = {action: f"ga4_{action}_audience" for action in _ACTIONS}
|
|
32
38
|
|
|
33
39
|
|
|
@@ -35,26 +41,60 @@ def _enum(value) -> str:
|
|
|
35
41
|
return getattr(value, "name", "") or str(value or "")
|
|
36
42
|
|
|
37
43
|
|
|
38
|
-
def
|
|
39
|
-
"""
|
|
44
|
+
def _condition(expression) -> dict | None:
|
|
45
|
+
"""``{"event": name}`` or ``{"page": text}`` for a filter this module writes, else None."""
|
|
46
|
+
event = getattr(expression, "event_filter", None)
|
|
47
|
+
name = getattr(event, "event_name", "")
|
|
48
|
+
if not name:
|
|
49
|
+
return None
|
|
50
|
+
params = getattr(getattr(event, "event_parameter_filter_expression", None), "and_group", None)
|
|
51
|
+
groups = list(getattr(params, "filter_expressions", None) or [])
|
|
52
|
+
if not groups:
|
|
53
|
+
return {"event": name}
|
|
54
|
+
inner = list(getattr(getattr(groups[0], "or_group", None), "filter_expressions", None) or [])
|
|
55
|
+
if name != _PAGE_EVENT or len(groups) != 1 or len(inner) != 1:
|
|
56
|
+
return None
|
|
57
|
+
field = getattr(inner[0], "dimension_or_metric_filter", None)
|
|
58
|
+
text = getattr(field, "string_filter", None)
|
|
59
|
+
if getattr(field, "field_name", "") != _PAGE_FIELD or _enum(getattr(text, "match_type", "")) != "CONTAINS":
|
|
60
|
+
return None
|
|
61
|
+
return {"page": text.value} if text.value else None
|
|
40
62
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
"""
|
|
45
|
-
simple = getattr(clause, "simple_filter", None)
|
|
46
|
-
expression = getattr(simple, "filter_expression", None)
|
|
63
|
+
|
|
64
|
+
def _any_of(expression) -> list[dict] | None:
|
|
65
|
+
"""The conditions of one AND group holding one OR group, else None."""
|
|
47
66
|
groups = list(getattr(getattr(expression, "and_group", None), "filter_expressions", None) or [])
|
|
48
67
|
if len(groups) != 1:
|
|
49
68
|
return None
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
69
|
+
items = list(getattr(getattr(groups[0], "or_group", None), "filter_expressions", None) or [])
|
|
70
|
+
conditions = [_condition(item) for item in items]
|
|
71
|
+
return conditions if conditions and all(conditions) else None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _clause_sequence(clause) -> list[dict] | None:
|
|
75
|
+
"""The steps of a sequence clause this module could have written, else None."""
|
|
76
|
+
steps = []
|
|
77
|
+
for position, step in enumerate(getattr(getattr(clause, "sequence_filter", None), "sequence_steps", None) or []):
|
|
78
|
+
conditions = _any_of(getattr(step, "filter_expression", None))
|
|
79
|
+
if not conditions or len(conditions) != 1:
|
|
55
80
|
return None
|
|
56
|
-
|
|
57
|
-
|
|
81
|
+
entry = dict(conditions[0])
|
|
82
|
+
if position and getattr(step, "immediately_follows", False):
|
|
83
|
+
entry["directly_followed"] = True
|
|
84
|
+
within = getattr(step, "constraint_duration", None)
|
|
85
|
+
seconds = within.total_seconds() if hasattr(within, "total_seconds") else getattr(within, "seconds", 0)
|
|
86
|
+
if position and seconds:
|
|
87
|
+
entry["within_minutes"] = int(seconds // 60)
|
|
88
|
+
steps.append(entry)
|
|
89
|
+
return steps or None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _is_sequence(clause) -> bool:
|
|
93
|
+
return bool(list(getattr(getattr(clause, "sequence_filter", None), "sequence_steps", None) or []))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _split(conditions: list[dict]) -> tuple[list[str], list[str]]:
|
|
97
|
+
return [c["event"] for c in conditions if "event" in c], [c["page"] for c in conditions if "page" in c]
|
|
58
98
|
|
|
59
99
|
|
|
60
100
|
def audience_entry(audience) -> dict:
|
|
@@ -65,24 +105,35 @@ def audience_entry(audience) -> dict:
|
|
|
65
105
|
"membership_duration_days": int(audience.membership_duration_days or 0),
|
|
66
106
|
"ads_personalization_enabled": bool(audience.ads_personalization_enabled),
|
|
67
107
|
}
|
|
68
|
-
include: list[
|
|
69
|
-
|
|
108
|
+
include: list[dict] | None = None
|
|
109
|
+
sequence: list[dict] | None = None
|
|
110
|
+
exclude: list[dict] = []
|
|
70
111
|
custom = False
|
|
71
112
|
for clause in audience.filter_clauses or []:
|
|
72
|
-
|
|
73
|
-
if
|
|
113
|
+
excluded = _enum(clause.clause_type) == "EXCLUDE"
|
|
114
|
+
if _is_sequence(clause):
|
|
115
|
+
steps = _clause_sequence(clause)
|
|
116
|
+
# This module writes one sequence, as the include clause.
|
|
117
|
+
if steps is None or excluded or sequence is not None or include is not None:
|
|
118
|
+
custom = True
|
|
119
|
+
else:
|
|
120
|
+
sequence = steps
|
|
121
|
+
continue
|
|
122
|
+
conditions = _any_of(getattr(getattr(clause, "simple_filter", None), "filter_expression", None))
|
|
123
|
+
if conditions is None:
|
|
74
124
|
custom = True
|
|
75
|
-
elif
|
|
76
|
-
exclude +=
|
|
77
|
-
|
|
125
|
+
elif excluded:
|
|
126
|
+
exclude += conditions
|
|
127
|
+
elif include is not None or sequence is not None:
|
|
78
128
|
# Clauses are AND'ed; this module only ever writes one include clause.
|
|
79
|
-
custom =
|
|
80
|
-
|
|
129
|
+
custom = True
|
|
130
|
+
else:
|
|
131
|
+
include = conditions
|
|
81
132
|
if not audience.filter_clauses:
|
|
82
133
|
# "All Users" and "Purchasers", which GA4 creates itself: the API
|
|
83
134
|
# returns no conditions for them.
|
|
84
135
|
entry["predefined"] = True
|
|
85
|
-
elif custom or
|
|
136
|
+
elif custom or (include is None and sequence is None):
|
|
86
137
|
# Built in GA4's own editor with conditions this module does not write.
|
|
87
138
|
entry["custom_conditions"] = True
|
|
88
139
|
try:
|
|
@@ -90,9 +141,20 @@ def audience_entry(audience) -> dict:
|
|
|
90
141
|
except Exception: # noqa: BLE001 - only there to show what the audience matches
|
|
91
142
|
pass
|
|
92
143
|
else:
|
|
93
|
-
|
|
144
|
+
if sequence is not None:
|
|
145
|
+
entry["sequence"] = sequence
|
|
146
|
+
else:
|
|
147
|
+
events, pages = _split(include)
|
|
148
|
+
if events:
|
|
149
|
+
entry["include_events"] = events
|
|
150
|
+
if pages:
|
|
151
|
+
entry["include_pages"] = pages
|
|
94
152
|
if exclude:
|
|
95
|
-
|
|
153
|
+
events, pages = _split(exclude)
|
|
154
|
+
if events:
|
|
155
|
+
entry["exclude_events"] = events
|
|
156
|
+
if pages:
|
|
157
|
+
entry["exclude_pages"] = pages
|
|
96
158
|
entry["exclude_permanently"] = _enum(audience.exclusion_duration_mode) == "EXCLUDE_PERMANENTLY"
|
|
97
159
|
return entry
|
|
98
160
|
|
|
@@ -189,6 +251,60 @@ def _events(label: str, values: list[str] | None, errors: list[str]) -> list[str
|
|
|
189
251
|
return names
|
|
190
252
|
|
|
191
253
|
|
|
254
|
+
def _pages(label: str, values: list[str] | None, errors: list[str]) -> list[str]:
|
|
255
|
+
pages = list(dict.fromkeys(str(v).strip() for v in values or [] if str(v).strip()))
|
|
256
|
+
for page in pages:
|
|
257
|
+
if len(page) > MAX_PAGE_LENGTH:
|
|
258
|
+
errors.append(f"{label} '{page[:40]}...' is longer than {MAX_PAGE_LENGTH} characters")
|
|
259
|
+
elif page == "/":
|
|
260
|
+
errors.append(f"{label} '/' is part of every URL; use include_events=['session_start'] for every visitor")
|
|
261
|
+
return pages
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _steps(values: list | None, errors: list[str]) -> list[dict]:
|
|
265
|
+
"""Sequence steps as ``{"event" | "page", directly_followed?, within_minutes?}``."""
|
|
266
|
+
steps: list[dict] = []
|
|
267
|
+
for position, raw in enumerate(values or []):
|
|
268
|
+
where = f"sequence step {position + 1}"
|
|
269
|
+
step = {"event": raw} if isinstance(raw, str) else raw
|
|
270
|
+
if not isinstance(step, dict):
|
|
271
|
+
errors.append(f"{where}: an event name, or an object with event or page")
|
|
272
|
+
continue
|
|
273
|
+
unknown = set(step) - _STEP_KEYS
|
|
274
|
+
if unknown:
|
|
275
|
+
errors.append(f"{where}: unknown key(s) {sorted(unknown)}; use event, page, directly_followed, within_minutes")
|
|
276
|
+
continue
|
|
277
|
+
event, page = str(step.get("event") or "").strip(), str(step.get("page") or "").strip()
|
|
278
|
+
if bool(event) == bool(page):
|
|
279
|
+
errors.append(f"{where}: give exactly one of event or page")
|
|
280
|
+
continue
|
|
281
|
+
entry = {"event": _events(f"{where}:", [event], errors)[0]} if event else {"page": page}
|
|
282
|
+
if page:
|
|
283
|
+
_pages(f"{where}:", [page], errors)
|
|
284
|
+
if step.get("directly_followed"):
|
|
285
|
+
if position == 0:
|
|
286
|
+
errors.append(f"{where}: directly_followed applies from the second step on")
|
|
287
|
+
entry["directly_followed"] = True
|
|
288
|
+
within = step.get("within_minutes")
|
|
289
|
+
if within is not None:
|
|
290
|
+
if position == 0 or isinstance(within, bool) or not isinstance(within, int) or within < 1:
|
|
291
|
+
errors.append(f"{where}: within_minutes is a whole number of minutes, from the second step on")
|
|
292
|
+
else:
|
|
293
|
+
entry["within_minutes"] = within
|
|
294
|
+
steps.append(entry)
|
|
295
|
+
if values and not errors and not 2 <= len(steps) <= MAX_SEQUENCE_STEPS:
|
|
296
|
+
errors.append(f"sequence needs 2 to {MAX_SEQUENCE_STEPS} steps")
|
|
297
|
+
return steps
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _label(condition: dict) -> str:
|
|
301
|
+
return f"viewed a page containing '{condition['page']}'" if "page" in condition else f"sent {condition['event']}"
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _conditions(events: list[str], pages: list[str]) -> list[dict]:
|
|
305
|
+
return [{"event": e} for e in events] + [{"page": p} for p in pages]
|
|
306
|
+
|
|
307
|
+
|
|
192
308
|
def _find(audiences: list[dict], audience: str) -> list[dict]:
|
|
193
309
|
wanted = audience.strip()
|
|
194
310
|
by_resource = [a for a in audiences if a["audience"] == wanted or a["audience"].rsplit("/", 1)[-1] == wanted]
|
|
@@ -199,11 +315,28 @@ def _editable(entry: dict) -> dict:
|
|
|
199
315
|
return {"display_name": entry["display_name"], "description": entry["description"]}
|
|
200
316
|
|
|
201
317
|
|
|
202
|
-
def
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
318
|
+
def _phrase(conditions: list[dict]) -> str:
|
|
319
|
+
events, pages = _split(conditions)
|
|
320
|
+
parts = []
|
|
321
|
+
if events:
|
|
322
|
+
parts.append(f"sent {' or '.join(events)}")
|
|
323
|
+
if pages:
|
|
324
|
+
quoted = " or ".join(f"'{page}'" for page in pages)
|
|
325
|
+
parts.append(f"viewed a page containing {quoted}")
|
|
326
|
+
return " or ".join(parts)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _generated_description(include: list[dict], exclude: list[dict], sequence: list[dict], days: int) -> str:
|
|
330
|
+
if sequence:
|
|
331
|
+
text = "Users who " + ", then ".join(_label(step) for step in sequence)
|
|
332
|
+
else:
|
|
333
|
+
text = f"Users who {_phrase(include)}"
|
|
334
|
+
if exclude and not _split(exclude)[1]:
|
|
335
|
+
text += f", without {' or '.join(_split(exclude)[0])}"
|
|
336
|
+
elif exclude:
|
|
337
|
+
text += f"; not those who {_phrase(exclude)}"
|
|
338
|
+
# GA4 caps the description at 150 characters.
|
|
339
|
+
return f"{text[:138].rstrip()}; {days} days."
|
|
207
340
|
|
|
208
341
|
|
|
209
342
|
def draft_ga4_audience(
|
|
@@ -218,6 +351,9 @@ def draft_ga4_audience(
|
|
|
218
351
|
membership_duration_days: int = 30,
|
|
219
352
|
exclude_permanently: bool = False,
|
|
220
353
|
audience: str = "",
|
|
354
|
+
include_pages: list[str] | None = None,
|
|
355
|
+
exclude_pages: list[str] | None = None,
|
|
356
|
+
sequence: list | None = None,
|
|
221
357
|
) -> dict:
|
|
222
358
|
"""Draft creating, renaming or archiving a GA4 audience: returns a PREVIEW."""
|
|
223
359
|
from adloop.ga4.admin import check_property, fingerprint, service_level
|
|
@@ -241,16 +377,22 @@ def draft_ga4_audience(
|
|
|
241
377
|
description = description.strip()
|
|
242
378
|
include = _events("include_events:", include_events, errors)
|
|
243
379
|
exclude = _events("exclude_events:", exclude_events, errors)
|
|
380
|
+
in_pages = _pages("include_pages:", include_pages, errors)
|
|
381
|
+
out_pages = _pages("exclude_pages:", exclude_pages, errors)
|
|
382
|
+
steps = _steps(sequence, errors)
|
|
383
|
+
has_exclusion = bool(exclude or out_pages)
|
|
244
384
|
|
|
245
385
|
if action == "create":
|
|
246
386
|
if not display_name:
|
|
247
387
|
errors.append("display_name is required")
|
|
248
|
-
if
|
|
388
|
+
if steps and (include or in_pages):
|
|
389
|
+
errors.append("pass either sequence or include_events / include_pages, not both")
|
|
390
|
+
elif not (include or in_pages or sequence):
|
|
249
391
|
errors.append(
|
|
250
|
-
"
|
|
251
|
-
"['
|
|
392
|
+
"say who joins: include_events (e.g. ['session_start'] for every visitor, ['purchase'] for "
|
|
393
|
+
"buyers), include_pages (e.g. ['/pricing']) or a sequence of steps"
|
|
252
394
|
)
|
|
253
|
-
overlap = sorted(set(include) & set(exclude))
|
|
395
|
+
overlap = sorted(set(include) & set(exclude)) + sorted(set(in_pages) & set(out_pages))
|
|
254
396
|
if overlap:
|
|
255
397
|
errors.append(f"{', '.join(overlap)} cannot be both included and excluded")
|
|
256
398
|
try:
|
|
@@ -259,8 +401,8 @@ def draft_ga4_audience(
|
|
|
259
401
|
days = 0
|
|
260
402
|
if not 1 <= days <= MAX_MEMBERSHIP_DAYS:
|
|
261
403
|
errors.append(f"membership_duration_days must be between 1 and {MAX_MEMBERSHIP_DAYS}")
|
|
262
|
-
if exclude_permanently and not
|
|
263
|
-
errors.append("exclude_permanently needs exclude_events")
|
|
404
|
+
if exclude_permanently and not has_exclusion:
|
|
405
|
+
errors.append("exclude_permanently needs exclude_events or exclude_pages")
|
|
264
406
|
elif not audience:
|
|
265
407
|
errors.append(f"name the audience to {action}: its display name or its resource name (list_ga4_audiences)")
|
|
266
408
|
if errors:
|
|
@@ -280,23 +422,35 @@ def draft_ga4_audience(
|
|
|
280
422
|
changes = {
|
|
281
423
|
"property_id": pid,
|
|
282
424
|
"display_name": display_name,
|
|
283
|
-
"description": description or _generated_description(
|
|
284
|
-
|
|
425
|
+
"description": description or _generated_description(
|
|
426
|
+
_conditions(include, in_pages), _conditions(exclude, out_pages), steps, days),
|
|
285
427
|
"membership_duration_days": days,
|
|
286
428
|
}
|
|
287
|
-
|
|
288
|
-
|
|
429
|
+
for key, value in (("sequence", steps), ("include_events", include), ("include_pages", in_pages),
|
|
430
|
+
("exclude_events", exclude), ("exclude_pages", out_pages)):
|
|
431
|
+
if value:
|
|
432
|
+
changes[key] = value
|
|
433
|
+
if has_exclusion:
|
|
289
434
|
changes["exclude_permanently"] = bool(exclude_permanently)
|
|
290
435
|
warnings += [
|
|
291
|
-
"The
|
|
436
|
+
"The conditions and the membership duration cannot be changed after creation; only the name and "
|
|
292
437
|
"description can. A wrong audience has to be archived and created again.",
|
|
293
438
|
"GA4 fills it from now on, and adds users who met the conditions in the last 30 days for its use "
|
|
294
439
|
"in Google Ads. It takes one to two days to appear in a linked Google Ads account.",
|
|
295
440
|
]
|
|
296
|
-
if
|
|
441
|
+
if in_pages or out_pages or any("page" in step for step in steps):
|
|
442
|
+
warnings.append(
|
|
443
|
+
"A page matches when its full URL contains the text, without regard to upper and lower case: "
|
|
444
|
+
"'/pricing' also matches '/pricing/enterprise' and '/en/pricing'. Page views are counted from "
|
|
445
|
+
"GA4's page_view event."
|
|
446
|
+
)
|
|
447
|
+
if steps:
|
|
297
448
|
warnings.append(
|
|
298
|
-
|
|
449
|
+
"The steps have to happen in this order; a user who did them in another order does not join."
|
|
299
450
|
)
|
|
451
|
+
if has_exclusion and exclude_permanently:
|
|
452
|
+
kept_out = " or ".join(_label(c) for c in _conditions(exclude, out_pages))
|
|
453
|
+
warnings.append(f"Users who ever {kept_out} are kept out for good, also after they stop.")
|
|
300
454
|
warnings += [c["detail"] for c in ads_readiness(config, pid) if c["status"] == "warn" or c["check"] == "consent"]
|
|
301
455
|
plan = ChangePlan(operation=operation, entity_type="ga4_audience", entity_id=display_name, changes=changes)
|
|
302
456
|
else:
|
|
@@ -328,9 +482,9 @@ def draft_ga4_audience(
|
|
|
328
482
|
if not description:
|
|
329
483
|
return {"error": "GA4 requires a description; it cannot be emptied."}
|
|
330
484
|
after["description"] = description
|
|
331
|
-
if include or exclude:
|
|
332
|
-
return {"error": "GA4 fixes an audience's
|
|
333
|
-
"can change; archive the audience and create a new one for other
|
|
485
|
+
if include or exclude or in_pages or out_pages or steps:
|
|
486
|
+
return {"error": "GA4 fixes an audience's conditions at creation. Only display_name and description "
|
|
487
|
+
"can change; archive the audience and create a new one for other conditions."}
|
|
334
488
|
changed = [k for k in after if after[k] != before[k]]
|
|
335
489
|
if not changed:
|
|
336
490
|
return {"status": "NO_CHANGE", "message": f"The audience '{current['display_name']}' already has these values.",
|
|
@@ -379,25 +533,62 @@ def preflight(config: AdLoopConfig, plan) -> dict:
|
|
|
379
533
|
return {"slots_left_after_apply": limit - len(audiences) - 1}
|
|
380
534
|
|
|
381
535
|
|
|
382
|
-
def
|
|
383
|
-
"""
|
|
536
|
+
def _expression(types, conditions: list[dict]):
|
|
537
|
+
"""Users who met any of ``conditions``, at any time.
|
|
384
538
|
|
|
385
539
|
GA4 wants an AND group at the top that holds OR groups, and event
|
|
386
540
|
filters only inside an OR group.
|
|
387
541
|
"""
|
|
542
|
+
def group(kind: str, items: list):
|
|
543
|
+
return types.AudienceFilterExpression(**{kind: types.AudienceFilterExpressionList(filter_expressions=items)})
|
|
544
|
+
|
|
545
|
+
def event_filter(condition: dict):
|
|
546
|
+
if "event" in condition:
|
|
547
|
+
return types.AudienceEventFilter(event_name=condition["event"])
|
|
548
|
+
field = types.AudienceDimensionOrMetricFilter(
|
|
549
|
+
field_name=_PAGE_FIELD,
|
|
550
|
+
string_filter=types.AudienceDimensionOrMetricFilter.StringFilter(
|
|
551
|
+
match_type=types.AudienceDimensionOrMetricFilter.StringFilter.MatchType.CONTAINS,
|
|
552
|
+
value=condition["page"],
|
|
553
|
+
),
|
|
554
|
+
at_any_point_in_time=True,
|
|
555
|
+
)
|
|
556
|
+
return types.AudienceEventFilter(
|
|
557
|
+
event_name=_PAGE_EVENT,
|
|
558
|
+
event_parameter_filter_expression=group("and_group", [
|
|
559
|
+
group("or_group", [types.AudienceFilterExpression(dimension_or_metric_filter=field)])
|
|
560
|
+
]),
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
return group("and_group", [
|
|
564
|
+
group("or_group", [types.AudienceFilterExpression(event_filter=event_filter(c)) for c in conditions])
|
|
565
|
+
])
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _clause(types, clause_type: str, conditions: list[dict]):
|
|
388
569
|
return types.AudienceFilterClause(
|
|
389
570
|
clause_type=types.AudienceFilterClause.AudienceClauseType[clause_type],
|
|
390
571
|
simple_filter=types.AudienceSimpleFilter(
|
|
391
|
-
scope=types.AudienceFilterScope[_SCOPE],
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
572
|
+
scope=types.AudienceFilterScope[_SCOPE], filter_expression=_expression(types, conditions)),
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _sequence_clause(types, steps: list[dict]):
|
|
577
|
+
from datetime import timedelta
|
|
578
|
+
|
|
579
|
+
scope = types.AudienceFilterScope[_SCOPE]
|
|
580
|
+
built = []
|
|
581
|
+
for step in steps:
|
|
582
|
+
kwargs = {}
|
|
583
|
+
if step.get("directly_followed"):
|
|
584
|
+
kwargs["immediately_follows"] = True
|
|
585
|
+
if step.get("within_minutes"):
|
|
586
|
+
kwargs["constraint_duration"] = timedelta(minutes=step["within_minutes"])
|
|
587
|
+
built.append(types.AudienceSequenceFilter.AudienceSequenceStep(
|
|
588
|
+
scope=scope, filter_expression=_expression(types, [step]), **kwargs))
|
|
589
|
+
return types.AudienceFilterClause(
|
|
590
|
+
clause_type=types.AudienceFilterClause.AudienceClauseType["INCLUDE"],
|
|
591
|
+
sequence_filter=types.AudienceSequenceFilter(scope=scope, sequence_steps=built),
|
|
401
592
|
)
|
|
402
593
|
|
|
403
594
|
|
|
@@ -405,10 +596,15 @@ def build_audience(changes: dict):
|
|
|
405
596
|
"""The Audience message for a create plan."""
|
|
406
597
|
from google.analytics.admin_v1alpha import types
|
|
407
598
|
|
|
408
|
-
|
|
599
|
+
if changes.get("sequence"):
|
|
600
|
+
clauses = [_sequence_clause(types, changes["sequence"])]
|
|
601
|
+
else:
|
|
602
|
+
clauses = [_clause(types, "INCLUDE", _conditions(changes.get("include_events") or [],
|
|
603
|
+
changes.get("include_pages") or []))]
|
|
409
604
|
kwargs = {}
|
|
410
|
-
|
|
411
|
-
|
|
605
|
+
excluded = _conditions(changes.get("exclude_events") or [], changes.get("exclude_pages") or [])
|
|
606
|
+
if excluded:
|
|
607
|
+
clauses.append(_clause(types, "EXCLUDE", excluded))
|
|
412
608
|
mode = "EXCLUDE_PERMANENTLY" if changes.get("exclude_permanently") else "EXCLUDE_TEMPORARILY"
|
|
413
609
|
kwargs["exclusion_duration_mode"] = types.Audience.AudienceExclusionDurationMode[mode]
|
|
414
610
|
return types.Audience(
|