Class: Invoicing::GoogleConversionReporter
- Inherits:
-
BaseService
- Object
- BaseService
- Invoicing::GoogleConversionReporter
- Defined in:
- app/services/invoicing/google_conversion_reporter.rb
Overview
Service object: google conversion reporter.
Constant Summary collapse
- WY_CHILD_LOCAL_ACCOUNT =
Child property seen as 989-705-2886 (the original ads account)
'9897052886'- PAGE_SIZE =
don't use
1000- CONVERSION_WINDOW_DAYS =
Conversion window days.
90- CRM_INVOICED_REVENUE_CTID =
"CRM API" This conversion does not belong to the heatwave manager, it is attached to the child account
'6517037943'- CRM_OPPORTUNITY_CTID =
Crm opportunity ctid.
'6686958170'- CRM_CONFIRMED_MANAGER_SALE_CTID =
don't use
'6514977040'- GOOGLE_ADS_SOURCE_ID =
Google ads source id.
1155- MOSS_DIGITAL_SOURCE_ID =
Moss digital source id.
4973- NARROWABLE_SOURCE_IDS =
Narrowable source ids.
[Source::UNKNOWN_ID, GOOGLE_ADS_SOURCE_ID, MOSS_DIGITAL_SOURCE_ID].freeze
- ATTRIBUTION_TIERS =
Attribution tiers.
[ { range: 0..30, pct: 1.0 }, { range: 31..60, pct: 0.75 }, { range: 61..90, pct: 0.50 }, { range: 91..180, pct: 0.25 } ].freeze
- ATTRIBUTION_FLOOR_PCT =
Attribution floor pct.
0.10
Instance Attribute Summary
Attributes inherited from BaseService
Class Method Summary collapse
- .client ⇒ Object
-
.manager_customer_id ⇒ Object
!!!!!! NOTE: "customer" in this context refers to WY as a customer of GOOGLE ads, NOT our customers.
Instance Method Summary collapse
- #alter_conversion(order) ⇒ Object
- #assign_campaign_source_to_order(order, click_date) ⇒ Object
-
#click_baseline_for(resource) ⇒ Object
Determine which identifier will be used and the corresponding click baseline time Returns [key, value, baseline_time].
-
#click_baseline_for_key(resource, id_key, id_val) ⇒ Object
Look up click date for a specific identifier key/value on the resource.
- #collect_visits(resource) ⇒ Object
- #compute_campaign_attribution(order, campaign_source, click_date) ⇒ Object
-
#enhance_conversion(order) ⇒ Object
Add info to conversion.
- #find_visit_baseline(visits, id_key, id_val) ⇒ Object
- #get_account_hierarchy(manager_customer_id, login_customer_id) ⇒ Object
- #get_client ⇒ Object
- #nice_query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) ⇒ Object
- #nicer_query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) ⇒ Object
-
#no_valuable_sales_records?(opportunity) ⇒ Boolean
A nil
Opportunity#valueis only anomalous when there was something to value in the first place. -
#normalize_and_hash(str) ⇒ Object
Returns the result of normalizing and then hashing the string using the provided digest.
-
#normalize_and_hash_email(email) ⇒ Object
Returns the result of normalizing and hashing an email address.
- #print_account_hierarchy(customer_client, cid_to_children, depth) ⇒ Object
- #query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) ⇒ Object
- #resolve_campaign_source(order) ⇒ Object
- #retract_conversion(order) ⇒ Object
- #send_new_opportunity_conversion(opportunity, conversion_date_time: nil) ⇒ Object
-
#send_new_order_conversion(order) ⇒ Object
test with "CjwKCAjwxr2iBhBJEiwAdXECwwhFa9nVWna4owzvkx8EXDv1HPwTQ14kFQT6rWNx4Z5R2D_PPDGYAxoCLwUQAvD_BwE".
-
#sibling_opportunity_already_reported(opportunity) ⇒ Object
When a rep creates a CRM opp for a customer who already had an open quote-builder / online opp, both opps can transition to follow_up and both would fire send_new_opportunity_conversion against the same Google click.
- #upload_conversion_adjustment(conversion_action_id:, gclid:, adjustment_type:, conversion_date_time:, adjustment_date_time:, restatement_value:, order_id:, customer_id: nil) ⇒ Object
-
#upload_conversion_enhancement(conversion_action_id:, order_id:, conversion_date_time:, user_agent:, customer_id: nil) ⇒ Object
DO NOT USE YET included only for future use.
- #upload_conversion_with_identifiers(customer_id:, conversion_action_id:, gclid:, gbraid:, wbraid:, email_address:, conversion_date_time:, conversion_value:, order_id:) ⇒ Object
-
#upload_offline_conversion(customer_id, conversion_action_id, gclid, gbraid, wbraid, conversion_date_time, conversion_value, conversion_custom_variable_id, conversion_custom_variable_value) ⇒ Object
DON'T USE.
-
#visit_click_identifier(visit, id_key) ⇒ Object
The gclid/gbraid/wbraid click identifiers moved from scalar Visit columns into Visit#marketing_meta (JSONB) via the 2026-05-14 backfill and the #822
legacy_*rename, soVisit#gclidno longer exists — read them through themarketing_meta_<key>accessor, matching Order#find_gclid's source.
Methods inherited from BaseService
#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #process, #tagged_logger
Constructor Details
This class inherits a constructor from BaseService
Class Method Details
.client ⇒ Object
985 986 987 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 985 def self.client new.get_client end |
.manager_customer_id ⇒ Object
!!!!!! NOTE: "customer" in this context refers to WY as a customer of GOOGLE ads, NOT our customers. INTUITIVE 🙈
WarmlyYours Google Ads manager account - fetched from configuration
9 10 11 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 9 def self.manager_customer_id Heatwave::Configuration.fetch(:google_ads_client, :login_customer_id) end |
Instance Method Details
#alter_conversion(order) ⇒ Object
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 345 def alter_conversion(order) # TODO: if restatement value < 0, goto retract_conversion # ua = order&.visit&.user_agent || order&.quote&.visit&.user_agent || order&.opportunity&.visit&.user_agent total = order.invoices.sum(&:profit_consolidated) || order.line_total conversion_date_time = order. || order.invoices.first&.created_at # Guard: Return early if no invoice is available unless conversion_date_time Rails.logger.warn "GoogleConversionReporter::alter_conversion: No invoice available for order #{order.reference_number}" ErrorReporting.warning('GoogleConversionReporter::alter_conversion: No invoice', { order_id: order.id, reference_number: order.reference_number, invoices_count: order.invoices.count }) return { success: false, reason: :no_invoice } end upload_conversion_adjustment( conversion_action_id: CRM_INVOICED_REVENUE_CTID, gclid: order.find_gclid, adjustment_type: :RESTATEMENT, conversion_date_time: conversion_date_time.to_fs(:google_ads), adjustment_date_time: Time.current.to_fs(:google_ads), restatement_value: total, order_id: order.reference_number ) end |
#assign_campaign_source_to_order(order, click_date) ⇒ Object
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 899 def assign_campaign_source_to_order(order, click_date) campaign_source = resolve_campaign_source(order) return unless campaign_source current_source_id = order.source_id narrowable = current_source_id.nil? || NARROWABLE_SOURCE_IDS.include?(current_source_id) if narrowable # Intentionally using update_column to bypass after_save callbacks # (add_customer_to_campaign, set_opportunity_source). Campaign enrollment # is not desired here — this is a post-hoc attribution correction, not a # new source assignment from a user action. The opportunity propagation # is handled explicitly below. order.update_column(:source_id, campaign_source.id) order.opportunity.update_column(:source_id, campaign_source.id) if order.opportunity && (order.opportunity.source_id.nil? || NARROWABLE_SOURCE_IDS.include?(order.opportunity.source_id)) Rails.logger.info "GoogleConversionReporter: Tagged order #{order.reference_number} source to #{campaign_source.full_name} (#{campaign_source.id})" end compute_campaign_attribution(order, campaign_source, click_date) rescue StandardError => e Rails.logger.error "GoogleConversionReporter: Failed to assign campaign source for #{order.reference_number}: #{e.}" ErrorReporting.warning('GoogleConversionReporter: assign_campaign_source_to_order failed', { order_id: order.id, error: e. }) end |
#click_baseline_for(resource) ⇒ Object
Determine which identifier will be used and the corresponding click baseline time
Returns [key, value, baseline_time]
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 515 def click_baseline_for(resource) id_key = nil id_val = nil if resource.respond_to?(:find_gclid) && (val = resource.find_gclid.presence) id_key = :gclid id_val = val elsif resource.respond_to?(:find_gbraid) && (val = resource.find_gbraid.presence) id_key = :gbraid id_val = val elsif resource.respond_to?(:find_wbraid) && (val = resource.find_wbraid.presence) id_key = :wbraid id_val = val end baseline_time = find_visit_baseline(collect_visits(resource), id_key, id_val) if id_key && id_val [id_key, id_val, baseline_time] end |
#click_baseline_for_key(resource, id_key, id_val) ⇒ Object
Look up click date for a specific identifier key/value on the resource
507 508 509 510 511 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 507 def click_baseline_for_key(resource, id_key, id_val) visits = collect_visits(resource) baseline_time = find_visit_baseline(visits, id_key, id_val) [id_key, id_val, baseline_time] end |
#collect_visits(resource) ⇒ Object
534 535 536 537 538 539 540 541 542 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 534 def collect_visits(resource) visits = [] visits << resource.visit if resource.respond_to?(:visit) && resource.visit.present? visits << resource.quote.visit if resource.respond_to?(:quote) && resource.quote.respond_to?(:visit) && resource.quote.visit.present? visits << resource.opportunity.visit if resource.respond_to?(:opportunity) && resource.opportunity.respond_to?(:visit) && resource.opportunity.visit.present? visits.concat(Array(resource.customer.visits)) if resource.respond_to?(:customer) && resource.customer.respond_to?(:visits) && resource.customer.visits.present? visits.compact! visits end |
#compute_campaign_attribution(order, campaign_source, click_date) ⇒ Object
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 959 def compute_campaign_attribution(order, campaign_source, click_date) return unless click_date && order.shipped_date days = (order.shipped_date.to_date - click_date.to_date).to_i days = 0 if days < 0 tier = ATTRIBUTION_TIERS.find { |t| t[:range].cover?(days) } pct = tier ? tier[:pct] : ATTRIBUTION_FLOOR_PCT total = order.invoices.sum { |inv| inv.revenue_consolidated || 0 } attributed = (total * pct).round(2) order.update_column(:google_campaign_attribution, { source_name: campaign_source.full_name, source_id: campaign_source.id, campaign_id: campaign_source.campaign_external_id, click_date: click_date.iso8601, days_since_click: days, attribution_pct: pct, attributed_revenue: attributed, total_revenue: total.round(2), model: 'tiered_v1', computed_at: Time.current.iso8601 }) end |
#enhance_conversion(order) ⇒ Object
Add info to conversion
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 406 def enhance_conversion(order) ua = order&.visit&.user_agent || order&.quote&.visit&.user_agent || order&.opportunity&.visit&.user_agent conversion_date_time = order.invoices.first&.created_at # Guard: Return early if no invoice is available unless conversion_date_time Rails.logger.warn "GoogleConversionReporter::enhance_conversion: No invoice available for order #{order.reference_number}" ErrorReporting.warning('GoogleConversionReporter::enhance_conversion: No invoice', { order_id: order.id, reference_number: order.reference_number, invoices_count: order.invoices.count }) return { success: false, reason: :no_invoice } end upload_conversion_enhancement( conversion_action_id: CRM_INVOICED_REVENUE_CTID, order_id: order.reference_number, conversion_date_time: conversion_date_time.to_fs(:google_ads), user_agent: ua ) end |
#find_visit_baseline(visits, id_key, id_val) ⇒ Object
544 545 546 547 548 549 550 551 552 553 554 555 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 544 def find_visit_baseline(visits, id_key, id_val) return nil unless id_key && id_val matched = visits.find { |v| visit_click_identifier(v, id_key) == id_val } return nil unless matched if matched.is_a?(Hash) matched[:started_at] || matched['started_at'] else matched.respond_to?(:started_at) ? matched.started_at : nil end end |
#get_account_hierarchy(manager_customer_id, login_customer_id) ⇒ Object
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 773 def get_account_hierarchy(manager_customer_id, login_customer_id) client = get_client # Set the specified login customer ID. client.configure do |config| if login_customer_id config.login_customer_id = login_customer_id.to_i elsif manager_customer_id config.login_customer_id = manager_customer_id.to_i end end google_ads_service = client.service.google_ads seed_customer_ids = [] if manager_customer_id seed_customer_ids << manager_customer_id else puts 'No manager customer ID is specified. The example will print the ' \ 'hierarchies of all accessible customer IDs:' customer_resource_names = client.service.customer .list_accessible_customers.resource_names customer_resource_names.each do |res| seed_customer_ids << res.split('/')[1] end end search_query = <<~QUERY SELECT customer_client.client_customer, customer_client.level, customer_client.manager, customer_client.descriptive_name, customer_client.currency_code, customer_client.time_zone, customer_client.id FROM customer_client WHERE customer_client.level <= 1 QUERY seed_customer_ids.each do |seed_cid| # Performs a breadth-first search to build a dictionary that maps managers # to their child accounts (cid_to_children). unprocessed_customer_ids = Queue.new unprocessed_customer_ids << seed_cid cid_to_children = Hash.new { |h, k| h[k] = [] } root_customer_client = nil until unprocessed_customer_ids.empty? cid = unprocessed_customer_ids.pop response = google_ads_service.search( customer_id: cid, query: search_query, page_size: PAGE_SIZE ) # Iterates over all rows in all pages to get all customer clients under # the specified customer's hierarchy. response.each do |row| customer_client = row.customer_client # The customer client that with level 0 is the specified customer if customer_client.level == 0 root_customer_client = customer_client if root_customer_client.nil? next end # For all level-1 (direct child) accounts that are a manager account, # the above query will be run against them to create a dictionary of # managers mapped to their child accounts for printing the hierarchy # afterwards. cid_to_children[cid.to_s] << customer_client next if customer_client.manager.nil? if !cid_to_children.key?(customer_client.id.to_s) && customer_client.level == 1 unprocessed_customer_ids << customer_client.id.to_s end end end if root_customer_client puts "The hierarychy of customer ID #{root_customer_client.id} is printed below:" print_account_hierarchy(root_customer_client, cid_to_children, 0) else puts "Customer ID #{manager_customer_id} is likely a test account, " \ 'so its customer client information cannot be retrieved.' end end end |
#get_client ⇒ Object
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 989 def get_client require 'google/ads/google_ads' google_ads_client = Heatwave::Configuration.fetch(:google_ads_client) Google::Ads::GoogleAds::GoogleAdsClient.new do |config| config.client_id = google_ads_client[:client_id] config.client_secret = google_ads_client[:client_secret] config.refresh_token = google_ads_client[:refresh_token] config.developer_token = google_ads_client[:developer_token] config.login_customer_id = google_ads_client[:login_customer_id] config.log_level = 'DEBUG' config.logger = logger end end |
#nice_query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) ⇒ Object
438 439 440 441 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 438 def nice_query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) res = query(q, customer_id) res.response.to_h[:results] end |
#nicer_query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) ⇒ Object
443 444 445 446 447 448 449 450 451 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 443 def nicer_query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) # this is a recursive compact. Google's api it typed, it responds with nil for every key you didn't request p = proc do |_, v| v.delete_if(&p) if v.respond_to? :delete_if v.nil? || (v.respond_to?(:empty?) && v.empty?) end nice_query(q, customer_id).map { |e| e.delete_if(&p) } end |
#no_valuable_sales_records?(opportunity) ⇒ Boolean
A nil Opportunity#value is only anomalous when there was something to
value in the first place.
Opportunity#calculate_value derives value exclusively from
orders.sales_orders and quotes.sales_quotes.active — and
Quote.sales_quotes is where(quote_type: SALES_QUOTE), i.e. SQ only.
An opportunity carrying only non-SQ quotes (MQ, …) therefore has a
permanently nil value by design: nothing in its record set is countable.
Treating that as an error just trends an expected data shape — AppSignal
#4142 fired three times in four months, every time on an opportunity whose
only quote was an MQ.
Existence, not amount, is the test on purpose: an active SQ that exists
but still yields no value (nil / zero line_total) is a genuine anomaly
and keeps its error.
501 502 503 504 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 501 def no_valuable_sales_records?(opportunity) !opportunity.orders.sales_orders.exists? && !opportunity.quotes.sales_quotes.active.exists? end |
#normalize_and_hash(str) ⇒ Object
Returns the result of normalizing and then hashing the string using the
provided digest. Private customer data must be hashed during upload, as
described at https://support.google.com/google-ads/answer/7474263.
754 755 756 757 758 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 754 def normalize_and_hash(str) # Remove leading and trailing whitespace and ensure all letters are lowercase # before hasing. Digest::SHA256.hexdigest(str.strip.downcase) end |
#normalize_and_hash_email(email) ⇒ Object
Returns the result of normalizing and hashing an email address. For this use
case, Google Ads requires removal of any '.' characters preceding 'gmail.com'
or 'googlemail.com'.
763 764 765 766 767 768 769 770 771 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 763 def normalize_and_hash_email(email) return nil if email.nil? email_parts = email.downcase.split('@') # Removes any '.' characters from the portion of the email address before the # domain if the domain is gmail.com or googlemail.com. email_parts[0] = email_parts[0].delete('.') if /^(gmail|googlemail)\.com\s*/.match?(email_parts.last) normalize_and_hash(email_parts.join('@')) end |
#print_account_hierarchy(customer_client, cid_to_children, depth) ⇒ Object
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 866 def print_account_hierarchy(customer_client, cid_to_children, depth) puts 'Customer ID (Descriptive Name, Currency Code, Time Zone)' if depth == 0 customer_id = customer_client.id puts ('-' * (depth * 2)) + "#{customer_id} #{customer_client.descriptive_name} " \ "#{customer_client.currency_code} #{customer_client.time_zone}" # Recursively call this function for all child accounts of customer_client return unless cid_to_children.key?(customer_id.to_s) cid_to_children[customer_id.to_s].each do |child| print_account_hierarchy(child, cid_to_children, depth + 1) end end |
#query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) ⇒ Object
429 430 431 432 433 434 435 436 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 429 def query(q, customer_id = WY_CHILD_LOCAL_ACCOUNT) client = get_client ga_service = client.service.google_ads ga_service.search( customer_id: customer_id, query: q ) end |
#resolve_campaign_source(order) ⇒ Object
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 926 def resolve_campaign_source(order) visits = [ order.visit, order.quote&.visit, order.opportunity&.visit ] if order.respond_to?(:customer) && order.customer visits << order.customer.visit visits.concat(Array(order.customer.visits)) end visits.compact! visits.uniq! visit = visits.find { |v| v..present? || v..present? || v..present? } return nil unless visit return visit.source if visit.source && visit.source.campaign_provider == 'google' && visit.source.campaign_external_id.present? utm = visit.utm_campaign.presence || visit.utm_id.presence if utm by_campaign_id = Source.find_by_campaign(provider: 'google', external_id: utm) return by_campaign_id if by_campaign_id by_utm = Source.where(parent_id: MOSS_DIGITAL_SOURCE_ID) .where(campaign_provider: 'google') .where.not(campaign_external_id: [nil, '']) .where.overlap(utm_campaign: [utm]).first return by_utm if by_utm end nil end |
#retract_conversion(order) ⇒ Object
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 373 def retract_conversion(order) # From here find the info you need and make api call. # use google api gem # invoice -> order -> visit || invoice -> order -> quote -> visit || invoice -> order -> opportunity -> visit # e.g o = Order.invoiced.where.not(visit_id: nil).joins(:visit).where(Visit[:gclid].not_eq(nil)).last # Note also handle RMAs order&.visit&.user_agent || order&.quote&.visit&.user_agent || order&.opportunity&.visit&.user_agent order.invoices.sum(&:profit_consolidated) || order.line_total conversion_date_time = order.invoices.first&.created_at # Guard: Return early if no invoice is available unless conversion_date_time Rails.logger.warn "GoogleConversionReporter::retract_conversion: No invoice available for order #{order.reference_number}" ErrorReporting.warning('GoogleConversionReporter::retract_conversion: No invoice', { order_id: order.id, reference_number: order.reference_number, invoices_count: order.invoices.count }) return { success: false, reason: :no_invoice } end upload_conversion_adjustment( conversion_action_id: CRM_INVOICED_REVENUE_CTID, gclid: order.find_gclid, adjustment_type: :RETRACTION, conversion_date_time: conversion_date_time.to_fs(:google_ads), adjustment_date_time: Time.current.to_fs(:google_ads), restatement_value: 0, order_id: order.reference_number ) end |
#send_new_opportunity_conversion(opportunity, conversion_date_time: nil) ⇒ Object
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 186 def send_new_opportunity_conversion(opportunity, conversion_date_time: nil) unless opportunity.sales_opportunity? Rails.logger.info "#{opportunity.reference_number} is not a sales opportunity and cannot be reported as conversion" return { success: false, reason: :not_a_sales_opportunity } end if opportunity..present? Rails.logger.warn "GoogleConversionReporter::send_new_opportunity_conversion: Opportunity #{opportunity.} already reported" ErrorReporting.warning('GoogleConversionReporter::send_new_opportunity_conversion: Opportunity already reported', { opportunity: opportunity, gclid: opportunity.find_gclid, wbraid: opportunity.find_wbraid }) return { success: false, reason: :already_reported, meta: opportunity. } end if (sibling = sibling_opportunity_already_reported(opportunity)) Rails.logger.info "GoogleConversionReporter::send_new_opportunity_conversion: Sibling opp #{sibling.reference_number} already reported; skipping #{opportunity.reference_number}" return { success: false, reason: :sibling_already_reported, sibling_opportunity_id: sibling.id } end if opportunity.value.nil? if no_valuable_sales_records?(opportunity) Rails.logger.info "GoogleConversionReporter::send_new_opportunity_conversion: Opportunity #{opportunity.reference_number} has no sales quote or order to value" return { success: false, reason: :no_valuable_sales_records } end Rails.logger.error "GoogleConversionReporter::send_new_opportunity_conversion: Opportunity #{opportunity.reference_number} missing value" ErrorReporting.error("GoogleConversionReporter::send_new_opportunity_conversion: Opportunity #{opportunity.reference_number} missing value", { opportunity: opportunity }) return { success: false, reason: :missing_value } end if opportunity.find_gclid.present? || (opportunity.respond_to?(:find_gbraid) && opportunity.find_gbraid.present?) || opportunity.find_wbraid.present? # Google uses the exact time to index datum, here we record the time before the request so that we # don't end up with 2 differing timestamps due to the network flight time conversion_date_time ||= opportunity.updated_at || opportunity.created_at # Lead value extrapolated from average conversion rate # Opportunity is a lead, not a closed sale, so it books a fraction of its # quoted value. PPC dial — /crm/settings/ad-conversion-values. fractional_conversion_value = opportunity.value * Setting.ad_conversion_opportunity_rate conversion_email = opportunity.emails.pick(:detail) || opportunity.customer.email # Skip submissions beyond 90-day conversion window or when click date is unknown chosen_key, chosen_val, baseline_time = click_baseline_for(opportunity) # If we can't determine click date, skip submission to avoid Google rejection if chosen_key && baseline_time.nil? = { result: 'skipped_unknown_click_date', gclid: (chosen_key == :gclid ? chosen_val : nil), gbraid: (chosen_key == :gbraid ? chosen_val : nil), wbraid: (chosen_key == :wbraid ? chosen_val : nil), attempted_at: Time.current, error: 'Cannot verify click is within conversion window; skipping to avoid Google rejection', conversion_date_time: conversion_date_time, fractional_conversion_value: fractional_conversion_value, conversion_email: conversion_email }.compact opportunity.update_column(:google_conversion_meta, ) Rails.logger.info "GoogleConversionReporter: Skipping opportunity #{opportunity.reference_number} - unknown click date for #{chosen_key}" return { success: false, reason: :unknown_click_date, meta: } end if baseline_time && (Time.current.to_date - baseline_time.to_date) > CONVERSION_WINDOW_DAYS = { result: 'skipped_outside_window', gclid: (chosen_key == :gclid ? chosen_val : nil), gbraid: (chosen_key == :gbraid ? chosen_val : nil), wbraid: (chosen_key == :wbraid ? chosen_val : nil), attempted_at: Time.current, error: "Conversion older than #{CONVERSION_WINDOW_DAYS} days; not resubmitted", conversion_date_time: conversion_date_time, fractional_conversion_value: fractional_conversion_value, conversion_email: conversion_email }.compact opportunity.update_column(:google_conversion_meta, ) return { success: false, reason: :outside_conversion_window, meta: } end if baseline_time && conversion_date_time < baseline_time = { result: 'skipped_conversion_precedes_click', gclid: (chosen_key == :gclid ? chosen_val : nil), gbraid: (chosen_key == :gbraid ? chosen_val : nil), wbraid: (chosen_key == :wbraid ? chosen_val : nil), attempted_at: Time.current, error: "Conversion date #{conversion_date_time} precedes click date #{baseline_time}; skipping to avoid Google rejection", conversion_date_time: conversion_date_time, fractional_conversion_value: fractional_conversion_value, conversion_email: conversion_email }.compact opportunity.update_column(:google_conversion_meta, ) Rails.logger.info "GoogleConversionReporter: Skipping opportunity #{opportunity.reference_number} - conversion precedes click" return { success: false, reason: :conversion_precedes_click, meta: } end attempts = [] chosen = { gclid: nil, gbraid: nil, wbraid: nil } res = nil identifiers = [ { gclid: opportunity.find_gclid.presence }, { gbraid: (opportunity.respond_to?(:find_gbraid) ? opportunity.find_gbraid.presence : nil) }, { wbraid: opportunity.find_wbraid.presence } ] identifiers.each do |ids| key, value = ids.find { |_, v| v.present? } next unless value attempts << key chosen = { gclid: nil, gbraid: nil, wbraid: nil }.merge(key => value) res = upload_conversion_with_identifiers( customer_id: self.class.manager_customer_id, conversion_action_id: CRM_OPPORTUNITY_CTID, gclid: chosen[:gclid], gbraid: chosen[:gbraid], wbraid: chosen[:wbraid], email_address: conversion_email, conversion_date_time: conversion_date_time, conversion_value: fractional_conversion_value, order_id: opportunity.reference_number ) break if res.is_a?(Hash) && res[:status] == :reported end reported = res.is_a?(Hash) && res[:status] == :reported = { result: res.is_a?(Hash) ? res[:status].to_s : res.to_s, error: res.is_a?(Hash) ? res[:error] : nil, gclid: chosen[:gclid], gbraid: chosen[:gbraid], wbraid: chosen[:wbraid], attempted_at: Time.current, reported_at: (Time.current if reported), attempted_identifiers: attempts, conversion_date_time: conversion_date_time, fractional_conversion_value: fractional_conversion_value, conversion_email: conversion_email }.compact opportunity.update_column(:google_conversion_meta, ) { success: true, meta: } else Rails.logger.info "GoogleConversionReporter::send_new_opportunity_conversion: No gclids present for opportunity #{opportunity.reference_number}" ErrorReporting.info('GoogleConversionReporter::send_new_opportunity_conversion: No gclids present', { opportunity: opportunity, gclid: opportunity.find_gclid, wbraid: opportunity.find_wbraid }) { success: false, reason: :no_gclids_present } end end |
#send_new_order_conversion(order) ⇒ Object
test with "CjwKCAjwxr2iBhBJEiwAdXECwwhFa9nVWna4owzvkx8EXDv1HPwTQ14kFQT6rWNx4Z5R2D_PPDGYAxoCLwUQAvD_BwE"
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 25 def send_new_order_conversion(order) unless order.is_sales_order? Rails.logger.info "#{order.reference_number} is not a sales order and cannot be reported as conversion" return { success: false, reason: :not_a_sales_order } end if order..present? Rails.logger.warn "GoogleConversionReporter::send_new_order_conversion: Already reported on #{order.reference_number}" ErrorReporting.warning('GoogleConversionReporter::send_new_order_conversion: Already reported', { order: order, gclid: order.find_gclid, wbraid: order.find_wbraid }) # We report on this but continue to hit the google API for confirmation # return { success: false, reason: :already_reported, meta: order.google_conversion_meta } end total = order.invoices.sum(&:revenue_consolidated) # Must be in USD || order.line_total # testing # gclid = "CjwKCAjwxr2iBhBJEiwAdXECwwhFa9nVWna4owzvkx8EXDv1HPwTQ14kFQT6rWNx4Z5R2D_PPDGYAxoCLwUQAvD_BwE" # Proceed if ANY click identifier is available if order.find_gclid.present? || (order.respond_to?(:find_gbraid) && order.find_gbraid.present?) || order.find_wbraid.present? conversion_date_time = order. || order.invoices.first&.created_at conversion_email = order.tracking_email&.first || order.order_emails.first # Guard: Return early if no invoice is available unless conversion_date_time Rails.logger.warn "GoogleConversionReporter::send_new_order_conversion: No invoice available for order #{order.reference_number}" ErrorReporting.warning('GoogleConversionReporter::send_new_order_conversion: No invoice', { order_id: order.id, reference_number: order.reference_number, invoices_count: order.invoices.count }) return { success: false, reason: :no_invoice } end # Skip submissions beyond 90-day conversion window or when click date is unknown chosen_key, chosen_val, baseline_time = click_baseline_for(order) # If we can't determine click date, skip submission to avoid Google rejection if chosen_key && baseline_time.nil? = { result: 'skipped_unknown_click_date', gclid: (chosen_key == :gclid ? chosen_val : nil), gbraid: (chosen_key == :gbraid ? chosen_val : nil), wbraid: (chosen_key == :wbraid ? chosen_val : nil), attempted_at: Time.current, error: 'Cannot verify click is within conversion window; skipping to avoid Google rejection', conversion_date_time: conversion_date_time, conversion_email: conversion_email }.compact order.update_column(:google_conversion_meta, ) Rails.logger.info "GoogleConversionReporter: Skipping order #{order.reference_number} - unknown click date for #{chosen_key}" return { success: false, reason: :unknown_click_date, meta: } end if baseline_time && (Time.current.to_date - baseline_time.to_date) > CONVERSION_WINDOW_DAYS = { result: 'skipped_outside_window', gclid: (chosen_key == :gclid ? chosen_val : nil), gbraid: (chosen_key == :gbraid ? chosen_val : nil), wbraid: (chosen_key == :wbraid ? chosen_val : nil), attempted_at: Time.current, error: "Conversion older than #{CONVERSION_WINDOW_DAYS} days; not resubmitted", conversion_date_time: conversion_date_time, conversion_email: conversion_email }.compact order.update_column(:google_conversion_meta, ) return { success: false, reason: :outside_conversion_window, meta: } end if baseline_time && conversion_date_time < baseline_time = { result: 'skipped_conversion_precedes_click', gclid: (chosen_key == :gclid ? chosen_val : nil), gbraid: (chosen_key == :gbraid ? chosen_val : nil), wbraid: (chosen_key == :wbraid ? chosen_val : nil), attempted_at: Time.current, error: "Conversion date #{conversion_date_time} precedes click date #{baseline_time}; skipping to avoid Google rejection", conversion_date_time: conversion_date_time, conversion_email: conversion_email }.compact order.update_column(:google_conversion_meta, ) Rails.logger.info "GoogleConversionReporter: Skipping order #{order.reference_number} - conversion precedes click" return { success: false, reason: :conversion_precedes_click, meta: } end # Try identifiers in order: gclid -> gbraid -> wbraid (only one at a time) attempts = [] chosen = { gclid: nil, gbraid: nil, wbraid: nil } res = nil identifiers = [ { gclid: order.find_gclid.presence }, { gbraid: (order.respond_to?(:find_gbraid) ? order.find_gbraid.presence : nil) }, { wbraid: order.find_wbraid.presence } ] identifiers.each do |ids| key, value = ids.find { |_, v| v.present? } next unless value attempts << key chosen = { gclid: nil, gbraid: nil, wbraid: nil }.merge(key => value) res = upload_conversion_with_identifiers( customer_id: self.class.manager_customer_id, conversion_action_id: CRM_INVOICED_REVENUE_CTID, gclid: chosen[:gclid], gbraid: chosen[:gbraid], wbraid: chosen[:wbraid], email_address: conversion_email, conversion_date_time: conversion_date_time, conversion_value: total, order_id: order.reference_number ) break if res.is_a?(Hash) && res[:status] == :reported end reported = res.is_a?(Hash) && res[:status] == :reported = { result: res.is_a?(Hash) ? res[:status].to_s : res.to_s, error: res.is_a?(Hash) ? res[:error] : nil, gclid: chosen[:gclid], gbraid: chosen[:gbraid], wbraid: chosen[:wbraid], attempted_at: Time.current, reported_at: (Time.current if reported), attempted_identifiers: attempts, conversion_date_time: conversion_date_time, conversion_email: conversion_email }.compact order.update_column(:google_conversion_meta, ) if reported winning_key = chosen.find { |_, v| v.present? }&.first if winning_key && winning_key != chosen_key _, _, actual_click_date = click_baseline_for_key(order, winning_key, chosen[winning_key]) assign_campaign_source_to_order(order, actual_click_date || baseline_time) else assign_campaign_source_to_order(order, baseline_time) end end { success: true, meta: order. } else Rails.logger.info "GoogleConversionReporter::send_new_order_conversion: No click identifiers (gclid/gbraid/wbraid) present for order #{order.reference_number}" ErrorReporting.info('GoogleConversionReporter::send_new_order_conversion: No click identifiers present', { order: order, gclid: order.find_gclid, gbraid: order.respond_to?(:find_gbraid) && order.find_gbraid, wbraid: order.find_wbraid }) { success: false, reason: :no_gclids_present } end end |
#sibling_opportunity_already_reported(opportunity) ⇒ Object
When a rep creates a CRM opp for a customer who already had an open
quote-builder / online opp, both opps can transition to follow_up and
both would fire send_new_opportunity_conversion against the same Google
click. Production data showed ~9% of opp uploads sharing a GCLID with a
sibling — phantom lead volume that biased smart-bidding.
Skip the upload when any other opp on the same customer / parent cluster
has already been reported. The cluster-aware check (parent_id /
merged_into_id) catches the auto-linked case; the customer + GCLID
fallback catches legacy unlinked siblings until the backfill runs.
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 463 def sibling_opportunity_already_reported(opportunity) customer_id = opportunity.customer_id return nil if customer_id.nil? cluster_ids = [opportunity.parent_id, opportunity.merged_into_id, opportunity.id].compact gclid = opportunity.find_gclid.presence scope = Opportunity .where(customer_id: customer_id) .where.not(id: opportunity.id) .google_conversion_reported cluster_match = scope.where.any_of( { id: cluster_ids }, { parent_id: cluster_ids }, { merged_into_id: cluster_ids } ).first return cluster_match if cluster_match return nil unless gclid scope.with_google_conversion_gclid(gclid).first end |
#upload_conversion_adjustment(conversion_action_id:, gclid:, adjustment_type:, conversion_date_time:, adjustment_date_time:, restatement_value:, order_id:, customer_id: nil) ⇒ Object
Go no further, the following needs additional work
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 622 def upload_conversion_adjustment( conversion_action_id:, gclid:, adjustment_type:, conversion_date_time:, adjustment_date_time:, restatement_value:, order_id:, customer_id: nil ) customer_id ||= self.class.manager_customer_id client = get_client # Associate conversion adjustments with the existing conversion action. # The GCLID should have been uploaded before with a conversion. # TODO: what about wbraid conversion_adjustment = client.resource.conversion_adjustment do |ca| ca.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) ca.adjustment_type = adjustment_type if order_id.nil? ca.gclid_date_time_pair = client.resource.gclid_date_time_pair do |gdtp| gdtp.gclid = gclid gdtp.conversion_date_time = conversion_date_time end else ca.order_id = order_id end ca.adjustment_date_time = adjustment_date_time # Set adjusted value for adjustment type RESTATEMENT. if adjustment_type == :RESTATEMENT ca.restatement_value = client.resource.restatement_value do |ra| ra.adjusted_value = restatement_value.to_f end end end # Issue a request to upload the conversion adjustment(s). response = client.service.conversion_adjustment_upload.upload_conversion_adjustments( customer_id: customer_id, # This example shows just one adjustment but you may upload multiple ones. conversion_adjustments: [conversion_adjustment], partial_failure: true ) if response.partial_failure_error.nil? # Process and print all results for multiple adjustments response.results.each do |result| puts "Uploaded conversion adjustment at #{result.adjustment_date_time} " \ "for adjustment #{result.adjustment_type} to #{result.conversion_action}." end else # Print any partial errors returned. failures = client.decode_partial_failure_error(response.partial_failure_error) puts 'Request failed. Failure details:' failures.each do |failure| failure.errors.each do |error| puts "\t#{error.error_code.error_code}: #{error.}" end end end end |
#upload_conversion_enhancement(conversion_action_id:, order_id:, conversion_date_time:, user_agent:, customer_id: nil) ⇒ Object
DO NOT USE YET
included only for future use
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 681 def upload_conversion_enhancement( conversion_action_id:, order_id:, conversion_date_time:, user_agent:, customer_id: nil ) customer_id ||= self.class.manager_customer_id client = get_client enhancement = client.resource.conversion_adjustment do |ca| ca.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) ca.adjustment_type = :ENHANCEMENT ca.order_id = order_id # Sets the conversion date and time if provided. Providing this value is # optional but recommended. unless conversion_date_time.nil? ca.gclid_date_time_pair = client.resource.gclid_date_time_pair do |pair| pair.conversion_date_time = conversion_date_time.to_fs(:google_ads) end end # Creates a user identifier using sample values for the user address. ca.user_identifiers << client.resource.user_identifier do |ui| ui.address_info = client.resource.offline_user_address_info do |info| # Certain fields must be hashed using SHA256 in order to handle # identifiers in a privacy-safe way, as described at # https://support.google.com/google-ads/answer/9888656. info.hashed_first_name = normalize_and_hash('Joanna') info.hashed_last_name = normalize_and_hash('Smith') info.hashed_street_address = normalize_and_hash('1600 Amphitheatre Pkwy') info.city = 'Mountain View' info.state = 'CA' info.postal_code = '94043' info.country_code = 'US' end # Optional: Specifies the user identifier source. ui.user_identifier_source = :FIRST_PARTY end # Creates a user identifier using the hashed email address. ca.user_identifiers << client.resource.user_identifier do |ui| # Uses the normalize and hash method specifically for email addresses. ui.hashed_email = normalize_and_hash_email('dana@example.com') ui.user_identifier_source = :FIRST_PARTY end # Sets optional fields where a value was provided. unless user_agent.nil? # Sets the user agent. This should match the user agent of the request # that sent the original conversion so the conversion and its enhancement # are either both attributed as same-device or both attributed as # cross-device. ca.user_agent = user_agent end end response = client.service.conversion_adjustment_upload.upload_conversion_adjustments( customer_id: customer_id, conversion_adjustments: [enhancement], # Partial failure must be set to true. partial_failure: true ) if response.partial_failure_error puts "Partial failure encountered: #{response.partial_failure_error.}." else result = response.results.first puts "Uploaded conversion adjustment of #{result.conversion_action} for " \ "order ID #{result.order_id}." end end |
#upload_conversion_with_identifiers(customer_id:, conversion_action_id:, gclid:, gbraid:, wbraid:, email_address:, conversion_date_time:, conversion_value:, order_id:) ⇒ Object
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 575 def upload_conversion_with_identifiers( customer_id:, conversion_action_id:, gclid:, # "CjwKCAjwxr2iBhBJEiwAdXECwwhFa9nVWna4owzvkx8EXDv1HPwTQ14kFQT6rWNx4Z5R2D_PPDGYAxoCLwUQAvD_BwE" gbraid:, wbraid:, email_address:, conversion_date_time:, conversion_value:, order_id: ) # Offline conversions now upload via the Data Manager API events:ingest (the # Google Ads API uploadClickConversions path is being sunset). The conversion # action is the destination and the operating account comes from the # :google_data_manager credentials, so the legacy manager `customer_id` is # retained only for logging continuity. return { status: :missing_identifier, error: 'No gclid/gbraid/wbraid present' } if [gclid, gbraid, wbraid].compact.blank? hashed_email = (normalize_and_hash_email(email_address) if gclid.present? && email_address.present?) result = Invoicing::ConversionEventUploader.new.upload( conversion_action_id: conversion_action_id, conversion_date_time: conversion_date_time, conversion_value: conversion_value, gclid: gclid, gbraid: gbraid, wbraid: wbraid, hashed_email: hashed_email, order_id: order_id ) context = { customer_id: customer_id, conversion_action_id: conversion_action_id, gclid: gclid, gbraid: gbraid, wbraid: wbraid, email_address: (email_address.present? ? '[REDACTED]' : nil), conversion_date_time: conversion_date_time, conversion_value: conversion_value, order_id: order_id, result: result.to_h } if result.status == :reported logger.info "upload_conversion_with_identifiers reported (request #{result.request_id}) for order #{order_id}" ErrorReporting.info('GoogleConversionReporter::upload_conversion_with_identifiers: succeeded', context) elsif result.status == :failed_to_report logger.error "GoogleConversionReporter::upload_conversion_with_identifiers failed: #{result.error}" ErrorReporting.error("GoogleConversionReporter::upload_conversion_with_identifiers: #{result.error || 'failed'}", context) end # Adapt the typed Result to the legacy {status:} hash the callers expect. { status: result.status, request_id: result.request_id, error: result.error }.compact end |
#upload_offline_conversion(customer_id, conversion_action_id, gclid, gbraid, wbraid, conversion_date_time, conversion_value, conversion_custom_variable_id, conversion_custom_variable_value) ⇒ Object
DON'T USE
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 1005 def upload_offline_conversion( customer_id, # "2111091309" jake-text conversion_action_id, # "6499952095" c3c # 6509720835 prod CRM CO gclid, # "CjwKCAjwxr2iBhBJEiwAdXECwwhFa9nVWna4owzvkx8EXDv1HPwTQ14kFQT6rWNx4Z5R2D_PPDGYAxoCLwUQAvD_BwE" gbraid, wbraid, conversion_date_time, conversion_value, conversion_custom_variable_id, conversion_custom_variable_value ) client = get_client # # Verifies that exactly one of gclid, gbraid, and wbraid is specified, as required. # # See https://developers.google.com/google-ads/api/docs/conversions/upload-clicks for details. # identifiers_specified = [gclid, gbraid, wbraid].reject {|v| v.nil?}.count # if identifiers_specified != 1 # raise "Must specify exactly one of GCLID, GBRAID, and WBRAID. " \ # "#{identifiers_specified} values were provided." # end click_conversion = client.resource.click_conversion do |cc| cc.conversion_action = client.path.conversion_action(customer_id, conversion_action_id) # Sets the single specified ID field. if !gclid.nil? cc.gclid = gclid elsif !gbraid.nil? cc.gbraid = gbraid else cc.wbraid = wbraid end cc.conversion_value = conversion_value.to_f cc.conversion_date_time = conversion_date_time.to_fs(:google_ads) cc.currency_code = 'USD' if conversion_custom_variable_id && conversion_custom_variable_value cc.custom_variables << client.resource.custom_variable do |cv| cv.conversion_custom_variable = client.path.conversion_custom_variable( customer_id, conversion_custom_variable_id ) cv.value = conversion_custom_variable_value end end end response = client.service.conversion_upload.upload_click_conversions( customer_id: customer_id, conversions: [click_conversion], partial_failure: true ) if response.partial_failure_error.nil? result = response.results.first puts "Uploaded conversion that occurred at #{result.conversion_date_time} " \ "from Google Click ID #{result.gclid} to #{result.conversion_action}." else failures = client.decode_partial_failure_error(response.partial_failure_error) puts 'Request failed. Failure details:' failures.each do |failure| failure.errors.each do |error| puts "\t#{error.error_code.error_code}: #{error.}" end end end end |
#visit_click_identifier(visit, id_key) ⇒ Object
The gclid/gbraid/wbraid click identifiers moved from scalar Visit columns
into Visit#marketing_meta (JSONB) via the 2026-05-14 backfill and the #822
legacy_* rename, so Visit#gclid no longer exists — read them through the
marketing_meta_<key> accessor, matching Order#find_gclid's source. Without
this, find_visit_baseline matched on a dead reader, returned a nil click
date, and every order was skipped as skipped_unknown_click_date. Falls back
to a bare reader for Hash visits or any object still exposing it.
564 565 566 567 568 569 570 571 572 573 |
# File 'app/services/invoicing/google_conversion_reporter.rb', line 564 def visit_click_identifier(visit, id_key) if visit.is_a?(Hash) visit[id_key] || visit[id_key.to_s] else accessor = :"marketing_meta_#{id_key}" return visit.public_send(accessor) if visit.respond_to?(accessor) visit.public_send(id_key) if visit.respond_to?(id_key) end end |