import Foundation import AnalyticsKit /// Everything a dashboard reads, the same on the Mac (local store) and the iPhone and iPad (iCloud snapshot). /// Points are indexed by subject and metric once, so a dashboard with many widgets stays quick. public struct PortfolioData { public var sites: [Site] public var apps: [StoreApp] public var socials: [SocialAccount] public var reviews: [Review] public var campaigns: [AdCampaign] public var videos: [Video] public var caveats: [Caveat] let bySubject: [String: [DataPoint]] let byMetric: [Metric: [DataPoint]] public init(sites: [Site], apps: [StoreApp], socials: [SocialAccount], points: [DataPoint], reviews: [Review]? = nil, campaigns: [AdCampaign]? = nil, videos: [Video]? = nil, caveats: [Caveat]? = nil) { self.sites = sites.filter { !$0.archived }; self.apps = apps; self.socials = socials self.reviews = reviews ?? []; self.campaigns = campaigns ?? []; self.videos = videos ?? []; self.caveats = caveats ?? [] bySubject = Dictionary(grouping: points) { "\($0.subject)|\($0.metric.rawValue)" } byMetric = Dictionary(grouping: points, by: \.metric) } public init(snapshot s: Snapshot) { self.init(sites: s.sites, apps: s.apps, socials: s.socials, points: s.points, reviews: s.reviews, campaigns: s.campaigns, videos: s.videos, caveats: s.caveats) } func points(_ metric: Metric, _ subject: String) -> [DataPoint] { bySubject["\(subject)|\(metric.rawValue)"] ?? [] } func points(_ metric: Metric, subjects: [String]?) -> [DataPoint] { guard let subjects else { return byMetric[metric] ?? [] } return subjects.flatMap { points(metric, $0) } } /// Daily values (no breakdown), oldest first. `events` filters key events; `engine` filters search metrics. func daily(_ metric: Metric, subjects: [String]? = nil, days: [String], events: Set? = nil, engine: String? = nil) -> [Double] { var byDay: [String: Double] = [:] for p in points(metric, subjects: subjects) where p.breakdown == nil && Self.matches(p, events: events, engine: engine) { byDay[p.day, default: 0] += p.value } return days.map { byDay[$0] ?? 0 } } func sum(_ metric: Metric, subjects: [String]? = nil, days: [String], events: Set? = nil, engine: String? = nil) -> Double { daily(metric, subjects: subjects, days: days, events: events, engine: engine).reduce(0, +) } /// Daily values of a daily breakdown family ("platform", "ai"), keyed by its value. func dailyFamily(_ metric: Metric, family: String, subjects: [String]? = nil, days: [String], events: Set? = nil) -> [String: [Double]] { let index = Dictionary(uniqueKeysWithValues: days.enumerated().map { ($1, $0) }) var out: [String: [Double]] = [:] for p in points(metric, subjects: subjects) where p.family == family && Self.matches(p, events: events, engine: nil) { guard let i = index[p.day], let v = p.breakdownValue else { continue } out[v, default: Array(repeating: 0, count: days.count)][i] += p.value } return out } /// The newest window totals of a family for each subject (top pages, channels, sections…). func window(_ metric: Metric, family: String, subject: String, events: Set? = nil, engine: String? = nil) -> [(label: String, event: String?, value: Double)] { let all = points(metric, subject).filter { $0.family == family && Self.matches($0, events: events, engine: engine) } guard let newest = all.map(\.day).max() else { return [] } return all.filter { $0.day == newest }.map { ($0.breakdownValue ?? "", $0.event, $0.value) } } /// Sums a window family across subjects by label. `prefix` names the site in front when it helps. func windowTotals(_ metric: Metric, family: String, subjects: [String], events: Set? = nil, engine: String? = nil, label: (String, String?, String) -> String = { l, _, _ in l }) -> [(String, Double)] { var totals: [String: Double] = [:] for s in subjects { for r in window(metric, family: family, subject: s, events: events, engine: engine) { totals[label(r.label, r.event, s), default: 0] += r.value } } return totals.sorted { $0.value > $1.value }.map { ($0.key, $0.value) } } static func matches(_ p: DataPoint, events: Set?, engine: String?) -> Bool { if let events, !events.contains(p.event ?? "") { return false } if let engine, p.event != engine { return false } return true } /// Unique visitors for the last 30 days and the 30 before. GA4's own 30-day counts when the refresh has them /// (a returning visitor counts once), otherwise the sum of daily visitors. func visitors(_ subject: String) -> (current: Double, previous: Double) { let period = window(.users, family: "period", subject: subject) if let cur = period.first(where: { $0.label == "last_30" }) { return (cur.value, period.first(where: { $0.label == "prev_30" })?.value ?? 0) } let all = DayKey.lastDays(60) return (sum(.users, subjects: [subject], days: Array(all.suffix(30))), sum(.users, subjects: [subject], days: Array(all.prefix(30)))) } /// The newest value of a once-a-day reading (followers, ratings), and the value about `daysAgo` before it. func latest(_ metric: Metric, _ subject: String, daysAgo: Int = 30) -> (value: Double, previous: Double?, day: String)? { let list = points(metric, subject).filter { $0.breakdown == nil }.sorted { $0.day < $1.day } guard let last = list.last else { return nil } let cutoff = DayKey.lastDays(daysAgo, endingBefore: TrendChartDay.date(last.day).addingTimeInterval(86_400)).first ?? last.day let before = list.last { $0.day <= cutoff } ?? (list.count > 1 ? list.first : nil) return (last.value, before?.value, last.day) } /// One value per day for a reading, carried forward over days with none. func carried(_ metric: Metric, _ subject: String, days: [String]) -> [Double] { let byDay = Dictionary(points(metric, subject).filter { $0.breakdown == nil }.map { ($0.day, $0.value) }, uniquingKeysWith: { _, b in b }) var last = points(metric, subject).filter { $0.breakdown == nil && $0.day < (days.first ?? "") }.max { $0.day < $1.day }?.value ?? 0 return days.map { d in if let v = byDay[d] { last = v }; return last } } public func site(_ id: String) -> Site? { sites.first { $0.id == id } } func name(_ id: String) -> String { site(id)?.name ?? apps.first { $0.id == id }?.name ?? id } } enum TrendChartDay { static func date(_ s: String) -> Date { ISO8601DateFormatter.day.date(from: s) ?? .now } }