import Foundation /// the owner's portfolio as Graphley tracks it: every Protomota site, section, app, account, ad campaign and the /// notes that explain the numbers (docs/handoff.md). `setup_portfolio` applies it to a workspace; running it /// again only fills in and corrects, it never removes a site, app or history. public enum Portfolio { static func url(_ s: String) -> URL? { URL(string: s) } static let protomotaAliases = ["/services-home": "/services", "/experiments-home": "/experiments"] /// Same order as the every-site table in the handoff. public static let sites: [Site] = { func site(_ id: String, _ name: String, _ url: String, _ property: String, _ measurement: String, color: Int, consent: Bool, note: String, gsc: String? = nil, bing: String? = nil) -> Site { var s = Site(id: id, name: name, url: URL(string: url), ga4PropertyID: property, colorIndex: color) s.measurementID = measurement; s.consentGated = consent; s.trackingNote = note // Not in Search Console or Bing yet (Glimmer, SkillFarm): "" leaves it out. s.searchConsoleProperty = gsc ?? (url.hasSuffix("/") ? url : url + "/"); s.bingSiteURL = bing ?? (url.hasSuffix("/") ? url : url + "/") if s.searchConsoleProperty == "" { s.searchConsoleProperty = nil } if s.bingSiteURL == "" { s.bingSiteURL = nil } return s } var protomota = site("protomota", "Protomota", "https://protomota.com", "516107059", "G-DRL62HKS7W", color: 0, consent: false, note: "Not gated · App Store buttons for Jotley and PulseCanvas", gsc: "sc-domain:protomota.com", bing: "https://protomota.com/") protomota.pageLimit = 100; protomota.pathAliases = protomotaAliases; protomota.funnelLandings = ["/ai-automation", "/custom-apps"] var personal = site("personal-site-info", "Personal site", "https://www.personal-site.info", "000000000", "G-XXXXXXXXXX", color: 6, consent: false, note: "Production only · no downloads · downloads tracked") personal.funnelLandings = ["/"] var services = Site(id: "protomota-services", name: "Protomota Services", url: URL(string: "https://protomota.com/services"), ga4PropertyID: "516107059", colorIndex: 5) services.parentID = "protomota"; services.pathPrefix = "/services"; services.legacyHost = "services.protomota.com" services.pageLimit = 100; services.pathAliases = protomotaAliases; services.trackingNote = "Section of protomota.com · no downloads" services.consentGated = false; services.searchConsoleProperty = "sc-domain:protomota.com" var experiments = Site(id: "protomota-experiments", name: "Protomota Experiments", url: URL(string: "https://protomota.com/experiments"), ga4PropertyID: "516107059", colorIndex: 3) experiments.parentID = "protomota"; experiments.pathPrefix = "/experiments"; experiments.legacyHost = "experiments.protomota.com" experiments.pageLimit = 100; experiments.pathAliases = protomotaAliases; experiments.trackingNote = "Section of protomota.com · no downloads" experiments.consentGated = false; experiments.searchConsoleProperty = "sc-domain:protomota.com" // Project ATOM (projectatom.ai) shares protomota.com's GA4 property and stream; it is matched by hostName. // "/projectatom" is the page's internal route, never a protomota.com URL, so the host matches, and so does // the "project-atom" content group its pages send. var atom = Site(id: "project-atom", name: "Project ATOM", url: URL(string: "https://projectatom.ai"), ga4PropertyID: "516107059", colorIndex: 2) atom.parentID = "protomota"; atom.pathPrefix = "/projectatom"; atom.legacyHost = "projectatom.ai"; atom.contentGroup = "project-atom" atom.pageLimit = 100; atom.trackingNote = "Own domain, same GA4 stream as protomota.com" atom.consentGated = false return [ protomota, site("inkspring", "Inkspring", "https://inkspring.ai", "522488509", "G-7318RMX8CB", color: 1, consent: true, note: "Opt-in since Nov 13 · Mac installer, download page"), site("pulsecanvas", "PulseCanvas", "https://pulsecanvas.ai", "558418515", "G-ZEMC2FSDCG", color: 2, consent: true, note: "Opt-in · Mac installer, App Store button, download page", gsc: "sc-domain:pulsecanvas.si", bing: "https://pulsecanvas.si/"), site("jotley", "Jotley", "https://jotley.ai", "492461347", "G-S3X8ZERECS", color: 3, consent: true, note: "Opt-in · Mac installer, App Store button, download page", gsc: "sc-domain:jotley.ai", bing: "https://jotley.ai/"), site("airesourcepro", "AIResourcePro", "https://airesourcepro.com", "486378178", "G-2XSYEJNQBQ", color: 4, consent: true, note: "Opt-in (Accept All) · no downloads"), site("lumen-gesso", "Lumen & Gesso", "https://lumengesso.com", "539690681", "G-51NL8JKBN3", color: 5, consent: false, note: "Not gated · no downloads · portrait builder funnel"), personal, site("textley", "Textley", "https://textley.ai", "564127557", "G-5RW12LV9B6", color: 0, consent: true, note: "Opt-in · Mac installer, download page"), site("opentalon", "OpenTalon", "https://opentalon.ai", "564126552", "G-6F8PWHNKYY", color: 1, consent: true, note: "Opt-in · Mac installer, download page (App Store button once the app is out)"), site("voxley", "Voxley", "https://voxley.si", "564118566", "G-HM6DMMWDN9", color: 2, consent: true, note: "Opt-in · Mac installer, download page"), site("glimmer", "Glimmer", "https://glimmertoday.ai", "565404653", "G-MMTF5S0X2L", color: 4, consent: true, note: "Opt-in · Mac installer, download page", gsc: "", bing: ""), site("skillfarm", "SkillFarm", "https://skillfarm.ai", "527940031", "G-LB5W3LD2QL", color: 5, consent: false, note: "Not gated · page views only, no download or button events · not in Search Console or Bing yet", gsc: "", bing: ""), site("graphley", "Graphley", "https://graphley.ai", "565768537", "G-5X9MHZPLGK", color: 6, consent: true, note: "Opt-in since Nov 24 · Mac installer, download page"), services, experiments, atom ] }() public static let apps: [StoreApp] = { func app(_ id: String, _ name: String, site: String, _ platforms: [String], desktop: String? = nil, onStore: Bool? = nil, note: String? = nil) -> StoreApp { var a = StoreApp(id: id, name: name, siteID: site) a.platforms = platforms; a.desktopCountsAs = desktop; a.onAppStore = onStore; a.note = note return a } return [ app("6746770199", "Jotley: Live AI Transcription", site: "jotley", ["iPhone", "iPad", "Mac (website)"], desktop: "iPhone", 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."), app("6821642700", "PulseCanvas Studio", site: "pulsecanvas", ["iPhone", "iPad", "Mac", "Vision Pro", "Mac (website)"], desktop: "Mac", note: "One universal listing, on the App Store since Oct 25, plus the Creators Edition DMG from pulsecanvas.ai."), app("6838869929", "Graphley", site: "graphley", ["Mac (website)", "iPhone"], onStore: false, note: "Mac installer from graphley.ai; iPhone in TestFlight, not released."), app("6833695057", "OpenTalon", site: "opentalon", ["Mac (website)"], onStore: false, note: "Mac installer from opentalon.ai; the App Store app isn't live yet."), app("mac-textley", "Textley", site: "textley", ["Mac (website)"]), app("mac-voxley", "Voxley", site: "voxley", ["Mac (website)"]), app("mac-inkspring", "Inkspring", site: "inkspring", ["Mac (website)"]), app("mac-glimmer", "Glimmer", site: "glimmer", ["Mac (website)"]) ] }() public static let socials: [SocialAccount] = { func account(_ id: String, _ platform: SocialAccount.Platform, _ handle: String, _ label: String, _ url: String, unit: String, source: String) -> SocialAccount { var a = SocialAccount(id: id, platform: platform, handle: handle) a.label = label; a.url = URL(string: url); a.unit = unit; a.source = source return a } return [ account("substack", .substack, "Protomota Lab", "Newsletter (Substack)", "https://newsletter.protomota.com", unit: "subscribers", source: "manual"), account("x", .x, "@ProtomotaLab", "X", "https://x.com/ProtomotaLab", unit: "followers", source: "api"), account("instagram", .instagram, "@protomota", "Instagram", "https://instagram.com/protomota", unit: "followers", source: "api"), account("linkedin", .linkedin, "the owner", "LinkedIn", "https://www.linkedin.com/in/personal-site", unit: "followers", source: "manual"), account("linkedin_company", .linkedin, "Protomota Lab", "LinkedIn (company page)", "https://www.linkedin.com/company/protomota", unit: "followers", source: "manual"), account("youtube_protomota", .youtube, "@protomota", "YouTube", "https://www.youtube.com/@protomota", unit: "subscribers", source: "api"), account("youtube_airesourcepro", .youtube, "@airesourcepro", "YouTube", "https://www.youtube.com/@airesourcepro", unit: "subscribers", source: "api"), account("github", .github, "protomota", "GitHub", "https://github.com/protomota", unit: "followers", source: "api") ] }() /// Every campaign the owner ran, all stopped on 2026-11-22. Kept with their history; never suggested again. public static let campaigns: [AdCampaign] = { func c(_ id: String, _ platform: String, _ name: String, budget: String?, start: String, end: String?, paused: String? = nil, landing: String? = nil) -> AdCampaign { var a = AdCampaign(id: id, platform: platform, name: name, status: "Expired") a.budget = budget; a.start = start; a.end = end; a.paused = paused; a.expired = "2026-11-22"; a.landing = landing return a } return [ 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", paused: "2026-11-11", landing: "App Store"), c("linkedin-career-reel", "LinkedIn", "personal-site.info - career reel (video)", budget: "$50 total", start: "2026-11-11", end: "2026-11-15", landing: "personal-site.info"), c("linkedin-hire", "LinkedIn", "personal-site.info - hire", budget: "$100 total ($51.77 spent)", start: "2026-11-05", end: "2026-11-14", paused: "2026-11-10", landing: "personal-site.info"), c("google-hire-branded-custom", "Google Ads", "the owner - hire, Branded, Custom apps", budget: "$2.25, $1, $6/day", start: "2026-11-05", end: nil, paused: "2026-11-07", landing: "personal-site.info, protomota.com/custom-apps"), c("google-ai-automation", "Google Ads", "AI automation", budget: "$6.50/day, $12 max CPC", start: "2026-11-05", end: nil, landing: "protomota.com/ai-automation") ] }() static let undercounting = ["jotley", "pulsecanvas", "airesourcepro", "textley", "voxley", "opentalon", "inkspring", "glimmer", "graphley"] public static let caveats: [Caveat] = [ 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), 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"), 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"), 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"]), 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"]), 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"]), 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"), Caveat(id: "partial-today", text: "Google Analytics numbers for today are partial, so every range ends yesterday.", subjects: []), Caveat(id: "ads-expired", text: "All ads stopped on Nov 22. Every campaign is kept here with its history and marked Expired.", subjects: []) ] /// Applies the catalog: adds what's missing, fills empty fields, keeps the user's order, names and archives. public static func apply(to ws: inout Workspace) { for wanted in sites { if let i = ws.sites.firstIndex(where: { $0.id == wanted.id || ($0.ga4PropertyID == wanted.ga4PropertyID && wanted.parentID == nil && $0.parentID == nil) }) { var s = ws.sites[i] s.url = s.url ?? wanted.url s.measurementID = wanted.measurementID s.parentID = wanted.parentID; s.pathPrefix = wanted.pathPrefix; s.legacyHost = wanted.legacyHost; s.contentGroup = wanted.contentGroup s.pathAliases = wanted.pathAliases; s.pageLimit = wanted.pageLimit; s.funnelLandings = wanted.funnelLandings s.trackingNote = wanted.trackingNote; s.consentGated = wanted.consentGated s.searchConsoleProperty = wanted.searchConsoleProperty s.bingSiteURL = wanted.bingSiteURL ws.sites[i] = s } else { ws.sites.append(wanted) } } // Keep the every-site order, sites added later included; anything else stays after them, in its own order. let siteOrder = sites.map(\.id) ws.sites = ws.sites.enumerated().sorted { a, b in let (x, y) = (siteOrder.firstIndex(of: a.element.id) ?? siteOrder.count + a.offset, siteOrder.firstIndex(of: b.element.id) ?? siteOrder.count + b.offset) return x < y }.map(\.element) for wanted in apps { if let i = ws.apps.firstIndex(where: { $0.id == wanted.id }) { var a = ws.apps[i] a.siteID = a.siteID ?? wanted.siteID; a.platforms = wanted.platforms; a.desktopCountsAs = wanted.desktopCountsAs a.onAppStore = wanted.onAppStore; a.note = wanted.note ws.apps[i] = a } else { ws.apps.append(wanted) } } for wanted in socials where !ws.socials.contains(where: { $0.id == wanted.id }) { ws.socials.append(wanted) } for i in ws.socials.indices { if let w = socials.first(where: { $0.id == ws.socials[i].id }) { ws.socials[i].label = w.label; ws.socials[i].url = w.url; ws.socials[i].unit = w.unit; ws.socials[i].source = w.source } } var campaignList = ws.campaigns ?? [] for wanted in campaigns { if let i = campaignList.firstIndex(where: { $0.id == wanted.id }) { campaignList[i] = wanted } else { campaignList.append(wanted) } } ws.campaigns = campaignList ws.caveats = caveats for board in dashboards { if let i = ws.dashboards.firstIndex(where: { $0.id == board.id }) { ws.dashboards[i] = board } else { ws.dashboards.append(board) } } // The old starter board is covered by Overview; keep it only if the user changed it. ws.dashboards.removeAll { $0.id == Dashboard.starter.id && $0 == Dashboard.starter } let order = dashboards.map(\.id) ws.dashboards.sort { (order.firstIndex(of: $0.id) ?? 99) < (order.firstIndex(of: $1.id) ?? 99) } } // MARK: Dashboards static func w(_ id: String, _ title: String, _ kind: Widget.Kind, _ metric: Metric = .users, days: Int = 30, subjects: [String] = [], breakdown: String? = nil, event: String? = nil, wide: Bool = true, items: [String]? = nil, subtitle: String? = nil) -> Widget { var widget = Widget(id: id, title: title, kind: kind, metric: metric, subjects: subjects, days: days, breakdown: breakdown, event: event) widget.wide = wide; widget.items = items; widget.subtitle = subtitle return widget } public static let dashboards: [Dashboard] = [ Dashboard(id: "overview", name: "Portfolio", widgets: [ w("kpis", "Last 30 days", .kpiRow, items: ["visitors", "appDownloads", "macInstaller", "appStoreButton", "followers"], subtitle: "Each vs the 30 days before"), w("visitors", "Visitors, all sites", .stackedArea, .users, subtitle: "Stacked by site"), w("downloads", "App Store downloads", .stackedBars, .appDownloads, breakdown: "platform", wide: false, subtitle: "By platform"), w("installer", "Mac installer downloads", .stackedBars, .keyEvent, event: "mac_installer_download", wide: false, subtitle: "Real .dmg downloads, by site"), w("notes", "Read these numbers with", .notes) ]), Dashboard(id: "every-site", name: "Every site", widgets: [ w("scorecard", "Every site", .siteScorecard, subtitle: "Last 30 days vs the 30 before, with how each site is tracked"), w("notes", "Notes", .notes) ]), Dashboard(id: "app-store", name: "App downloads", widgets: [ 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"), w("per-day", "App Store downloads per day", .stackedBars, .appDownloads, breakdown: "platform", wide: false), w("ratings", "Ratings and reviews", .ratings, .rating, wide: false, subtitle: "Every storefront"), w("notes", "Notes", .notes, subjects: ["6746770199", "jotley"]) ]), Dashboard(id: "downloads", name: "Website downloads", widgets: [ w("buttons", "Downloads by button", .downloadButtons, .keyEvent, subtitle: "Mac installer = the real .dmg download. Buttons are clicks, not downloads."), w("source", "Source code", .downloadButtons, .keyEvent, items: ["source_click", "source_download"], subtitle: "Left out of download totals") ]), Dashboard(id: "traffic", name: "Pages and sources", widgets: [ w("ai", "Visits from AI assistants", .aiVisits, .sessions, days: 90, subtitle: "Sessions from ChatGPT, Perplexity, Claude, Gemini, Copilot and others"), w("channels", "Channels", .breakdown, .sessions, breakdown: "channel", wide: false, subtitle: "Sessions by default channel group"), w("sources", "Top sources", .breakdown, .sessions, breakdown: "source", wide: false, subtitle: "Top 10 source / medium per site"), w("pages", "Top pages", .breakdown, .pageViews, breakdown: "page", subtitle: "Page views per site") ]), Dashboard(id: "site-detail", name: "Site detail", widgets: [ w("protomota", "Protomota", .siteDetail, subjects: ["protomota"], subtitle: "Clicks, sections, scroll, forms, video, calls and leads"), w("personal", "Personal site", .siteDetail, subjects: ["personal-site-info"], subtitle: "Résumé downloads by format and click-outs by domain"), w("lumen", "Lumen & Gesso", .siteDetail, subjects: ["lumen-gesso"], subtitle: "Portrait builder funnel"), w("apps", "App sites", .siteDetail, subjects: ["jotley", "pulsecanvas", "inkspring", "textley", "voxley", "opentalon", "glimmer", "graphley", "airesourcepro"], subtitle: "Shared tracker: clicks by section and destination, scroll, sections seen, video") ]), Dashboard(id: "search", name: "Search", widgets: [ w("search", "Google Search Console and Bing", .search, .searchClicks, days: 28, subtitle: "Clicks, impressions, CTR and position per site"), w("queries", "Top queries", .breakdown, .searchClicks, days: 28, breakdown: "query", wide: false, subtitle: "Google, last 28 days"), w("search-pages", "Top search pages", .breakdown, .searchClicks, days: 28, breakdown: "spage", wide: false, subtitle: "Google, last 28 days") ]), Dashboard(id: "followers", name: "Followers", widgets: [ w("accounts", "Newsletter and social followers", .followers, .followers, days: 90), w("videos", "YouTube videos", .videos, .videoViews, days: 30, subtitle: "Newest five and top ten per channel") ]), Dashboard(id: "ads", name: "Paid ads", widgets: [ w("campaigns", "Campaigns", .ads, .adSpend, days: 90, subtitle: "All ads stopped Nov 22. History kept, every row Expired."), 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") ]) ] // MARK: Event names /// Download buttons per site, in table order. Clicks on a button that leads to a download page aren't downloads. public static let downloadEvents = ["mac_installer_download", "download_click_mac", "app_store_click", "download_click_ios"] public static let sourceEvents = ["source_click", "source_download"] public static func eventTitle(_ event: String) -> String { switch event { case "mac_installer_download": "Mac installer download" case "download_click_mac": "Download page button (download_click_mac)" case "app_store_click": "App Store button (app_store_click)" case "download_click_ios": "App Store button (download_click_ios)" case "source_click": "Source code (source_click)" case "source_download": "Source code (source_download)" case "book_call": "Calls booked" case "generate_lead": "Leads" case "resume_download": "Résumé downloads" case "resume_open": "Résumé opened" case "outbound_click": "Click-outs" case "section_view": "Sections seen" case "scroll_depth": "Scroll depth" case "builder_step": "Builder steps" case "begin_checkout": "Checkout started" case "cta_click": "Button clicks" case "form_submitted": "Forms sent" case "video_play": "Video plays" default: event.replacingOccurrences(of: "_", with: " ").capitalizedFirst } } } extension String { var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() } } // MARK: Migration and history import public extension Portfolio { /// Brings older stored points up to date: App Store platforms named the way Graphley shows them (Desktop is /// a Mac, or the iPhone for Jotley), and ratings as average + count instead of the 0.1 breakdowns. static func migrate(_ points: inout [DataPoint], apps: [StoreApp]) { let desktop = Dictionary(apps.map { ($0.id, $0.desktopCountsAs ?? "Mac") }, uniquingKeysWith: { a, _ in a }) var merged: [String: DataPoint] = [:] var rest: [DataPoint] = [] for var p in points { if p.metric == .rating, p.breakdown == "average" || p.breakdown == "count" { if p.breakdown == "count" { p.metric = .ratingCount } p.breakdown = nil } if [.appDownloads, .appRedownloads].contains(p.metric), p.family == "platform", let raw = p.breakdownValue { p.breakdown = "platform:" + AppStoreConnect.platform(device: raw, desktopCountsAs: desktop[p.subject] ?? "Mac") let key = "\(p.subject)|\(p.metric.rawValue)|\(p.day)|\(p.breakdown!)" if var existing = merged[key] { existing.value += p.value; merged[key] = existing } else { merged[key] = p } continue } rest.append(p) } points = rest + merged.values } /// Imports rows exported by the old pull (`~/.config/ga4-pull`). Returns how many rows were taken. static func importHistory(kind: String, rows: [[String: Any]], store: WorkspaceStore, markSent: Bool = false) throws -> Int { func str(_ r: [String: Any], _ k: String) -> String? { (r[k] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? (r[k] as? Int).map(String.init) } func num(_ r: [String: Any], _ k: String) -> Double? { (r[k] as? Double) ?? (r[k] as? Int).map(Double.init) } var points: [DataPoint] = [] switch kind { case "followers": for r in rows { guard let account = str(r, "account"), let day = str(r, "day"), let count = num(r, "count") else { continue } points.append(DataPoint(day: day, subject: account, metric: .followers, value: count)) } case "videos": var videos: [Video] = [] for r in rows { guard let id = str(r, "video_id"), let account = str(r, "account"), let day = str(r, "day") else { continue } videos.append(Video(id: id, account: account, title: str(r, "title") ?? id, kind: str(r, "kind") ?? "video", published: str(r, "published"), url: str(r, "url") ?? "https://www.youtube.com/watch?v=\(id)")) if let v = num(r, "views") { points.append(DataPoint(day: day, subject: id, metric: .videoViews, value: v)) } if let l = num(r, "likes") { points.append(DataPoint(day: day, subject: id, metric: .videoLikes, value: l)) } } try store.update { ws in var all = Dictionary((ws.videos ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) for v in videos { var merged = all[v.id] ?? v merged.title = v.title merged.published = merged.published ?? v.published if v.kind != "video" { merged.kind = v.kind } all[v.id] = merged } ws.videos = all.values.sorted { ($0.published ?? "") > ($1.published ?? "") } } case "ads": for r in rows { guard let id = str(r, "campaign_id"), let day = str(r, "day") else { continue } for (field, metric) in [("cost", Metric.adSpend), ("clicks", .adClicks), ("impressions", .adImpressions), ("conversions", .adConversions)] { if let v = num(r, field) { points.append(DataPoint(day: day, subject: id, metric: metric, value: v)) } } } case "ratings": for r in rows { guard let id = str(r, "apple_id"), let day = str(r, "day") else { continue } points.append(DataPoint(day: day, subject: id, metric: .ratingCount, value: num(r, "count") ?? 0)) if let avg = num(r, "avg") { points.append(DataPoint(day: day, subject: id, metric: .rating, value: avg)) } } case "reviews": let reviews = rows.compactMap { r -> Review? in guard let id = str(r, "review_id"), let app = str(r, "apple_id") else { return nil } return Review(id: id, appID: app, appName: str(r, "app") ?? app, country: str(r, "country") ?? "US", stars: Int(num(r, "stars") ?? 0), title: str(r, "title") ?? "", text: str(r, "text") ?? "", version: str(r, "version") ?? "", author: str(r, "author") ?? "", date: str(r, "date") ?? "", firstSeen: str(r, "first_seen") ?? str(r, "date") ?? "", url: str(r, "url") ?? "") } try store.update { ws in var all = Dictionary((ws.reviews ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) for r in reviews where all[r.id] == nil { all[r.id] = r } ws.reviews = all.values.sorted { $0.date > $1.date } // The old pull already made these to-dos. if markSent { ws.todoKeys = Array(Set((ws.todoKeys ?? []) + reviews.map { "appstore-review-\($0.appID)-\($0.id)" })) } } return reviews.count default: throw AnalyticsError.missing("Unknown kind \(kind).") } try store.merge(points) return points.count } }