Class: Seo::Ga4SyncService

Inherits:
BaseService show all
Defined in:
app/services/seo/ga4_sync_service.rb

Overview

Syncs engagement data from Google Analytics 4 to site_map_data_points.
Creates time-series records with explicit date ranges.

GA4 provides engagement metrics that complement Search Console and Ahrefs data:

  • Search Console: How pages perform in search results (before click)
  • GA4: How users engage with pages (after click)
  • Ahrefs: External SEO metrics (backlinks, keyword rankings)

Examples:

Basic usage (last 30 days)

Seo::Ga4SyncService.new.process

Custom date range

Seo::Ga4SyncService.new(
  start_date: 90.days.ago.to_date,
  end_date: Date.yesterday
).process

Constant Summary collapse

DEFAULT_DATE_RANGE =

days

30

Instance Method Summary collapse

Methods inherited from BaseService

#log_debug, #log_error, #log_info, #log_warning, #logger, #options, #tagged_logger

Constructor Details

#initialize(options = {}) ⇒ Ga4SyncService

Returns a new instance of Ga4SyncService.



24
25
26
27
28
29
30
# File 'app/services/seo/ga4_sync_service.rb', line 24

def initialize(options = {})
  super
  @start_date = options[:start_date] || DEFAULT_DATE_RANGE.days.ago.to_date
  @end_date = options[:end_date] || Date.yesterday
  @batch_id = SecureRandom.uuid
  @stats = { pages_updated: 0, pages_skipped: 0, errors: [] }
end

Instance Method Details

#processObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/services/seo/ga4_sync_service.rb', line 32

def process
  @logger.info "[Ga4SyncService] Starting sync for #{@start_date} to #{@end_date}"

  unless ga4_configured?
    @logger.warn '[Ga4SyncService] GA4 not configured, skipping sync'
    return @stats
  end

  # Fetch all pages data from GA4
  pages_data = fetch_all_pages
  return @stats if pages_data.blank?

  @logger.info "[Ga4SyncService] Fetched #{pages_data.size} pages from GA4"

  # Match GA4 page paths to SiteMap records and create data points
  process_pages(pages_data)

  @logger.info "[Ga4SyncService] Completed: #{@stats[:pages_updated]} updated, #{@stats[:pages_skipped]} skipped"
  @stats
end