adloop 0.37.0__tar.gz → 0.38.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.
Files changed (77) hide show
  1. {adloop-0.37.0 → adloop-0.38.0}/PKG-INFO +3 -3
  2. {adloop-0.37.0 → adloop-0.38.0}/README.md +2 -2
  3. {adloop-0.37.0 → adloop-0.38.0}/pyproject.toml +1 -1
  4. {adloop-0.37.0 → adloop-0.38.0}/pyproject.toml.orig +1 -1
  5. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/assets.py +5 -3
  6. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/conversion_actions.py +61 -12
  7. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/pmax.py +255 -1
  8. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/write.py +228 -83
  9. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/adloop.md +5 -4
  10. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/server.py +40 -7
  11. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/__init__.py +0 -0
  12. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/__main__.py +0 -0
  13. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/_mcp_patches.py +0 -0
  14. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/__init__.py +0 -0
  15. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/ai_max.py +0 -0
  16. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/audiences.py +0 -0
  17. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/brands.py +0 -0
  18. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/campaign_settings.py +0 -0
  19. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/client.py +0 -0
  20. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/currency.py +0 -0
  21. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/custom_conversion_goals.py +0 -0
  22. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/enums.py +0 -0
  23. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/forecast.py +0 -0
  24. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/gaql.py +0 -0
  25. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/image_fetch.py +0 -0
  26. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/read.py +0 -0
  27. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/recommendation_subscriptions.py +0 -0
  28. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/recommendations.py +0 -0
  29. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/shopping.py +0 -0
  30. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/snippet_headers.py +0 -0
  31. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ads/validate_only.py +0 -0
  32. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/auth.py +0 -0
  33. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/cli.py +0 -0
  34. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/config.py +0 -0
  35. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/crossref.py +0 -0
  36. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/diagnostics.py +0 -0
  37. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ga4/__init__.py +0 -0
  38. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ga4/client.py +0 -0
  39. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ga4/reports.py +0 -0
  40. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ga4/tracking.py +0 -0
  41. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/ga4/write.py +0 -0
  42. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gsc/__init__.py +0 -0
  43. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gsc/client.py +0 -0
  44. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gsc/reports.py +0 -0
  45. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gtm/__init__.py +0 -0
  46. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gtm/client.py +0 -0
  47. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gtm/entities.py +0 -0
  48. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gtm/read.py +0 -0
  49. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/gtm/write.py +0 -0
  50. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/merchant/__init__.py +0 -0
  51. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/merchant/client.py +0 -0
  52. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/merchant/read.py +0 -0
  53. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/pagespeed.py +0 -0
  54. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/reddit/__init__.py +0 -0
  55. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/reddit/auth.py +0 -0
  56. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/reddit/client.py +0 -0
  57. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/reddit/read.py +0 -0
  58. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/reddit/schedule.py +0 -0
  59. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/reddit/write.py +0 -0
  60. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/__init__.py +0 -0
  61. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/commands/analyze-performance.md +0 -0
  62. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/commands/budget-plan.md +0 -0
  63. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/commands/create-ad.md +0 -0
  64. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/commands/create-campaign.md +0 -0
  65. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/commands/diagnose-tracking.md +0 -0
  66. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules/commands/optimize-campaign.md +0 -0
  67. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/rules_install.py +0 -0
  68. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/runtime.py +0 -0
  69. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/safety/__init__.py +0 -0
  70. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/safety/approval.py +0 -0
  71. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/safety/approval_card.html +0 -0
  72. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/safety/audit.py +0 -0
  73. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/safety/guards.py +0 -0
  74. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/safety/preview.py +0 -0
  75. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/tracking.py +0 -0
  76. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/upload_card.html +0 -0
  77. {adloop-0.37.0 → adloop-0.38.0}/src/adloop/uploads.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: adloop
3
- Version: 0.37.0
3
+ Version: 0.38.0
4
4
  Summary: The AI command center for Google Ads, Reddit Ads, GA4, and tracking code.
5
5
  Keywords: mcp,google-ads,reddit-ads,google-analytics,ga4,cursor,marketing
6
6
  Author: Daniel Klose
@@ -303,7 +303,7 @@ All write operations follow a **draft → preview → confirm** workflow. Nothin
303
303
  | `draft_asset_group_assets` | Add and remove Performance Max assets (text, images incl. uploads, YouTube videos) in one change, so replacing an asset never drops a group below Google's minimums |
304
304
  | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group |
305
305
  | `draft_pmax_product_exclusions` | Exclude products from a retail PMax asset group by item id, brand or custom label |
306
- | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
306
+ | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, campaign-level broad match (Smart Bidding only), Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
307
307
  | `draft_ad_group` | Create a paused SEARCH_STANDARD ad group inside an existing campaign, with optional MANUAL_CPC `max_cpc`. |
308
308
  | `update_ad_group` | Update an ad group name and/or MANUAL_CPC `max_cpc`. Use `pause_entity` / `enable_entity` for ad-group status changes. |
309
309
  | `draft_responsive_search_ad` | Create RSA preview (3-15 headlines ≤30 chars, 2-4 descriptions ≤90 chars). Warns if headline/description count is below best practice. |
@@ -316,7 +316,7 @@ All write operations follow a **draft → preview → confirm** workflow. Nothin
316
316
  | `add_ad_schedule` | Add ad schedule windows to a campaign; overlaps are refused, and a campaign's first schedule needs a double confirmation. |
317
317
  | `draft_promotion` / `update_promotion` | Create a promotion asset, or edit one in place without losing the fields you don't pass; amounts in the account currency. |
318
318
  | `draft_price_asset` | Create a price asset with 3-8 offerings, in the account currency. |
319
- | `draft_image_assets` | Create campaign image assets from local files, public image URLs or uploads (PNG, JPEG, or GIF). |
319
+ | `draft_image_assets` | Create campaign image assets from local files, public image URLs or uploads (PNG, JPEG, or GIF); a business logo can also go on the account. |
320
320
  | `draft_keywords` | Propose keyword additions with match types. Proactively checks bidding strategy — flags BROAD match on campaigns without Smart Bidding as dangerous in the preview. |
321
321
  | `add_negative_keywords` | Propose negative keywords directly on a campaign |
322
322
  | `add_negative_locations` | Propose negative geo exclusions on a campaign — exclude cities/regions while keeping broader positive targets |
@@ -275,7 +275,7 @@ All write operations follow a **draft → preview → confirm** workflow. Nothin
275
275
  | `draft_asset_group_assets` | Add and remove Performance Max assets (text, images incl. uploads, YouTube videos) in one change, so replacing an asset never drops a group below Google's minimums |
276
276
  | `draft_asset_group_signals` | Add search themes or set the audience signal of a PMax asset group |
277
277
  | `draft_pmax_product_exclusions` | Exclude products from a retail PMax asset group by item id, brand or custom label |
278
- | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
278
+ | `update_campaign` | Modify existing campaign settings — bidding, budget, geo/language targeting, the location option, campaign URL options, campaign-level broad match (Smart Bidding only), Search partners, display expansion, and TARGET_SPEND (Maximize Clicks) `max_cpc` caps. |
279
279
  | `draft_ad_group` | Create a paused SEARCH_STANDARD ad group inside an existing campaign, with optional MANUAL_CPC `max_cpc`. |
280
280
  | `update_ad_group` | Update an ad group name and/or MANUAL_CPC `max_cpc`. Use `pause_entity` / `enable_entity` for ad-group status changes. |
281
281
  | `draft_responsive_search_ad` | Create RSA preview (3-15 headlines ≤30 chars, 2-4 descriptions ≤90 chars). Warns if headline/description count is below best practice. |
@@ -288,7 +288,7 @@ All write operations follow a **draft → preview → confirm** workflow. Nothin
288
288
  | `add_ad_schedule` | Add ad schedule windows to a campaign; overlaps are refused, and a campaign's first schedule needs a double confirmation. |
289
289
  | `draft_promotion` / `update_promotion` | Create a promotion asset, or edit one in place without losing the fields you don't pass; amounts in the account currency. |
290
290
  | `draft_price_asset` | Create a price asset with 3-8 offerings, in the account currency. |
291
- | `draft_image_assets` | Create campaign image assets from local files, public image URLs or uploads (PNG, JPEG, or GIF). |
291
+ | `draft_image_assets` | Create campaign image assets from local files, public image URLs or uploads (PNG, JPEG, or GIF); a business logo can also go on the account. |
292
292
  | `draft_keywords` | Propose keyword additions with match types. Proactively checks bidding strategy — flags BROAD match on campaigns without Smart Bidding as dangerous in the preview. |
293
293
  | `add_negative_keywords` | Propose negative keywords directly on a campaign |
294
294
  | `add_negative_locations` | Propose negative geo exclusions on a campaign — exclude cities/regions while keeping broader positive targets |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.37.0"
3
+ version = "0.38.0"
4
4
  description = "The AI command center for Google Ads, Reddit Ads, GA4, and tracking code."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.37.0"
3
+ version = "0.38.0"
4
4
  description = "The AI command center for Google Ads, Reddit Ads, GA4, and tracking code."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -609,7 +609,8 @@ def _create_and_link(client, cid: str, assets: list[dict], field_type, populate,
609
609
  """Create assets and link them at the plan's scope in one Mutate.
610
610
 
611
611
  Plans from before scopes existed have no ``scope`` and link to their
612
- campaign, as they always did.
612
+ campaign, as they always did. ``field_type`` is one enum value for all
613
+ assets, or a function of the asset's payload.
613
614
  """
614
615
  scope = changes.get("scope") or "campaign"
615
616
  asset_service = client.get_service("AssetService")
@@ -621,9 +622,10 @@ def _create_and_link(client, cid: str, assets: list[dict], field_type, populate,
621
622
  asset.resource_name = asset_service.asset_path(cid, str(-(i + 1)))
622
623
  populate(asset, payload)
623
624
  operations.append(op)
624
- for i in range(len(assets)):
625
+ for i, payload in enumerate(assets):
625
626
  operations.append(_link_operation(
626
- client, cid, asset_service.asset_path(cid, str(-(i + 1))), field_type, scope,
627
+ client, cid, asset_service.asset_path(cid, str(-(i + 1))),
628
+ field_type(payload) if callable(field_type) else field_type, scope,
627
629
  changes.get("campaign_id", ""), changes.get("ad_group_id", ""),
628
630
  ))
629
631
  response = googleads_service.mutate(customer_id=cid, mutate_operations=operations)
@@ -598,6 +598,29 @@ def _sha256_hex(value: str) -> str:
598
598
  return hashlib.sha256(value.encode("utf-8")).hexdigest()
599
599
 
600
600
 
601
+ _SHA256_HEX_RE = re.compile(r"[0-9a-fA-F]{64}")
602
+ _SHA256_OF_NOTHING = hashlib.sha256(b"").hexdigest()
603
+
604
+
605
+ def _prehashed(value: str) -> str:
606
+ """A cell that already holds a SHA-256 hex digest, lowercased; else "".
607
+
608
+ A CRM export can hash before it writes, so raw values never reach disk.
609
+ Hashing such a digest again, or reading it as a malformed address, would
610
+ upload an identifier that matches nobody.
611
+ """
612
+ text = (value or "").strip()
613
+ return text.lower() if _SHA256_HEX_RE.fullmatch(text) else ""
614
+
615
+
616
+ def _blank_if_hash_of_nothing(value: str) -> str:
617
+ """An export that hashes every cell turns a blank one into the digest of "".
618
+
619
+ That digest identifies nobody, so it counts as the blank it was.
620
+ """
621
+ return "" if _prehashed(value) == _SHA256_OF_NOTHING else value
622
+
623
+
601
624
  def _normalize_email(email: str) -> str:
602
625
  """Normalize an email the way Enhanced Conversions expect it hashed.
603
626
 
@@ -2348,7 +2371,9 @@ def _parse_ec_for_leads_csv(
2348
2371
  Each is normalized (email→trim+lowercase, phone→E.164, names→trim+
2349
2372
  lowercase) and then SHA-256-hashed here. Returned rows contain ONLY the
2350
2373
  hashes (``*_sha256`` keys) plus non-PII fields — the raw values never
2351
- leave this function.
2374
+ leave this function. A cell that already is a SHA-256 hex digest is used
2375
+ as it is (``prehashed_cells`` counts those), and the digest of an empty
2376
+ string counts as a blank cell.
2352
2377
  """
2353
2378
  records, errors, timezone = _read_upload_csv(csv_path)
2354
2379
  if errors:
@@ -2394,16 +2419,22 @@ def _parse_ec_for_leads_csv(
2394
2419
  if "Order ID" in optional_col:
2395
2420
  order_id = raw[optional_col["Order ID"]].strip()
2396
2421
  # Normalize THEN hash. Raw values are discarded immediately.
2397
- raw_email = raw[col["Email"]]
2422
+ raw_email = _blank_if_hash_of_nothing(raw[col["Email"]])
2423
+ email_hash = _prehashed(raw_email)
2398
2424
  email_norm = _normalize_email(raw_email)
2399
- raw_phone = raw[col["Phone Number"]]
2400
- phone_norm = _normalize_phone_e164(raw_phone, default_region)
2425
+ raw_phone = _blank_if_hash_of_nothing(raw[col["Phone Number"]])
2426
+ phone_hash = _prehashed(raw_phone)
2427
+ phone_norm = _normalize_phone_e164(raw_phone, default_region) if not phone_hash else ""
2401
2428
  # A phone that is not E.164 hashes to a value Google can never match —
2402
2429
  # sending it would only pad the payload. Keep the row (email/address
2403
2430
  # may still match) but drop the identifier and say so.
2404
- phone_usable = phone_norm.startswith("+")
2405
- first_norm = _normalize_name(raw[col["First Name"]])
2406
- last_norm = _normalize_name(raw[col["Last Name"]])
2431
+ phone_usable = bool(phone_hash) or phone_norm.startswith("+")
2432
+ raw_first = _blank_if_hash_of_nothing(raw[col["First Name"]])
2433
+ raw_last = _blank_if_hash_of_nothing(raw[col["Last Name"]])
2434
+ first_hash = _prehashed(raw_first)
2435
+ last_hash = _prehashed(raw_last)
2436
+ first_norm = _normalize_name(raw_first)
2437
+ last_norm = _normalize_name(raw_last)
2407
2438
 
2408
2439
  def _optional(name: str) -> str:
2409
2440
  return raw[optional_col[name]].strip() if name in optional_col else ""
@@ -2446,13 +2477,14 @@ def _parse_ec_for_leads_csv(
2446
2477
  postal = ""
2447
2478
  out.append({
2448
2479
  "source_line": source_line,
2449
- "email_sha256": _sha256_hex(email_norm),
2480
+ "email_sha256": email_hash or _sha256_hex(email_norm),
2450
2481
  "email_was_given": bool((raw_email or "").strip()),
2451
- "phone_sha256": _sha256_hex(phone_norm) if phone_usable else "",
2482
+ "phone_sha256": phone_hash or (_sha256_hex(phone_norm) if phone_usable else ""),
2452
2483
  "phone_was_given": bool((raw_phone or "").strip()),
2453
2484
  "phone_usable": phone_usable,
2454
- "first_name_sha256": _sha256_hex(first_norm),
2455
- "last_name_sha256": _sha256_hex(last_norm),
2485
+ "first_name_sha256": first_hash or _sha256_hex(first_norm),
2486
+ "last_name_sha256": last_hash or _sha256_hex(last_norm),
2487
+ "prehashed_cells": sum(map(bool, (email_hash, phone_hash, first_hash, last_hash))),
2456
2488
  "postal_code": postal,
2457
2489
  "country_code": country,
2458
2490
  "conversion_name": raw[col["Conversion Name"]].strip(),
@@ -2483,6 +2515,7 @@ def _match_warnings(
2483
2515
  address_without_names: list[int],
2484
2516
  unusable_phones: list[int],
2485
2517
  unusable_emails: list[int],
2518
+ prehashed: list[int] | None = None,
2486
2519
  ) -> list[str]:
2487
2520
  """Warnings about identifiers that will not match, said up front.
2488
2521
 
@@ -2522,6 +2555,13 @@ def _match_warnings(
2522
2555
  "match. Those rows are uploaded without the email identifier; "
2523
2556
  f"first affected rows: {unusable_emails[:5]}."
2524
2557
  )
2558
+ if prehashed:
2559
+ warnings.append(
2560
+ f"{len(prehashed)} row(s) carry identifiers that already are SHA-256 "
2561
+ "digests, used as they are. They match only if the values were normalized "
2562
+ "the way Google asks before hashing, which cannot be checked from a "
2563
+ f"digest; first affected rows: {prehashed[:5]}."
2564
+ )
2525
2565
  return warnings
2526
2566
 
2527
2567
 
@@ -2540,7 +2580,9 @@ def draft_upload_enhanced_conversions_for_leads(
2540
2580
  Email / Phone / First Name / Last Name columns, and previews what will
2541
2581
  be pushed via ConversionUploadService.UploadClickConversions with
2542
2582
  user_identifiers populated. Only the hashes are stored in the plan —
2543
- raw PII never lands in plan.changes or the audit log.
2583
+ raw PII never lands in plan.changes or the audit log. A cell that already
2584
+ is a SHA-256 hex digest (a CRM export that hashes before writing) is used
2585
+ as it is, and the preview says how many rows carry one.
2544
2586
 
2545
2587
  The target conversion action must be of type UPLOAD_CLICKS (EC for Leads
2546
2588
  layers user-identifier matching on top of click conversions). Works
@@ -2684,6 +2726,11 @@ def draft_upload_enhanced_conversions_for_leads(
2684
2726
  for index, r in enumerate(rows, start=1)
2685
2727
  if r["email_was_given"] and not r["email_sha256"]
2686
2728
  ]
2729
+ prehashed_rows = [
2730
+ _source_line(r, index)
2731
+ for index, r in enumerate(rows, start=1)
2732
+ if r.get("prehashed_cells")
2733
+ ]
2687
2734
  names_without_address = [
2688
2735
  _source_line(r, index)
2689
2736
  for index, r in enumerate(rows, start=1)
@@ -2761,6 +2808,7 @@ def draft_upload_enhanced_conversions_for_leads(
2761
2808
  "rows_with_phone": with_phone,
2762
2809
  "rows_with_order_id": with_order_id,
2763
2810
  "rows_with_address": with_address,
2811
+ **({"rows_with_prehashed_identifiers": len(prehashed_rows)} if prehashed_rows else {}),
2764
2812
  "skipped_count": len(skipped),
2765
2813
  "skipped_rows": skipped,
2766
2814
  # Say it in prose too: the count is easy to miss in a JSON blob.
@@ -2782,6 +2830,7 @@ def draft_upload_enhanced_conversions_for_leads(
2782
2830
  address_without_names,
2783
2831
  unusable_phones,
2784
2832
  unusable_emails,
2833
+ prehashed_rows,
2785
2834
  ),
2786
2835
  "sample_rows": [
2787
2836
  {
@@ -1,4 +1,4 @@
1
- """Performance Max asset groups: add and remove assets — draft → preview → apply.
1
+ """Performance Max: read tools, and asset group writes (draft → preview → apply).
2
2
 
3
3
  ``draft_asset_group_assets`` changes the assets of one existing asset group
4
4
  in one atomic GoogleAdsService.Mutate: new assets are created with temp ids
@@ -16,6 +16,9 @@ from __future__ import annotations
16
16
 
17
17
  from typing import TYPE_CHECKING, Any
18
18
 
19
+ from adloop.ads.currency import get_currency_code
20
+ from adloop.ads.read import _date_clause, _enrich_cost_fields
21
+
19
22
  if TYPE_CHECKING:
20
23
  from adloop.config import AdLoopConfig
21
24
 
@@ -719,3 +722,254 @@ def apply_pmax_product_filter(client: object, cid: str, changes: dict) -> dict:
719
722
  "newly_excluded": changes.get("newly_excluded", []),
720
723
  "no_longer_excluded": changes.get("no_longer_excluded", []),
721
724
  }
725
+
726
+
727
+ # ---------------------------------------------------------------------------
728
+ # Read tools
729
+ # ---------------------------------------------------------------------------
730
+
731
+
732
+ def get_pmax_performance(
733
+ config: AdLoopConfig,
734
+ *,
735
+ customer_id: str = "",
736
+ date_range_start: str = "",
737
+ date_range_end: str = "",
738
+ ) -> dict:
739
+ """Get Performance Max campaign metrics with network breakdown and asset group ad strength."""
740
+ from adloop.ads.gaql import execute_query
741
+
742
+ date_clause = _date_clause(date_range_start, date_range_end)
743
+
744
+ campaign_query = f"""
745
+ SELECT campaign.id, campaign.name, campaign.status,
746
+ campaign.bidding_strategy_type,
747
+ metrics.impressions, metrics.clicks, metrics.cost_micros,
748
+ metrics.conversions, metrics.conversions_value,
749
+ metrics.ctr, metrics.average_cpc,
750
+ segments.ad_network_type
751
+ FROM campaign
752
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
753
+ AND campaign.status != 'REMOVED'
754
+ {date_clause}
755
+ ORDER BY metrics.cost_micros DESC
756
+ """
757
+
758
+ campaigns = execute_query(config, customer_id, campaign_query)
759
+ currency_code = get_currency_code(config, customer_id)
760
+ _enrich_cost_fields(campaigns, currency_code)
761
+
762
+ asset_group_query = f"""
763
+ SELECT asset_group.id, asset_group.name, asset_group.status,
764
+ asset_group.ad_strength, asset_group.campaign,
765
+ metrics.impressions, metrics.clicks, metrics.cost_micros,
766
+ metrics.conversions, metrics.conversions_value
767
+ FROM asset_group
768
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
769
+ {date_clause}
770
+ ORDER BY metrics.cost_micros DESC
771
+ """
772
+
773
+ asset_groups = execute_query(config, customer_id, asset_group_query)
774
+ _enrich_cost_fields(asset_groups, currency_code)
775
+
776
+ insights: list[str] = []
777
+
778
+ poor_strength = [
779
+ ag for ag in asset_groups
780
+ if ag.get("asset_group.ad_strength") in ("POOR", "AVERAGE")
781
+ ]
782
+ if poor_strength:
783
+ names = ", ".join(
784
+ ag.get("asset_group.name", "?") for ag in poor_strength[:5]
785
+ )
786
+ insights.append(
787
+ f"{len(poor_strength)} asset group(s) have POOR or AVERAGE ad strength: "
788
+ f"{names}. Add more diverse assets (headlines, descriptions, images) to improve."
789
+ )
790
+
791
+ zero_conv_groups = [
792
+ ag for ag in asset_groups
793
+ if (ag.get("metrics.clicks", 0) or 0) > 10
794
+ and (ag.get("metrics.conversions", 0) or 0) == 0
795
+ ]
796
+ if zero_conv_groups:
797
+ names = ", ".join(
798
+ ag.get("asset_group.name", "?") for ag in zero_conv_groups[:5]
799
+ )
800
+ insights.append(
801
+ f"{len(zero_conv_groups)} asset group(s) have clicks but zero conversions: {names}."
802
+ )
803
+
804
+ network_counts: dict[str, int] = {}
805
+ for c in campaigns:
806
+ net = c.get("segments.ad_network_type", "UNKNOWN")
807
+ network_counts[net] = network_counts.get(net, 0) + (
808
+ c.get("metrics.impressions", 0) or 0
809
+ )
810
+ if network_counts:
811
+ total_impr = sum(network_counts.values()) or 1
812
+ dist = {
813
+ k: f"{round(v / total_impr * 100, 1)}%"
814
+ for k, v in sorted(network_counts.items(), key=lambda x: -x[1])
815
+ }
816
+ insights.append(f"PMax network distribution by impressions: {dist}")
817
+
818
+ if not campaigns:
819
+ insights.append("No Performance Max campaigns found in this account.")
820
+
821
+ return {
822
+ "campaigns": campaigns,
823
+ "asset_groups": asset_groups,
824
+ "total_campaigns": len(campaigns),
825
+ "total_asset_groups": len(asset_groups),
826
+ "insights": insights,
827
+ }
828
+
829
+
830
+ def get_asset_performance(
831
+ config: AdLoopConfig,
832
+ *,
833
+ customer_id: str = "",
834
+ campaign_id: str = "",
835
+ ) -> dict:
836
+ """Get per-asset details for Performance Max asset groups.
837
+
838
+ Returns each asset's field type, status, primary serving status, and
839
+ content. ``primary_status`` shows whether the asset is eligible to serve
840
+ (ELIGIBLE, NOT_ELIGIBLE, PAUSED, PENDING).
841
+
842
+ Note: the Google Ads API does not expose per-asset performance labels
843
+ (BEST/GOOD/LOW) for PMax assets via GAQL. Use ``get_detailed_asset_performance``
844
+ to see which asset *combinations* Google selects most — that's the closest
845
+ proxy for individual asset quality.
846
+ """
847
+ from adloop.ads.gaql import execute_query
848
+
849
+ campaign_filter = ""
850
+ if campaign_id:
851
+ campaign_filter = f"AND campaign.id = {campaign_id}"
852
+
853
+ query = f"""
854
+ SELECT asset_group_asset.asset, asset_group_asset.field_type,
855
+ asset_group_asset.status, asset_group_asset.primary_status,
856
+ asset_group.id, asset_group.name,
857
+ campaign.id, campaign.name,
858
+ asset.name, asset.type,
859
+ asset.text_asset.text,
860
+ asset.image_asset.full_size.url
861
+ FROM asset_group_asset
862
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
863
+ {campaign_filter}
864
+ """
865
+
866
+ rows = execute_query(config, customer_id, query)
867
+
868
+ status_counts: dict[str, int] = {}
869
+ field_type_counts: dict[str, int] = {}
870
+ for row in rows:
871
+ status = row.get("asset_group_asset.primary_status", "UNSPECIFIED")
872
+ status_counts[status] = status_counts.get(status, 0) + 1
873
+ ftype = row.get("asset_group_asset.field_type", "UNSPECIFIED")
874
+ field_type_counts[ftype] = field_type_counts.get(ftype, 0) + 1
875
+
876
+ insights: list[str] = []
877
+ if not rows:
878
+ insights.append(
879
+ "No PMax assets found. This account has no Performance Max campaigns, "
880
+ "or the specified campaign_id does not match a PMax campaign."
881
+ )
882
+ else:
883
+ not_eligible = [
884
+ r for r in rows
885
+ if r.get("asset_group_asset.primary_status") == "NOT_ELIGIBLE"
886
+ ]
887
+ if not_eligible:
888
+ insights.append(
889
+ f"{len(not_eligible)} asset(s) are NOT_ELIGIBLE to serve — "
890
+ f"check policy status or asset quality."
891
+ )
892
+
893
+ return {
894
+ "assets": rows,
895
+ "total_assets": len(rows),
896
+ "by_status": status_counts,
897
+ "by_field_type": field_type_counts,
898
+ "insights": insights,
899
+ }
900
+
901
+
902
+ def get_detailed_asset_performance(
903
+ config: AdLoopConfig,
904
+ *,
905
+ customer_id: str = "",
906
+ campaign_id: str = "",
907
+ ) -> dict:
908
+ """Get top-performing asset combinations for Performance Max campaigns.
909
+
910
+ Uses the ``asset_group_top_combination_view`` resource directly (not
911
+ ``execute_query``) because the nested proto structure requires custom
912
+ extraction.
913
+ """
914
+ from adloop.ads.client import get_ads_client, normalize_customer_id
915
+
916
+ client = get_ads_client(config)
917
+ service = client.get_service("GoogleAdsService")
918
+ cid = normalize_customer_id(customer_id)
919
+
920
+ campaign_filter = ""
921
+ if campaign_id:
922
+ campaign_filter = f"AND campaign.id = {campaign_id}"
923
+
924
+ query = f"""
925
+ SELECT asset_group_top_combination_view.asset_group_top_combinations,
926
+ campaign.id, campaign.name,
927
+ asset_group.id, asset_group.name
928
+ FROM asset_group_top_combination_view
929
+ WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
930
+ {campaign_filter}
931
+ """
932
+
933
+ combinations: list[dict] = []
934
+ for row in service.search(customer_id=cid, query=query):
935
+ campaign_name = row.campaign.name
936
+ campaign_id_val = row.campaign.id
937
+ ag_name = row.asset_group.name
938
+ ag_id = row.asset_group.id
939
+
940
+ top_combos = row.asset_group_top_combination_view.asset_group_top_combinations
941
+ for combo in top_combos:
942
+ assets_in_combo: list[dict] = []
943
+ for served_info in getattr(combo, "asset_combination_serving_infos", []):
944
+ for asset_usage in getattr(served_info, "served_assets", []):
945
+ field_type = getattr(asset_usage, "served_asset_field_type", None)
946
+ assets_in_combo.append({
947
+ "asset": getattr(asset_usage, "asset", ""),
948
+ "field_type": (
949
+ field_type.name
950
+ if hasattr(field_type, "name")
951
+ else str(field_type)
952
+ ),
953
+ })
954
+
955
+ if assets_in_combo:
956
+ combinations.append({
957
+ "campaign.id": campaign_id_val,
958
+ "campaign.name": campaign_name,
959
+ "asset_group.id": ag_id,
960
+ "asset_group.name": ag_name,
961
+ "assets": assets_in_combo,
962
+ })
963
+
964
+ insights: list[str] = []
965
+ if not combinations:
966
+ insights.append(
967
+ "No top asset combinations found. This account has no Performance Max "
968
+ "campaigns, or the specified campaign_id does not match a PMax campaign."
969
+ )
970
+
971
+ return {
972
+ "top_combinations": combinations,
973
+ "total_combinations": len(combinations),
974
+ "insights": insights,
975
+ }