Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 113 additions & 14 deletions src/adloop/ads/conversion_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,9 @@ def draft_create_conversion_action(
False = Secondary (records but doesn't affect bidding).
include_in_conversions_metric: True (default) = appears in the
"Conversions" column; False = "All conversions" only. NOTE: this is
IMMUTABLE on create — Google derives it from the category and rejects
any value set in the create mutate. To change it, use
IMMUTABLE — Google derives it from primary_for_goal and the category's
goal and rejects any value set directly. To change whether an action
counts, use primary_for_goal or category in
draft_update_conversion_action after the create succeeds.
click_through_window_days / view_through_window_days: attribution
windows. 30/1 is the typical lead-gen pair.
Expand Down Expand Up @@ -305,13 +306,19 @@ def draft_update_conversion_action(
click_through_window_days: int = 0,
view_through_window_days: int = 0,
attribution_model: str = "",
category: str = "",
) -> dict:
"""Draft a partial UPDATE of an existing ConversionAction — returns PREVIEW.

Only the parameters you pass non-empty/non-default will be sent to the
API. Use this to rename, demote a Primary to Secondary, change value,
adjust the call-duration threshold, or change attribution settings.
include_in_conversions_metric IS mutable here (unlike on create).
adjust the call-duration threshold, change attribution settings, or move
the action to another goal (category; the preview shows the current one,
and the apply sends nothing if it changed in Google Ads since).

include_in_conversions_metric is refused: Google answers IMMUTABLE_FIELD
at apply, and validate_only does not catch it. It derives the value from
primary_for_goal and whether the goal of the action's category is biddable.

conversion_action_id: numeric ID. Find via:
SELECT conversion_action.id, conversion_action.name FROM conversion_action
Expand Down Expand Up @@ -341,9 +348,44 @@ def draft_update_conversion_action(
view_through_window_days=view_through_window_days,
attribution_model=attribution_model,
)
if include_in_conversions_metric is not None:
errors.append(
"include_in_conversions_metric cannot be changed: Google answers "
"IMMUTABLE_FIELD at apply, and a dry run does not catch it. Whether an "
"action counts in Conversions follows primary_for_goal and whether the "
"goal of its category is biddable: set primary_for_goal, or move it to "
"a biddable goal with category."
)
category = category.strip().upper()
if category and category not in _VALID_CATEGORIES:
errors.append(
f"category '{category}' invalid; valid: {sorted(_VALID_CATEGORIES)}"
)
if category and not str(conversion_action_id).strip().isdigit():
errors.append(
f"conversion_action_id must be numeric, got '{conversion_action_id}'"
)
if errors:
return {"error": "Validation failed", "details": errors}

warnings: list[str] = []
current_category = ""
if category:
current = _current_conversion_action(config, customer_id, conversion_action_id)
if current is None:
return {"error": f"Conversion action {conversion_action_id} was not found in this account"}
if current["status"] == "REMOVED":
return {"error": f"Conversion action {conversion_action_id} is removed"}
if current["category"] == category:
return {"error": f"Conversion action {conversion_action_id} is already in category {category}"}
current_category = current["category"]
warnings.append(
f"Moves '{current['name']}' from the {current_category} goal to the {category} "
"goal. It counts in Conversions only if it is primary and the new goal is "
"biddable, so campaigns bidding on these goals can start or stop optimizing "
"toward it, which restarts Smart Bidding's learning period."
)

# Track which fields the caller actually wants to update so we build
# the right field_mask at apply time.
changes: dict = {"conversion_action_id": str(conversion_action_id)}
Expand All @@ -361,10 +403,9 @@ def draft_update_conversion_action(
changes["counting_type"] = counting_type
if phone_call_duration_seconds:
changes["phone_call_duration_seconds"] = int(phone_call_duration_seconds)
if include_in_conversions_metric is not None:
changes["include_in_conversions_metric"] = bool(
include_in_conversions_metric
)
if category:
changes["current_category"] = current_category
changes["category"] = category
if click_through_window_days:
changes["click_through_window_days"] = int(click_through_window_days)
if view_through_window_days:
Expand All @@ -375,7 +416,6 @@ def draft_update_conversion_action(
if len(changes) == 1: # only conversion_action_id
return {"error": "No fields to update"}

warnings: list[str] = []
# Same fallback-vs-override nuance as create: on update, a positive
# default_value with always_use_default_value explicitly set to False is
# legal (fallback). Warn rather than silently overriding intent.
Expand Down Expand Up @@ -404,6 +444,24 @@ def draft_update_conversion_action(
return preview


def _current_conversion_action(
config: AdLoopConfig, customer_id: str, conversion_action_id: str
) -> dict | None:
"""Name, category and status of a conversion action, or None if not found."""
from adloop.ads.gaql import execute_query

rows = execute_query(config, customer_id, (
"SELECT conversion_action.name, conversion_action.category, conversion_action.status "
f"FROM conversion_action WHERE conversion_action.id = {str(conversion_action_id).strip()} LIMIT 1"))
if not rows:
return None
return {
"name": rows[0].get("conversion_action.name") or "",
"category": str(rows[0].get("conversion_action.category") or ""),
"status": str(rows[0].get("conversion_action.status") or ""),
}


def draft_remove_conversion_action(
config: AdLoopConfig,
*,
Expand Down Expand Up @@ -472,8 +530,8 @@ def _apply_create_conversion_action(client: object, cid: str, changes: dict) ->
ca.primary_for_goal = changes["primary_for_goal"]
# NOTE: include_in_conversions_metric is IMMUTABLE on create — Google
# derives it from the conversion category and rejects any value set in
# the create mutate (IMMUTABLE_FIELD). To change it, use
# draft_update_conversion_action after the create succeeds.
# the create mutate (IMMUTABLE_FIELD). draft_update_conversion_action
# changes what it derives from: primary_for_goal and category.
if changes.get("phone_call_duration_seconds"):
ca.phone_call_duration_seconds = changes["phone_call_duration_seconds"]
if changes.get("click_through_window_days"):
Expand All @@ -491,10 +549,40 @@ def _apply_create_conversion_action(client: object, cid: str, changes: dict) ->
return {"resource_name": response.results[0].resource_name}


def _check_category_unchanged(client: object, cid: str, changes: dict) -> None:
"""Refuse a category move when the category changed in Google Ads after the preview.

Moving an action to another goal can start or stop campaigns bidding on
it, so the move is pinned to ``current_category``, the category the
preview showed. A read, so it also runs in the dry run: the validate-only
client passes searches through. The value is converted as the draft's GAQL
read converts it (the enum name), so the two compare like for like.
"""
from adloop.ads.gaql import _extract_field

action_id = str(changes["conversion_action_id"]).strip()
service = client.get_service("GoogleAdsService")
rows = list(service.search(customer_id=cid, query=(
"SELECT conversion_action.category FROM conversion_action "
f"WHERE conversion_action.id = {action_id}")))
if not rows:
raise RuntimeError(f"Conversion action {action_id} no longer exists; nothing was sent.")
now = str(_extract_field(rows[0], "conversion_action.category") or "")
pinned = changes.get("current_category", "")
if now != pinned:
raise RuntimeError(
f"Conversion action {action_id} was changed in Google Ads after this preview "
f"(its category is now {now}, the preview showed {pinned}); nothing was sent. "
"Draft the edit again so the preview shows the current category."
)


def _apply_update_conversion_action(client: object, cid: str, changes: dict) -> dict:
"""Partial update of an existing ConversionAction.

Builds a FieldMask listing only the fields the caller wanted to update.
A category move first re-reads the action and sends nothing if its
category changed in Google Ads since the preview (dry run included).
"""
from google.protobuf import field_mask_pb2

Expand All @@ -505,6 +593,15 @@ def _apply_update_conversion_action(client: object, cid: str, changes: dict) ->
cid, changes["conversion_action_id"]
)

if "include_in_conversions_metric" in changes:
# A plan drafted before the draft refused it; Google would reject it.
raise ValueError(
"include_in_conversions_metric cannot be changed; nothing was sent. "
"Draft again with primary_for_goal or category."
)
if "category" in changes:
_check_category_unchanged(client, cid, changes)

paths: list[str] = []

if "name" in changes:
Expand All @@ -530,9 +627,11 @@ def _apply_update_conversion_action(client: object, cid: str, changes: dict) ->
if "phone_call_duration_seconds" in changes:
ca.phone_call_duration_seconds = changes["phone_call_duration_seconds"]
paths.append("phone_call_duration_seconds")
if "include_in_conversions_metric" in changes:
ca.include_in_conversions_metric = changes["include_in_conversions_metric"]
paths.append("include_in_conversions_metric")
if "category" in changes:
ca.category = getattr(
client.enums.ConversionActionCategoryEnum, changes["category"]
)
paths.append("category")
if "click_through_window_days" in changes:
ca.click_through_lookback_window_days = changes["click_through_window_days"]
paths.append("click_through_lookback_window_days")
Expand Down
22 changes: 15 additions & 7 deletions src/adloop/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8574,9 +8574,8 @@ def draft_create_conversion_action(
category). 0 leaves Google's default.
primary_for_goal: True (default) makes it a Primary action that Smart
Bidding optimizes toward; False makes it Secondary (recorded only).
include_in_conversions_metric: IMMUTABLE on create — Google derives it
from the category, so this value is not sent; change it later via
draft_update_conversion_action.
include_in_conversions_metric: IMMUTABLE — Google derives it from
primary_for_goal and the category's goal, so this value is not sent.
click_through_window_days: Click-through attribution window in days,
1-90. 0 leaves Google's default.
view_through_window_days: View-through attribution window in days,
Expand Down Expand Up @@ -8625,12 +8624,14 @@ def draft_update_conversion_action(
view_through_window_days: int = 0,
attribution_model: str = "",
customer_id: str = "",
category: str = "",
) -> dict:
"""Draft a partial UPDATE of an existing ConversionAction — returns PREVIEW.

Only parameters passed non-empty/non-default are sent to the API.
Covers renaming, demoting a Primary to Secondary, changing value,
adjusting the call-duration threshold, or changing attribution.
adjusting the call-duration threshold, changing attribution, or moving
the action to another goal with category.
SMART_CAMPAIGN_* and GOOGLE_HOSTED types reject mutations with
MUTATE_NOT_ALLOWED at apply time. Returns a preview with a plan_id (plus
warnings where relevant); nothing changes until confirm_and_apply applies
Expand All @@ -8655,9 +8656,10 @@ def draft_update_conversion_action(
unchanged.
phone_call_duration_seconds: Minimum call length in seconds for a call
to count. 0 leaves it unchanged.
include_in_conversions_metric: True shows the action in the
"Conversions" column; False in "All conversions" only. Mutable here
(unlike on create). Omit to leave unchanged.
include_in_conversions_metric: Refused when passed: Google answers
IMMUTABLE_FIELD at apply, and a dry run does not catch it. It derives
the value from primary_for_goal and whether the goal of the action's
category is biddable; use those instead.
click_through_window_days: Click-through attribution window in days,
1-90. 0 leaves it unchanged.
view_through_window_days: View-through attribution window in days,
Expand All @@ -8666,6 +8668,11 @@ def draft_update_conversion_action(
GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN. Empty leaves it unchanged.
customer_id: Google Ads customer ID (digits, dashes allowed). Defaults
to the configured account.
category: ConversionActionCategory to move the action to, e.g.
PHONE_CALL_LEAD; that decides which goal it belongs to. The preview
pins the current one (current_category); if the category is changed
in Google Ads before the apply, nothing is sent. Empty leaves it
unchanged.
"""
from adloop.ads.conversion_actions import (
draft_update_conversion_action as _impl,
Expand All @@ -8686,6 +8693,7 @@ def draft_update_conversion_action(
click_through_window_days=click_through_window_days,
view_through_window_days=view_through_window_days,
attribution_model=attribution_model,
category=category,
)


Expand Down
Loading
Loading