import Foundation /// Everything the app knows, saved locally on the Mac. Credentials are never stored here: /// they live in the Keychain (see `Keychain`). The iPhone gets a read-only `Snapshot` through iCloud. public struct Workspace: Codable, Sendable, Equatable { public var sites: [Site] = [] public var apps: [StoreApp] = [] public var socials: [SocialAccount] = [] public var dashboards: [Dashboard] = [.starter] public var settings = Settings() public var agentLog: [AgentAction] = [] /// Written App Store reviews, kept forever with the day each was first seen. public var reviews: [Review]? /// Ad campaigns and their status (all marked Expired since 2026-11-22). Spend is in the data points. public var campaigns: [AdCampaign]? /// YouTube videos seen on the tracked channels; views per day are data points. public var videos: [Video]? /// Notes shown in the app next to the numbers they explain (consent undercounts, gaps, test clicks). public var caveats: [Caveat]? /// Review to-dos already sent to OpenTalon (dedupe keys), and the ones waiting for OpenTalon to be reachable. public var todoKeys: [String]? public var pendingTodos: [ReviewTodo]? public init() {} /// Moves a site to sit where `target` is now (the user's drag order). Archived sites keep their /// place in the array but don't count, so the visible order is exactly what the user dragged. /// Returns false when nothing moved. @discardableResult public mutating func moveSite(_ id: String, to target: String) -> Bool { guard id != target, let from = sites.firstIndex(where: { $0.id == id }), let to = sites.firstIndex(where: { $0.id == target }) else { return false } let site = sites.remove(at: from) sites.insert(site, at: to) return true } /// Moves a site one place up (-1) or down (+1) among the visible (not archived) sites. @discardableResult public mutating func moveSite(_ id: String, by step: Int) -> Bool { let visible = sites.filter { !$0.archived }.map(\.id) guard let i = visible.firstIndex(of: id), visible.indices.contains(i + step) else { return false } return moveSite(id, to: visible[i + step]) } } public struct Settings: Codable, Sendable, Equatable { /// Hour of day (local time) for the daily refresh. public var refreshHour = 9 /// Lets connected agents use write tools (add sites, edit dashboards). Read tools always work while MCP is on. public var agentsCanWrite = true /// Lets agents save API keys into the Keychain. Off by default, like Inkspring. public var agentsCanSetKeys = false public var shareWithIPhone = true /// When the last refresh finished, shown in the toolbar ("Updated 9:02"). public var lastRefreshAt: Date? /// When the Mac last shared a snapshot with the iPhone. public var lastSharedAt: Date? public init() {} } public struct Site: Codable, Sendable, Identifiable, Hashable { public var id: String // stable slug, e.g. "jotley" public var name: String // "Jotley" public var url: URL? public var ga4PropertyID: String? // "564127557" public var colorIndex: Int public var archived = false /// GA4 web stream measurement ID ("G-DRL62HKS7W"), used to match properties. public var measurementID: String? /// A section of another site reported as its own site (protomota.com/services). It reads the parent's /// property, matched by page path prefix OR an old host name (the section's subdomain before it moved). public var parentID: String? public var pathPrefix: String? public var legacyHost: String? /// A GA4 content group (the `content_group` page parameter) that also marks this section's pages. public var contentGroup: String? /// Page paths shown under another path (`/services-home` → `/services`). public var pathAliases: [String: String]? /// How many top pages to keep (10 unless set; Protomota keeps 100 so small ad landing pages stay). public var pageLimit: Int? /// Paid-ad landing pages whose funnel is pulled per day (sessions, CTA clicks, calls, leads). public var funnelLandings: [String]? /// One line on how the site is tracked ("opt-in · Mac installer, download page"), shown in the every-site table. public var trackingNote: String? /// True when analytics only count visitors who accept the consent banner (numbers undercount). public var consentGated: Bool? /// Search Console property ("https://protomota.com/" or "sc-domain:inkspring.ai") and Bing site URL. public var searchConsoleProperty: String? public var bingSiteURL: String? public init(id: String, name: String, url: URL? = nil, ga4PropertyID: String? = nil, colorIndex: Int = 0) { self.id = id; self.name = name; self.url = url; self.ga4PropertyID = ga4PropertyID; self.colorIndex = colorIndex } } public struct StoreApp: Codable, Sendable, Identifiable, Hashable { public var id: String // Apple ID, e.g. "6746770199"; "mac-" for an app with no App Store listing public var name: String // the newest App Store name, so renames merge into one row public var siteID: String? // links the app to its website (its Mac installer downloads come from there) /// Platforms in display order: "iPhone", "iPad", "Mac", "Vision Pro", "Mac (website)". public var platforms: [String]? /// Where Apple's "Desktop" device goes. "iPhone" for an iOS app that runs on Apple Silicon Macs (Jotley has no Mac /// App Store app), "Mac" otherwise. public var desktopCountsAs: String? /// False for an App Store record that isn't released yet, or nil/absent listing. public var onAppStore: Bool? /// Short note shown under the app ("Renamed Nov 1 from …; downloads combined"). public var note: String? public init(id: String, name: String, siteID: String? = nil) { self.id = id; self.name = name; self.siteID = siteID } /// Numeric Apple ID with a live listing: sales reports, ratings and reviews apply. public var hasAppStoreListing: Bool { id.allSatisfy(\.isNumber) && onAppStore != false } /// "Jotley" for "Jotley: Live AI Transcription". public var shortName: String { name.components(separatedBy: ":").first ?? name } } public struct SocialAccount: Codable, Sendable, Identifiable, Hashable { public enum Platform: String, Codable, Sendable, CaseIterable { case youtube, substack, linkedin, x, instagram, github } public var id: String public var platform: Platform public var handle: String /// "Newsletter (Substack)", "LinkedIn (company page)": the platform as shown. public var label: String? public var url: URL? /// "followers" or "subscribers". public var unit: String? /// How the count arrives: "api" (fetched every refresh) or "manual" (an agent or hand entry records it). public var source: String? public init(id: String, platform: Platform, handle: String) { self.id = id; self.platform = platform; self.handle = handle } public var title: String { label ?? platform.rawValue.capitalized } } public struct Review: Codable, Sendable, Identifiable, Hashable { public var id: String // Apple's review ID public var appID: String public var appName: String public var country: String public var stars: Int public var title: String public var text: String public var version: String public var author: String public var date: String // YYYY-MM-DD the review was written or updated public var firstSeen: String public var url: String public init(id: String, appID: String, appName: String, country: String, stars: Int, title: String, text: String, version: String, author: String, date: String, firstSeen: String, url: String) { self.id = id; self.appID = appID; self.appName = appName; self.country = country; self.stars = stars; self.title = title self.text = text; self.version = version; self.author = author; self.date = date; self.firstSeen = firstSeen; self.url = url } } /// An OpenTalon to-do waiting to be created (OpenTalon wasn't reachable yet). public struct ReviewTodo: Codable, Sendable, Hashable { public var key: String // appstore-review-- public var board: String public var title: String public var notes: String public var priority: String public var due: String? public init(key: String, board: String, title: String, notes: String, priority: String, due: String?) { self.key = key; self.board = board; self.title = title; self.notes = notes; self.priority = priority; self.due = due } } public struct AdCampaign: Codable, Sendable, Identifiable, Hashable { public var id: String public var platform: String // "Google Ads", "LinkedIn", "Apple Ads" public var name: String public var budget: String? public var start: String? public var end: String? public var paused: String? /// "Expired" for every campaign since the owner stopped all ads on 2026-11-22. public var status: String public var expired: String? public var landing: String? public init(id: String, platform: String, name: String, status: String) { self.id = id; self.platform = platform; self.name = name; self.status = status } } public struct Video: Codable, Sendable, Identifiable, Hashable { public var id: String // YouTube video ID public var account: String // SocialAccount ID public var title: String public var kind: String // "video", "short", "live" public var published: String? public var url: String public init(id: String, account: String, title: String, kind: String, published: String?, url: String) { self.id = id; self.account = account; self.title = title; self.kind = kind; self.published = published; self.url = url } } public struct Caveat: Codable, Sendable, Identifiable, Hashable { public var id: String public var text: String /// Sites or apps the note is about; empty means the whole portfolio. public var subjects: [String] /// The days it covers, when it is about a span (a tracking gap). public var from: String? public var to: String? public init(id: String, text: String, subjects: [String] = [], from: String? = nil, to: String? = nil) { self.id = id; self.text = text; self.subjects = subjects; self.from = from; self.to = to } } /// The metrics the app can chart. Each maps to a GA4 metric or an App Store report column. public enum Metric: String, Codable, Sendable, CaseIterable { case users, newUsers, sessions, pageViews, engagedSessions case keyEvent // a GA4 key event, named in `Widget.event` case appDownloads, appRedownloads case followers case rating // average stars (weighted across storefronts) case ratingCount case searchClicks, searchImpressions, searchPosition // `event` is the engine: "google" or "bing" case videoViews, videoLikes // subject is a YouTube video ID case adSpend, adClicks, adImpressions, adConversions // subject is an AdCampaign ID public var title: String { switch self { case .users: "Visitors" case .newUsers: "New visitors" case .sessions: "Sessions" case .pageViews: "Page views" case .engagedSessions: "Engaged sessions" case .keyEvent: "Key event" case .appDownloads: "App Store downloads" case .appRedownloads: "Redownloads" case .followers: "Followers" case .rating: "Rating" case .ratingCount: "Ratings" case .searchClicks: "Search clicks" case .searchImpressions: "Search impressions" case .searchPosition: "Average position" case .videoViews: "Video views" case .videoLikes: "Video likes" case .adSpend: "Ad spend" case .adClicks: "Ad clicks" case .adImpressions: "Ad impressions" case .adConversions: "Conversions" } } public var ga4Name: String? { switch self { case .users: "activeUsers" case .newUsers: "newUsers" case .sessions: "sessions" case .pageViews: "screenPageViews" case .engagedSessions: "engagedSessions" case .keyEvent: "eventCount" default: nil } } } /// One value for one day. `subject` is a site ID, an app ID or a social account ID; `breakdown` is an /// optional "family:value" dimension (a page path, a platform such as "iPhone", a channel group). /// Families in `DataPoint.windowFamilies` hold totals for a recent window (the last 30 days), stored on the /// last day; a refresh replaces the whole family. The others are per day. public struct DataPoint: Codable, Sendable, Hashable { public var day: String // YYYY-MM-DD, in the site's GA4 time zone public var subject: String public var metric: Metric public var breakdown: String? public var event: String? public var value: Double public init(day: String, subject: String, metric: Metric, breakdown: String? = nil, event: String? = nil, value: Double) { self.day = day; self.subject = subject; self.metric = metric; self.breakdown = breakdown; self.event = event; self.value = value } /// Window totals (last 30 days unless the family says otherwise): pages, channels, sources, detail /// breakdowns, search queries and pages, ratings by country, last-30 vs previous-30 summaries. public static let windowFamilies: Set = ["page", "channel", "source", "section", "domain", "scroll", "form", "field", "video", "file", "cta", "step", "query", "spage", "country", "period", "ailanding"] public var family: String { breakdown.map { String($0.prefix { $0 != ":" }) } ?? "" } public var breakdownValue: String? { breakdown.map { String($0.drop { $0 != ":" }.dropFirst()) } } public var isWindow: Bool { Self.windowFamilies.contains(family) } /// What a refresh replaces together: one subject's metric, breakdown family and (except key events, which are /// all pulled at once) event. public var mergeKey: String { "\(subject)|\(metric.rawValue)|\(family)|\(metric == .keyEvent ? "" : event ?? "")" } } public struct Dashboard: Codable, Sendable, Identifiable, Hashable { public var id: String public var name: String public var widgets: [Widget] public init(id: String, name: String, widgets: [Widget]) { self.id = id; self.name = name; self.widgets = widgets } public static let starter = Dashboard(id: "main", name: "My dashboard", widgets: [ Widget(id: "visitors", title: "Visitors, all sites", kind: .area, metric: .users, subjects: [], days: 30), Widget(id: "downloads", title: "App Store downloads", kind: .stackedBars, metric: .appDownloads, subjects: [], days: 30, breakdown: "platform"), Widget(id: "topsites", title: "Top sites this month", kind: .ranking, metric: .users, subjects: [], days: 30) ]) } public struct Widget: Codable, Sendable, Identifiable, Hashable { public enum Kind: String, Codable, Sendable, CaseIterable { case number, area, line, stackedArea, stackedBars, ranking, table /// Portfolio widgets: each draws one section of the old Portfolio Analytics dashboard. case kpiRow, siteScorecard, appPlatforms, ratings, downloadButtons, breakdown, aiVisits, siteDetail, search, followers, videos, ads, funnel, notes } public var id: String public var title: String public var kind: Kind public var metric: Metric /// Site, app or account IDs. Empty means all. public var subjects: [String] public var days: Int public var breakdown: String? public var event: String? /// Takes the whole row (tables). Narrow widgets sit two to a row on Mac and iPad. public var wide: Bool? /// Widget-specific list: tiles for kpiRow, event names for downloadButtons. public var items: [String]? public var subtitle: String? public init(id: String, title: String, kind: Kind, metric: Metric, subjects: [String], days: Int, breakdown: String? = nil, event: String? = nil) { self.id = id; self.title = title; self.kind = kind; self.metric = metric; self.subjects = subjects; self.days = days; self.breakdown = breakdown; self.event = event } } /// A change an agent made through MCP, shown in the Agents screen so the user can review it. public struct AgentAction: Codable, Sendable, Identifiable, Hashable { public var id = UUID() public var at = Date() public var client: String // "Claude Code", "Codex" public var tool: String public var summary: String public init(client: String, tool: String, summary: String) { self.client = client; self.tool = tool; self.summary = summary } } /// What the iPhone sees: the workspace minus settings and log, plus the last 90 days of data. public struct Snapshot: Codable, Sendable, Equatable { public var refreshedAt: Date public var sites: [Site] public var apps: [StoreApp] public var socials: [SocialAccount] public var dashboards: [Dashboard] public var points: [DataPoint] public var reviews: [Review]? public var campaigns: [AdCampaign]? public var videos: [Video]? public var caveats: [Caveat]? public init(refreshedAt: Date, sites: [Site], apps: [StoreApp], socials: [SocialAccount], dashboards: [Dashboard], points: [DataPoint], reviews: [Review]? = nil, campaigns: [AdCampaign]? = nil, videos: [Video]? = nil, caveats: [Caveat]? = nil) { self.refreshedAt = refreshedAt; self.sites = sites; self.apps = apps; self.socials = socials; self.dashboards = dashboards; self.points = points self.reviews = reviews; self.campaigns = campaigns; self.videos = videos; self.caveats = caveats } } public extension Array where Element == DataPoint { /// Daily totals for one metric, oldest first, with missing days filled with zero. func daily(_ metric: Metric, subjects: Set = [], days: [String]) -> [Double] { var byDay: [String: Double] = [:] for p in self where p.metric == metric && p.breakdown == nil && (subjects.isEmpty || subjects.contains(p.subject)) { byDay[p.day, default: 0] += p.value } return days.map { byDay[$0] ?? 0 } } /// Mac installer downloads from an app's website per day, or nil when the app has no website download. func websiteDownloads(_ app: StoreApp, days: [String]) -> [Double]? { guard let site = app.siteID, (app.platforms ?? []).contains("Mac (website)") else { return nil } var byDay: [String: Double] = [:] for p in self where p.subject == site && p.metric == .keyEvent && p.event == "mac_installer_download" && p.breakdown == nil { byDay[p.day, default: 0] += p.value } return days.map { byDay[$0] ?? 0 } } /// Every download of one app per day: App Store first-time downloads plus Mac installers from its website, /// so apps without an App Store listing count too. func appDownloads(_ app: StoreApp, days: [String]) -> [Double] { let store = app.hasAppStoreListing ? daily(.appDownloads, subjects: [app.id], days: days) : days.map { _ in 0 } guard let web = websiteDownloads(app, days: days) else { return store } return zip(store, web).map(+) } } public enum DayKey { public static func string(_ date: Date, calendar: Calendar = .current) -> String { let c = calendar.dateComponents([.year, .month, .day], from: date) return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0) } /// The last `count` days ending yesterday (GA4 data for today is partial). public static func lastDays(_ count: Int, endingBefore now: Date = .now, calendar: Calendar = .current) -> [String] { (1...max(1, count)).reversed().compactMap { calendar.date(byAdding: .day, value: -$0, to: now) }.map { string($0, calendar: calendar) } } }