Skip to content

Open source CapCut alternative.

TypeScript

fix(ios): analytics reads the billing list and charts revenue on the billing window

David Lebeb8423796b9
diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swift
index 0b595951..07489fe0 100644
--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift
+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift
@@ -718,10 +718,7 @@ extension CutCloudClient: AnalyticsServicing {
case 401, 403: throw CloudSyncError.unauthorized
default: throw CloudSyncError.refused("The server answered \(http.statusCode).")
}
- guard let rollup = try? JSONDecoder().decode(AnalyticsRollup.self, from: data) else {
- throw AnalyticsError.unreadable
- }
- return rollup
+ return try AnalyticsRollup.decode(data)
}
}
diff --git a/apps/ios/DonkeyKit/Package.swift b/apps/ios/DonkeyKit/Package.swift
index 78f984ad..7df4eda7 100644
--- a/apps/ios/DonkeyKit/Package.swift
+++ b/apps/ios/DonkeyKit/Package.swift
@@ -25,6 +25,9 @@ let package = Package(
.testTarget(
name: "DonkeyKitModelsTests",
dependencies: ["DonkeyKitModels"],
+ // Fixtures/analytics-rollup.json is written by the site's
+ // analytics pipeline (npm run analytics:rollup-fixture).
+ resources: [.copy("Fixtures")],
swiftSettings: [.defaultIsolation(MainActor.self)]
),
]
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift
index cd463945..a89c1639 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift
@@ -35,14 +35,34 @@ nonisolated public struct AnalyticsRollup: Decodable, Sendable {
}
}
+ nonisolated public struct Canceling: Decodable, Sendable {
+ public var subscriptionId: String
+
+ public init(subscriptionId: String) {
+ self.subscriptionId = subscriptionId
+ }
+ }
+
+ /// The billing window, oldest → newest, ending today. It runs a day
+ /// past the activity window; `revenue` aligns with this list.
+ public var days: [String]
public var subscribers: Int
- public var canceling: Int
+ /// Live subscriptions set to end on their own.
+ public var canceling: [Canceling]
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]) {
+ public init(
+ days: [String],
+ subscribers: Int,
+ canceling: [Canceling],
+ funded: Int,
+ fundedMicros: String,
+ revenue: [Revenue]
+ ) {
+ self.days = days
self.subscribers = subscribers
self.canceling = canceling
self.funded = funded
@@ -77,6 +97,58 @@ nonisolated public struct AnalyticsRollup: Decodable, Sendable {
self.billing = billing
self.users = users
}
+
+ /// Decodes the API's JSON. A body this build cannot read fails as
+ /// `AnalyticsError.unreadable` naming the field, so the screen says
+ /// which part of the contract moved.
+ public static func decode(_ data: Data) throws -> AnalyticsRollup {
+ do {
+ return try JSONDecoder().decode(AnalyticsRollup.self, from: data)
+ } catch let error as DecodingError {
+ throw AnalyticsError.unreadable(mismatch(error))
+ } catch {
+ throw AnalyticsError.unreadable(error.localizedDescription)
+ }
+ }
+
+ /// "billing.canceling is not an array", "users[0].activity is missing".
+ static func mismatch(_ error: DecodingError) -> String {
+ func path(_ context: DecodingError.Context) -> String {
+ let joined = context.codingPath.reduce(into: "") { text, key in
+ if let index = key.intValue {
+ text += "[\(index)]"
+ } else {
+ text += text.isEmpty ? key.stringValue : ".\(key.stringValue)"
+ }
+ }
+ return joined.isEmpty ? "the rollup" : joined
+ }
+ func name(_ type: Any.Type) -> String {
+ switch type {
+ case is String.Type: return "a string"
+ case is Bool.Type: return "a boolean"
+ case is Int.Type, is Double.Type, is Float.Type, is Int64.Type, is UInt.Type: return "a number"
+ default:
+ let text = String(describing: type)
+ if text.hasPrefix("Array<") { return "an array" }
+ if text.hasPrefix("Dictionary<") { return "an object" }
+ return text
+ }
+ }
+ switch error {
+ case .typeMismatch(let type, let context):
+ return "\(path(context)) is not \(name(type))"
+ case .valueNotFound(let type, let context):
+ return "\(path(context)) is null, expected \(name(type))"
+ case .keyNotFound(let key, let context):
+ let parent = path(context)
+ return parent == "the rollup" ? "\(key.stringValue) is missing" : "\(parent).\(key.stringValue) is missing"
+ case .dataCorrupted(let context):
+ return context.debugDescription
+ @unknown default:
+ return String(describing: error)
+ }
+ }
}
/// The rollup reduced to what the dashboard draws: one point per day plus the
@@ -90,32 +162,39 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {
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
- ) {
+ public init(day: Date, active: Int?, working: Int?, signups: Int, totalRegistered: Int) {
self.day = day
self.active = active
self.working = working
self.signups = signups
self.totalRegistered = totalRegistered
+ }
+ }
+
+ /// One day of the billing window. That window ends today, a day past
+ /// the activity points, so money charts on its own axis.
+ nonisolated public struct RevenuePoint: Sendable, Equatable, Identifiable {
+ public var day: Date
+ public var proDollars: Double
+ public var topupDollars: Double
+
+ public var id: Date { day }
+ public var revenueDollars: Double { proDollars + topupDollars }
+
+ public init(day: Date, proDollars: Double, topupDollars: Double) {
+ self.day = day
self.proDollars = proDollars
self.topupDollars = topupDollars
}
}
public var points: [DayPoint]
+ /// Paid charges per day across the billing window; empty when the rollup
+ /// predates billing.
+ public var revenue: [RevenuePoint]
public var registered: Int
public var signups7d: Int
public var signupsWindow: Int
@@ -167,18 +246,26 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {
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")
+ totalRegistered: totalRegistered
))
}
+ // Money rides the billing window, which runs through today.
+ let revenue = rollup.billing.map { billing in
+ zip(billing.days, billing.revenue).map { day, entry in
+ RevenuePoint(
+ day: Self.date(fromDay: day),
+ proDollars: Self.dollars(fromMicros: entry.proMicros),
+ topupDollars: Self.dollars(fromMicros: entry.topupMicros)
+ )
+ }
+ } ?? []
+
// 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
@@ -194,6 +281,7 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {
let activePrior7d = activeInRange(len - 14, len - 7)
self.points = points
+ self.revenue = revenue
registered = rollup.users.count
signups7d = rollup.days.suffix(7).reduce(0) { $0 + (signupsByDay[$1] ?? 0) }
signupsWindow = points.reduce(0) { $0 + $1.signups }
@@ -206,10 +294,10 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {
}
balanceDollars = rollup.users.reduce(0) { $0 + Self.dollars(fromMicros: $1.balanceMicros) }
subscribers = rollup.billing?.subscribers
- canceling = rollup.billing?.canceling
+ canceling = rollup.billing?.canceling.count
funded = rollup.billing?.funded
fundedDollars = rollup.billing.map { Self.dollars(fromMicros: $0.fundedMicros) }
- revenueDollars = rollup.billing.map { _ in points.reduce(0) { $0 + $1.revenueDollars } }
+ revenueDollars = rollup.billing.map { _ in revenue.reduce(0) { $0 + $1.revenueDollars } }
missingDayCount = missingDays.count
generatedAt = Self.timestamp(from: rollup.generatedAt)
}
@@ -246,8 +334,9 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {
nonisolated public enum AnalyticsError: Error, Equatable {
/// The nightly job hasn't written a rollup yet.
case noRollup
- /// The answer came back, and it was not a rollup this build can read.
- case unreadable
+ /// The answer came back, and it was not a rollup this build can read;
+ /// the text names the field that moved.
+ case unreadable(String)
}
/// What the app target's CutCloudClient does for the analytics dashboard.
@@ -304,8 +393,8 @@ public final class AnalyticsModel {
message
case CloudSyncError.unreachable(let reach, let code):
"\(reach.sentence) (\(code))"
- case AnalyticsError.unreadable:
- "The rollup came back in a shape this build doesn't read."
+ case AnalyticsError.unreadable(let detail):
+ "The rollup came back in a shape this build doesn't read: \(detail)."
default:
"The rollup didn't load. Try again."
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift
index 9f0b6551..0709c223 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift
@@ -83,9 +83,9 @@ private struct SummaryList: View {
MetricSection(
title: "Revenue",
value: dollars(revenueDollars),
- caption: "Paid charges, last \(summary.points.count) days"
+ caption: "Paid charges, last \(summary.revenue.count) days"
) {
- RevenueChart(points: summary.points)
+ RevenueChart(points: summary.revenue)
}
}
@@ -264,7 +264,7 @@ private struct SignupsChart: View {
}
private struct RevenueChart: View {
- let points: [AnalyticsSummary.DayPoint]
+ let points: [AnalyticsSummary.RevenuePoint]
var body: some View {
Chart {
diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
index a2cbaa5c..8d295be4 100644
--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
@@ -1255,33 +1255,109 @@ import Testing
#expect(summary.balanceDollars == 3.5)
}
- @Test func billingRidesIntoRevenue() {
+ @Test func billingChartsOnItsOwnWindow() {
+ // The billing window runs a day past the activity window, and every
+ // day of it counts: today's money is in the total the day it lands.
let billing = AnalyticsRollup.Billing(
+ days: ["2026-08-18", "2026-08-19", "2026-08-20", "2026-08-21"],
subscribers: 4,
- canceling: 1,
+ canceling: [.init(subscriptionId: "sub_1")],
funded: 6,
fundedMicros: "120000000",
revenue: [
.init(proMicros: "10000000", topupMicros: "0"),
.init(proMicros: "0", topupMicros: "5000000"),
.init(proMicros: "0", topupMicros: "0"),
+ .init(proMicros: "30000000", topupMicros: "0"),
]
)
let summary = AnalyticsSummary(rollup: rollup(billing: billing))
#expect(summary.subscribers == 4)
+ #expect(summary.canceling == 1)
#expect(summary.fundedDollars == 120)
- #expect(summary.revenueDollars == 15)
- #expect(summary.points[0].proDollars == 10)
- #expect(summary.points[1].topupDollars == 5)
+ #expect(summary.revenue.count == 4)
+ #expect(summary.revenueDollars == 45)
+ #expect(summary.revenue[0].proDollars == 10)
+ #expect(summary.revenue[1].topupDollars == 5)
+ #expect(summary.revenue[3].revenueDollars == 30)
}
@Test func billinglessRollupLeavesRevenueUnknown() {
let summary = AnalyticsSummary(rollup: rollup())
#expect(summary.revenueDollars == nil)
+ #expect(summary.revenue.isEmpty)
#expect(summary.subscribers == nil)
}
}
+/// The rollup the site's pipeline writes today, decoded by this build. The
+/// fixture is generated by `npm run analytics:rollup-fixture` in site/ and
+/// checked by the site's tests, so a shape change on the server fails here
+/// before it reaches a phone.
+@Suite struct AnalyticsContractTests {
+ func fixture() throws -> Data {
+ let url = try #require(Bundle.module.url(
+ forResource: "analytics-rollup",
+ withExtension: "json",
+ subdirectory: "Fixtures"
+ ))
+ return try Data(contentsOf: url)
+ }
+
+ @Test func decodesTheRollupThePipelineWrites() throws {
+ let rollup = try AnalyticsRollup.decode(fixture())
+ let summary = AnalyticsSummary(rollup: rollup)
+ #expect(rollup.days == ["2026-08-30", "2026-08-31", "2026-09-01"])
+ #expect(summary.registered == 3)
+ #expect(summary.points.map(\.active) == [2, nil, 3])
+ #expect(summary.points.map(\.working) == [2, nil, 1])
+ #expect(summary.points.map(\.signups) == [0, 1, 0])
+ #expect(summary.points.map(\.totalRegistered) == [2, 3, 3])
+ #expect(summary.missingDayCount == 1)
+ #expect(summary.balanceDollars == 3.5)
+ #expect(summary.subscribers == 2)
+ #expect(summary.canceling == 1)
+ #expect(summary.funded == 2)
+ #expect(summary.fundedDollars == 25)
+ #expect(summary.revenue.count == 4)
+ #expect(summary.revenue.map(\.proDollars) == [20, 0, 0, 0])
+ #expect(summary.revenue.map(\.topupDollars) == [0, 0, 5, 0])
+ #expect(summary.revenueDollars == 25)
+ #expect(summary.generatedAt != nil)
+ }
+
+ @Test func aMovedFieldIsNamed() throws {
+ var json = try #require(try JSONSerialization.jsonObject(with: fixture()) as? [String: Any])
+ var billing = try #require(json["billing"] as? [String: Any])
+ billing["canceling"] = 3
+ json["billing"] = billing
+ let data = try JSONSerialization.data(withJSONObject: json)
+ #expect(throws: AnalyticsError.unreadable("billing.canceling is not an array")) {
+ try AnalyticsRollup.decode(data)
+ }
+ }
+
+ @Test func aMovedScalarIsNamedInWords() throws {
+ var json = try #require(try JSONSerialization.jsonObject(with: fixture()) as? [String: Any])
+ var billing = try #require(json["billing"] as? [String: Any])
+ billing["subscribers"] = "2"
+ json["billing"] = billing
+ let data = try JSONSerialization.data(withJSONObject: json)
+ #expect(throws: AnalyticsError.unreadable("billing.subscribers is not a number")) {
+ try AnalyticsRollup.decode(data)
+ }
+ }
+
+ @Test func aMissingFieldIsNamed() throws {
+ var json = try #require(try JSONSerialization.jsonObject(with: fixture()) as? [String: Any])
+ json["days"] = nil
+ let data = try JSONSerialization.data(withJSONObject: json)
+ #expect(throws: AnalyticsError.unreadable("days is missing")) {
+ try AnalyticsRollup.decode(data)
+ }
+ }
+}
+
@Suite struct AnalyticsModelTests {
final class Service: AnalyticsServicing, @unchecked Sendable {
var answer: Result<AnalyticsRollup, any Error> = .failure(CloudSyncError.transport)