Open source CapCut alternative.
TypeScript
feat(ios): super-user analytics dashboard from the avatar menu
David Le7e59e2dd5127
diff --git a/apps/ios/Donkey/Controllers/AuthController.swift b/apps/ios/Donkey/Controllers/AuthController.swiftindex a6b73244..f6ee0013 100644--- a/apps/ios/Donkey/Controllers/AuthController.swift+++ b/apps/ios/Donkey/Controllers/AuthController.swift@@ -129,6 +129,7 @@ final class AuthController: NSObject, AuthServicing {}private func fetchProfile(token: String) async throws -> UserProfile {+ async let superUser = fetchSuperUser(token: token)var request = URLRequest(url: AuthBackend.baseURL.appending(path: "/api/auth/get-session"))request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")let (data, response) = try await URLSession.shared.data(for: request)@@ -147,7 +148,20 @@ final class AuthController: NSObject, AuthServicing {guard let user = try? JSONDecoder().decode(SessionResponse.self, from: data).user else {throw AuthError.server("Your session has expired. Sign in again.")}- return UserProfile(id: user.id, name: user.name ?? "", email: user.email)+ return UserProfile(id: user.id, name: user.name ?? "", email: user.email, superUser: await superUser)+ }++ /// The session payload carries identity only; /api/account/me carries the+ /// super-user bit. Best-effort: a failed read means a regular account+ /// until the next restore.+ private func fetchSuperUser(token: String) async -> Bool {+ var request = URLRequest(url: AuthBackend.baseURL.appending(path: "/api/account/me"))+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")+ guard let (data, response) = try? await URLSession.shared.data(for: request),+ let http = response as? HTTPURLResponse,+ (200..<300).contains(http.statusCode) else { return false }+ struct MeResponse: Decodable { var superUser: Bool? }+ return (try? JSONDecoder().decode(MeResponse.self, from: data))?.superUser == true}private static func serverMessage(from data: Data, status: Int) -> String {diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swiftindex 86cd8e63..2845b8c6 100644--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift@@ -398,6 +398,31 @@ extension CutCloudClient: CloudProjectsServicing {}}+// MARK: - Analytics++extension CutCloudClient: AnalyticsServicing {+ /// The nightly analytics rollup. The API serves it to super users only,+ /// so a regular account reads as unauthorized here.+ func fetchAnalyticsRollup() async throws -> AnalyticsRollup {+ let request = try request("GET", "/api/analytics/rollup")+ let data: Data+ let response: URLResponse+ do {+ (data, response) = try await URLSession.shared.data(for: request)+ } catch {+ throw CloudSyncError.transport+ }+ guard let http = response as? HTTPURLResponse else { throw CloudSyncError.transport }+ switch http.statusCode {+ case 200..<300: break+ case 404: throw AnalyticsError.noRollup+ case 401, 403: throw CloudSyncError.unauthorized+ default: throw CloudSyncError.transport+ }+ return try decode(AnalyticsRollup.self, from: data)+ }+}+// MARK: - Recording payloadsextension CutCloudClient {diff --git a/apps/ios/Donkey/DonkeyApp.swift b/apps/ios/Donkey/DonkeyApp.swiftindex 887d2ed4..6e88c6ce 100644--- a/apps/ios/Donkey/DonkeyApp.swift+++ b/apps/ios/Donkey/DonkeyApp.swift@@ -15,7 +15,8 @@ struct DonkeyApp: App {camera: wiring.camera,media: wiring.media,projects: wiring.projects,- auth: wiring.auth+ auth: wiring.auth,+ analytics: wiring.analytics) {CameraPreviewView(host: wiring.cameraController.previewView) {wiring.camera.toggleRecording()@@ -36,6 +37,7 @@ final class AppWiring {let media: MediaModellet projects: ProjectsModellet auth: AuthModel+ let analytics: AnalyticsModellet cameraController: CameraControllerlet sync: SyncEngineprivate let networkMonitor: NetworkMonitor@@ -69,6 +71,7 @@ final class AppWiring {self.auth = authself.sync = synccamera = CameraModel()+ analytics = AnalyticsModel(service: cloud)projects = ProjectsModel(service: cloud)cameraController = CameraController()networkMonitor = NetworkMonitor { sync.network = $0 }diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swiftnew file mode 100644index 00000000..3af90331--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift@@ -0,0 +1,287 @@+import Foundation++/// The nightly analytics rollup as /api/analytics/rollup serves it, pared to+/// the fields the phone renders.+nonisolated public struct AnalyticsRollup: Decodable, Sendable {+ nonisolated public struct MissingEntry: Decodable, Sendable {+ public var day: String++ public init(day: String) {+ self.day = day+ }+ }++ nonisolated public struct User: Decodable, Sendable {+ public var registeredAt: String+ public var balanceMicros: String+ /// One source bitmask per entry of `days`.+ public var activity: [Int]++ public init(registeredAt: String, balanceMicros: String, activity: [Int]) {+ self.registeredAt = registeredAt+ self.balanceMicros = balanceMicros+ self.activity = activity+ }+ }++ nonisolated public struct Billing: Decodable, Sendable {+ nonisolated public struct Revenue: Decodable, Sendable {+ public var proMicros: String+ public var topupMicros: String++ public init(proMicros: String, topupMicros: String) {+ self.proMicros = proMicros+ self.topupMicros = topupMicros+ }+ }++ public var subscribers: Int+ public var canceling: Int+ public var funded: Int+ public var fundedMicros: String+ /// Per-day paid charges, aligned with `days`.+ public var revenue: [Revenue]++ public init(subscribers: Int, canceling: Int, funded: Int, fundedMicros: String, revenue: [Revenue]) {+ self.subscribers = subscribers+ self.canceling = canceling+ self.funded = funded+ self.fundedMicros = fundedMicros+ self.revenue = revenue+ }+ }++ public var generatedAt: String+ /// Oldest → newest; every user's activity array aligns with this.+ public var days: [String]+ /// Bit order of the activity masks.+ public var sources: [String]+ /// Days the consolidation could not read; their counts are unknown.+ public var missing: [MissingEntry]+ /// Absent from rollups written before billing shipped.+ public var billing: Billing?+ public var users: [User]++ public init(+ generatedAt: String,+ days: [String],+ sources: [String],+ missing: [MissingEntry],+ billing: Billing?,+ users: [User]+ ) {+ self.generatedAt = generatedAt+ self.days = days+ self.sources = sources+ self.missing = missing+ self.billing = billing+ self.users = users+ }+}++/// The rollup reduced to what the dashboard draws: one point per day plus the+/// headline numbers. Pure derivation, mirrored from the web dashboard.+nonisolated public struct AnalyticsSummary: Sendable, Equatable {+ nonisolated public struct DayPoint: Sendable, Equatable, Identifiable {+ public var day: Date+ /// Nil on a day without an extract: unknown, not zero.+ public var active: Int?+ /// Actives narrowed to the DB event sources — did something, not just opened the app.+ public var working: Int?+ public var signups: Int+ public var totalRegistered: Int+ public var proDollars: Double+ public var topupDollars: Double++ public var id: Date { day }+ public var revenueDollars: Double { proDollars + topupDollars }++ public init(+ day: Date,+ active: Int?,+ working: Int?,+ signups: Int,+ totalRegistered: Int,+ proDollars: Double,+ topupDollars: Double+ ) {+ self.day = day+ self.active = active+ self.working = working+ self.signups = signups+ self.totalRegistered = totalRegistered+ self.proDollars = proDollars+ self.topupDollars = topupDollars+ }+ }++ public var points: [DayPoint]+ public var registered: Int+ public var signups7d: Int+ public var signupsWindow: Int+ public var activeYesterday: Int?+ public var active7d: Int?+ /// Active last 7 days against the prior 7; nil without a baseline.+ public var weekDeltaPercent: Double?+ public var balanceDollars: Double+ public var subscribers: Int?+ public var canceling: Int?+ public var funded: Int?+ public var fundedDollars: Double?+ /// Paid charges across the window; nil when the rollup predates billing.+ public var revenueDollars: Double?+ public var missingDayCount: Int+ public var generatedAt: Date?++ public init(rollup: AnalyticsRollup) {+ // Any source bit marks a day active; the DB sources mark it working.+ let workBits = rollup.sources.enumerated().reduce(0) { mask, entry in+ entry.element == "posthog" ? mask : mask | (1 << entry.offset)+ }+ let missingDays = Set(rollup.missing.map(\.day))++ var signupsByDay: [String: Int] = [:]+ for user in rollup.users {+ signupsByDay[String(user.registeredAt.prefix(10)), default: 0] += 1+ }++ // Cumulative registrations start from everyone who signed up before+ // the window, so the total line carries the real base.+ let firstDay = rollup.days.first ?? ""+ var totalRegistered = rollup.users.filter { String($0.registeredAt.prefix(10)) < firstDay }.count++ var points: [DayPoint] = []+ for (i, day) in rollup.days.enumerated() {+ let signups = signupsByDay[day] ?? 0+ totalRegistered += signups+ var active: Int?+ var working: Int?+ if !missingDays.contains(day) {+ var visited = 0+ var worked = 0+ for user in rollup.users {+ let mask = i < user.activity.count ? user.activity[i] : 0+ if mask != 0 { visited += 1 }+ if mask & workBits != 0 { worked += 1 }+ }+ active = visited+ working = worked+ }+ let revenue = rollup.billing.flatMap { $0.revenue.indices.contains(i) ? $0.revenue[i] : nil }+ points.append(DayPoint(+ day: Self.date(fromDay: day),+ active: active,+ working: working,+ signups: signups,+ totalRegistered: totalRegistered,+ proDollars: Self.dollars(fromMicros: revenue?.proMicros ?? "0"),+ topupDollars: Self.dollars(fromMicros: revenue?.topupMicros ?? "0")+ ))+ }++ // Counts users active on any known day in the range; nil when the+ // whole range went unextracted.+ let activeInRange = { (from: Int, to: Int) -> Int? in+ let known = (max(0, from)..<max(0, to)).filter { !missingDays.contains(rollup.days[$0]) }+ guard !known.isEmpty else { return nil }+ return rollup.users.filter { user in+ known.contains { ($0 < user.activity.count ? user.activity[$0] : 0) != 0 }+ }.count+ }++ let len = rollup.days.count+ let active7d = activeInRange(len - 7, len)+ let activePrior7d = activeInRange(len - 14, len - 7)++ self.points = points+ registered = rollup.users.count+ signups7d = rollup.days.suffix(7).reduce(0) { $0 + (signupsByDay[$1] ?? 0) }+ signupsWindow = points.reduce(0) { $0 + $1.signups }+ activeYesterday = points.last?.active ?? nil+ self.active7d = active7d+ weekDeltaPercent = if let active7d, let activePrior7d, activePrior7d > 0 {+ Double(active7d - activePrior7d) / Double(activePrior7d) * 100+ } else {+ nil+ }+ balanceDollars = rollup.users.reduce(0) { $0 + Self.dollars(fromMicros: $1.balanceMicros) }+ subscribers = rollup.billing?.subscribers+ canceling = rollup.billing?.canceling+ funded = rollup.billing?.funded+ fundedDollars = rollup.billing.map { Self.dollars(fromMicros: $0.fundedMicros) }+ revenueDollars = rollup.billing.map { _ in points.reduce(0) { $0 + $1.revenueDollars } }+ missingDayCount = missingDays.count+ generatedAt = Self.timestamp(from: rollup.generatedAt)+ }++ private static func dollars(fromMicros micros: String) -> Double {+ (Double(micros) ?? 0) / 1_000_000+ }++ /// "YYYY-MM-DD" as midnight UTC, matching the rollup's day keys.+ private static func date(fromDay day: String) -> Date {+ let parts = day.split(separator: "-").compactMap { Int($0) }+ var components = DateComponents()+ components.year = parts.count > 0 ? parts[0] : nil+ components.month = parts.count > 1 ? parts[1] : nil+ components.day = parts.count > 2 ? parts[2] : nil+ return utcCalendar.date(from: components) ?? .distantPast+ }++ private static let utcCalendar: Calendar = {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "UTC") ?? .current+ return calendar+ }()++ /// The rollup stamps milliseconds (JS toISOString).+ private static func timestamp(from string: String) -> Date? {+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ if let date = formatter.date(from: string) { return date }+ return ISO8601DateFormatter().date(from: string)+ }+}++nonisolated public enum AnalyticsError: Error, Equatable {+ /// The nightly job hasn't written a rollup yet.+ case noRollup+}++/// What the app target's CutCloudClient does for the analytics dashboard.+public protocol AnalyticsServicing: AnyObject {+ func fetchAnalyticsRollup() async throws -> AnalyticsRollup+}++@Observable+public final class AnalyticsModel {+ public enum State {+ case loading+ case loaded(AnalyticsSummary)+ /// The API answered but no rollup exists yet.+ case empty+ case failed+ }++ public private(set) var state: State = .loading++ private let service: any AnalyticsServicing++ public init(service: any AnalyticsServicing) {+ self.service = service+ }++ /// Fetches the rollup. A refresh over loaded data keeps the charts up+ /// while it runs and on failure; a first load surfaces the error.+ public func refresh() async {+ do {+ let rollup = try await service.fetchAnalyticsRollup()+ state = .loaded(AnalyticsSummary(rollup: rollup))+ } catch AnalyticsError.noRollup {+ state = .empty+ } catch {+ if case .loaded = state { return }+ state = .failed+ }+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swiftindex 4a124d7a..8bcaab19 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift@@ -33,6 +33,9 @@ public final class AppModel {/// A transient confirmation message ("Note saved"), cleared by the UI.public var toast: String?+ /// The super-user analytics dashboard, opened from the avatar menu.+ public var showsAnalytics = false+private let defaults: UserDefaultsprivate static let appearanceKey = "appearancePreference"private static let cellularKey = "syncOverCellular"diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swiftindex b91cd5b4..aa959bdd 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swift@@ -4,11 +4,23 @@ nonisolated public struct UserProfile: Equatable, Codable, Sendable {public var id: Stringpublic var name: Stringpublic var email: String+ /// Accounts with the operator role; gates the analytics dashboard.+ public var superUser: Bool- public init(id: String, name: String, email: String) {+ public init(id: String, name: String, email: String, superUser: Bool = false) {self.id = idself.name = nameself.email = email+ self.superUser = superUser+ }++ /// Profiles cached before the role field existed decode with it off.+ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ id = try container.decode(String.self, forKey: .id)+ name = try container.decode(String.self, forKey: .name)+ email = try container.decode(String.self, forKey: .email)+ superUser = try container.decodeIfPresent(Bool.self, forKey: .superUser) ?? false}public var initial: String {diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swiftnew file mode 100644index 00000000..f5e0d487--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift@@ -0,0 +1,320 @@+#if os(iOS)+import Charts+import DonkeyKitModels+import SwiftUI++/// The super-user dashboard: the nightly rollup as a stat grid and borderless+/// chart sections, opened from the avatar menu.+public struct AnalyticsScreen: View {+ var analytics: AnalyticsModel+ @Environment(\.dismiss) private var dismiss++ public init(analytics: AnalyticsModel) {+ self.analytics = analytics+ }++ public var body: some View {+ NavigationStack {+ Group {+ switch analytics.state {+ case .loading:+ ProgressView()+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ case .empty:+ EmptyState(+ title: "No data yet",+ message: "The nightly analytics job hasn't produced a rollup."+ )+ case .failed:+ EmptyState(+ title: "Couldn't load analytics",+ message: "Check your connection and try again.",+ actionTitle: "Retry"+ ) {+ Task { await analytics.refresh() }+ }+ case .loaded(let summary):+ SummaryList(summary: summary)+ .refreshable { await analytics.refresh() }+ }+ }+ .navigationTitle("Analytics")+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ Button("Done") { dismiss() }+ .fontWeight(.semibold)+ }+ }+ }+ .task { await analytics.refresh() }+ }+}++private struct SummaryList: View {+ let summary: AnalyticsSummary++ var body: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 0) {+ StatGrid(summary: summary)+ .padding(.vertical, 20)++ Divider()+ MetricSection(+ title: "Active users",+ value: summary.active7d.map { $0.formatted() } ?? "—",+ caption: activeCaption,+ deltaPercent: summary.weekDeltaPercent+ ) {+ ActiveChart(points: summary.points)+ }++ Divider()+ MetricSection(+ title: "Signups",+ value: summary.signupsWindow.formatted(),+ caption: "Last \(summary.points.count) days"+ ) {+ SignupsChart(points: summary.points)+ }++ if let revenueDollars = summary.revenueDollars {+ Divider()+ MetricSection(+ title: "Revenue",+ value: dollars(revenueDollars),+ caption: "Paid charges, last \(summary.points.count) days"+ ) {+ RevenueChart(points: summary.points)+ }+ }++ Divider()+ MetricSection(+ title: "Total registered",+ value: summary.registered.formatted(),+ caption: "Cumulative registrations"+ ) {+ RegisteredChart(points: summary.points)+ }++ if let generatedAt = summary.generatedAt {+ Text("From the nightly rollup generated \(generatedAt.formatted(date: .abbreviated, time: .shortened)).")+ .font(.caption)+ .foregroundStyle(.secondary)+ .padding(.vertical, 16)+ }+ }+ .padding(.horizontal, 20)+ }+ }++ private var activeCaption: String {+ let base = "Active in the last 7 days"+ guard summary.missingDayCount > 0 else { return base }+ return "\(base) · \(summary.missingDayCount) days without data"+ }+}++// MARK: - Stats++private struct StatGrid: View {+ let summary: AnalyticsSummary++ var body: some View {+ LazyVGrid(columns: [GridItem(.flexible(), alignment: .topLeading), GridItem(.flexible(), alignment: .topLeading)], spacing: 20) {+ StatTile(+ label: "Registered users",+ value: summary.registered.formatted(),+ sub: "+\(summary.signups7d.formatted()) last 7 days"+ )+ StatTile(+ label: "Active yesterday",+ value: summary.activeYesterday.map { $0.formatted() } ?? "—",+ sub: summary.activeYesterday == nil ? "no extract yet" : "of \(summary.registered.formatted()) registered"+ )+ StatTile(+ label: "Pro subscribers",+ value: summary.subscribers.map { $0.formatted() } ?? "—",+ sub: summary.canceling.map { "\($0.formatted()) canceling" } ?? "not in this rollup"+ )+ StatTile(+ label: "Paid all time",+ value: summary.fundedDollars.map(dollars) ?? "—",+ sub: summary.funded.map { "by \($0.formatted()) people" } ?? "not in this rollup"+ )+ }+ }+}++private struct StatTile: View {+ let label: String+ let value: String+ let sub: String++ var body: some View {+ VStack(alignment: .leading, spacing: 2) {+ Text(label)+ .font(.footnote)+ .foregroundStyle(.secondary)+ Text(value)+ .font(.title2.weight(.semibold))+ .monospacedDigit()+ Text(sub)+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+}++// MARK: - Sections++private struct MetricSection<ChartContent: View>: View {+ let title: String+ let value: String+ let caption: String+ var deltaPercent: Double?+ @ViewBuilder let chart: () -> ChartContent++ var body: some View {+ VStack(alignment: .leading, spacing: 3) {+ HStack(alignment: .firstTextBaseline) {+ Text(title)+ .font(.headline)+ Spacer()+ if let deltaPercent {+ DeltaBadge(percent: deltaPercent)+ }+ }+ Text(value)+ .font(.title.weight(.semibold))+ .monospacedDigit()+ Text(caption)+ .font(.footnote)+ .foregroundStyle(.secondary)+ chart()+ .frame(height: 200)+ .padding(.top, 16)+ }+ .padding(.vertical, 20)+ }+}++private struct DeltaBadge: View {+ let percent: Double++ var body: some View {+ Text("\(percent >= 0 ? "+" : "")\(percent.formatted(.number.precision(.fractionLength(1))))%")+ .font(.footnote.weight(.semibold))+ .monospacedDigit()+ .foregroundStyle(percent < 0 ? .red : .green)+ .padding(.horizontal, 8)+ .padding(.vertical, 3)+ .background((percent < 0 ? Color.red : Color.green).opacity(0.12), in: Capsule())+ }+}++// MARK: - Charts++private let workingPurple = Color(hex: "#9d7bff")++private struct ActiveChart: View {+ let points: [AnalyticsSummary.DayPoint]++ var body: some View {+ Chart {+ ForEach(points.filter { $0.active != nil }) { point in+ LineMark(+ x: .value("Day", point.day, unit: .day),+ y: .value("Users", point.active ?? 0)+ )+ .foregroundStyle(by: .value("Series", "Active"))+ .interpolationMethod(.monotone)+ }+ ForEach(points.filter { $0.working != nil }) { point in+ LineMark(+ x: .value("Day", point.day, unit: .day),+ y: .value("Users", point.working ?? 0)+ )+ .foregroundStyle(by: .value("Series", "Working"))+ .interpolationMethod(.monotone)+ }+ }+ .chartForegroundStyleScale(["Active": Color.accentBlue, "Working": workingPurple])+ .chartLegend(position: .bottom, spacing: 12)+ .analyticsAxes()+ }+}++private struct SignupsChart: View {+ let points: [AnalyticsSummary.DayPoint]++ var body: some View {+ Chart(points) { point in+ BarMark(+ x: .value("Day", point.day, unit: .day),+ y: .value("Signups", point.signups)+ )+ .foregroundStyle(Color.accentBlue)+ }+ .analyticsAxes()+ }+}++private struct RevenueChart: View {+ let points: [AnalyticsSummary.DayPoint]++ var body: some View {+ Chart {+ ForEach(points) { point in+ BarMark(+ x: .value("Day", point.day, unit: .day),+ y: .value("Dollars", point.proDollars)+ )+ .foregroundStyle(by: .value("Series", "Pro"))+ BarMark(+ x: .value("Day", point.day, unit: .day),+ y: .value("Dollars", point.topupDollars)+ )+ .foregroundStyle(by: .value("Series", "Top-ups"))+ }+ }+ .chartForegroundStyleScale(["Pro": Color.accentBlue, "Top-ups": workingPurple])+ .chartLegend(position: .bottom, spacing: 12)+ .analyticsAxes()+ }+}++private struct RegisteredChart: View {+ let points: [AnalyticsSummary.DayPoint]++ var body: some View {+ Chart(points) { point in+ LineMark(+ x: .value("Day", point.day, unit: .day),+ y: .value("Users", point.totalRegistered)+ )+ .foregroundStyle(Color.accentBlue)+ .interpolationMethod(.monotone)+ }+ .chartYScale(domain: .automatic(includesZero: false))+ .analyticsAxes()+ }+}++extension View {+ fileprivate func analyticsAxes() -> some View {+ chartXAxis {+ AxisMarks(values: .automatic(desiredCount: 4)) {+ AxisGridLine()+ AxisValueLabel(format: .dateTime.month(.abbreviated).day(), centered: false)+ }+ }+ }+}++private func dollars(_ value: Double) -> String {+ value.formatted(.currency(code: "USD").precision(.fractionLength(value == value.rounded() ? 0 : 2)))+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swiftindex eadd7623..ae9ec27b 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift@@ -27,6 +27,12 @@ struct AvatarMenu: View {var body: some View {Menu {+ if auth.user?.superUser == true {+ Button("Analytics", systemImage: "chart.xyaxis.line") {+ app.showsAnalytics = true+ }+ Divider()+ }Picker("Appearance", selection: $app.appearance) {Text("System").tag(AppearancePreference.system)Text("Light").tag(AppearancePreference.light)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swiftindex 8974c888..6885cafd 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift@@ -12,6 +12,7 @@ public struct RootView<CameraPreview: View>: View {var media: MediaModelvar projects: ProjectsModelvar auth: AuthModel+ var analytics: AnalyticsModellet cameraPreview: () -> CameraPreview@Environment(\.scenePhase) private var scenePhase@@ -23,6 +24,7 @@ public struct RootView<CameraPreview: View>: View {media: MediaModel,projects: ProjectsModel,auth: AuthModel,+ analytics: AnalyticsModel,@ViewBuilder cameraPreview: @escaping () -> CameraPreview) {self.app = app@@ -31,6 +33,7 @@ public struct RootView<CameraPreview: View>: View {self.media = mediaself.projects = projectsself.auth = auth+ self.analytics = analyticsself.cameraPreview = cameraPreview}@@ -62,6 +65,11 @@ public struct RootView<CameraPreview: View>: View {.tint(.accentBlue).animation(.default, value: auth.isSignedIn).preferredColorScheme(app.appearance.colorScheme)+ .fullScreenCover(isPresented: $app.showsAnalytics) {+ AnalyticsScreen(analytics: analytics)+ .tint(.accentBlue)+ .preferredColorScheme(app.appearance.colorScheme)+ }.task { await auth.restore() }.onChange(of: scenePhase) { _, phase inif phase == .active, auth.isSignedIn {@@ -69,7 +77,10 @@ public struct RootView<CameraPreview: View>: View {}}.onChange(of: auth.isSignedIn) { _, signedIn in- guard signedIn else { return }+ guard signedIn else {+ app.showsAnalytics = false+ return+ }media.sync?.kick()Task { await projects.refresh() }}diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftindex 6edf0d01..61fba987 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -523,3 +523,84 @@ import Testing#expect(!model.isTorchOn)}}++@Suite struct AnalyticsSummaryTests {+ // Three days over two sources (one DB, one posthog); day two never got+ // extracted. User A signed up before the window and works daily; user B+ // signed up on day two and only opened the app on day three.+ func rollup(billing: AnalyticsRollup.Billing? = nil) -> AnalyticsRollup {+ AnalyticsRollup(+ generatedAt: "2026-08-21T04:00:00.000Z",+ days: ["2026-08-18", "2026-08-19", "2026-08-20"],+ sources: ["renders", "posthog"],+ missing: [.init(day: "2026-08-19")],+ billing: billing,+ users: [+ .init(registeredAt: "2026-08-01T10:00:00.000Z", balanceMicros: "3000000", activity: [1, 0, 3]),+ .init(registeredAt: "2026-08-19T12:00:00.000Z", balanceMicros: "500000", activity: [0, 0, 2]),+ ]+ )+ }++ @Test func derivesCountsAndSkipsMissingDays() {+ let summary = AnalyticsSummary(rollup: rollup())+ #expect(summary.registered == 2)+ #expect(summary.points.count == 3)+ #expect(summary.points[0].active == 1)+ #expect(summary.points[0].working == 1)+ #expect(summary.points[1].active == nil)+ #expect(summary.points[2].active == 2)+ #expect(summary.points[2].working == 1)+ #expect(summary.missingDayCount == 1)+ #expect(summary.activeYesterday == 2)+ #expect(summary.active7d == 2)+ }++ @Test func signupsAndTotalsCarryThePreWindowBase() {+ let summary = AnalyticsSummary(rollup: rollup())+ #expect(summary.points.map(\.signups) == [0, 1, 0])+ #expect(summary.points.map(\.totalRegistered) == [1, 2, 2])+ #expect(summary.signups7d == 1)+ #expect(summary.balanceDollars == 3.5)+ }++ @Test func billingRidesIntoRevenue() {+ let billing = AnalyticsRollup.Billing(+ subscribers: 4,+ canceling: 1,+ funded: 6,+ fundedMicros: "120000000",+ revenue: [+ .init(proMicros: "10000000", topupMicros: "0"),+ .init(proMicros: "0", topupMicros: "5000000"),+ .init(proMicros: "0", topupMicros: "0"),+ ]+ )+ let summary = AnalyticsSummary(rollup: rollup(billing: billing))+ #expect(summary.subscribers == 4)+ #expect(summary.fundedDollars == 120)+ #expect(summary.revenueDollars == 15)+ #expect(summary.points[0].proDollars == 10)+ #expect(summary.points[1].topupDollars == 5)+ }++ @Test func billinglessRollupLeavesRevenueUnknown() {+ let summary = AnalyticsSummary(rollup: rollup())+ #expect(summary.revenueDollars == nil)+ #expect(summary.subscribers == nil)+ }+}++@Suite struct UserProfileDecodingTests {+ @Test func profileCachedBeforeRoleFieldDecodesAsRegular() throws {+ let data = Data(#"{"id":"u1","name":"Dana","email":"[email protected]"}"#.utf8)+ let profile = try JSONDecoder().decode(UserProfile.self, from: data)+ #expect(profile.superUser == false)+ }++ @Test func superUserRoundTrips() throws {+ let profile = UserProfile(id: "u1", name: "Dana", email: "[email protected]", superUser: true)+ let decoded = try JSONDecoder().decode(UserProfile.self, from: JSONEncoder().encode(profile))+ #expect(decoded.superUser)+ }+}