Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / AnalyticsReport.swift
| 1 | import CoreFoundation |
| 2 | import Foundation |
| 3 | |
| 4 | struct AnalyticsReport { |
| 5 | enum Metric: String, CaseIterable, Identifiable { |
| 6 | case engagement, likes, replies, shares, views, score |
| 7 | var id: String { rawValue } |
| 8 | |
| 9 | func label(for platform: SocialPlatform) -> String { |
| 10 | switch self { |
| 11 | case .engagement: "Interactions" |
| 12 | case .likes: "Likes" |
| 13 | case .replies: "Replies" |
| 14 | case .shares: "Shares" |
| 15 | case .views: "Views" |
| 16 | case .score: "Net score" |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | struct Followers: Identifiable { |
| 22 | let at: Date |
| 23 | let count: Int |
| 24 | let accountPosts: Int? |
| 25 | var id: Date { at } |
| 26 | } |
| 27 | |
| 28 | struct Activity: Identifiable { |
| 29 | let day: Date |
| 30 | let count: Int |
| 31 | var id: Date { day } |
| 32 | } |
| 33 | |
| 34 | struct Post: Identifiable { |
| 35 | let record: WorkspaceRecord |
| 36 | let publishedAt: Date |
| 37 | var id: String { record.id } |
| 38 | var observedAt: Date? { scheduleDate(record["observedAt"]) } |
| 39 | |
| 40 | func value(_ metric: Metric) -> Double? { |
| 41 | if metric == .engagement { |
| 42 | return AnalyticsReport.sum([.likes, .replies, .shares].compactMap(value)) |
| 43 | } |
| 44 | let values = record.fields["metrics"] as? [String: Any] |
| 45 | return AnalyticsReport.integerMetric(values?[metric.rawValue], signed: metric == .score).map(Double.init) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | let latestFollowers: Followers? |
| 50 | let followers: [Followers] |
| 51 | let growth: Double? |
| 52 | let posts: [Post] |
| 53 | let oldestPostAt: Date? |
| 54 | let activity: [Activity] |
| 55 | let confirmedCount: Int |
| 56 | let replyCount: Int |
| 57 | |
| 58 | init(records: [WorkspaceRecord], platform: SocialPlatform, accountID: String?, days: Int, sort: Metric, |
| 59 | now: Date = .now) { |
| 60 | let cutoff = days == 0 ? Date.distantPast : now.addingTimeInterval(-Double(days) * 86_400) |
| 61 | let selected = records.filter { |
| 62 | $0["platform"] == platform.rawValue && $0["accountId"] == accountID |
| 63 | } |
| 64 | var observed: [Date: Followers] = [:] |
| 65 | for record in selected where record.kind == "analytics-day" { |
| 66 | for key in ["first", "last"] { |
| 67 | guard let snapshot = record.fields[key] as? [String: Any], let raw = snapshot["at"] as? String, |
| 68 | let date = scheduleDate(raw), let count = Self.integerMetric(snapshot["followers"]) else { continue } |
| 69 | observed[date] = Followers(at: date, count: count, accountPosts: Self.integerMetric(snapshot["accountPosts"])) |
| 70 | } |
| 71 | } |
| 72 | let history = observed.values.sorted { $0.at < $1.at } |
| 73 | latestFollowers = history.last |
| 74 | followers = history.filter { $0.at >= cutoff } |
| 75 | if followers.count > 1, let first = followers.first, let last = followers.last { |
| 76 | growth = Double(last.count) - Double(first.count) |
| 77 | } else { |
| 78 | growth = nil |
| 79 | } |
| 80 | |
| 81 | posts = selected.compactMap { row in |
| 82 | guard row.kind == "analytics-post", let date = scheduleDate(row["publishedAt"]), date >= cutoff else { return nil } |
| 83 | return Post(record: row, publishedAt: date) |
| 84 | }.sorted { a, b in |
| 85 | let left = a.value(sort) ?? -.infinity |
| 86 | let right = b.value(sort) ?? -.infinity |
| 87 | if left != right { return left > right } |
| 88 | return a.publishedAt == b.publishedAt ? a.id < b.id : a.publishedAt > b.publishedAt |
| 89 | } |
| 90 | oldestPostAt = posts.map(\.publishedAt).min() |
| 91 | |
| 92 | let receipts = Self.receipts(selected).values.filter { $0.date >= cutoff } |
| 93 | confirmedCount = receipts.count |
| 94 | replyCount = receipts.filter(\.reply).count |
| 95 | var utc = Calendar(identifier: .gregorian) |
| 96 | utc.timeZone = TimeZone(secondsFromGMT: 0)! |
| 97 | activity = Dictionary(grouping: receipts) { utc.startOfDay(for: $0.date) } |
| 98 | .map { Activity(day: $0.key, count: $0.value.count) }.sorted { $0.day < $1.day } |
| 99 | } |
| 100 | |
| 101 | func total(_ metric: Metric) -> (value: Double?, covered: Int) { |
| 102 | let values = posts.compactMap { $0.value(metric) } |
| 103 | return (Self.sum(values), values.count) |
| 104 | } |
| 105 | |
| 106 | static func allConfirmed(_ records: [WorkspaceRecord]) -> Int { receipts(records).count } |
| 107 | |
| 108 | static func integerMetric(_ raw: Any?, signed: Bool = false) -> Int? { |
| 109 | guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil } |
| 110 | let value = number.doubleValue |
| 111 | let maximum = 9_007_199_254_740_991.0 |
| 112 | guard ((signed ? -maximum : 0)...maximum).contains(value) else { return nil } |
| 113 | return Int(exactly: value) |
| 114 | } |
| 115 | |
| 116 | private struct Receipt: Hashable { |
| 117 | let platform: String |
| 118 | let account: String |
| 119 | let post: String |
| 120 | } |
| 121 | |
| 122 | private static func receipts(_ records: [WorkspaceRecord]) -> [Receipt: (date: Date, reply: Bool)] { |
| 123 | var confirmed: [Receipt: (date: Date, reply: Bool)] = [:] |
| 124 | for row in records where row.kind == "publication" { |
| 125 | let fallback = scheduleDate(row["publishedAt"]) ?? scheduleDate(row["createdAt"]) |
| 126 | var steps = row.fields["steps"] as? [[String: Any]] ?? [] |
| 127 | if steps.isEmpty && row["status"] == "published" { steps = [["id": row.id]] } |
| 128 | for step in steps { |
| 129 | guard let post = step["id"] as? String, !post.isEmpty, |
| 130 | let date = (step["at"] as? String).flatMap(scheduleDate) ?? fallback else { continue } |
| 131 | let key = Receipt(platform: row["platform"], account: row["accountId"], post: post) |
| 132 | if let existing = confirmed[key] { |
| 133 | confirmed[key] = (min(date, existing.date), existing.reply || !row["replyToId"].isEmpty) |
| 134 | } else { |
| 135 | confirmed[key] = (date, !row["replyToId"].isEmpty) |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | return confirmed |
| 140 | } |
| 141 | |
| 142 | private static func sum(_ values: [Double]) -> Double? { |
| 143 | let sum = values.reduce(0, +) |
| 144 | return !values.isEmpty && sum.isFinite ? sum : nil |
| 145 | } |
| 146 | } |