adstack 0.2.0__py3-none-any.whl

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.
adstack/plan.py ADDED
@@ -0,0 +1,177 @@
1
+ """Plan documents: hashing, plan files, and Terraform-style rendering.
2
+
3
+ A plan is a JSON document. It embeds the configuration it was made from, a hash
4
+ of the account state it was made against, the reviewed changes and the exact
5
+ API operations. Applying a plan recomputes all of it from the embedded
6
+ configuration and the account's current state, and refuses any difference.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from .errors import PlanError
17
+
18
+ PLAN_FORMAT = "adstack-plan/1"
19
+ METADATA = ("adstack_version", "created_at")
20
+ """Keys that describe when and how a plan was made; they are not compared when verifying it."""
21
+
22
+ GATES = {
23
+ "allow_enable": "a paused campaign will start serving ads",
24
+ "allow_budget_increase": "a budget or bid on an existing resource will increase",
25
+ "allow_live_changes": "a campaign that is serving now (ENABLED) will change",
26
+ }
27
+ """Permissions a plan can require, in addition to approving the plan."""
28
+
29
+ _SYMBOL = {"create": "+", "update": "~", "remove": "-"}
30
+ _COLOR = {"create": "32", "update": "33", "remove": "31"}
31
+ _TITLE = {
32
+ "campaign": "campaign",
33
+ "budget": "daily budget",
34
+ "location": "location",
35
+ "negative_keyword": "negative keyword",
36
+ "ad_group": "ad group",
37
+ "keyword": "keyword",
38
+ "ad": "",
39
+ }
40
+
41
+
42
+ def fingerprint(value: Any) -> str:
43
+ """SHA-256 of canonical JSON."""
44
+ encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
45
+ return hashlib.sha256(encoded).hexdigest()
46
+
47
+
48
+ def body(plan: dict[str, Any]) -> dict[str, Any]:
49
+ return {key: value for key, value in plan.items() if key not in METADATA}
50
+
51
+
52
+ def plan_hash(plan: dict[str, Any]) -> str:
53
+ return fingerprint(body(plan))
54
+
55
+
56
+ def counts(changes: list[dict[str, Any]]) -> dict[str, int]:
57
+ return {
58
+ "add": sum(change["action"] == "create" for change in changes),
59
+ "change": sum(change["action"] == "update" for change in changes),
60
+ "remove": sum(change["action"] == "remove" for change in changes),
61
+ }
62
+
63
+
64
+ def save(plan: dict[str, Any], path: str | Path) -> None:
65
+ """Write a plan file. Existing files are never overwritten."""
66
+ try:
67
+ with Path(path).open("x", encoding="utf-8") as file:
68
+ json.dump(plan, file, indent=2, ensure_ascii=False)
69
+ file.write("\n")
70
+ except FileExistsError:
71
+ raise PlanError(f"{path} already exists; plan files are never overwritten, choose a new name") from None
72
+
73
+
74
+ def load(path: str | Path) -> dict[str, Any]:
75
+ try:
76
+ plan = json.loads(Path(path).read_text(encoding="utf-8"))
77
+ except (OSError, ValueError) as exc:
78
+ raise PlanError(f"{path}: cannot read the plan file ({exc})") from None
79
+ if not isinstance(plan, dict) or plan.get("format") != PLAN_FORMAT:
80
+ raise PlanError(f"{path}: not an Adstack plan file (or one from an incompatible version)")
81
+ return plan
82
+
83
+
84
+ def is_plan_file(path: str | Path) -> bool:
85
+ path = Path(path)
86
+ if not path.is_file() or path.suffix in (".yaml", ".yml"):
87
+ return False
88
+ try:
89
+ data = json.loads(path.read_text(encoding="utf-8"))
90
+ except (OSError, ValueError):
91
+ return False
92
+ return isinstance(data, dict) and data.get("format") == PLAN_FORMAT
93
+
94
+
95
+ def summary_line(plan: dict[str, Any]) -> str:
96
+ total = plan["summary"]
97
+ return f"Plan: {total['add']} to add, {total['change']} to change, {total['remove']} to remove."
98
+
99
+
100
+ def render(plan: dict[str, Any], *, color: bool = False) -> str:
101
+ """Human-readable plan, in the spirit of ``terraform plan``."""
102
+ lines: list[str] = []
103
+ if plan["changes"]:
104
+ lines += [f"Adstack will perform the following actions in {plan['target']}:", ""]
105
+ lines += render_changes(plan["changes"], color=color)
106
+ lines.append("")
107
+ if plan["blockers"]:
108
+ lines.append("Blocked: this plan cannot be applied until the following are resolved:")
109
+ lines += [f" - {blocker}" for blocker in plan["blockers"]]
110
+ lines.append("")
111
+ required = [gate for gate, needed in plan["requires"].items() if needed]
112
+ if required:
113
+ lines.append("Applying this plan also requires explicit permission:")
114
+ lines += [f" --{gate.replace('_', '-'):<24} {GATES.get(gate, '')}" for gate in required]
115
+ lines.append("")
116
+ if plan["operations"]:
117
+ lines.append(_paint(summary_line(plan), "1", color))
118
+ elif not plan["blockers"]:
119
+ lines.append(f"No changes. The {plan['target']} matches the configuration.")
120
+ return "\n".join(lines).rstrip("\n")
121
+
122
+
123
+ def render_changes(changes: list[dict[str, Any]], *, color: bool = False) -> list[str]:
124
+ lines: list[str] = []
125
+ shown_campaign: str | None = None
126
+ shown_group: str | None = None
127
+ for change in changes:
128
+ resource, campaign, group = change["resource"], change["campaign"], change.get("ad_group")
129
+ if resource == "campaign":
130
+ lines += _entry(change, 0, f"campaign {campaign}", color)
131
+ shown_campaign, shown_group = campaign, None
132
+ continue
133
+ if campaign != shown_campaign:
134
+ lines.append(f" campaign {campaign}")
135
+ shown_campaign, shown_group = campaign, None
136
+ if resource == "ad_group":
137
+ lines += _entry(change, 1, f"ad group {group}", color)
138
+ shown_group = group
139
+ continue
140
+ level = 1
141
+ if group:
142
+ level = 2
143
+ if group != shown_group:
144
+ lines.append(f" ad group {group}")
145
+ shown_group = group
146
+ title = " ".join(part for part in (_TITLE.get(resource, resource), change.get("name") or "") if part)
147
+ if resource == "budget":
148
+ title = _TITLE["budget"]
149
+ lines += _entry(change, level, title, color)
150
+ return lines
151
+
152
+
153
+ def _entry(change: dict[str, Any], level: int, title: str, color: bool) -> list[str]:
154
+ indent = " " + " " * level
155
+ action = change["action"]
156
+ line = f"{indent}{_paint(_SYMBOL[action], _COLOR[action], color)} {title}"
157
+ attributes = change.get("attributes") or {}
158
+ if attributes:
159
+ line += " (" + ", ".join(f"{key} = {_value(value)}" for key, value in attributes.items()) + ")"
160
+ if change.get("note"):
161
+ line += f" # {change['note']}"
162
+ lines = [line]
163
+ for field, (old, new) in (change.get("diff") or {}).items():
164
+ lines.append(f"{indent} {field}: {_value(old)} -> {_value(new)}")
165
+ return lines
166
+
167
+
168
+ def _value(value: Any) -> str:
169
+ if value is None:
170
+ return "(unset)"
171
+ if isinstance(value, bool):
172
+ return "true" if value else "false"
173
+ return str(value)
174
+
175
+
176
+ def _paint(text: str, code: str, color: bool) -> str:
177
+ return f"\033[{code}m{text}\033[0m" if color else text
@@ -0,0 +1,23 @@
1
+ """Ad platform providers.
2
+
3
+ A provider validates its part of the configuration, reads live state, and plans
4
+ changes. The core workflow (saved plans, approval, receipts, the MCP server) is
5
+ shared by every provider. See CONTRIBUTING.md for how to add one.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ..errors import ConfigError
11
+ from .base import Backend, Provider
12
+
13
+ PROVIDERS = ("google_ads",)
14
+
15
+ __all__ = ["PROVIDERS", "Backend", "Provider", "get_provider"]
16
+
17
+
18
+ def get_provider(name: str) -> Provider:
19
+ if name == "google_ads":
20
+ from .google_ads import GoogleAdsProvider
21
+
22
+ return GoogleAdsProvider()
23
+ raise ConfigError(f"provider: unknown provider {name!r} (available: {', '.join(PROVIDERS)})")
@@ -0,0 +1,62 @@
1
+ """The interface between Adstack's workflow (plan, apply, MCP) and an ad platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any, Protocol
8
+
9
+
10
+ class Backend(Protocol):
11
+ """A connection to one ad account: the platform's real API, or a local sandbox."""
12
+
13
+ account: str
14
+ """The account ID that plans are bound to."""
15
+ sandbox: bool
16
+
17
+ def read(self) -> dict[str, Any]:
18
+ """Return a JSON-serializable snapshot of everything Adstack manages in the account."""
19
+ ...
20
+
21
+ def mutate(self, operations: list[dict[str, Any]], *, validate_only: bool) -> dict[str, Any]:
22
+ """Apply operations atomically, or only ask the platform to validate them."""
23
+ ...
24
+
25
+ def report(self, kind: str, days: int, *, all_campaigns: bool = False) -> list[dict[str, Any]]:
26
+ """Return performance rows (``kind`` is ``performance`` or ``search_terms``)."""
27
+ ...
28
+
29
+
30
+ class Provider(Protocol):
31
+ """An ad platform. Everything except ``connect`` is pure and makes no network requests."""
32
+
33
+ name: str
34
+ """Configuration key, for example ``google_ads``."""
35
+ title: str
36
+ """Human-readable platform name, for example ``Google Ads``."""
37
+
38
+ def load(self, settings: Any, document: dict[str, Any]) -> dict[str, Any]:
39
+ """Validate the provider block and the rest of the configuration; return the desired state."""
40
+ ...
41
+
42
+ def summary(self, desired: dict[str, Any]) -> str:
43
+ """One line describing the desired state, for example ``2 campaigns, 5 ad groups``."""
44
+ ...
45
+
46
+ def connect(self, desired: dict[str, Any], *, sandbox_dir: Path | None, env: Mapping[str, str]) -> Backend:
47
+ """Open the configured account, or the local sandbox when ``sandbox_dir`` is set."""
48
+ ...
49
+
50
+ def plan(
51
+ self, desired: dict[str, Any], state: dict[str, Any], account: str, *, prune: bool, destroy: bool
52
+ ) -> dict[str, Any]:
53
+ """Compute ``changes``, ``blockers``, ``requires`` and ``operations``. Must be deterministic."""
54
+ ...
55
+
56
+ def inventory(self, desired: dict[str, Any], state: dict[str, Any]) -> list[dict[str, Any]]:
57
+ """Flatten a snapshot into records with resource, campaign, ad_group, name, status and details."""
58
+ ...
59
+
60
+ def format_account(self, account: str) -> str:
61
+ """Display form of an account ID."""
62
+ ...
@@ -0,0 +1,40 @@
1
+ """Google Ads provider: Search campaigns with manual CPC bidding, managed through the REST API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from . import planner, schema
10
+ from .api import ApiBackend
11
+ from .sandbox import SandboxBackend
12
+
13
+
14
+ class GoogleAdsProvider:
15
+ name = "google_ads"
16
+ title = "Google Ads"
17
+
18
+ def load(self, settings: Any, document: dict[str, Any]) -> dict[str, Any]:
19
+ return schema.load(settings, document)
20
+
21
+ def summary(self, desired: dict[str, Any]) -> str:
22
+ return schema.summary(desired)
23
+
24
+ def connect(
25
+ self, desired: dict[str, Any], *, sandbox_dir: Path | None, env: Mapping[str, str]
26
+ ) -> ApiBackend | SandboxBackend:
27
+ if sandbox_dir is not None:
28
+ return SandboxBackend(Path(sandbox_dir) / "google_ads.json", desired["namespace"], desired["currency"])
29
+ return ApiBackend.connect(desired, env)
30
+
31
+ def plan(
32
+ self, desired: dict[str, Any], state: dict[str, Any], account: str, *, prune: bool, destroy: bool
33
+ ) -> dict[str, Any]:
34
+ return planner.plan(desired, state, account, prune=prune, destroy=destroy)
35
+
36
+ def inventory(self, desired: dict[str, Any], state: dict[str, Any]) -> list[dict[str, Any]]:
37
+ return planner.inventory(state, desired["currency"])
38
+
39
+ def format_account(self, account: str) -> str:
40
+ return schema.format_customer_id(account)
@@ -0,0 +1,342 @@
1
+ """Google Ads REST API backend: OAuth, GAQL search, atomic mutate and reports.
2
+
3
+ Every request goes to ``customers/<account>`` and every mutate uses
4
+ ``partialFailure=false``, so a request either applies completely or not at all.
5
+ Mutations are never retried automatically: after a network failure the outcome
6
+ is unknown, and the only safe next step is to read the account again.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections.abc import Callable, Mapping
13
+ from typing import Any
14
+
15
+ import requests
16
+
17
+ from ... import __version__
18
+ from ...errors import ConfigError, ProviderError
19
+ from .schema import PREFIX, customer_id, format_customer_id
20
+
21
+ API_VERSION = "v26"
22
+ BASE_URL = f"https://googleads.googleapis.com/{API_VERSION}"
23
+ TOKEN_URL = "https://oauth2.googleapis.com/token"
24
+
25
+ ENV_CUSTOMER_ID = "GOOGLE_ADS_CUSTOMER_ID"
26
+ ENV_LOGIN_CUSTOMER_ID = "GOOGLE_ADS_LOGIN_CUSTOMER_ID"
27
+ ENV_ACCESS_TOKEN = "GOOGLE_ADS_ACCESS_TOKEN"
28
+ ENV_CLIENT_ID = "GOOGLE_ADS_CLIENT_ID"
29
+ ENV_CLIENT_SECRET = "GOOGLE_ADS_CLIENT_SECRET"
30
+ ENV_REFRESH_TOKEN = "GOOGLE_ADS_REFRESH_TOKEN"
31
+
32
+ REPORT_KINDS = ("performance", "search_terms")
33
+ REPORT_DAYS = (7, 14, 30)
34
+
35
+ Search = Callable[[str], list[dict[str, Any]]]
36
+
37
+
38
+ def resolve_account(desired: dict[str, Any], env: Mapping[str, str]) -> str:
39
+ """The account comes from the configuration, or else from GOOGLE_ADS_CUSTOMER_ID. They must agree."""
40
+ configured = desired.get("customer_id")
41
+ from_env = customer_id(env[ENV_CUSTOMER_ID], ENV_CUSTOMER_ID) if env.get(ENV_CUSTOMER_ID) else None
42
+ if configured and from_env and configured != from_env:
43
+ raise ConfigError(
44
+ f"The configuration targets account {format_customer_id(configured)}, but {ENV_CUSTOMER_ID} is "
45
+ f"{format_customer_id(from_env)}; unset {ENV_CUSTOMER_ID} or change provider.google_ads.customer_id"
46
+ )
47
+ account = configured or from_env
48
+ if not account:
49
+ raise ConfigError(f"Set provider.google_ads.customer_id in the configuration, or {ENV_CUSTOMER_ID}")
50
+ return account
51
+
52
+
53
+ def resolve_login_customer(desired: dict[str, Any], env: Mapping[str, str]) -> str | None:
54
+ if desired.get("login_customer_id"):
55
+ return desired["login_customer_id"]
56
+ value = env.get(ENV_LOGIN_CUSTOMER_ID)
57
+ return customer_id(value, ENV_LOGIN_CUSTOMER_ID) if value else None
58
+
59
+
60
+ class GoogleAdsClient:
61
+ """A minimal client for the Google Ads REST interface."""
62
+
63
+ def __init__(
64
+ self,
65
+ account: str,
66
+ *,
67
+ env: Mapping[str, str],
68
+ login_customer_id: str | None = None,
69
+ session: requests.Session | None = None,
70
+ ):
71
+ self.account = account
72
+ self.http = session or requests.Session()
73
+ token = env.get(ENV_ACCESS_TOKEN)
74
+ if not token:
75
+ credentials = {
76
+ "client_id": env.get(ENV_CLIENT_ID),
77
+ "client_secret": env.get(ENV_CLIENT_SECRET),
78
+ "refresh_token": env.get(ENV_REFRESH_TOKEN),
79
+ }
80
+ if not all(credentials.values()):
81
+ raise ProviderError(
82
+ f"Google Ads credentials are not set: set {ENV_ACCESS_TOKEN}, or {ENV_CLIENT_ID}, "
83
+ f"{ENV_CLIENT_SECRET} and {ENV_REFRESH_TOKEN}"
84
+ )
85
+ token = self._refresh(credentials)
86
+ self.http.headers.update(
87
+ {
88
+ "Authorization": f"Bearer {token}",
89
+ "Content-Type": "application/json",
90
+ "User-Agent": f"adstack/{__version__}",
91
+ }
92
+ )
93
+ if login_customer_id:
94
+ self.http.headers["login-customer-id"] = login_customer_id
95
+
96
+ def _refresh(self, credentials: dict[str, Any]) -> str:
97
+ try:
98
+ response = self.http.post(TOKEN_URL, data={**credentials, "grant_type": "refresh_token"}, timeout=30)
99
+ response.raise_for_status()
100
+ return response.json()["access_token"]
101
+ except (requests.RequestException, KeyError, ValueError) as exc:
102
+ raise ProviderError(
103
+ "OAuth token refresh failed; check the Google Ads OAuth credentials and their access to the account"
104
+ ) from exc
105
+
106
+ def post(self, endpoint: str, body: dict[str, Any]) -> dict[str, Any]:
107
+ try:
108
+ response = self.http.post(f"{BASE_URL}/customers/{self.account}/{endpoint}", json=body, timeout=60)
109
+ except requests.RequestException as exc:
110
+ raise ProviderError(
111
+ f"{endpoint}: network failure. If this was a mutate, its outcome is unknown: do not retry blindly, "
112
+ "run plan again to see the account's current state."
113
+ ) from exc
114
+ if not response.ok:
115
+ request_id = response.headers.get("request-id", "unknown")
116
+ raise ProviderError(
117
+ f"{endpoint}: HTTP {response.status_code} (request-id {request_id})\n{response.text[:12000]}"
118
+ )
119
+ try:
120
+ return response.json()
121
+ except ValueError as exc:
122
+ raise ProviderError(f"{endpoint}: the response was not JSON") from exc
123
+
124
+ def search(self, query: str) -> list[dict[str, Any]]:
125
+ """Run a GAQL query and return every row, following page tokens."""
126
+ rows: list[dict[str, Any]] = []
127
+ page = None
128
+ while True:
129
+ body = {"query": query}
130
+ if page:
131
+ body["pageToken"] = page
132
+ data = self.post("googleAds:search", body)
133
+ rows.extend(data.get("results", []))
134
+ page = data.get("nextPageToken")
135
+ if not page:
136
+ return rows
137
+
138
+ def mutate(self, operations: list[dict[str, Any]], *, validate_only: bool) -> dict[str, Any]:
139
+ return self.post(
140
+ "googleAds:mutate",
141
+ {"mutateOperations": operations, "partialFailure": False, "validateOnly": validate_only},
142
+ )
143
+
144
+
145
+ class ApiBackend:
146
+ """The real Google Ads account."""
147
+
148
+ sandbox = False
149
+
150
+ def __init__(self, client: GoogleAdsClient, namespace: str):
151
+ self.client = client
152
+ self.account = client.account
153
+ self.namespace = namespace
154
+
155
+ @classmethod
156
+ def connect(cls, desired: dict[str, Any], env: Mapping[str, str]) -> ApiBackend:
157
+ account = resolve_account(desired, env)
158
+ login = resolve_login_customer(desired, env)
159
+ return cls(GoogleAdsClient(account, env=env, login_customer_id=login), desired["namespace"])
160
+
161
+ def read(self) -> dict[str, Any]:
162
+ return snapshot(self.client.search, self.account, self.namespace)
163
+
164
+ def mutate(self, operations: list[dict[str, Any]], *, validate_only: bool) -> dict[str, Any]:
165
+ return self.client.mutate(operations, validate_only=validate_only)
166
+
167
+ def report(self, kind: str, days: int, *, all_campaigns: bool = False) -> list[dict[str, Any]]:
168
+ return report(self.client.search, kind, days, namespace=None if all_campaigns else self.namespace)
169
+
170
+
171
+ def _resource(value: Any, collection: str, account: str) -> str:
172
+ if not isinstance(value, str) or not re.fullmatch(rf"customers/{account}/{collection}/[0-9]+", value):
173
+ raise ProviderError(f"unexpected {collection} resource name in the API response: {value!r}")
174
+ return value
175
+
176
+
177
+ def _quoted(values: list[str]) -> str:
178
+ return ", ".join(f"'{value}'" for value in values)
179
+
180
+
181
+ def _normalize_ad(row: dict[str, Any]) -> dict[str, Any]:
182
+ """Keep only ad fields Adstack compares, so review metadata does not change the state hash."""
183
+ ad = dict(row.get("ad", {}))
184
+ rsa = ad.get("responsiveSearchAd")
185
+ if isinstance(rsa, dict):
186
+ ad["responsiveSearchAd"] = {
187
+ field: [
188
+ {key: asset[key] for key in ("text", "pinnedField") if key in asset} for asset in rsa.get(field, [])
189
+ ]
190
+ for field in ("headlines", "descriptions")
191
+ }
192
+ return {**row, "ad": ad}
193
+
194
+
195
+ def snapshot(search: Search, account: str, namespace: str) -> dict[str, Any]:
196
+ """Read every campaign in the namespace and the resources Adstack manages under each one."""
197
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", namespace):
198
+ raise ConfigError(f"invalid namespace {namespace!r}")
199
+ customer = search("SELECT customer.id, customer.currency_code FROM customer")
200
+ if len(customer) != 1 or str(customer[0]["customer"]["id"]) != account:
201
+ raise ProviderError(f"Could not verify access to account {format_customer_id(account)}")
202
+ state: dict[str, Any] = {"currency": customer[0]["customer"]["currencyCode"], "campaigns": {}}
203
+
204
+ prefix = f"{PREFIX}:{namespace}:"
205
+ rows = search(
206
+ "SELECT campaign.resource_name, campaign.name, campaign.status, campaign.advertising_channel_type, "
207
+ "campaign.campaign_budget, campaign.bidding_strategy_type, "
208
+ "campaign.network_settings.target_google_search, campaign.network_settings.target_search_network, "
209
+ "campaign.network_settings.target_content_network, "
210
+ "campaign.network_settings.target_partner_search_network, "
211
+ "campaign.geo_target_type_setting.positive_geo_target_type "
212
+ f"FROM campaign WHERE campaign.name LIKE '{prefix}%' AND campaign.status != 'REMOVED'"
213
+ )
214
+ campaigns: dict[str, dict[str, Any]] = {}
215
+ for row in rows:
216
+ campaign = row["campaign"]
217
+ if not campaign.get("name", "").startswith(prefix):
218
+ continue
219
+ _resource(campaign["resourceName"], "campaigns", account)
220
+ _resource(campaign.get("campaignBudget"), "campaignBudgets", account)
221
+ if campaign["name"] in campaigns:
222
+ raise ProviderError(f"More than one campaign is named {campaign['name']!r}")
223
+ campaigns[campaign["name"]] = {
224
+ "campaign": campaign,
225
+ "budget": None,
226
+ "groups": [],
227
+ "keywords": [],
228
+ "ads": [],
229
+ "criteria": [],
230
+ }
231
+ if not campaigns:
232
+ return state
233
+
234
+ by_resource = {entry["campaign"]["resourceName"]: entry for entry in campaigns.values()}
235
+ budget_names = sorted({entry["campaign"]["campaignBudget"] for entry in campaigns.values()})
236
+ budgets = {
237
+ row["campaignBudget"]["resourceName"]: row["campaignBudget"]
238
+ for row in search(
239
+ "SELECT campaign_budget.resource_name, campaign_budget.amount_micros, "
240
+ "campaign_budget.explicitly_shared, campaign_budget.reference_count, campaign_budget.period "
241
+ f"FROM campaign_budget WHERE campaign_budget.resource_name IN ({_quoted(budget_names)})"
242
+ )
243
+ }
244
+ for entry in campaigns.values():
245
+ entry["budget"] = budgets.get(entry["campaign"]["campaignBudget"])
246
+ if entry["budget"] is None:
247
+ raise ProviderError(f"Could not read the budget of campaign {entry['campaign']['name']!r}")
248
+
249
+ scope = f"campaign.resource_name IN ({_quoted(sorted(by_resource))})"
250
+ queries = {
251
+ "groups": (
252
+ "adGroup",
253
+ (
254
+ "SELECT campaign.resource_name, ad_group.resource_name, ad_group.name, ad_group.status, "
255
+ f"ad_group.type, ad_group.cpc_bid_micros FROM ad_group WHERE {scope} AND ad_group.status != 'REMOVED'"
256
+ ),
257
+ ),
258
+ "keywords": (
259
+ "adGroupCriterion",
260
+ (
261
+ "SELECT campaign.resource_name, ad_group_criterion.resource_name, ad_group_criterion.ad_group, "
262
+ "ad_group_criterion.status, ad_group_criterion.keyword.text, ad_group_criterion.keyword.match_type, "
263
+ f"ad_group_criterion.negative FROM ad_group_criterion WHERE {scope} "
264
+ "AND ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status != 'REMOVED' "
265
+ "AND ad_group.status != 'REMOVED'"
266
+ ),
267
+ ),
268
+ "ads": (
269
+ "adGroupAd",
270
+ (
271
+ "SELECT campaign.resource_name, ad_group_ad.resource_name, ad_group_ad.ad_group, ad_group_ad.status, "
272
+ "ad_group_ad.ad.type, ad_group_ad.ad.final_urls, ad_group_ad.ad.responsive_search_ad.headlines, "
273
+ f"ad_group_ad.ad.responsive_search_ad.descriptions FROM ad_group_ad WHERE {scope} "
274
+ "AND ad_group_ad.status != 'REMOVED' AND ad_group.status != 'REMOVED'"
275
+ ),
276
+ ),
277
+ "criteria": (
278
+ "campaignCriterion",
279
+ (
280
+ "SELECT campaign.resource_name, campaign_criterion.resource_name, campaign_criterion.status, "
281
+ "campaign_criterion.type, campaign_criterion.negative, "
282
+ "campaign_criterion.location.geo_target_constant, "
283
+ "campaign_criterion.keyword.text, campaign_criterion.keyword.match_type FROM campaign_criterion "
284
+ f"WHERE {scope} AND campaign_criterion.type IN ('LOCATION', 'KEYWORD') "
285
+ "AND campaign_criterion.status != 'REMOVED'"
286
+ ),
287
+ ),
288
+ }
289
+ for key, (field, query) in queries.items():
290
+ for row in search(query):
291
+ entry = by_resource.get(row.get("campaign", {}).get("resourceName"))
292
+ if entry is None:
293
+ raise ProviderError(f"unexpected campaign in {field} results")
294
+ entry[key].append(_normalize_ad(row[field]) if key == "ads" else row[field])
295
+ for entry in campaigns.values():
296
+ for key in queries:
297
+ entry[key].sort(key=lambda resource: resource["resourceName"])
298
+ state["campaigns"] = dict(sorted(campaigns.items()))
299
+ return state
300
+
301
+
302
+ def _metrics(row: dict[str, Any]) -> dict[str, Any]:
303
+ metrics = row.get("metrics", {})
304
+ return {
305
+ "impressions": int(metrics.get("impressions", 0)),
306
+ "clicks": int(metrics.get("clicks", 0)),
307
+ "cost": f"{int(metrics.get('costMicros', 0)) / 1_000_000:.2f}",
308
+ "conversions": float(metrics.get("conversions", 0)),
309
+ }
310
+
311
+
312
+ def report(search: Search, kind: str, days: int, *, namespace: str | None = None) -> list[dict[str, Any]]:
313
+ """Performance or search-term rows for the last 7, 14 or 30 days. Cost is in account currency."""
314
+ if kind not in REPORT_KINDS:
315
+ raise ConfigError(f"unknown report {kind!r} (choose from {', '.join(REPORT_KINDS)})")
316
+ if days not in REPORT_DAYS:
317
+ raise ConfigError("days must be 7, 14 or 30")
318
+ scope = f" AND campaign.name LIKE '{PREFIX}:{namespace}:%'" if namespace else ""
319
+ if kind == "performance":
320
+ rows = search(
321
+ "SELECT campaign.name, campaign.status, metrics.impressions, metrics.clicks, metrics.cost_micros, "
322
+ f"metrics.conversions FROM campaign WHERE segments.date DURING LAST_{days}_DAYS{scope} "
323
+ "ORDER BY metrics.cost_micros DESC"
324
+ )
325
+ return [
326
+ {"campaign": row["campaign"]["name"], "status": row["campaign"].get("status"), **_metrics(row)}
327
+ for row in rows
328
+ ]
329
+ rows = search(
330
+ "SELECT campaign.name, ad_group.name, search_term_view.search_term, metrics.impressions, metrics.clicks, "
331
+ "metrics.cost_micros, metrics.conversions FROM search_term_view "
332
+ f"WHERE segments.date DURING LAST_{days}_DAYS{scope} ORDER BY metrics.cost_micros DESC"
333
+ )
334
+ return [
335
+ {
336
+ "campaign": row["campaign"]["name"],
337
+ "ad_group": row.get("adGroup", {}).get("name"),
338
+ "search_term": row.get("searchTermView", {}).get("searchTerm"),
339
+ **_metrics(row),
340
+ }
341
+ for row in rows
342
+ ]