Graphley / app · graphley.ai / Sources / AnalyticsUI / PortfolioData.swift
| 1 | import Foundation |
| 2 | import AnalyticsKit |
| 3 | |
| 4 | /// Everything a dashboard reads, the same on the Mac (local store) and the iPhone and iPad (iCloud snapshot). |
| 5 | /// Points are indexed by subject and metric once, so a dashboard with many widgets stays quick. |
| 6 | public struct PortfolioData { |
| 7 | public var sites: [Site] |
| 8 | public var apps: [StoreApp] |
| 9 | public var socials: [SocialAccount] |
| 10 | public var reviews: [Review] |
| 11 | public var campaigns: [AdCampaign] |
| 12 | public var videos: [Video] |
| 13 | public var caveats: [Caveat] |
| 14 | let bySubject: [String: [DataPoint]] |
| 15 | let byMetric: [Metric: [DataPoint]] |
| 16 | |
| 17 | public init(sites: [Site], apps: [StoreApp], socials: [SocialAccount], points: [DataPoint], reviews: [Review]? = nil, |
| 18 | campaigns: [AdCampaign]? = nil, videos: [Video]? = nil, caveats: [Caveat]? = nil) { |
| 19 | self.sites = sites.filter { !$0.archived }; self.apps = apps; self.socials = socials |
| 20 | self.reviews = reviews ?? []; self.campaigns = campaigns ?? []; self.videos = videos ?? []; self.caveats = caveats ?? [] |
| 21 | bySubject = Dictionary(grouping: points) { "\($0.subject)|\($0.metric.rawValue)" } |
| 22 | byMetric = Dictionary(grouping: points, by: \.metric) |
| 23 | } |
| 24 | |
| 25 | public init(snapshot s: Snapshot) { |
| 26 | 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) |
| 27 | } |
| 28 | |
| 29 | func points(_ metric: Metric, _ subject: String) -> [DataPoint] { bySubject["\(subject)|\(metric.rawValue)"] ?? [] } |
| 30 | func points(_ metric: Metric, subjects: [String]?) -> [DataPoint] { |
| 31 | guard let subjects else { return byMetric[metric] ?? [] } |
| 32 | return subjects.flatMap { points(metric, $0) } |
| 33 | } |
| 34 | |
| 35 | /// Daily values (no breakdown), oldest first. `events` filters key events; `engine` filters search metrics. |
| 36 | func daily(_ metric: Metric, subjects: [String]? = nil, days: [String], events: Set<String>? = nil, engine: String? = nil) -> [Double] { |
| 37 | var byDay: [String: Double] = [:] |
| 38 | 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 } |
| 39 | return days.map { byDay[$0] ?? 0 } |
| 40 | } |
| 41 | |
| 42 | func sum(_ metric: Metric, subjects: [String]? = nil, days: [String], events: Set<String>? = nil, engine: String? = nil) -> Double { |
| 43 | daily(metric, subjects: subjects, days: days, events: events, engine: engine).reduce(0, +) |
| 44 | } |
| 45 | |
| 46 | /// Daily values of a daily breakdown family ("platform", "ai"), keyed by its value. |
| 47 | func dailyFamily(_ metric: Metric, family: String, subjects: [String]? = nil, days: [String], events: Set<String>? = nil) -> [String: [Double]] { |
| 48 | let index = Dictionary(uniqueKeysWithValues: days.enumerated().map { ($1, $0) }) |
| 49 | var out: [String: [Double]] = [:] |
| 50 | for p in points(metric, subjects: subjects) where p.family == family && Self.matches(p, events: events, engine: nil) { |
| 51 | guard let i = index[p.day], let v = p.breakdownValue else { continue } |
| 52 | out[v, default: Array(repeating: 0, count: days.count)][i] += p.value |
| 53 | } |
| 54 | return out |
| 55 | } |
| 56 | |
| 57 | /// The newest window totals of a family for each subject (top pages, channels, sections…). |
| 58 | func window(_ metric: Metric, family: String, subject: String, events: Set<String>? = nil, engine: String? = nil) -> [(label: String, event: String?, value: Double)] { |
| 59 | let all = points(metric, subject).filter { $0.family == family && Self.matches($0, events: events, engine: engine) } |
| 60 | guard let newest = all.map(\.day).max() else { return [] } |
| 61 | return all.filter { $0.day == newest }.map { ($0.breakdownValue ?? "", $0.event, $0.value) } |
| 62 | } |
| 63 | |
| 64 | /// Sums a window family across subjects by label. `prefix` names the site in front when it helps. |
| 65 | func windowTotals(_ metric: Metric, family: String, subjects: [String], events: Set<String>? = nil, engine: String? = nil, |
| 66 | label: (String, String?, String) -> String = { l, _, _ in l }) -> [(String, Double)] { |
| 67 | var totals: [String: Double] = [:] |
| 68 | 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 } } |
| 69 | return totals.sorted { $0.value > $1.value }.map { ($0.key, $0.value) } |
| 70 | } |
| 71 | |
| 72 | static func matches(_ p: DataPoint, events: Set<String>?, engine: String?) -> Bool { |
| 73 | if let events, !events.contains(p.event ?? "") { return false } |
| 74 | if let engine, p.event != engine { return false } |
| 75 | return true |
| 76 | } |
| 77 | |
| 78 | /// Unique visitors for the last 30 days and the 30 before. GA4's own 30-day counts when the refresh has them |
| 79 | /// (a returning visitor counts once), otherwise the sum of daily visitors. |
| 80 | func visitors(_ subject: String) -> (current: Double, previous: Double) { |
| 81 | let period = window(.users, family: "period", subject: subject) |
| 82 | if let cur = period.first(where: { $0.label == "last_30" }) { |
| 83 | return (cur.value, period.first(where: { $0.label == "prev_30" })?.value ?? 0) |
| 84 | } |
| 85 | let all = DayKey.lastDays(60) |
| 86 | return (sum(.users, subjects: [subject], days: Array(all.suffix(30))), sum(.users, subjects: [subject], days: Array(all.prefix(30)))) |
| 87 | } |
| 88 | |
| 89 | /// The newest value of a once-a-day reading (followers, ratings), and the value about `daysAgo` before it. |
| 90 | func latest(_ metric: Metric, _ subject: String, daysAgo: Int = 30) -> (value: Double, previous: Double?, day: String)? { |
| 91 | let list = points(metric, subject).filter { $0.breakdown == nil }.sorted { $0.day < $1.day } |
| 92 | guard let last = list.last else { return nil } |
| 93 | let cutoff = DayKey.lastDays(daysAgo, endingBefore: TrendChartDay.date(last.day).addingTimeInterval(86_400)).first ?? last.day |
| 94 | let before = list.last { $0.day <= cutoff } ?? (list.count > 1 ? list.first : nil) |
| 95 | return (last.value, before?.value, last.day) |
| 96 | } |
| 97 | |
| 98 | /// One value per day for a reading, carried forward over days with none. |
| 99 | func carried(_ metric: Metric, _ subject: String, days: [String]) -> [Double] { |
| 100 | let byDay = Dictionary(points(metric, subject).filter { $0.breakdown == nil }.map { ($0.day, $0.value) }, uniquingKeysWith: { _, b in b }) |
| 101 | var last = points(metric, subject).filter { $0.breakdown == nil && $0.day < (days.first ?? "") }.max { $0.day < $1.day }?.value ?? 0 |
| 102 | return days.map { d in if let v = byDay[d] { last = v }; return last } |
| 103 | } |
| 104 | |
| 105 | public func site(_ id: String) -> Site? { sites.first { $0.id == id } } |
| 106 | func name(_ id: String) -> String { site(id)?.name ?? apps.first { $0.id == id }?.name ?? id } |
| 107 | } |
| 108 | |
| 109 | enum TrendChartDay { |
| 110 | static func date(_ s: String) -> Date { ISO8601DateFormatter.day.date(from: s) ?? .now } |
| 111 | } |