Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsKit / Portfolio.swift

Raw 29.0 KB on 089159c793cd9cbff9078de2ee49995b60c6b768
1import Foundation
2
3/// the owner's portfolio as Graphley tracks it: every Protomota site, section, app, account, ad campaign and the
4/// notes that explain the numbers (docs/handoff.md). `setup_portfolio` applies it to a workspace; running it
5/// again only fills in and corrects, it never removes a site, app or history.
6public enum Portfolio {
7 static func url(_ s: String) -> URL? { URL(string: s) }
8
9 static let protomotaAliases = ["/services-home": "/services", "/experiments-home": "/experiments"]
10
11 /// Same order as the every-site table in the handoff.
12 public static let sites: [Site] = {
13 func site(_ id: String, _ name: String, _ url: String, _ property: String, _ measurement: String, color: Int,
14 consent: Bool, note: String, gsc: String? = nil, bing: String? = nil) -> Site {
15 var s = Site(id: id, name: name, url: URL(string: url), ga4PropertyID: property, colorIndex: color)
16 s.measurementID = measurement; s.consentGated = consent; s.trackingNote = note
17 // Not in Search Console or Bing yet (Glimmer, SkillFarm): "" leaves it out.
18 s.searchConsoleProperty = gsc ?? (url.hasSuffix("/") ? url : url + "/"); s.bingSiteURL = bing ?? (url.hasSuffix("/") ? url : url + "/")
19 if s.searchConsoleProperty == "" { s.searchConsoleProperty = nil }
20 if s.bingSiteURL == "" { s.bingSiteURL = nil }
21 return s
22 }
23 var protomota = site("protomota", "Protomota", "https://protomota.com", "516107059", "G-DRL62HKS7W", color: 0, consent: false,
24 note: "Not gated · App Store buttons for Jotley and PulseCanvas", gsc: "sc-domain:protomota.com", bing: "https://protomota.com/")
25 protomota.pageLimit = 100; protomota.pathAliases = protomotaAliases; protomota.funnelLandings = ["/ai-automation", "/custom-apps"]
26 var personal = site("personal-site-info", "Personal site", "https://www.personal-site.info", "000000000", "G-XXXXXXXXXX", color: 6, consent: false,
27 note: "Production only · no downloads · downloads tracked")
28 personal.funnelLandings = ["/"]
29 var services = Site(id: "protomota-services", name: "Protomota Services", url: URL(string: "https://protomota.com/services"),
30 ga4PropertyID: "516107059", colorIndex: 5)
31 services.parentID = "protomota"; services.pathPrefix = "/services"; services.legacyHost = "services.protomota.com"
32 services.pageLimit = 100; services.pathAliases = protomotaAliases; services.trackingNote = "Section of protomota.com · no downloads"
33 services.consentGated = false; services.searchConsoleProperty = "sc-domain:protomota.com"
34 var experiments = Site(id: "protomota-experiments", name: "Protomota Experiments", url: URL(string: "https://protomota.com/experiments"),
35 ga4PropertyID: "516107059", colorIndex: 3)
36 experiments.parentID = "protomota"; experiments.pathPrefix = "/experiments"; experiments.legacyHost = "experiments.protomota.com"
37 experiments.pageLimit = 100; experiments.pathAliases = protomotaAliases; experiments.trackingNote = "Section of protomota.com · no downloads"
38 experiments.consentGated = false; experiments.searchConsoleProperty = "sc-domain:protomota.com"
39 // Project ATOM (projectatom.ai) shares protomota.com's GA4 property and stream; it is matched by hostName.
40 // "/projectatom" is the page's internal route, never a protomota.com URL, so the host matches, and so does
41 // the "project-atom" content group its pages send.
42 var atom = Site(id: "project-atom", name: "Project ATOM", url: URL(string: "https://projectatom.ai"),
43 ga4PropertyID: "516107059", colorIndex: 2)
44 atom.parentID = "protomota"; atom.pathPrefix = "/projectatom"; atom.legacyHost = "projectatom.ai"; atom.contentGroup = "project-atom"
45 atom.pageLimit = 100; atom.trackingNote = "Own domain, same GA4 stream as protomota.com"
46 atom.consentGated = false
47 return [
48 protomota,
49 site("inkspring", "Inkspring", "https://inkspring.ai", "522488509", "G-7318RMX8CB", color: 1, consent: true,
50 note: "Opt-in since Nov 13 · Mac installer, download page"),
51 site("pulsecanvas", "PulseCanvas", "https://pulsecanvas.ai", "558418515", "G-ZEMC2FSDCG", color: 2, consent: true,
52 note: "Opt-in · Mac installer, App Store button, download page", gsc: "sc-domain:pulsecanvas.si", bing: "https://pulsecanvas.si/"),
53 site("jotley", "Jotley", "https://jotley.ai", "492461347", "G-S3X8ZERECS", color: 3, consent: true,
54 note: "Opt-in · Mac installer, App Store button, download page", gsc: "sc-domain:jotley.ai", bing: "https://jotley.ai/"),
55 site("airesourcepro", "AIResourcePro", "https://airesourcepro.com", "486378178", "G-2XSYEJNQBQ", color: 4, consent: true,
56 note: "Opt-in (Accept All) · no downloads"),
57 site("lumen-gesso", "Lumen & Gesso", "https://lumengesso.com", "539690681", "G-51NL8JKBN3", color: 5, consent: false,
58 note: "Not gated · no downloads · portrait builder funnel"),
59 personal,
60 site("textley", "Textley", "https://textley.ai", "564127557", "G-5RW12LV9B6", color: 0, consent: true,
61 note: "Opt-in · Mac installer, download page"),
62 site("opentalon", "OpenTalon", "https://opentalon.ai", "564126552", "G-6F8PWHNKYY", color: 1, consent: true,
63 note: "Opt-in · Mac installer, download page (App Store button once the app is out)"),
64 site("voxley", "Voxley", "https://voxley.si", "564118566", "G-HM6DMMWDN9", color: 2, consent: true,
65 note: "Opt-in · Mac installer, download page"),
66 site("glimmer", "Glimmer", "https://glimmertoday.ai", "565404653", "G-MMTF5S0X2L", color: 4, consent: true,
67 note: "Opt-in · Mac installer, download page", gsc: "", bing: ""),
68 site("skillfarm", "SkillFarm", "https://skillfarm.ai", "527940031", "G-LB5W3LD2QL", color: 5, consent: false,
69 note: "Not gated · page views only, no download or button events · not in Search Console or Bing yet", gsc: "", bing: ""),
70 site("graphley", "Graphley", "https://graphley.ai", "565768537", "G-5X9MHZPLGK", color: 6, consent: true,
71 note: "Opt-in since Nov 24 · Mac installer, download page"),
72 services, experiments, atom
73 ]
74 }()
75
76 public static let apps: [StoreApp] = {
77 func app(_ id: String, _ name: String, site: String, _ platforms: [String], desktop: String? = nil, onStore: Bool? = nil, note: String? = nil) -> StoreApp {
78 var a = StoreApp(id: id, name: name, siteID: site)
79 a.platforms = platforms; a.desktopCountsAs = desktop; a.onAppStore = onStore; a.note = note
80 return a
81 }
82 return [
83 app("6746770199", "Jotley: Live AI Transcription", site: "jotley", ["iPhone", "iPad", "Mac (website)"], desktop: "iPhone",
84 note: "No Mac App Store app: Apple's Desktop downloads (the iPhone app on an Apple Silicon Mac) count under iPhone. Renamed Nov 1 from “Jotley: Private AI Notes”, same Apple ID, one row."),
85 app("6821642700", "PulseCanvas Studio", site: "pulsecanvas", ["iPhone", "iPad", "Mac", "Vision Pro", "Mac (website)"], desktop: "Mac",
86 note: "One universal listing, on the App Store since Oct 25, plus the Creators Edition DMG from pulsecanvas.ai."),
87 app("6838869929", "Graphley", site: "graphley", ["Mac (website)", "iPhone"], onStore: false,
88 note: "Mac installer from graphley.ai; iPhone in TestFlight, not released."),
89 app("6833695057", "OpenTalon", site: "opentalon", ["Mac (website)"], onStore: false,
90 note: "Mac installer from opentalon.ai; the App Store app isn't live yet."),
91 app("mac-textley", "Textley", site: "textley", ["Mac (website)"]),
92 app("mac-voxley", "Voxley", site: "voxley", ["Mac (website)"]),
93 app("mac-inkspring", "Inkspring", site: "inkspring", ["Mac (website)"]),
94 app("mac-glimmer", "Glimmer", site: "glimmer", ["Mac (website)"])
95 ]
96 }()
97
98 public static let socials: [SocialAccount] = {
99 func account(_ id: String, _ platform: SocialAccount.Platform, _ handle: String, _ label: String, _ url: String, unit: String, source: String) -> SocialAccount {
100 var a = SocialAccount(id: id, platform: platform, handle: handle)
101 a.label = label; a.url = URL(string: url); a.unit = unit; a.source = source
102 return a
103 }
104 return [
105 account("substack", .substack, "Protomota Lab", "Newsletter (Substack)", "https://newsletter.protomota.com", unit: "subscribers", source: "manual"),
106 account("x", .x, "@ProtomotaLab", "X", "https://x.com/ProtomotaLab", unit: "followers", source: "api"),
107 account("instagram", .instagram, "@protomota", "Instagram", "https://instagram.com/protomota", unit: "followers", source: "api"),
108 account("linkedin", .linkedin, "the owner", "LinkedIn", "https://www.linkedin.com/in/personal-site", unit: "followers", source: "manual"),
109 account("linkedin_company", .linkedin, "Protomota Lab", "LinkedIn (company page)", "https://www.linkedin.com/company/protomota", unit: "followers", source: "manual"),
110 account("youtube_protomota", .youtube, "@protomota", "YouTube", "https://www.youtube.com/@protomota", unit: "subscribers", source: "api"),
111 account("youtube_airesourcepro", .youtube, "@airesourcepro", "YouTube", "https://www.youtube.com/@airesourcepro", unit: "subscribers", source: "api"),
112 account("github", .github, "protomota", "GitHub", "https://github.com/protomota", unit: "followers", source: "api")
113 ]
114 }()
115
116 /// Every campaign the owner ran, all stopped on 2026-11-22. Kept with their history; never suggested again.
117 public static let campaigns: [AdCampaign] = {
118 func c(_ id: String, _ platform: String, _ name: String, budget: String?, start: String, end: String?, paused: String? = nil, landing: String? = nil) -> AdCampaign {
119 var a = AdCampaign(id: id, platform: platform, name: name, status: "Expired")
120 a.budget = budget; a.start = start; a.end = end; a.paused = paused; a.expired = "2026-11-22"; a.landing = landing
121 return a
122 }
123 return [
124 c("apple-ads-tests", "Apple Ads", "Jotley and PulseCanvas tests (4 campaigns, rerun Nov 13)", budget: "$55/day max", start: "2026-11-04", end: "2026-11-25",
125 paused: "2026-11-11", landing: "App Store"),
126 c("linkedin-career-reel", "LinkedIn", "personal-site.info - career reel (video)", budget: "$50 total", start: "2026-11-11", end: "2026-11-15",
127 landing: "personal-site.info"),
128 c("linkedin-hire", "LinkedIn", "personal-site.info - hire", budget: "$100 total ($51.77 spent)", start: "2026-11-05", end: "2026-11-14",
129 paused: "2026-11-10", landing: "personal-site.info"),
130 c("google-hire-branded-custom", "Google Ads", "the owner - hire, Branded, Custom apps", budget: "$2.25, $1, $6/day", start: "2026-11-05",
131 end: nil, paused: "2026-11-07", landing: "personal-site.info, protomota.com/custom-apps"),
132 c("google-ai-automation", "Google Ads", "AI automation", budget: "$6.50/day, $12 max CPC", start: "2026-11-05", end: nil,
133 landing: "protomota.com/ai-automation")
134 ]
135 }()
136
137 static let undercounting = ["jotley", "pulsecanvas", "airesourcepro", "textley", "voxley", "opentalon", "inkspring", "glimmer", "graphley"]
138
139 public static let caveats: [Caveat] = [
140 Caveat(id: "consent", text: "Jotley, PulseCanvas, AIResourcePro, Textley, Voxley, OpenTalon, Inkspring, Glimmer and Graphley count only visitors who accept analytics, so their numbers undercount.", subjects: undercounting),
141 Caveat(id: "inkspring-gap", text: "Inkspring had no analytics from Oct 18 to Nov 13 (the relaunch shipped without it on purpose). Zeros then are a gap, not a drop.", subjects: ["inkspring"], from: "2026-10-18", to: "2026-11-13"),
142 Caveat(id: "test-clicks", text: "Nov 18: a full live test of every download link added about one click per app.", subjects: ["jotley", "pulsecanvas", "textley", "voxley", "opentalon", "inkspring", "glimmer"], from: "2026-11-18", to: "2026-11-18"),
143 Caveat(id: "sections", text: "Protomota Services and Protomota Experiments are sections of protomota.com (subdomains until Nov 1). Protomota counts the rest of the site; a visitor who sees both counts in both.", subjects: ["protomota", "protomota-services", "protomota-experiments"]),
144 Caveat(id: "project-atom", text: "Project ATOM (projectatom.ai) sends to the protomota.com GA4 property and is split out by host name. Protomota counts the rest; a visitor to both counts in both.", subjects: ["protomota", "project-atom"]),
145 Caveat(id: "jotley-app", text: "Jotley's rename (Nov 1) is merged into one row. Jotley for Mac comes only from the website installer; Apple's Desktop downloads are the iPhone app on a Mac.", subjects: ["6746770199", "jotley"]),
146 Caveat(id: "aiResourcePro-tag", text: "AIResourcePro's tag was half broken before Oct 31, so its early numbers are low.", subjects: ["airesourcepro"], to: "2026-10-31"),
147 Caveat(id: "partial-today", text: "Google Analytics numbers for today are partial, so every range ends yesterday.", subjects: []),
148 Caveat(id: "ads-expired", text: "All ads stopped on Nov 22. Every campaign is kept here with its history and marked Expired.", subjects: [])
149 ]
150
151 /// Applies the catalog: adds what's missing, fills empty fields, keeps the user's order, names and archives.
152 public static func apply(to ws: inout Workspace) {
153 for wanted in sites {
154 if let i = ws.sites.firstIndex(where: { $0.id == wanted.id || ($0.ga4PropertyID == wanted.ga4PropertyID && wanted.parentID == nil && $0.parentID == nil) }) {
155 var s = ws.sites[i]
156 s.url = s.url ?? wanted.url
157 s.measurementID = wanted.measurementID
158 s.parentID = wanted.parentID; s.pathPrefix = wanted.pathPrefix; s.legacyHost = wanted.legacyHost; s.contentGroup = wanted.contentGroup
159 s.pathAliases = wanted.pathAliases; s.pageLimit = wanted.pageLimit; s.funnelLandings = wanted.funnelLandings
160 s.trackingNote = wanted.trackingNote; s.consentGated = wanted.consentGated
161 s.searchConsoleProperty = wanted.searchConsoleProperty
162 s.bingSiteURL = wanted.bingSiteURL
163 ws.sites[i] = s
164 } else {
165 ws.sites.append(wanted)
166 }
167 }
168 // Keep the every-site order, sites added later included; anything else stays after them, in its own order.
169 let siteOrder = sites.map(\.id)
170 ws.sites = ws.sites.enumerated().sorted { a, b in
171 let (x, y) = (siteOrder.firstIndex(of: a.element.id) ?? siteOrder.count + a.offset, siteOrder.firstIndex(of: b.element.id) ?? siteOrder.count + b.offset)
172 return x < y
173 }.map(\.element)
174 for wanted in apps {
175 if let i = ws.apps.firstIndex(where: { $0.id == wanted.id }) {
176 var a = ws.apps[i]
177 a.siteID = a.siteID ?? wanted.siteID; a.platforms = wanted.platforms; a.desktopCountsAs = wanted.desktopCountsAs
178 a.onAppStore = wanted.onAppStore; a.note = wanted.note
179 ws.apps[i] = a
180 } else {
181 ws.apps.append(wanted)
182 }
183 }
184 for wanted in socials where !ws.socials.contains(where: { $0.id == wanted.id }) { ws.socials.append(wanted) }
185 for i in ws.socials.indices {
186 if let w = socials.first(where: { $0.id == ws.socials[i].id }) {
187 ws.socials[i].label = w.label; ws.socials[i].url = w.url; ws.socials[i].unit = w.unit; ws.socials[i].source = w.source
188 }
189 }
190 var campaignList = ws.campaigns ?? []
191 for wanted in campaigns {
192 if let i = campaignList.firstIndex(where: { $0.id == wanted.id }) { campaignList[i] = wanted } else { campaignList.append(wanted) }
193 }
194 ws.campaigns = campaignList
195 ws.caveats = caveats
196 for board in dashboards {
197 if let i = ws.dashboards.firstIndex(where: { $0.id == board.id }) { ws.dashboards[i] = board } else { ws.dashboards.append(board) }
198 }
199 // The old starter board is covered by Overview; keep it only if the user changed it.
200 ws.dashboards.removeAll { $0.id == Dashboard.starter.id && $0 == Dashboard.starter }
201 let order = dashboards.map(\.id)
202 ws.dashboards.sort { (order.firstIndex(of: $0.id) ?? 99) < (order.firstIndex(of: $1.id) ?? 99) }
203 }
204
205 // MARK: Dashboards
206
207 static func w(_ id: String, _ title: String, _ kind: Widget.Kind, _ metric: Metric = .users, days: Int = 30, subjects: [String] = [],
208 breakdown: String? = nil, event: String? = nil, wide: Bool = true, items: [String]? = nil, subtitle: String? = nil) -> Widget {
209 var widget = Widget(id: id, title: title, kind: kind, metric: metric, subjects: subjects, days: days, breakdown: breakdown, event: event)
210 widget.wide = wide; widget.items = items; widget.subtitle = subtitle
211 return widget
212 }
213
214 public static let dashboards: [Dashboard] = [
215 Dashboard(id: "overview", name: "Portfolio", widgets: [
216 w("kpis", "Last 30 days", .kpiRow, items: ["visitors", "appDownloads", "macInstaller", "appStoreButton", "followers"],
217 subtitle: "Each vs the 30 days before"),
218 w("visitors", "Visitors, all sites", .stackedArea, .users, subtitle: "Stacked by site"),
219 w("downloads", "App Store downloads", .stackedBars, .appDownloads, breakdown: "platform", wide: false, subtitle: "By platform"),
220 w("installer", "Mac installer downloads", .stackedBars, .keyEvent, event: "mac_installer_download", wide: false, subtitle: "Real .dmg downloads, by site"),
221 w("notes", "Read these numbers with", .notes)
222 ]),
223 Dashboard(id: "every-site", name: "Every site", widgets: [
224 w("scorecard", "Every site", .siteScorecard, subtitle: "Last 30 days vs the 30 before, with how each site is tracked"),
225 w("notes", "Notes", .notes)
226 ]),
227 Dashboard(id: "app-store", name: "App downloads", widgets: [
228 w("platforms", "Downloads by app and platform", .appPlatforms, .appDownloads, subtitle: "First downloads and redownloads, App Store Connect; Mac (website) is the installer from each app's site"),
229 w("per-day", "App Store downloads per day", .stackedBars, .appDownloads, breakdown: "platform", wide: false),
230 w("ratings", "Ratings and reviews", .ratings, .rating, wide: false, subtitle: "Every storefront"),
231 w("notes", "Notes", .notes, subjects: ["6746770199", "jotley"])
232 ]),
233 Dashboard(id: "downloads", name: "Website downloads", widgets: [
234 w("buttons", "Downloads by button", .downloadButtons, .keyEvent, subtitle: "Mac installer = the real .dmg download. Buttons are clicks, not downloads."),
235 w("source", "Source code", .downloadButtons, .keyEvent, items: ["source_click", "source_download"], subtitle: "Left out of download totals")
236 ]),
237 Dashboard(id: "traffic", name: "Pages and sources", widgets: [
238 w("ai", "Visits from AI assistants", .aiVisits, .sessions, days: 90, subtitle: "Sessions from ChatGPT, Perplexity, Claude, Gemini, Copilot and others"),
239 w("channels", "Channels", .breakdown, .sessions, breakdown: "channel", wide: false, subtitle: "Sessions by default channel group"),
240 w("sources", "Top sources", .breakdown, .sessions, breakdown: "source", wide: false, subtitle: "Top 10 source / medium per site"),
241 w("pages", "Top pages", .breakdown, .pageViews, breakdown: "page", subtitle: "Page views per site")
242 ]),
243 Dashboard(id: "site-detail", name: "Site detail", widgets: [
244 w("protomota", "Protomota", .siteDetail, subjects: ["protomota"], subtitle: "Clicks, sections, scroll, forms, video, calls and leads"),
245 w("personal", "Personal site", .siteDetail, subjects: ["personal-site-info"], subtitle: "Résumé downloads by format and click-outs by domain"),
246 w("lumen", "Lumen & Gesso", .siteDetail, subjects: ["lumen-gesso"], subtitle: "Portrait builder funnel"),
247 w("apps", "App sites", .siteDetail, subjects: ["jotley", "pulsecanvas", "inkspring", "textley", "voxley", "opentalon", "glimmer", "graphley", "airesourcepro"],
248 subtitle: "Shared tracker: clicks by section and destination, scroll, sections seen, video")
249 ]),
250 Dashboard(id: "search", name: "Search", widgets: [
251 w("search", "Google Search Console and Bing", .search, .searchClicks, days: 28, subtitle: "Clicks, impressions, CTR and position per site"),
252 w("queries", "Top queries", .breakdown, .searchClicks, days: 28, breakdown: "query", wide: false, subtitle: "Google, last 28 days"),
253 w("search-pages", "Top search pages", .breakdown, .searchClicks, days: 28, breakdown: "spage", wide: false, subtitle: "Google, last 28 days")
254 ]),
255 Dashboard(id: "followers", name: "Followers", widgets: [
256 w("accounts", "Newsletter and social followers", .followers, .followers, days: 90),
257 w("videos", "YouTube videos", .videos, .videoViews, days: 30, subtitle: "Newest five and top ten per channel")
258 ]),
259 Dashboard(id: "ads", name: "Paid ads", widgets: [
260 w("campaigns", "Campaigns", .ads, .adSpend, days: 90, subtitle: "All ads stopped Nov 22. History kept, every row Expired."),
261 w("funnel", "Landing page funnel", .funnel, .sessions, days: 90, subjects: ["protomota", "personal-site-info"], subtitle: "Paid and ad landing page sessions, CTA clicks, calls and leads")
262 ])
263 ]
264
265 // MARK: Event names
266
267 /// Download buttons per site, in table order. Clicks on a button that leads to a download page aren't downloads.
268 public static let downloadEvents = ["mac_installer_download", "download_click_mac", "app_store_click", "download_click_ios"]
269 public static let sourceEvents = ["source_click", "source_download"]
270
271 public static func eventTitle(_ event: String) -> String {
272 switch event {
273 case "mac_installer_download": "Mac installer download"
274 case "download_click_mac": "Download page button (download_click_mac)"
275 case "app_store_click": "App Store button (app_store_click)"
276 case "download_click_ios": "App Store button (download_click_ios)"
277 case "source_click": "Source code (source_click)"
278 case "source_download": "Source code (source_download)"
279 case "book_call": "Calls booked"
280 case "generate_lead": "Leads"
281 case "resume_download": "Résumé downloads"
282 case "resume_open": "Résumé opened"
283 case "outbound_click": "Click-outs"
284 case "section_view": "Sections seen"
285 case "scroll_depth": "Scroll depth"
286 case "builder_step": "Builder steps"
287 case "begin_checkout": "Checkout started"
288 case "cta_click": "Button clicks"
289 case "form_submitted": "Forms sent"
290 case "video_play": "Video plays"
291 default: event.replacingOccurrences(of: "_", with: " ").capitalizedFirst
292 }
293 }
294}
295
296extension String {
297 var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() }
298}
299
300// MARK: Migration and history import
301
302public extension Portfolio {
303 /// Brings older stored points up to date: App Store platforms named the way Graphley shows them (Desktop is
304 /// a Mac, or the iPhone for Jotley), and ratings as average + count instead of the 0.1 breakdowns.
305 static func migrate(_ points: inout [DataPoint], apps: [StoreApp]) {
306 let desktop = Dictionary(apps.map { ($0.id, $0.desktopCountsAs ?? "Mac") }, uniquingKeysWith: { a, _ in a })
307 var merged: [String: DataPoint] = [:]
308 var rest: [DataPoint] = []
309 for var p in points {
310 if p.metric == .rating, p.breakdown == "average" || p.breakdown == "count" {
311 if p.breakdown == "count" { p.metric = .ratingCount }
312 p.breakdown = nil
313 }
314 if [.appDownloads, .appRedownloads].contains(p.metric), p.family == "platform", let raw = p.breakdownValue {
315 p.breakdown = "platform:" + AppStoreConnect.platform(device: raw, desktopCountsAs: desktop[p.subject] ?? "Mac")
316 let key = "\(p.subject)|\(p.metric.rawValue)|\(p.day)|\(p.breakdown!)"
317 if var existing = merged[key] { existing.value += p.value; merged[key] = existing } else { merged[key] = p }
318 continue
319 }
320 rest.append(p)
321 }
322 points = rest + merged.values
323 }
324
325 /// Imports rows exported by the old pull (`~/.config/ga4-pull`). Returns how many rows were taken.
326 static func importHistory(kind: String, rows: [[String: Any]], store: WorkspaceStore, markSent: Bool = false) throws -> Int {
327 func str(_ r: [String: Any], _ k: String) -> String? { (r[k] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? (r[k] as? Int).map(String.init) }
328 func num(_ r: [String: Any], _ k: String) -> Double? { (r[k] as? Double) ?? (r[k] as? Int).map(Double.init) }
329 var points: [DataPoint] = []
330 switch kind {
331 case "followers":
332 for r in rows {
333 guard let account = str(r, "account"), let day = str(r, "day"), let count = num(r, "count") else { continue }
334 points.append(DataPoint(day: day, subject: account, metric: .followers, value: count))
335 }
336 case "videos":
337 var videos: [Video] = []
338 for r in rows {
339 guard let id = str(r, "video_id"), let account = str(r, "account"), let day = str(r, "day") else { continue }
340 videos.append(Video(id: id, account: account, title: str(r, "title") ?? id, kind: str(r, "kind") ?? "video",
341 published: str(r, "published"), url: str(r, "url") ?? "https://www.youtube.com/watch?v=\(id)"))
342 if let v = num(r, "views") { points.append(DataPoint(day: day, subject: id, metric: .videoViews, value: v)) }
343 if let l = num(r, "likes") { points.append(DataPoint(day: day, subject: id, metric: .videoLikes, value: l)) }
344 }
345 try store.update { ws in
346 var all = Dictionary((ws.videos ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
347 for v in videos {
348 var merged = all[v.id] ?? v
349 merged.title = v.title
350 merged.published = merged.published ?? v.published
351 if v.kind != "video" { merged.kind = v.kind }
352 all[v.id] = merged
353 }
354 ws.videos = all.values.sorted { ($0.published ?? "") > ($1.published ?? "") }
355 }
356 case "ads":
357 for r in rows {
358 guard let id = str(r, "campaign_id"), let day = str(r, "day") else { continue }
359 for (field, metric) in [("cost", Metric.adSpend), ("clicks", .adClicks), ("impressions", .adImpressions), ("conversions", .adConversions)] {
360 if let v = num(r, field) { points.append(DataPoint(day: day, subject: id, metric: metric, value: v)) }
361 }
362 }
363 case "ratings":
364 for r in rows {
365 guard let id = str(r, "apple_id"), let day = str(r, "day") else { continue }
366 points.append(DataPoint(day: day, subject: id, metric: .ratingCount, value: num(r, "count") ?? 0))
367 if let avg = num(r, "avg") { points.append(DataPoint(day: day, subject: id, metric: .rating, value: avg)) }
368 }
369 case "reviews":
370 let reviews = rows.compactMap { r -> Review? in
371 guard let id = str(r, "review_id"), let app = str(r, "apple_id") else { return nil }
372 return Review(id: id, appID: app, appName: str(r, "app") ?? app, country: str(r, "country") ?? "US", stars: Int(num(r, "stars") ?? 0),
373 title: str(r, "title") ?? "", text: str(r, "text") ?? "", version: str(r, "version") ?? "", author: str(r, "author") ?? "",
374 date: str(r, "date") ?? "", firstSeen: str(r, "first_seen") ?? str(r, "date") ?? "", url: str(r, "url") ?? "")
375 }
376 try store.update { ws in
377 var all = Dictionary((ws.reviews ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
378 for r in reviews where all[r.id] == nil { all[r.id] = r }
379 ws.reviews = all.values.sorted { $0.date > $1.date }
380 // The old pull already made these to-dos.
381 if markSent { ws.todoKeys = Array(Set((ws.todoKeys ?? []) + reviews.map { "appstore-review-\($0.appID)-\($0.id)" })) }
382 }
383 return reviews.count
384 default:
385 throw AnalyticsError.missing("Unknown kind \(kind).")
386 }
387 try store.merge(points)
388 return points.count
389 }
390}