Branchwell

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

1import Foundation
2
3/// Everything the app knows, saved locally on the Mac. Credentials are never stored here:
4/// they live in the Keychain (see `Keychain`). The iPhone gets a read-only `Snapshot` through iCloud.
5public struct Workspace: Codable, Sendable, Equatable {
6 public var sites: [Site] = []
7 public var apps: [StoreApp] = []
8 public var socials: [SocialAccount] = []
9 public var dashboards: [Dashboard] = [.starter]
10 public var settings = Settings()
11 public var agentLog: [AgentAction] = []
12 /// Written App Store reviews, kept forever with the day each was first seen.
13 public var reviews: [Review]?
14 /// Ad campaigns and their status (all marked Expired since 2026-11-22). Spend is in the data points.
15 public var campaigns: [AdCampaign]?
16 /// YouTube videos seen on the tracked channels; views per day are data points.
17 public var videos: [Video]?
18 /// Notes shown in the app next to the numbers they explain (consent undercounts, gaps, test clicks).
19 public var caveats: [Caveat]?
20 /// Review to-dos already sent to OpenTalon (dedupe keys), and the ones waiting for OpenTalon to be reachable.
21 public var todoKeys: [String]?
22 public var pendingTodos: [ReviewTodo]?
23 public init() {}
24
25 /// Moves a site to sit where `target` is now (the user's drag order). Archived sites keep their
26 /// place in the array but don't count, so the visible order is exactly what the user dragged.
27 /// Returns false when nothing moved.
28 @discardableResult
29 public mutating func moveSite(_ id: String, to target: String) -> Bool {
30 guard id != target, let from = sites.firstIndex(where: { $0.id == id }),
31 let to = sites.firstIndex(where: { $0.id == target }) else { return false }
32 let site = sites.remove(at: from)
33 sites.insert(site, at: to)
34 return true
35 }
36
37 /// Moves a site one place up (-1) or down (+1) among the visible (not archived) sites.
38 @discardableResult
39 public mutating func moveSite(_ id: String, by step: Int) -> Bool {
40 let visible = sites.filter { !$0.archived }.map(\.id)
41 guard let i = visible.firstIndex(of: id), visible.indices.contains(i + step) else { return false }
42 return moveSite(id, to: visible[i + step])
43 }
44}
45
46public struct Settings: Codable, Sendable, Equatable {
47 /// Hour of day (local time) for the daily refresh.
48 public var refreshHour = 9
49 /// Lets connected agents use write tools (add sites, edit dashboards). Read tools always work while MCP is on.
50 public var agentsCanWrite = true
51 /// Lets agents save API keys into the Keychain. Off by default, like Inkspring.
52 public var agentsCanSetKeys = false
53 public var shareWithIPhone = true
54 /// When the last refresh finished, shown in the toolbar ("Updated 9:02").
55 public var lastRefreshAt: Date?
56 /// When the Mac last shared a snapshot with the iPhone.
57 public var lastSharedAt: Date?
58 public init() {}
59}
60
61public struct Site: Codable, Sendable, Identifiable, Hashable {
62 public var id: String // stable slug, e.g. "jotley"
63 public var name: String // "Jotley"
64 public var url: URL?
65 public var ga4PropertyID: String? // "564127557"
66 public var colorIndex: Int
67 public var archived = false
68 /// GA4 web stream measurement ID ("G-DRL62HKS7W"), used to match properties.
69 public var measurementID: String?
70 /// A section of another site reported as its own site (protomota.com/services). It reads the parent's
71 /// property, matched by page path prefix OR an old host name (the section's subdomain before it moved).
72 public var parentID: String?
73 public var pathPrefix: String?
74 public var legacyHost: String?
75 /// A GA4 content group (the `content_group` page parameter) that also marks this section's pages.
76 public var contentGroup: String?
77 /// Page paths shown under another path (`/services-home` → `/services`).
78 public var pathAliases: [String: String]?
79 /// How many top pages to keep (10 unless set; Protomota keeps 100 so small ad landing pages stay).
80 public var pageLimit: Int?
81 /// Paid-ad landing pages whose funnel is pulled per day (sessions, CTA clicks, calls, leads).
82 public var funnelLandings: [String]?
83 /// One line on how the site is tracked ("opt-in · Mac installer, download page"), shown in the every-site table.
84 public var trackingNote: String?
85 /// True when analytics only count visitors who accept the consent banner (numbers undercount).
86 public var consentGated: Bool?
87 /// Search Console property ("https://protomota.com/" or "sc-domain:inkspring.ai") and Bing site URL.
88 public var searchConsoleProperty: String?
89 public var bingSiteURL: String?
90 public init(id: String, name: String, url: URL? = nil, ga4PropertyID: String? = nil, colorIndex: Int = 0) {
91 self.id = id; self.name = name; self.url = url; self.ga4PropertyID = ga4PropertyID; self.colorIndex = colorIndex
92 }
93}
94
95public struct StoreApp: Codable, Sendable, Identifiable, Hashable {
96 public var id: String // Apple ID, e.g. "6746770199"; "mac-<site>" for an app with no App Store listing
97 public var name: String // the newest App Store name, so renames merge into one row
98 public var siteID: String? // links the app to its website (its Mac installer downloads come from there)
99 /// Platforms in display order: "iPhone", "iPad", "Mac", "Vision Pro", "Mac (website)".
100 public var platforms: [String]?
101 /// Where Apple's "Desktop" device goes. "iPhone" for an iOS app that runs on Apple Silicon Macs (Jotley has no Mac
102 /// App Store app), "Mac" otherwise.
103 public var desktopCountsAs: String?
104 /// False for an App Store record that isn't released yet, or nil/absent listing.
105 public var onAppStore: Bool?
106 /// Short note shown under the app ("Renamed Nov 1 from …; downloads combined").
107 public var note: String?
108 public init(id: String, name: String, siteID: String? = nil) { self.id = id; self.name = name; self.siteID = siteID }
109
110 /// Numeric Apple ID with a live listing: sales reports, ratings and reviews apply.
111 public var hasAppStoreListing: Bool { id.allSatisfy(\.isNumber) && onAppStore != false }
112 /// "Jotley" for "Jotley: Live AI Transcription".
113 public var shortName: String { name.components(separatedBy: ":").first ?? name }
114}
115
116public struct SocialAccount: Codable, Sendable, Identifiable, Hashable {
117 public enum Platform: String, Codable, Sendable, CaseIterable { case youtube, substack, linkedin, x, instagram, github }
118 public var id: String
119 public var platform: Platform
120 public var handle: String
121 /// "Newsletter (Substack)", "LinkedIn (company page)": the platform as shown.
122 public var label: String?
123 public var url: URL?
124 /// "followers" or "subscribers".
125 public var unit: String?
126 /// How the count arrives: "api" (fetched every refresh) or "manual" (an agent or hand entry records it).
127 public var source: String?
128 public init(id: String, platform: Platform, handle: String) { self.id = id; self.platform = platform; self.handle = handle }
129 public var title: String { label ?? platform.rawValue.capitalized }
130}
131
132public struct Review: Codable, Sendable, Identifiable, Hashable {
133 public var id: String // Apple's review ID
134 public var appID: String
135 public var appName: String
136 public var country: String
137 public var stars: Int
138 public var title: String
139 public var text: String
140 public var version: String
141 public var author: String
142 public var date: String // YYYY-MM-DD the review was written or updated
143 public var firstSeen: String
144 public var url: String
145 public init(id: String, appID: String, appName: String, country: String, stars: Int, title: String, text: String,
146 version: String, author: String, date: String, firstSeen: String, url: String) {
147 self.id = id; self.appID = appID; self.appName = appName; self.country = country; self.stars = stars; self.title = title
148 self.text = text; self.version = version; self.author = author; self.date = date; self.firstSeen = firstSeen; self.url = url
149 }
150}
151
152/// An OpenTalon to-do waiting to be created (OpenTalon wasn't reachable yet).
153public struct ReviewTodo: Codable, Sendable, Hashable {
154 public var key: String // appstore-review-<appid>-<reviewid>
155 public var board: String
156 public var title: String
157 public var notes: String
158 public var priority: String
159 public var due: String?
160 public init(key: String, board: String, title: String, notes: String, priority: String, due: String?) {
161 self.key = key; self.board = board; self.title = title; self.notes = notes; self.priority = priority; self.due = due
162 }
163}
164
165public struct AdCampaign: Codable, Sendable, Identifiable, Hashable {
166 public var id: String
167 public var platform: String // "Google Ads", "LinkedIn", "Apple Ads"
168 public var name: String
169 public var budget: String?
170 public var start: String?
171 public var end: String?
172 public var paused: String?
173 /// "Expired" for every campaign since the owner stopped all ads on 2026-11-22.
174 public var status: String
175 public var expired: String?
176 public var landing: String?
177 public init(id: String, platform: String, name: String, status: String) { self.id = id; self.platform = platform; self.name = name; self.status = status }
178}
179
180public struct Video: Codable, Sendable, Identifiable, Hashable {
181 public var id: String // YouTube video ID
182 public var account: String // SocialAccount ID
183 public var title: String
184 public var kind: String // "video", "short", "live"
185 public var published: String?
186 public var url: String
187 public init(id: String, account: String, title: String, kind: String, published: String?, url: String) {
188 self.id = id; self.account = account; self.title = title; self.kind = kind; self.published = published; self.url = url
189 }
190}
191
192public struct Caveat: Codable, Sendable, Identifiable, Hashable {
193 public var id: String
194 public var text: String
195 /// Sites or apps the note is about; empty means the whole portfolio.
196 public var subjects: [String]
197 /// The days it covers, when it is about a span (a tracking gap).
198 public var from: String?
199 public var to: String?
200 public init(id: String, text: String, subjects: [String] = [], from: String? = nil, to: String? = nil) {
201 self.id = id; self.text = text; self.subjects = subjects; self.from = from; self.to = to
202 }
203}
204
205/// The metrics the app can chart. Each maps to a GA4 metric or an App Store report column.
206public enum Metric: String, Codable, Sendable, CaseIterable {
207 case users, newUsers, sessions, pageViews, engagedSessions
208 case keyEvent // a GA4 key event, named in `Widget.event`
209 case appDownloads, appRedownloads
210 case followers
211 case rating // average stars (weighted across storefronts)
212 case ratingCount
213 case searchClicks, searchImpressions, searchPosition // `event` is the engine: "google" or "bing"
214 case videoViews, videoLikes // subject is a YouTube video ID
215 case adSpend, adClicks, adImpressions, adConversions // subject is an AdCampaign ID
216
217 public var title: String {
218 switch self {
219 case .users: "Visitors"
220 case .newUsers: "New visitors"
221 case .sessions: "Sessions"
222 case .pageViews: "Page views"
223 case .engagedSessions: "Engaged sessions"
224 case .keyEvent: "Key event"
225 case .appDownloads: "App Store downloads"
226 case .appRedownloads: "Redownloads"
227 case .followers: "Followers"
228 case .rating: "Rating"
229 case .ratingCount: "Ratings"
230 case .searchClicks: "Search clicks"
231 case .searchImpressions: "Search impressions"
232 case .searchPosition: "Average position"
233 case .videoViews: "Video views"
234 case .videoLikes: "Video likes"
235 case .adSpend: "Ad spend"
236 case .adClicks: "Ad clicks"
237 case .adImpressions: "Ad impressions"
238 case .adConversions: "Conversions"
239 }
240 }
241
242 public var ga4Name: String? {
243 switch self {
244 case .users: "activeUsers"
245 case .newUsers: "newUsers"
246 case .sessions: "sessions"
247 case .pageViews: "screenPageViews"
248 case .engagedSessions: "engagedSessions"
249 case .keyEvent: "eventCount"
250 default: nil
251 }
252 }
253}
254
255/// One value for one day. `subject` is a site ID, an app ID or a social account ID; `breakdown` is an
256/// optional "family:value" dimension (a page path, a platform such as "iPhone", a channel group).
257/// Families in `DataPoint.windowFamilies` hold totals for a recent window (the last 30 days), stored on the
258/// last day; a refresh replaces the whole family. The others are per day.
259public struct DataPoint: Codable, Sendable, Hashable {
260 public var day: String // YYYY-MM-DD, in the site's GA4 time zone
261 public var subject: String
262 public var metric: Metric
263 public var breakdown: String?
264 public var event: String?
265 public var value: Double
266 public init(day: String, subject: String, metric: Metric, breakdown: String? = nil, event: String? = nil, value: Double) {
267 self.day = day; self.subject = subject; self.metric = metric; self.breakdown = breakdown; self.event = event; self.value = value
268 }
269
270 /// Window totals (last 30 days unless the family says otherwise): pages, channels, sources, detail
271 /// breakdowns, search queries and pages, ratings by country, last-30 vs previous-30 summaries.
272 public static let windowFamilies: Set<String> = ["page", "channel", "source", "section", "domain", "scroll", "form", "field",
273 "video", "file", "cta", "step", "query", "spage", "country", "period", "ailanding"]
274 public var family: String { breakdown.map { String($0.prefix { $0 != ":" }) } ?? "" }
275 public var breakdownValue: String? { breakdown.map { String($0.drop { $0 != ":" }.dropFirst()) } }
276 public var isWindow: Bool { Self.windowFamilies.contains(family) }
277 /// What a refresh replaces together: one subject's metric, breakdown family and (except key events, which are
278 /// all pulled at once) event.
279 public var mergeKey: String { "\(subject)|\(metric.rawValue)|\(family)|\(metric == .keyEvent ? "" : event ?? "")" }
280}
281
282public struct Dashboard: Codable, Sendable, Identifiable, Hashable {
283 public var id: String
284 public var name: String
285 public var widgets: [Widget]
286 public init(id: String, name: String, widgets: [Widget]) { self.id = id; self.name = name; self.widgets = widgets }
287
288 public static let starter = Dashboard(id: "main", name: "My dashboard", widgets: [
289 Widget(id: "visitors", title: "Visitors, all sites", kind: .area, metric: .users, subjects: [], days: 30),
290 Widget(id: "downloads", title: "App Store downloads", kind: .stackedBars, metric: .appDownloads, subjects: [], days: 30, breakdown: "platform"),
291 Widget(id: "topsites", title: "Top sites this month", kind: .ranking, metric: .users, subjects: [], days: 30)
292 ])
293}
294
295public struct Widget: Codable, Sendable, Identifiable, Hashable {
296 public enum Kind: String, Codable, Sendable, CaseIterable {
297 case number, area, line, stackedArea, stackedBars, ranking, table
298 /// Portfolio widgets: each draws one section of the old Portfolio Analytics dashboard.
299 case kpiRow, siteScorecard, appPlatforms, ratings, downloadButtons, breakdown, aiVisits, siteDetail, search, followers, videos, ads, funnel, notes
300 }
301 public var id: String
302 public var title: String
303 public var kind: Kind
304 public var metric: Metric
305 /// Site, app or account IDs. Empty means all.
306 public var subjects: [String]
307 public var days: Int
308 public var breakdown: String?
309 public var event: String?
310 /// Takes the whole row (tables). Narrow widgets sit two to a row on Mac and iPad.
311 public var wide: Bool?
312 /// Widget-specific list: tiles for kpiRow, event names for downloadButtons.
313 public var items: [String]?
314 public var subtitle: String?
315 public init(id: String, title: String, kind: Kind, metric: Metric, subjects: [String], days: Int, breakdown: String? = nil, event: String? = nil) {
316 self.id = id; self.title = title; self.kind = kind; self.metric = metric; self.subjects = subjects; self.days = days; self.breakdown = breakdown; self.event = event
317 }
318}
319
320/// A change an agent made through MCP, shown in the Agents screen so the user can review it.
321public struct AgentAction: Codable, Sendable, Identifiable, Hashable {
322 public var id = UUID()
323 public var at = Date()
324 public var client: String // "Claude Code", "Codex"
325 public var tool: String
326 public var summary: String
327 public init(client: String, tool: String, summary: String) { self.client = client; self.tool = tool; self.summary = summary }
328}
329
330/// What the iPhone sees: the workspace minus settings and log, plus the last 90 days of data.
331public struct Snapshot: Codable, Sendable, Equatable {
332 public var refreshedAt: Date
333 public var sites: [Site]
334 public var apps: [StoreApp]
335 public var socials: [SocialAccount]
336 public var dashboards: [Dashboard]
337 public var points: [DataPoint]
338 public var reviews: [Review]?
339 public var campaigns: [AdCampaign]?
340 public var videos: [Video]?
341 public var caveats: [Caveat]?
342 public init(refreshedAt: Date, sites: [Site], apps: [StoreApp], socials: [SocialAccount], dashboards: [Dashboard], points: [DataPoint],
343 reviews: [Review]? = nil, campaigns: [AdCampaign]? = nil, videos: [Video]? = nil, caveats: [Caveat]? = nil) {
344 self.refreshedAt = refreshedAt; self.sites = sites; self.apps = apps; self.socials = socials; self.dashboards = dashboards; self.points = points
345 self.reviews = reviews; self.campaigns = campaigns; self.videos = videos; self.caveats = caveats
346 }
347}
348
349public extension Array where Element == DataPoint {
350 /// Daily totals for one metric, oldest first, with missing days filled with zero.
351 func daily(_ metric: Metric, subjects: Set<String> = [], days: [String]) -> [Double] {
352 var byDay: [String: Double] = [:]
353 for p in self where p.metric == metric && p.breakdown == nil && (subjects.isEmpty || subjects.contains(p.subject)) {
354 byDay[p.day, default: 0] += p.value
355 }
356 return days.map { byDay[$0] ?? 0 }
357 }
358
359 /// Mac installer downloads from an app's website per day, or nil when the app has no website download.
360 func websiteDownloads(_ app: StoreApp, days: [String]) -> [Double]? {
361 guard let site = app.siteID, (app.platforms ?? []).contains("Mac (website)") else { return nil }
362 var byDay: [String: Double] = [:]
363 for p in self where p.subject == site && p.metric == .keyEvent && p.event == "mac_installer_download" && p.breakdown == nil {
364 byDay[p.day, default: 0] += p.value
365 }
366 return days.map { byDay[$0] ?? 0 }
367 }
368
369 /// Every download of one app per day: App Store first-time downloads plus Mac installers from its website,
370 /// so apps without an App Store listing count too.
371 func appDownloads(_ app: StoreApp, days: [String]) -> [Double] {
372 let store = app.hasAppStoreListing ? daily(.appDownloads, subjects: [app.id], days: days) : days.map { _ in 0 }
373 guard let web = websiteDownloads(app, days: days) else { return store }
374 return zip(store, web).map(+)
375 }
376}
377
378public enum DayKey {
379 public static func string(_ date: Date, calendar: Calendar = .current) -> String {
380 let c = calendar.dateComponents([.year, .month, .day], from: date)
381 return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
382 }
383 /// The last `count` days ending yesterday (GA4 data for today is partial).
384 public static func lastDays(_ count: Int, endingBefore now: Date = .now, calendar: Calendar = .current) -> [String] {
385 (1...max(1, count)).reversed().compactMap { calendar.date(byAdding: .day, value: -$0, to: now) }.map { string($0, calendar: calendar) }
386 }
387}