import Foundation /// Everything Graphley pulls from GA4 for one site, the same reports as the old `ga4_pull.py`: /// daily traffic, 30-day summaries, top pages, channels, top sources, visits from AI assistants, every /// tracked event per day, detail breakdowns (clicks by section and destination, scroll, sections seen, /// forms, video, files, builder steps, CTAs) and the paid landing-page funnel. public struct GA4SiteView: Sendable { public struct Section: Sendable, Hashable { public var prefix: String; public var host: String?; public var contentGroup: String? = nil } public enum Scope: Sendable, Hashable { case whole /// A site that has sections reported on their own: everything except them (old pull's main view). case excluding([Section]) /// A section of a site: page path prefix OR its old host name OR its content group. case only(Section) } public var site: Site public var property: String public var scope: Scope public var isSection: Bool { if case .only = scope { true } else { false } } /// One view per tracked site, with the parent's sections taken out of the parent. public static func views(for sites: [Site]) -> [GA4SiteView] { let live = sites.filter { !$0.archived } return live.compactMap { site in if let parentID = site.parentID { guard let parent = live.first(where: { $0.id == parentID }) ?? sites.first(where: { $0.id == parentID }), let property = site.ga4PropertyID ?? parent.ga4PropertyID, let prefix = site.pathPrefix else { return nil } return GA4SiteView(site: site, property: property, scope: .only(Section(prefix: prefix, host: site.legacyHost, contentGroup: site.contentGroup))) } guard let property = site.ga4PropertyID else { return nil } let sections = live.filter { $0.parentID == site.id }.compactMap { s in s.pathPrefix.map { Section(prefix: $0, host: s.legacyHost, contentGroup: s.contentGroup) } } return GA4SiteView(site: site, property: property, scope: sections.isEmpty ? .whole : .excluding(sections)) } } var filter: [String: Any]? { func expr(_ s: Section) -> [String: Any] { var parts: [[String: Any]] = [["filter": ["fieldName": "pagePath", "stringFilter": ["matchType": "BEGINS_WITH", "value": s.prefix]]]] if let host = s.host { parts.append(["filter": ["fieldName": "hostName", "stringFilter": ["matchType": "EXACT", "value": host]]]) } if let group = s.contentGroup { parts.append(["filter": ["fieldName": "contentGroup", "stringFilter": ["matchType": "EXACT", "value": group]]]) } return ["orGroup": ["expressions": parts]] } switch scope { case .whole: return nil case .only(let s): return expr(s) case .excluding(let list): return ["notExpression": ["orGroup": ["expressions": list.map(expr)]]] } } } public extension GoogleAnalytics { /// Every event the sites send that Graphley counts per day (downloads, buttons and detail tracking). static let trackedEvents = [ "mac_installer_download", "download_click_mac", "app_store_click", "download_click_ios", "source_click", "source_download", "newsletter_click", "bug_report_click", "film_play_sound", "tutorial_play", "sign_in_click", "save_tutorial", "unsave_tutorial", "roadmap_create", "roadmap_recalibrate", "book_call", "generate_lead", "resume_open", "resume_download", "email_click", "outbound_click", "nav_click", "internal_click", "cta_click", "button_click", "product_site_click", "phone_click", "file_download_click", "section_click", "text_copy", "scroll_depth", "section_view", "engaged_time", "form_started", "form_submitted", "form_abandon", "form_start", "video_play", "video_start", "video_progress", "video_complete", "askp_message", "builder_step", "begin_checkout", "app_feedback", "petition_signed", "petition_resigned", "congress_message_copied" ] static let clickEvents = ["nav_click", "internal_click", "outbound_click", "app_store_click", "product_site_click", "email_click", "phone_click", "file_download_click", "button_click", "section_click", "cta_click", "newsletter_click", "resume_open", "resume_download", "source_click", "download_click_mac", "download_click_ios", "mac_installer_download"] /// AI assistants by source text (the old pull's AI_ASSISTANTS), first match wins. static let aiAssistants: [(pattern: String, name: String)] = [ ("chatgpt|openai", "ChatGPT"), ("perplexity", "Perplexity"), ("claude|anthropic", "Claude"), ("gemini\\.google|bard\\.google", "Gemini"), ("copilot", "Copilot"), ("(^|\\.)grok\\.com|^x\\.ai$", "Grok"), ("(^|\\.)meta\\.ai", "Meta AI"), ("deepseek", "DeepSeek"), ("mistral\\.ai", "Mistral"), ("(^|\\.)you\\.com", "You.com"), ("phind", "Phind"), ("(^|\\.)poe\\.com", "Poe"), ("duck\\.ai", "Duck.ai"), ("kagi\\.com", "Kagi") ] static func aiAssistant(_ source: String) -> String { aiAssistants.first { source.range(of: $0.pattern, options: [.regularExpression, .caseInsensitive]) != nil }?.name ?? "Other AI" } static let paidSources = ["google / cpc": "google / cpc", "linkedin / paid-social": "linkedin / paid-social", "linkedin / paid_social": "linkedin / paid-social"] static let funnelEvents = ["book_call", "generate_lead", "form_start", "scroll", "resume_download", "file_download", "outbound_click"] /// All reports for one site. `days` of daily history (180 so a 90-day range can compare with the 90 before). func pull(_ view: GA4SiteView, days: Int = 180) async throws -> [DataPoint] { let subject = view.site.id let yesterday = DayKey.lastDays(1).last ?? DayKey.string(.now) var out: [DataPoint] = [] // Daily traffic. let metrics: [Metric] = [.users, .newUsers, .sessions, .pageViews, .engagedSessions] for row in try await rows(view, ["date"], metrics.compactMap(\.ga4Name), start: "\(days)daysAgo") { for (m, v) in zip(metrics, row.values) { out.append(DataPoint(day: Self.dayKey(row.dims[0]), subject: subject, metric: m, value: v)) } } // Unique visitors over the last 30 days and the 30 before (what the old summary compared). let summary = try await runReport(property: view.property, body: body(view, [], ["activeUsers", "newUsers", "sessions", "screenPageViews"], ranges: [["startDate": "30daysAgo", "endDate": "yesterday", "name": "last_30"], ["startDate": "60daysAgo", "endDate": "31daysAgo", "name": "prev_30"]])) for row in Self.table(summary) { let period = row.dims.last ?? "" for (m, v) in zip([Metric.users, .newUsers, .sessions, .pageViews], row.values) { out.append(DataPoint(day: yesterday, subject: subject, metric: m, breakdown: "period:" + period, value: v)) } } // Top pages, with paths that moved shown under their new path. var pages: [String: Double] = [:] for row in try await rows(view, ["pagePath"], ["screenPageViews"], start: "30daysAgo", order: "screenPageViews", limit: view.site.pageLimit ?? 10) { let path = view.site.pathAliases?[row.dims[0]] ?? row.dims[0] pages[path, default: 0] += row.values[0] } out += pages.map { DataPoint(day: yesterday, subject: subject, metric: .pageViews, breakdown: "page:" + $0.key, value: $0.value) } for row in try await rows(view, ["sessionDefaultChannelGroup"], ["sessions"], start: "30daysAgo", order: "sessions") { out.append(DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "channel:" + row.dims[0], value: row.values[0])) } for row in try await rows(view, ["sessionSourceMedium"], ["sessions"], start: "30daysAgo", order: "sessions", limit: 10) { out.append(DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "source:" + row.dims[0], value: row.values[0])) } // Visits from AI assistants: GA4's AI Assistant channel plus sources GA4 hasn't classified yet. let aiFilter: [String: Any] = ["orGroup": ["expressions": [ ["filter": ["fieldName": "sessionDefaultChannelGroup", "stringFilter": ["matchType": "EXACT", "value": "AI Assistant"]]], ["filter": ["fieldName": "sessionSource", "stringFilter": ["matchType": "PARTIAL_REGEXP", "value": Self.aiAssistants.map(\.pattern).joined(separator: "|"), "caseSensitive": false]]] ]]] var ai: [String: Double] = [:], aiLanding: [String: Double] = [:] for row in try await rows(view, ["date", "sessionSource", "landingPage"], ["sessions"], start: "90daysAgo", filter: aiFilter) { let name = Self.aiAssistant(row.dims[1]) ai["\(Self.dayKey(row.dims[0]))|\(name)", default: 0] += row.values[0] let landing = row.dims[2].components(separatedBy: "?").first.flatMap { $0.isEmpty ? "/" : $0 } ?? "/" if Self.dayKey(row.dims[0]) >= (DayKey.lastDays(30).first ?? "") { aiLanding["\(name) → \(landing)", default: 0] += row.values[0] } } out += ai.map { key, v in let p = key.components(separatedBy: "|") return DataPoint(day: p[0], subject: subject, metric: .sessions, breakdown: "ai:" + p[1], value: v) } out += aiLanding.map { DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "ailanding:" + $0.key, value: $0.value) } // Every tracked event, per day. let eventFilter: [String: Any] = ["filter": ["fieldName": "eventName", "inListFilter": ["values": Self.trackedEvents]]] for row in try await rows(view, ["date", "eventName"], ["eventCount"], start: "\(days)daysAgo", filter: eventFilter) { out.append(DataPoint(day: Self.dayKey(row.dims[0]), subject: subject, metric: .keyEvent, event: row.dims[1], value: row.values[0])) } if !view.isSection { out += try await detail(view, day: yesterday) } if let landings = view.site.funnelLandings, !landings.isEmpty { out += try await funnel(view, landings: landings) } return out } /// 30-day detail breakdowns. Custom dimensions are used only once registered on the property. func detail(_ view: GA4SiteView, day: String) async throws -> [DataPoint] { let have = try await dimensions(property: view.property) func first(_ names: String...) -> String? { names.first(where: have.contains) } func list(_ events: [String]) -> [String: Any] { ["filter": ["fieldName": "eventName", "inListFilter": ["values": events]]] } let subject = view.site.id var totals: [String: Double] = [:] // "event|family:value" func add(_ dim: String?, family: String, events: [String], clean: (String) -> String = { $0 }) async throws { guard let dim else { return } // Per property, like the old pull: detail isn't split by section. for row in try await rows(view, ["eventName", dim], ["eventCount"], start: "30daysAgo", limit: 2_000, filter: list(events), sectionFilter: false) { let value = row.dims[1] guard !value.isEmpty, value != "(not set)" else { continue } totals["\(row.dims[0])|\(family):\(clean(value))", default: 0] += row.values[0] } } let clicks = Self.clickEvents try await add(first("customEvent:link_section", "contentId"), family: "section", events: clicks + ["section_view"].filter { _ in first("customEvent:section_id") == nil }) if let sectionID = first("customEvent:section_id") { try await add(sectionID, family: "section", events: ["section_view"]) } try await add("linkDomain", family: "domain", events: clicks) { $0.hasPrefix("www.") ? String($0.dropFirst(4)) : $0 } try await add(first("customEvent:percent_scrolled", "percentScrolled"), family: "scroll", events: ["scroll_depth", "scroll"]) try await add(first("customEvent:form_id"), family: "form", events: ["form_started", "form_submitted", "form_abandon", "form_start"]) try await add(first("customEvent:last_field"), family: "field", events: ["form_abandon"]) try await add("videoTitle", family: "video", events: ["video_play", "video_start", "video_progress", "video_complete"]) try await add("fileName", family: "file", events: ["resume_download", "file_download_click", "mac_installer_download", "source_download"]) try await add("contentId", family: "step", events: ["builder_step", "begin_checkout"]) try await add(first("customEvent:cta"), family: "cta", events: ["cta_click"]) return totals.map { key, v in let p = key.split(separator: "|", maxSplits: 1).map(String.init) return DataPoint(day: day, subject: subject, metric: .keyEvent, breakdown: p[1], event: p[0], value: v) } } /// Paid-ad funnel per day per landing page per paid source: sessions, engaged sessions, funnel events and CTA /// clicks split by their `cta` parameter (`book_call_open`, `lp_write_instead`). Ads are off, the funnel stays. func funnel(_ view: GA4SiteView, landings: [String]) async throws -> [DataPoint] { let subject = view.site.id func key(_ dims: [String]) -> String? { let source = Self.paidSources[dims[2]] ?? "other" guard source != "other" || landings.contains(dims[1]) else { return nil } return "\(Self.dayKey(dims[0]))|funnel:\(dims[1])|\(source)" } var out: [DataPoint] = [] var sums: [String: [Double]] = [:] for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium"], ["sessions", "engagedSessions"], start: "90daysAgo", sectionFilter: false) { guard let k = key(row.dims) else { continue } sums[k] = zip(sums[k] ?? [0, 0], row.values).map(+) } for (k, v) in sums { let p = k.components(separatedBy: "|"), b = p[1] + "|" + p[2] out.append(DataPoint(day: p[0], subject: subject, metric: .sessions, breakdown: b, value: v[0])) out.append(DataPoint(day: p[0], subject: subject, metric: .engagedSessions, breakdown: b, value: v[1])) } var events: [String: Double] = [:] let filter: [String: Any] = ["filter": ["fieldName": "eventName", "inListFilter": ["values": Self.funnelEvents]]] for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium", "eventName"], ["eventCount"], start: "90daysAgo", filter: filter, sectionFilter: false) { guard let k = key(row.dims) else { continue } events[k + "|" + row.dims[3], default: 0] += row.values[0] } if try await dimensions(property: view.property).contains("customEvent:cta") { let cta: [String: Any] = ["filter": ["fieldName": "eventName", "stringFilter": ["value": "cta_click"]]] for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium", "customEvent:cta"], ["eventCount"], start: "90daysAgo", filter: cta, sectionFilter: false) { guard let k = key(row.dims) else { continue } let name = ["book_call_open", "lp_write_instead"].contains(row.dims[3]) ? row.dims[3] : "other_cta" events[k + "|cta:" + name, default: 0] += row.values[0] } } for (k, v) in events { let p = k.components(separatedBy: "|") out.append(DataPoint(day: p[0], subject: subject, metric: .keyEvent, breakdown: p[1] + "|" + p[2], event: p[3], value: v)) } return out } // MARK: Plumbing struct Row { var dims: [String]; var values: [Double] } func rows(_ view: GA4SiteView, _ dims: [String], _ metrics: [String], start: String, order: String? = nil, limit: Int? = nil, filter: [String: Any]? = nil, sectionFilter: Bool = true) async throws -> [Row] { var b = body(view, dims, metrics, ranges: [["startDate": start, "endDate": "yesterday"]], filter: filter, sectionFilter: sectionFilter) if let order { b["orderBys"] = [["metric": ["metricName": order], "desc": true]] } b["limit"] = limit ?? 25_000 return Self.table(try await runReport(property: view.property, body: b)) } func body(_ view: GA4SiteView, _ dims: [String], _ metrics: [String], ranges: [[String: String]], filter: [String: Any]? = nil, sectionFilter: Bool = true) -> [String: Any] { var b: [String: Any] = ["dateRanges": ranges, "dimensions": dims.map { ["name": $0] }, "metrics": metrics.map { ["name": $0] }] let parts = [filter, sectionFilter ? view.filter : nil].compactMap { $0 } if parts.count == 1 { b["dimensionFilter"] = parts[0] } else if parts.count == 2 { b["dimensionFilter"] = ["andGroup": ["expressions": parts]] } return b } static func table(_ json: [String: Any]) -> [Row] { (json["rows"] as? [[String: Any]] ?? []).map { Row(dims: dims($0), values: mets($0)) } } /// API names of the dimensions a property can report (custom dimensions appear once registered). func dimensions(property: String) async throws -> Set { let token = try await auth.accessToken() var r = URLRequest(url: URL(string: "https://analyticsdata.googleapis.com/v1beta/properties/\(property)/metadata")!) r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let json = try await session.json(r, retries: 3) return Set((json["dimensions"] as? [[String: Any]] ?? []).compactMap { $0["apiName"] as? String }) } /// Web stream measurement IDs and URLs of a property ("G-DRL62HKS7W"), to match sites the way the old pull did. func streams(property: String) async throws -> [(measurementID: String, url: String)] { let token = try await auth.accessToken() var r = URLRequest(url: URL(string: "https://analyticsadmin.googleapis.com/v1beta/properties/\(property)/dataStreams")!) r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let json = try await session.json(r, retries: 2) return (json["dataStreams"] as? [[String: Any]] ?? []).compactMap { s in guard let web = s["webStreamData"] as? [String: Any], let id = web["measurementId"] as? String else { return nil } return (id, web["defaultUri"] as? String ?? "") } } }