Graphley / app · graphley.ai / Sources / AnalyticsKit / GA4Reports.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Everything Graphley pulls from GA4 for one site, the same reports as the old `ga4_pull.py`: |
| 4 | /// daily traffic, 30-day summaries, top pages, channels, top sources, visits from AI assistants, every |
| 5 | /// tracked event per day, detail breakdowns (clicks by section and destination, scroll, sections seen, |
| 6 | /// forms, video, files, builder steps, CTAs) and the paid landing-page funnel. |
| 7 | public struct GA4SiteView: Sendable { |
| 8 | public struct Section: Sendable, Hashable { |
| 9 | public var prefix: String; public var host: String?; public var contentGroup: String? = nil |
| 10 | } |
| 11 | public enum Scope: Sendable, Hashable { |
| 12 | case whole |
| 13 | /// A site that has sections reported on their own: everything except them (old pull's main view). |
| 14 | case excluding([Section]) |
| 15 | /// A section of a site: page path prefix OR its old host name OR its content group. |
| 16 | case only(Section) |
| 17 | } |
| 18 | public var site: Site |
| 19 | public var property: String |
| 20 | public var scope: Scope |
| 21 | public var isSection: Bool { if case .only = scope { true } else { false } } |
| 22 | |
| 23 | /// One view per tracked site, with the parent's sections taken out of the parent. |
| 24 | public static func views(for sites: [Site]) -> [GA4SiteView] { |
| 25 | let live = sites.filter { !$0.archived } |
| 26 | return live.compactMap { site in |
| 27 | if let parentID = site.parentID { |
| 28 | guard let parent = live.first(where: { $0.id == parentID }) ?? sites.first(where: { $0.id == parentID }), |
| 29 | let property = site.ga4PropertyID ?? parent.ga4PropertyID, let prefix = site.pathPrefix else { return nil } |
| 30 | return GA4SiteView(site: site, property: property, scope: .only(Section(prefix: prefix, host: site.legacyHost, contentGroup: site.contentGroup))) |
| 31 | } |
| 32 | guard let property = site.ga4PropertyID else { return nil } |
| 33 | let sections = live.filter { $0.parentID == site.id }.compactMap { s in s.pathPrefix.map { Section(prefix: $0, host: s.legacyHost, contentGroup: s.contentGroup) } } |
| 34 | return GA4SiteView(site: site, property: property, scope: sections.isEmpty ? .whole : .excluding(sections)) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | var filter: [String: Any]? { |
| 39 | func expr(_ s: Section) -> [String: Any] { |
| 40 | var parts: [[String: Any]] = [["filter": ["fieldName": "pagePath", "stringFilter": ["matchType": "BEGINS_WITH", "value": s.prefix]]]] |
| 41 | if let host = s.host { parts.append(["filter": ["fieldName": "hostName", "stringFilter": ["matchType": "EXACT", "value": host]]]) } |
| 42 | if let group = s.contentGroup { parts.append(["filter": ["fieldName": "contentGroup", "stringFilter": ["matchType": "EXACT", "value": group]]]) } |
| 43 | return ["orGroup": ["expressions": parts]] |
| 44 | } |
| 45 | switch scope { |
| 46 | case .whole: return nil |
| 47 | case .only(let s): return expr(s) |
| 48 | case .excluding(let list): return ["notExpression": ["orGroup": ["expressions": list.map(expr)]]] |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public extension GoogleAnalytics { |
| 54 | /// Every event the sites send that Graphley counts per day (downloads, buttons and detail tracking). |
| 55 | static let trackedEvents = [ |
| 56 | "mac_installer_download", "download_click_mac", "app_store_click", "download_click_ios", "source_click", "source_download", |
| 57 | "newsletter_click", "bug_report_click", "film_play_sound", "tutorial_play", "sign_in_click", "save_tutorial", "unsave_tutorial", |
| 58 | "roadmap_create", "roadmap_recalibrate", "book_call", "generate_lead", "resume_open", "resume_download", "email_click", |
| 59 | "outbound_click", "nav_click", "internal_click", "cta_click", "button_click", "product_site_click", "phone_click", |
| 60 | "file_download_click", "section_click", "text_copy", "scroll_depth", "section_view", "engaged_time", "form_started", |
| 61 | "form_submitted", "form_abandon", "form_start", "video_play", "video_start", "video_progress", "video_complete", |
| 62 | "askp_message", "builder_step", "begin_checkout", "app_feedback", "petition_signed", "petition_resigned", |
| 63 | "congress_message_copied" |
| 64 | ] |
| 65 | static let clickEvents = ["nav_click", "internal_click", "outbound_click", "app_store_click", "product_site_click", "email_click", |
| 66 | "phone_click", "file_download_click", "button_click", "section_click", "cta_click", "newsletter_click", |
| 67 | "resume_open", "resume_download", "source_click", "download_click_mac", "download_click_ios", "mac_installer_download"] |
| 68 | |
| 69 | /// AI assistants by source text (the old pull's AI_ASSISTANTS), first match wins. |
| 70 | static let aiAssistants: [(pattern: String, name: String)] = [ |
| 71 | ("chatgpt|openai", "ChatGPT"), ("perplexity", "Perplexity"), ("claude|anthropic", "Claude"), |
| 72 | ("gemini\\.google|bard\\.google", "Gemini"), ("copilot", "Copilot"), ("(^|\\.)grok\\.com|^x\\.ai$", "Grok"), |
| 73 | ("(^|\\.)meta\\.ai", "Meta AI"), ("deepseek", "DeepSeek"), ("mistral\\.ai", "Mistral"), ("(^|\\.)you\\.com", "You.com"), |
| 74 | ("phind", "Phind"), ("(^|\\.)poe\\.com", "Poe"), ("duck\\.ai", "Duck.ai"), ("kagi\\.com", "Kagi") |
| 75 | ] |
| 76 | static func aiAssistant(_ source: String) -> String { |
| 77 | aiAssistants.first { source.range(of: $0.pattern, options: [.regularExpression, .caseInsensitive]) != nil }?.name ?? "Other AI" |
| 78 | } |
| 79 | |
| 80 | static let paidSources = ["google / cpc": "google / cpc", "linkedin / paid-social": "linkedin / paid-social", "linkedin / paid_social": "linkedin / paid-social"] |
| 81 | static let funnelEvents = ["book_call", "generate_lead", "form_start", "scroll", "resume_download", "file_download", "outbound_click"] |
| 82 | |
| 83 | /// All reports for one site. `days` of daily history (180 so a 90-day range can compare with the 90 before). |
| 84 | func pull(_ view: GA4SiteView, days: Int = 180) async throws -> [DataPoint] { |
| 85 | let subject = view.site.id |
| 86 | let yesterday = DayKey.lastDays(1).last ?? DayKey.string(.now) |
| 87 | var out: [DataPoint] = [] |
| 88 | |
| 89 | // Daily traffic. |
| 90 | let metrics: [Metric] = [.users, .newUsers, .sessions, .pageViews, .engagedSessions] |
| 91 | for row in try await rows(view, ["date"], metrics.compactMap(\.ga4Name), start: "\(days)daysAgo") { |
| 92 | for (m, v) in zip(metrics, row.values) { out.append(DataPoint(day: Self.dayKey(row.dims[0]), subject: subject, metric: m, value: v)) } |
| 93 | } |
| 94 | |
| 95 | // Unique visitors over the last 30 days and the 30 before (what the old summary compared). |
| 96 | let summary = try await runReport(property: view.property, body: body(view, [], ["activeUsers", "newUsers", "sessions", "screenPageViews"], |
| 97 | ranges: [["startDate": "30daysAgo", "endDate": "yesterday", "name": "last_30"], ["startDate": "60daysAgo", "endDate": "31daysAgo", "name": "prev_30"]])) |
| 98 | for row in Self.table(summary) { |
| 99 | let period = row.dims.last ?? "" |
| 100 | for (m, v) in zip([Metric.users, .newUsers, .sessions, .pageViews], row.values) { |
| 101 | out.append(DataPoint(day: yesterday, subject: subject, metric: m, breakdown: "period:" + period, value: v)) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // Top pages, with paths that moved shown under their new path. |
| 106 | var pages: [String: Double] = [:] |
| 107 | for row in try await rows(view, ["pagePath"], ["screenPageViews"], start: "30daysAgo", order: "screenPageViews", limit: view.site.pageLimit ?? 10) { |
| 108 | let path = view.site.pathAliases?[row.dims[0]] ?? row.dims[0] |
| 109 | pages[path, default: 0] += row.values[0] |
| 110 | } |
| 111 | out += pages.map { DataPoint(day: yesterday, subject: subject, metric: .pageViews, breakdown: "page:" + $0.key, value: $0.value) } |
| 112 | |
| 113 | for row in try await rows(view, ["sessionDefaultChannelGroup"], ["sessions"], start: "30daysAgo", order: "sessions") { |
| 114 | out.append(DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "channel:" + row.dims[0], value: row.values[0])) |
| 115 | } |
| 116 | for row in try await rows(view, ["sessionSourceMedium"], ["sessions"], start: "30daysAgo", order: "sessions", limit: 10) { |
| 117 | out.append(DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "source:" + row.dims[0], value: row.values[0])) |
| 118 | } |
| 119 | |
| 120 | // Visits from AI assistants: GA4's AI Assistant channel plus sources GA4 hasn't classified yet. |
| 121 | let aiFilter: [String: Any] = ["orGroup": ["expressions": [ |
| 122 | ["filter": ["fieldName": "sessionDefaultChannelGroup", "stringFilter": ["matchType": "EXACT", "value": "AI Assistant"]]], |
| 123 | ["filter": ["fieldName": "sessionSource", "stringFilter": ["matchType": "PARTIAL_REGEXP", "value": Self.aiAssistants.map(\.pattern).joined(separator: "|"), "caseSensitive": false]]] |
| 124 | ]]] |
| 125 | var ai: [String: Double] = [:], aiLanding: [String: Double] = [:] |
| 126 | for row in try await rows(view, ["date", "sessionSource", "landingPage"], ["sessions"], start: "90daysAgo", filter: aiFilter) { |
| 127 | let name = Self.aiAssistant(row.dims[1]) |
| 128 | ai["\(Self.dayKey(row.dims[0]))|\(name)", default: 0] += row.values[0] |
| 129 | let landing = row.dims[2].components(separatedBy: "?").first.flatMap { $0.isEmpty ? "/" : $0 } ?? "/" |
| 130 | if Self.dayKey(row.dims[0]) >= (DayKey.lastDays(30).first ?? "") { aiLanding["\(name) → \(landing)", default: 0] += row.values[0] } |
| 131 | } |
| 132 | out += ai.map { key, v in |
| 133 | let p = key.components(separatedBy: "|") |
| 134 | return DataPoint(day: p[0], subject: subject, metric: .sessions, breakdown: "ai:" + p[1], value: v) |
| 135 | } |
| 136 | out += aiLanding.map { DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "ailanding:" + $0.key, value: $0.value) } |
| 137 | |
| 138 | // Every tracked event, per day. |
| 139 | let eventFilter: [String: Any] = ["filter": ["fieldName": "eventName", "inListFilter": ["values": Self.trackedEvents]]] |
| 140 | for row in try await rows(view, ["date", "eventName"], ["eventCount"], start: "\(days)daysAgo", filter: eventFilter) { |
| 141 | out.append(DataPoint(day: Self.dayKey(row.dims[0]), subject: subject, metric: .keyEvent, event: row.dims[1], value: row.values[0])) |
| 142 | } |
| 143 | |
| 144 | if !view.isSection { out += try await detail(view, day: yesterday) } |
| 145 | if let landings = view.site.funnelLandings, !landings.isEmpty { out += try await funnel(view, landings: landings) } |
| 146 | return out |
| 147 | } |
| 148 | |
| 149 | /// 30-day detail breakdowns. Custom dimensions are used only once registered on the property. |
| 150 | func detail(_ view: GA4SiteView, day: String) async throws -> [DataPoint] { |
| 151 | let have = try await dimensions(property: view.property) |
| 152 | func first(_ names: String...) -> String? { names.first(where: have.contains) } |
| 153 | func list(_ events: [String]) -> [String: Any] { ["filter": ["fieldName": "eventName", "inListFilter": ["values": events]]] } |
| 154 | let subject = view.site.id |
| 155 | var totals: [String: Double] = [:] // "event|family:value" |
| 156 | func add(_ dim: String?, family: String, events: [String], clean: (String) -> String = { $0 }) async throws { |
| 157 | guard let dim else { return } |
| 158 | // Per property, like the old pull: detail isn't split by section. |
| 159 | for row in try await rows(view, ["eventName", dim], ["eventCount"], start: "30daysAgo", limit: 2_000, filter: list(events), sectionFilter: false) { |
| 160 | let value = row.dims[1] |
| 161 | guard !value.isEmpty, value != "(not set)" else { continue } |
| 162 | totals["\(row.dims[0])|\(family):\(clean(value))", default: 0] += row.values[0] |
| 163 | } |
| 164 | } |
| 165 | let clicks = Self.clickEvents |
| 166 | try await add(first("customEvent:link_section", "contentId"), family: "section", events: clicks + ["section_view"].filter { _ in first("customEvent:section_id") == nil }) |
| 167 | if let sectionID = first("customEvent:section_id") { try await add(sectionID, family: "section", events: ["section_view"]) } |
| 168 | try await add("linkDomain", family: "domain", events: clicks) { $0.hasPrefix("www.") ? String($0.dropFirst(4)) : $0 } |
| 169 | try await add(first("customEvent:percent_scrolled", "percentScrolled"), family: "scroll", events: ["scroll_depth", "scroll"]) |
| 170 | try await add(first("customEvent:form_id"), family: "form", events: ["form_started", "form_submitted", "form_abandon", "form_start"]) |
| 171 | try await add(first("customEvent:last_field"), family: "field", events: ["form_abandon"]) |
| 172 | try await add("videoTitle", family: "video", events: ["video_play", "video_start", "video_progress", "video_complete"]) |
| 173 | try await add("fileName", family: "file", events: ["resume_download", "file_download_click", "mac_installer_download", "source_download"]) |
| 174 | try await add("contentId", family: "step", events: ["builder_step", "begin_checkout"]) |
| 175 | try await add(first("customEvent:cta"), family: "cta", events: ["cta_click"]) |
| 176 | return totals.map { key, v in |
| 177 | let p = key.split(separator: "|", maxSplits: 1).map(String.init) |
| 178 | return DataPoint(day: day, subject: subject, metric: .keyEvent, breakdown: p[1], event: p[0], value: v) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /// Paid-ad funnel per day per landing page per paid source: sessions, engaged sessions, funnel events and CTA |
| 183 | /// clicks split by their `cta` parameter (`book_call_open`, `lp_write_instead`). Ads are off, the funnel stays. |
| 184 | func funnel(_ view: GA4SiteView, landings: [String]) async throws -> [DataPoint] { |
| 185 | let subject = view.site.id |
| 186 | func key(_ dims: [String]) -> String? { |
| 187 | let source = Self.paidSources[dims[2]] ?? "other" |
| 188 | guard source != "other" || landings.contains(dims[1]) else { return nil } |
| 189 | return "\(Self.dayKey(dims[0]))|funnel:\(dims[1])|\(source)" |
| 190 | } |
| 191 | var out: [DataPoint] = [] |
| 192 | var sums: [String: [Double]] = [:] |
| 193 | for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium"], ["sessions", "engagedSessions"], start: "90daysAgo", sectionFilter: false) { |
| 194 | guard let k = key(row.dims) else { continue } |
| 195 | sums[k] = zip(sums[k] ?? [0, 0], row.values).map(+) |
| 196 | } |
| 197 | for (k, v) in sums { |
| 198 | let p = k.components(separatedBy: "|"), b = p[1] + "|" + p[2] |
| 199 | out.append(DataPoint(day: p[0], subject: subject, metric: .sessions, breakdown: b, value: v[0])) |
| 200 | out.append(DataPoint(day: p[0], subject: subject, metric: .engagedSessions, breakdown: b, value: v[1])) |
| 201 | } |
| 202 | var events: [String: Double] = [:] |
| 203 | let filter: [String: Any] = ["filter": ["fieldName": "eventName", "inListFilter": ["values": Self.funnelEvents]]] |
| 204 | for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium", "eventName"], ["eventCount"], start: "90daysAgo", filter: filter, sectionFilter: false) { |
| 205 | guard let k = key(row.dims) else { continue } |
| 206 | events[k + "|" + row.dims[3], default: 0] += row.values[0] |
| 207 | } |
| 208 | if try await dimensions(property: view.property).contains("customEvent:cta") { |
| 209 | let cta: [String: Any] = ["filter": ["fieldName": "eventName", "stringFilter": ["value": "cta_click"]]] |
| 210 | for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium", "customEvent:cta"], ["eventCount"], start: "90daysAgo", filter: cta, sectionFilter: false) { |
| 211 | guard let k = key(row.dims) else { continue } |
| 212 | let name = ["book_call_open", "lp_write_instead"].contains(row.dims[3]) ? row.dims[3] : "other_cta" |
| 213 | events[k + "|cta:" + name, default: 0] += row.values[0] |
| 214 | } |
| 215 | } |
| 216 | for (k, v) in events { |
| 217 | let p = k.components(separatedBy: "|") |
| 218 | out.append(DataPoint(day: p[0], subject: subject, metric: .keyEvent, breakdown: p[1] + "|" + p[2], event: p[3], value: v)) |
| 219 | } |
| 220 | return out |
| 221 | } |
| 222 | |
| 223 | // MARK: Plumbing |
| 224 | |
| 225 | struct Row { var dims: [String]; var values: [Double] } |
| 226 | |
| 227 | func rows(_ view: GA4SiteView, _ dims: [String], _ metrics: [String], start: String, order: String? = nil, limit: Int? = nil, |
| 228 | filter: [String: Any]? = nil, sectionFilter: Bool = true) async throws -> [Row] { |
| 229 | var b = body(view, dims, metrics, ranges: [["startDate": start, "endDate": "yesterday"]], filter: filter, sectionFilter: sectionFilter) |
| 230 | if let order { b["orderBys"] = [["metric": ["metricName": order], "desc": true]] } |
| 231 | b["limit"] = limit ?? 25_000 |
| 232 | return Self.table(try await runReport(property: view.property, body: b)) |
| 233 | } |
| 234 | |
| 235 | func body(_ view: GA4SiteView, _ dims: [String], _ metrics: [String], ranges: [[String: String]], filter: [String: Any]? = nil, |
| 236 | sectionFilter: Bool = true) -> [String: Any] { |
| 237 | var b: [String: Any] = ["dateRanges": ranges, "dimensions": dims.map { ["name": $0] }, "metrics": metrics.map { ["name": $0] }] |
| 238 | let parts = [filter, sectionFilter ? view.filter : nil].compactMap { $0 } |
| 239 | if parts.count == 1 { b["dimensionFilter"] = parts[0] } |
| 240 | else if parts.count == 2 { b["dimensionFilter"] = ["andGroup": ["expressions": parts]] } |
| 241 | return b |
| 242 | } |
| 243 | |
| 244 | static func table(_ json: [String: Any]) -> [Row] { |
| 245 | (json["rows"] as? [[String: Any]] ?? []).map { Row(dims: dims($0), values: mets($0)) } |
| 246 | } |
| 247 | |
| 248 | /// API names of the dimensions a property can report (custom dimensions appear once registered). |
| 249 | func dimensions(property: String) async throws -> Set<String> { |
| 250 | let token = try await auth.accessToken() |
| 251 | var r = URLRequest(url: URL(string: "https://analyticsdata.googleapis.com/v1beta/properties/\(property)/metadata")!) |
| 252 | r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") |
| 253 | let json = try await session.json(r, retries: 3) |
| 254 | return Set((json["dimensions"] as? [[String: Any]] ?? []).compactMap { $0["apiName"] as? String }) |
| 255 | } |
| 256 | |
| 257 | /// Web stream measurement IDs and URLs of a property ("G-DRL62HKS7W"), to match sites the way the old pull did. |
| 258 | func streams(property: String) async throws -> [(measurementID: String, url: String)] { |
| 259 | let token = try await auth.accessToken() |
| 260 | var r = URLRequest(url: URL(string: "https://analyticsadmin.googleapis.com/v1beta/properties/\(property)/dataStreams")!) |
| 261 | r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") |
| 262 | let json = try await session.json(r, retries: 2) |
| 263 | return (json["dataStreams"] as? [[String: Any]] ?? []).compactMap { s in |
| 264 | guard let web = s["webStreamData"] as? [String: Any], let id = web["measurementId"] as? String else { return nil } |
| 265 | return (id, web["defaultUri"] as? String ?? "") |
| 266 | } |
| 267 | } |
| 268 | } |