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.
@@ -0,0 +1,710 @@
1
+ """Pure, deterministic reconciliation of desired and live Google Ads state.
2
+
3
+ ``plan`` makes no network requests. It compares the desired state from the
4
+ configuration with a snapshot of the account and returns:
5
+
6
+ - ``operations``: GoogleAdsService mutate operations, in dependency order;
7
+ - ``changes``: one record per affected resource, for people and tools to review;
8
+ - ``blockers``: conditions that make the plan unsafe to apply;
9
+ - ``requires``: the explicit permissions that applying the plan needs.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from collections import defaultdict
16
+ from collections.abc import Callable, Iterable
17
+ from typing import Any
18
+
19
+ from ...errors import PlanError
20
+ from .schema import PREFIX, keyword_label
21
+
22
+ NETWORK_SETTINGS = {
23
+ "targetGoogleSearch": True,
24
+ "targetSearchNetwork": False,
25
+ "targetContentNetwork": False,
26
+ "targetPartnerSearchNetwork": False,
27
+ }
28
+
29
+ _EMPTY = {"campaign": None, "budget": None, "groups": [], "keywords": [], "ads": [], "criteria": []}
30
+
31
+
32
+ def keyword_key(keyword: dict[str, Any]) -> tuple[str, Any]:
33
+ return (" ".join(str(keyword.get("text", "")).lower().split()), keyword.get("matchType"))
34
+
35
+
36
+ def creative(ad: dict[str, Any]) -> tuple:
37
+ """What makes two responsive search ads equivalent (order of assets does not matter)."""
38
+ rsa = ad.get("responsiveSearchAd", {})
39
+
40
+ def assets(field: str) -> list[tuple[str, str]]:
41
+ return sorted((a.get("text", ""), a.get("pinnedField", "UNSPECIFIED")) for a in rsa.get(field, []))
42
+
43
+ return (
44
+ tuple(sorted(ad.get("finalUrls", []))),
45
+ assets("headlines"),
46
+ assets("descriptions"),
47
+ rsa.get("path1", ""),
48
+ rsa.get("path2", ""),
49
+ )
50
+
51
+
52
+ def plan(
53
+ desired: dict[str, Any],
54
+ state: dict[str, Any],
55
+ account: str,
56
+ *,
57
+ prune: bool = False,
58
+ destroy: bool = False,
59
+ ) -> dict[str, Any]:
60
+ if state["currency"] != desired["currency"]:
61
+ raise PlanError(
62
+ f"The account's currency is {state['currency']}, but the configuration declares {desired['currency']}"
63
+ )
64
+ builder = _Builder(account, desired["currency"])
65
+ if destroy:
66
+ # Destroy never deletes anything in Google Ads: it pauses every managed campaign.
67
+ for name, current in state["campaigns"].items():
68
+ builder.pause_campaign(name, current, note="destroy")
69
+ return builder.result()
70
+
71
+ configured = {campaign["name"] for campaign in desired["campaigns"]}
72
+ for spec in desired["campaigns"]:
73
+ _reconcile(builder, spec, state["campaigns"].get(spec["name"]), prune)
74
+ for name, current in state["campaigns"].items():
75
+ if name in configured:
76
+ continue
77
+ status = current["campaign"].get("status")
78
+ if prune:
79
+ builder.pause_campaign(name, current, note="not in configuration")
80
+ elif status != "PAUSED":
81
+ builder.blockers.append(
82
+ f"campaign {_short(name)}: exists in the account ({status}) but not in the configuration; "
83
+ "re-plan with --prune to pause it"
84
+ )
85
+ return builder.result()
86
+
87
+
88
+ class _Builder:
89
+ """Accumulates operations and change records for one plan."""
90
+
91
+ def __init__(self, account: str, currency: str):
92
+ self.base = f"customers/{account}"
93
+ self.currency = currency
94
+ self.operations: list[dict[str, Any]] = []
95
+ self.changes: list[dict[str, Any]] = []
96
+ self.blockers: list[str] = []
97
+ self.enable = False
98
+ self.increase = False
99
+ self.live = False
100
+ self.serving = False # True while reconciling a campaign that is currently ENABLED
101
+ self._temp = 0
102
+ self._updates: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {}
103
+
104
+ def money(self, micros: int | str) -> str:
105
+ return f"{int(micros) / 1_000_000:.2f} {self.currency}"
106
+
107
+ def temp_name(self, collection: str) -> str:
108
+ """A temporary resource name: a negative ID, unique within the request."""
109
+ self._temp -= 1
110
+ return f"{self.base}/{collection}/{self._temp}"
111
+
112
+ def operation(self, kind: str, body: dict[str, Any]) -> None:
113
+ self.operations.append({f"{kind}Operation": body})
114
+ if self.serving:
115
+ self.live = True
116
+
117
+ def record(self, action: str, resource: str, campaign: str, **labels: Any) -> dict[str, Any]:
118
+ change = {
119
+ "action": action,
120
+ "resource": resource,
121
+ "campaign": campaign,
122
+ "ad_group": labels.pop("ad_group", None),
123
+ "name": labels.pop("name", None),
124
+ }
125
+ change.update({key: value for key, value in labels.items() if value is not None})
126
+ self.changes.append(change)
127
+ return change
128
+
129
+ def create(self, kind: str, fields: dict[str, Any], resource: str, campaign: str, **labels: Any) -> None:
130
+ self.operation(kind, {"create": fields})
131
+ self.record("create", resource, campaign, **labels)
132
+
133
+ def update(
134
+ self,
135
+ kind: str,
136
+ resource_name: str,
137
+ fields: dict[str, Any],
138
+ resource: str,
139
+ campaign: str,
140
+ *,
141
+ diff: dict[str, list[Any]],
142
+ mask: Iterable[str] | None = None,
143
+ **labels: Any,
144
+ ) -> None:
145
+ mask = list(mask or fields)
146
+ if resource_name in self._updates:
147
+ # Google rejects a request that mutates one resource twice (ID_EXISTS_IN_MULTIPLE_MUTATES),
148
+ # so later changes to an already-updated resource join its operation and update mask.
149
+ body, change = self._updates[resource_name]
150
+ if set(fields) & set(body["update"]):
151
+ raise PlanError(f"internal error: conflicting updates to {resource_name}")
152
+ body["update"].update(fields)
153
+ body["updateMask"] += "," + ",".join(mask)
154
+ change["diff"].update(diff)
155
+ return
156
+ body = {"update": {"resourceName": resource_name, **fields}, "updateMask": ",".join(mask)}
157
+ self.operation(kind, body)
158
+ change = self.record("update", resource, campaign, diff=dict(diff), **labels)
159
+ self._updates[resource_name] = (body, change)
160
+
161
+ def remove(self, kind: str, resource_name: str, resource: str, campaign: str, **labels: Any) -> None:
162
+ self.operation(kind, {"remove": resource_name})
163
+ self.record("remove", resource, campaign, **labels)
164
+
165
+ def extra(
166
+ self,
167
+ prune: bool,
168
+ kind: str,
169
+ row: dict[str, Any],
170
+ resource: str,
171
+ campaign: str,
172
+ *,
173
+ name: str,
174
+ ad_group: str | None = None,
175
+ remove: bool = False,
176
+ ) -> None:
177
+ """Handle something that exists in the account but not in the configuration."""
178
+ if not prune:
179
+ where = f"campaign {campaign}" + (f", ad group {ad_group}" if ad_group else "")
180
+ verb = "remove" if remove else "pause"
181
+ self.blockers.append(
182
+ f"{where}: {resource.replace('_', ' ')} {name} exists in the account but not in the "
183
+ f"configuration; re-plan with --prune to {verb} it"
184
+ )
185
+ elif remove:
186
+ self.remove(
187
+ kind, row["resourceName"], resource, campaign, ad_group=ad_group, name=name, note="not in configuration"
188
+ )
189
+ elif row.get("status") != "PAUSED":
190
+ self.update(
191
+ kind,
192
+ row["resourceName"],
193
+ {"status": "PAUSED"},
194
+ resource,
195
+ campaign,
196
+ ad_group=ad_group,
197
+ name=name,
198
+ note="not in configuration",
199
+ diff={"status": [row.get("status"), "PAUSED"]},
200
+ )
201
+
202
+ def pause_campaign(self, name: str, current: dict[str, Any], *, note: str) -> None:
203
+ campaign = current["campaign"]
204
+ status = campaign.get("status")
205
+ if status == "PAUSED":
206
+ return
207
+ self.serving = status == "ENABLED"
208
+ self.update(
209
+ "campaign",
210
+ campaign["resourceName"],
211
+ {"status": "PAUSED"},
212
+ "campaign",
213
+ _short(name),
214
+ name=name,
215
+ note=note,
216
+ diff={"status": [status, "PAUSED"]},
217
+ )
218
+ self.serving = False
219
+
220
+ def result(self) -> dict[str, Any]:
221
+ return {
222
+ "changes": self.changes,
223
+ "blockers": self.blockers,
224
+ "requires": {
225
+ "allow_enable": self.enable,
226
+ "allow_budget_increase": self.increase,
227
+ "allow_live_changes": self.live,
228
+ },
229
+ "operations": self.operations,
230
+ }
231
+
232
+
233
+ def _short(name: str) -> str:
234
+ """``adstack:<namespace>:<id>`` -> ``<id>``."""
235
+ return name.split(":", 2)[-1]
236
+
237
+
238
+ def _snake(field: str) -> str:
239
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", field).lower()
240
+
241
+
242
+ def _unique(rows: Iterable[dict[str, Any]], key: Callable[[dict[str, Any]], Any], what: str) -> dict[Any, Any]:
243
+ result: dict[Any, Any] = {}
244
+ for row in rows:
245
+ identity = key(row)
246
+ if identity in result:
247
+ raise PlanError(f"duplicate {what} in the account: {identity}")
248
+ result[identity] = row
249
+ return result
250
+
251
+
252
+ def _reconcile(b: _Builder, spec: dict[str, Any], current: dict[str, Any] | None, prune: bool) -> None:
253
+ current = current or _EMPTY
254
+ if current["campaign"] is None:
255
+ campaign_rn = _create_campaign(b, spec)
256
+ else:
257
+ campaign_rn = _reconcile_settings(b, spec, current)
258
+ _reconcile_criteria(b, spec, current, campaign_rn, prune)
259
+ _reconcile_ad_groups(b, spec, current, campaign_rn, prune)
260
+ b.serving = False
261
+
262
+
263
+ def _create_campaign(b: _Builder, spec: dict[str, Any]) -> str:
264
+ cid = spec["id"]
265
+ if spec["status"] != "PAUSED":
266
+ raise PlanError(
267
+ f"campaign {cid}: new campaigns are created PAUSED. Create it with status: PAUSED, "
268
+ "then set status: ENABLED in a later plan"
269
+ )
270
+ b.serving = False
271
+ budget_rn, campaign_rn = b.temp_name("campaignBudgets"), b.temp_name("campaigns")
272
+ b.record(
273
+ "create",
274
+ "campaign",
275
+ cid,
276
+ name=spec["name"],
277
+ attributes={
278
+ "status": "PAUSED",
279
+ "type": "SEARCH",
280
+ "bidding": "MANUAL_CPC",
281
+ "networks": "Google Search only",
282
+ "geo_targeting": "PRESENCE",
283
+ },
284
+ )
285
+ b.record("create", "budget", cid, name="daily budget", attributes={"amount": b.money(spec["budget"])})
286
+ b.operation(
287
+ "campaignBudget",
288
+ {
289
+ "create": {
290
+ "resourceName": budget_rn,
291
+ "name": f"{spec['name']}:budget",
292
+ "amountMicros": str(spec["budget"]),
293
+ "deliveryMethod": "STANDARD",
294
+ "explicitlyShared": False,
295
+ }
296
+ },
297
+ )
298
+ b.operation(
299
+ "campaign",
300
+ {
301
+ "create": {
302
+ "resourceName": campaign_rn,
303
+ "name": spec["name"],
304
+ "status": "PAUSED",
305
+ "advertisingChannelType": "SEARCH",
306
+ "campaignBudget": budget_rn,
307
+ "manualCpc": {},
308
+ "networkSettings": dict(NETWORK_SETTINGS),
309
+ "containsEuPoliticalAdvertising": "DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING",
310
+ "geoTargetTypeSetting": {"positiveGeoTargetType": "PRESENCE"},
311
+ }
312
+ },
313
+ )
314
+ return campaign_rn
315
+
316
+
317
+ def _reconcile_settings(b: _Builder, spec: dict[str, Any], current: dict[str, Any]) -> str:
318
+ cid, campaign, budget = spec["id"], current["campaign"], current["budget"]
319
+ if campaign.get("advertisingChannelType") != "SEARCH" or campaign.get("biddingStrategyType") != "MANUAL_CPC":
320
+ raise PlanError(
321
+ f"campaign {cid}: {spec['name']} exists but is not a SEARCH campaign with MANUAL_CPC bidding; "
322
+ "Adstack will not adopt or convert it"
323
+ )
324
+ status = campaign.get("status")
325
+ if status not in ("PAUSED", "ENABLED"):
326
+ raise PlanError(f"campaign {cid}: unexpected status {status!r}")
327
+ if (
328
+ not budget
329
+ or budget.get("explicitlyShared")
330
+ or int(budget.get("referenceCount", 0)) > 1
331
+ or budget.get("period") != "DAILY"
332
+ ):
333
+ raise PlanError(f"campaign {cid}: its budget must be a dedicated daily budget that no other campaign uses")
334
+ b.serving = status == "ENABLED"
335
+ campaign_rn = campaign["resourceName"]
336
+ labels = {"name": spec["name"]}
337
+ network = campaign.get("networkSettings", {})
338
+ drift = {key: value for key, value in NETWORK_SETTINGS.items() if network.get(key, False) != value}
339
+ if drift:
340
+ b.update(
341
+ "campaign",
342
+ campaign_rn,
343
+ {"networkSettings": drift},
344
+ "campaign",
345
+ cid,
346
+ **labels,
347
+ diff={_snake(key): [network.get(key, False), value] for key, value in drift.items()},
348
+ mask=[f"networkSettings.{key}" for key in drift],
349
+ )
350
+ geo = campaign.get("geoTargetTypeSetting", {}).get("positiveGeoTargetType")
351
+ if geo != "PRESENCE":
352
+ b.update(
353
+ "campaign",
354
+ campaign_rn,
355
+ {"geoTargetTypeSetting": {"positiveGeoTargetType": "PRESENCE"}},
356
+ "campaign",
357
+ cid,
358
+ **labels,
359
+ diff={"positive_geo_target_type": [geo, "PRESENCE"]},
360
+ mask=["geoTargetTypeSetting.positiveGeoTargetType"],
361
+ )
362
+ if status != spec["status"]:
363
+ b.enable = b.enable or spec["status"] == "ENABLED"
364
+ b.update(
365
+ "campaign",
366
+ campaign_rn,
367
+ {"status": spec["status"]},
368
+ "campaign",
369
+ cid,
370
+ **labels,
371
+ diff={"status": [status, spec["status"]]},
372
+ )
373
+ amount = int(budget["amountMicros"])
374
+ if amount != spec["budget"]:
375
+ b.increase = b.increase or spec["budget"] > amount
376
+ b.update(
377
+ "campaignBudget",
378
+ budget["resourceName"],
379
+ {"amountMicros": str(spec["budget"])},
380
+ "budget",
381
+ cid,
382
+ name="daily budget",
383
+ diff={"amount": [b.money(amount), b.money(spec["budget"])]},
384
+ )
385
+ return campaign_rn
386
+
387
+
388
+ def _reconcile_criteria(
389
+ b: _Builder, spec: dict[str, Any], current: dict[str, Any], campaign_rn: str, prune: bool
390
+ ) -> None:
391
+ cid = spec["id"]
392
+ locations: dict[str, dict[str, Any]] = {}
393
+ negatives: dict[tuple[str, Any], dict[str, Any]] = {}
394
+ for criterion in current["criteria"]:
395
+ kind, negative = criterion.get("type"), bool(criterion.get("negative", False))
396
+ if kind == "LOCATION" and not negative:
397
+ geo = criterion["location"]["geoTargetConstant"].rsplit("/", 1)[-1]
398
+ if geo in locations:
399
+ raise PlanError(f"campaign {cid}: location {geo} is targeted twice in the account")
400
+ locations[geo] = criterion
401
+ elif kind == "KEYWORD" and negative:
402
+ key = keyword_key(criterion["keyword"])
403
+ if key in negatives:
404
+ raise PlanError(f"campaign {cid}: negative keyword {keyword_label(criterion['keyword'])} is duplicated")
405
+ negatives[key] = criterion
406
+ else:
407
+ what = f"{'negative ' if negative else ''}{kind}"
408
+ b.blockers.append(
409
+ f"campaign {cid}: unmanaged {what} criterion {criterion['resourceName']}; remove or review it manually"
410
+ )
411
+ for geo in spec["locations"]:
412
+ if geo not in locations:
413
+ b.create(
414
+ "campaignCriterion",
415
+ {"campaign": campaign_rn, "location": {"geoTargetConstant": f"geoTargetConstants/{geo}"}},
416
+ "location",
417
+ cid,
418
+ name=geo,
419
+ )
420
+ elif locations[geo].get("status") == "PAUSED":
421
+ b.update(
422
+ "campaignCriterion",
423
+ locations[geo]["resourceName"],
424
+ {"status": "ENABLED"},
425
+ "location",
426
+ cid,
427
+ name=geo,
428
+ diff={"status": ["PAUSED", "ENABLED"]},
429
+ )
430
+ for geo, criterion in locations.items():
431
+ if geo not in spec["locations"]:
432
+ b.extra(prune, "campaignCriterion", criterion, "location", cid, name=geo, remove=True)
433
+
434
+ wanted = {keyword_key(k): k for k in spec["negatives"]}
435
+ for key, negative_keyword in wanted.items():
436
+ label = keyword_label(negative_keyword)
437
+ if key not in negatives:
438
+ b.create(
439
+ "campaignCriterion",
440
+ {"campaign": campaign_rn, "negative": True, "keyword": negative_keyword},
441
+ "negative_keyword",
442
+ cid,
443
+ name=label,
444
+ )
445
+ elif negatives[key].get("status") == "PAUSED":
446
+ b.blockers.append(f"campaign {cid}: negative keyword {label} is paused in the account; review it manually")
447
+ for key, criterion in negatives.items():
448
+ if key not in wanted:
449
+ b.extra(
450
+ prune,
451
+ "campaignCriterion",
452
+ criterion,
453
+ "negative_keyword",
454
+ cid,
455
+ name=keyword_label(criterion["keyword"]),
456
+ remove=True,
457
+ )
458
+
459
+
460
+ def _reconcile_ad_groups(
461
+ b: _Builder, spec: dict[str, Any], current: dict[str, Any], campaign_rn: str, prune: bool
462
+ ) -> None:
463
+ cid = spec["id"]
464
+ existing_groups = _unique(current["groups"], lambda g: g["name"], f"ad group name in campaign {cid}")
465
+ keywords: dict[str, list[dict[str, Any]]] = defaultdict(list)
466
+ ads: dict[str, list[dict[str, Any]]] = defaultdict(list)
467
+ for row in current["keywords"]:
468
+ keywords[row["adGroup"]].append(row)
469
+ for row in current["ads"]:
470
+ ads[row["adGroup"]].append(row)
471
+
472
+ for group in spec["groups"]:
473
+ gid = group["id"]
474
+ labels = {"ad_group": gid}
475
+ old = existing_groups.get(group["name"])
476
+ if old is None:
477
+ group_rn = b.temp_name("adGroups")
478
+ b.create(
479
+ "adGroup",
480
+ {
481
+ "resourceName": group_rn,
482
+ "campaign": campaign_rn,
483
+ "name": group["name"],
484
+ "type": "SEARCH_STANDARD",
485
+ "status": "ENABLED",
486
+ "cpcBidMicros": str(group["bid"]),
487
+ },
488
+ "ad_group",
489
+ cid,
490
+ **labels,
491
+ name=group["name"],
492
+ attributes={"cpc_bid": b.money(group["bid"])},
493
+ )
494
+ else:
495
+ group_rn = old["resourceName"]
496
+ if old.get("type") != "SEARCH_STANDARD":
497
+ raise PlanError(f"campaign {cid}, ad group {gid}: the existing ad group has an unexpected type")
498
+ old_bid = int(old.get("cpcBidMicros", 0))
499
+ if old_bid != group["bid"]:
500
+ b.increase = b.increase or group["bid"] > old_bid
501
+ b.update(
502
+ "adGroup",
503
+ group_rn,
504
+ {"cpcBidMicros": str(group["bid"])},
505
+ "ad_group",
506
+ cid,
507
+ **labels,
508
+ name=group["name"],
509
+ diff={"cpc_bid": [b.money(old_bid), b.money(group["bid"])]},
510
+ )
511
+ if old.get("status") != "ENABLED":
512
+ b.update(
513
+ "adGroup",
514
+ group_rn,
515
+ {"status": "ENABLED"},
516
+ "ad_group",
517
+ cid,
518
+ **labels,
519
+ name=group["name"],
520
+ diff={"status": [old.get("status"), "ENABLED"]},
521
+ )
522
+ _reconcile_keywords(b, cid, group, group_rn, keywords[group_rn], prune)
523
+ _reconcile_ad(b, cid, group, group_rn, ads[group_rn])
524
+
525
+ configured = {group["name"] for group in spec["groups"]}
526
+ for name, old in existing_groups.items():
527
+ if name in configured or old.get("status") == "PAUSED":
528
+ continue
529
+ if name.startswith(f"{PREFIX}:"):
530
+ b.extra(prune, "adGroup", old, "ad_group", cid, ad_group=name.split(":", 1)[1], name=name)
531
+ else:
532
+ b.blockers.append(f"campaign {cid}: unmanaged active ad group {name!r}; pause or review it manually")
533
+
534
+
535
+ def _reconcile_keywords(
536
+ b: _Builder, cid: str, group: dict[str, Any], group_rn: str, rows: list[dict[str, Any]], prune: bool
537
+ ) -> None:
538
+ gid = group["id"]
539
+ for row in rows:
540
+ if row.get("negative"):
541
+ b.blockers.append(
542
+ f"campaign {cid}, ad group {gid}: unmanaged negative keyword {keyword_label(row['keyword'])}; "
543
+ "review it manually"
544
+ )
545
+ existing = _unique(
546
+ (row for row in rows if not row.get("negative")),
547
+ lambda row: keyword_key(row["keyword"]),
548
+ f"keyword in campaign {cid}, ad group {gid}",
549
+ )
550
+ wanted = {keyword_key(k): k for k in group["keywords"]}
551
+ for key, wanted_keyword in wanted.items():
552
+ label = keyword_label(wanted_keyword)
553
+ if key not in existing:
554
+ b.create(
555
+ "adGroupCriterion",
556
+ {"adGroup": group_rn, "status": "ENABLED", "keyword": wanted_keyword},
557
+ "keyword",
558
+ cid,
559
+ ad_group=gid,
560
+ name=label,
561
+ )
562
+ elif existing[key].get("status") != "ENABLED":
563
+ b.update(
564
+ "adGroupCriterion",
565
+ existing[key]["resourceName"],
566
+ {"status": "ENABLED"},
567
+ "keyword",
568
+ cid,
569
+ ad_group=gid,
570
+ name=label,
571
+ diff={"status": [existing[key].get("status"), "ENABLED"]},
572
+ )
573
+ for key, row in existing.items():
574
+ if key not in wanted and row.get("status") != "PAUSED":
575
+ b.extra(prune, "adGroupCriterion", row, "keyword", cid, ad_group=gid, name=keyword_label(row["keyword"]))
576
+
577
+
578
+ def _reconcile_ad(b: _Builder, cid: str, group: dict[str, Any], group_rn: str, rows: list[dict[str, Any]]) -> None:
579
+ """Keep exactly one enabled responsive search ad that matches the configuration."""
580
+ gid = group["id"]
581
+ responsive = [row for row in rows if row["ad"].get("type") == "RESPONSIVE_SEARCH_AD"]
582
+ for row in rows:
583
+ if row["ad"].get("type") != "RESPONSIVE_SEARCH_AD" and row.get("status") != "PAUSED":
584
+ b.blockers.append(
585
+ f"campaign {cid}, ad group {gid}: unmanaged active {row['ad'].get('type')} ad "
586
+ f"{row['resourceName']}; pause or review it manually"
587
+ )
588
+ target = creative(group["ad"])
589
+ matches = [row for row in responsive if creative(row["ad"]) == target]
590
+ chosen = next((row for row in matches if row.get("status") == "ENABLED"), matches[0] if matches else None)
591
+ if chosen is None:
592
+ rsa = group["ad"]["responsiveSearchAd"]
593
+ b.create(
594
+ "adGroupAd",
595
+ {"adGroup": group_rn, "status": "ENABLED", "ad": group["ad"]},
596
+ "ad",
597
+ cid,
598
+ ad_group=gid,
599
+ name="responsive search ad",
600
+ attributes={
601
+ "template": group["ad_template"] or "(inline)",
602
+ "headlines": len(rsa["headlines"]),
603
+ "descriptions": len(rsa["descriptions"]),
604
+ "final_url": group["ad"]["finalUrls"][0],
605
+ },
606
+ )
607
+ elif chosen.get("status") != "ENABLED":
608
+ b.update(
609
+ "adGroupAd",
610
+ chosen["resourceName"],
611
+ {"status": "ENABLED"},
612
+ "ad",
613
+ cid,
614
+ ad_group=gid,
615
+ name=_ad_name(chosen),
616
+ diff={"status": [chosen.get("status"), "ENABLED"]},
617
+ )
618
+ for row in responsive:
619
+ if row is not chosen and row.get("status") != "PAUSED":
620
+ b.update(
621
+ "adGroupAd",
622
+ row["resourceName"],
623
+ {"status": "PAUSED"},
624
+ "ad",
625
+ cid,
626
+ ad_group=gid,
627
+ name=_ad_name(row),
628
+ note="superseded",
629
+ diff={"status": [row.get("status"), "PAUSED"]},
630
+ )
631
+
632
+
633
+ def _ad_name(row: dict[str, Any]) -> str:
634
+ return f"responsive search ad {row['resourceName'].rsplit('~', 1)[-1]}"
635
+
636
+
637
+ def inventory(state: dict[str, Any], currency: str) -> list[dict[str, Any]]:
638
+ """Flatten a snapshot into display records: what exists in the account under the namespace."""
639
+
640
+ def money(micros: Any) -> str:
641
+ return f"{int(micros) / 1_000_000:.2f} {currency}"
642
+
643
+ records: list[dict[str, Any]] = []
644
+ for name, entry in state["campaigns"].items():
645
+ cid, campaign = _short(name), entry["campaign"]
646
+ records.append(
647
+ {
648
+ "resource": "campaign",
649
+ "campaign": cid,
650
+ "ad_group": None,
651
+ "name": name,
652
+ "status": campaign.get("status"),
653
+ "details": f"daily budget {money(entry['budget']['amountMicros'])}",
654
+ }
655
+ )
656
+ for criterion in entry["criteria"]:
657
+ if criterion.get("type") == "LOCATION":
658
+ resource = "excluded_location" if criterion.get("negative") else "location"
659
+ label = criterion["location"]["geoTargetConstant"].rsplit("/", 1)[-1]
660
+ else:
661
+ resource = "negative_keyword" if criterion.get("negative") else "keyword"
662
+ label = keyword_label(criterion.get("keyword", {}))
663
+ records.append(
664
+ {
665
+ "resource": resource,
666
+ "campaign": cid,
667
+ "ad_group": None,
668
+ "name": label,
669
+ "status": criterion.get("status"),
670
+ }
671
+ )
672
+ for group in entry["groups"]:
673
+ managed = group["name"].startswith(f"{PREFIX}:")
674
+ gid = group["name"].split(":", 1)[1] if managed else group["name"]
675
+ records.append(
676
+ {
677
+ "resource": "ad_group",
678
+ "campaign": cid,
679
+ "ad_group": gid,
680
+ "name": group["name"],
681
+ "status": group.get("status"),
682
+ "details": f"cpc_bid {money(group.get('cpcBidMicros', 0))}"
683
+ + ("" if managed else " (not managed by Adstack)"),
684
+ }
685
+ )
686
+ for row in entry["keywords"]:
687
+ if row["adGroup"] == group["resourceName"]:
688
+ label = keyword_label(row["keyword"])
689
+ records.append(
690
+ {
691
+ "resource": "negative_keyword" if row.get("negative") else "keyword",
692
+ "campaign": cid,
693
+ "ad_group": gid,
694
+ "name": label,
695
+ "status": row.get("status"),
696
+ }
697
+ )
698
+ for row in entry["ads"]:
699
+ if row["adGroup"] == group["resourceName"]:
700
+ kind = row["ad"].get("type", "AD").lower().replace("_", " ")
701
+ records.append(
702
+ {
703
+ "resource": "ad",
704
+ "campaign": cid,
705
+ "ad_group": gid,
706
+ "name": f"{kind} {row['resourceName'].rsplit('~', 1)[-1]}",
707
+ "status": row.get("status"),
708
+ }
709
+ )
710
+ return records