Sources/OrgstarMobile/ProStore.swift

286 lines · 11570 bytes

  1#if os(iOS)
  2import OrgApp
  3import StoreKit
  4import SwiftUI
  5import UIKit
  6
  7/// orgstar+ from the App Store: a monthly or yearly subscription, or a lifetime purchase. It
  8/// keeps `ProAccess.shared` current; installs from before Pro keep it without buying.
  9@MainActor @Observable
 10final class ProStore {
 11    static let shared = ProStore()
 12
 13    static let monthly = "sh.krz.orgstar.pro.monthly"
 14    static let yearly = "sh.krz.orgstar.pro.yearly"
 15    static let lifetime = "sh.krz.orgstar.pro.lifetime"
 16    static let productIDs = [monthly, yearly, lifetime]
 17
 18    private(set) var products: [Product] = []
 19    private(set) var activeProductID: String?
 20    private(set) var busy = false
 21    var message: String?
 22
 23    @ObservationIgnored private var updates: Task<Void, Never>?
 24
 25    private init() {}
 26
 27    /// Starts listening for transactions and checks what's owned. Call once at launch.
 28    func start() {
 29        guard updates == nil else { return }
 30        updates = Task.detached(priority: .background) {
 31            for await result in Transaction.updates {
 32                guard case .verified(let transaction) = result else { continue }
 33                await transaction.finish()
 34                await ProStore.shared.refresh()
 35            }
 36        }
 37        Task { await refresh() }
 38    }
 39
 40    func loadProducts() async {
 41        guard products.isEmpty else { return }
 42        do {
 43            let fetched = try await Product.products(for: Self.productIDs)
 44            products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
 45        } catch {
 46            message = "The App Store can't be reached right now."
 47        }
 48    }
 49
 50    /// Sets Pro from the current entitlements, or from the original download predating Pro.
 51    func refresh() async {
 52        var active: String?
 53        for await result in Transaction.currentEntitlements {
 54            guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
 55                  transaction.revocationDate == nil else { continue }
 56            if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
 57        }
 58        activeProductID = active
 59        if active != nil {
 60            ProAccess.shared.set(.purchase)
 61        } else if await Self.predatesPro() {
 62            ProAccess.shared.set(.grandfathered)
 63        } else if ProAccess.shared.grant != .grandfathered {
 64            // A cached grandfathered grant survives the App Store being unreachable.
 65            ProAccess.shared.set(nil)
 66        }
 67    }
 68
 69    /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
 70    /// Store reports real original versions; sandbox and Xcode always say "1.0".
 71    private static func predatesPro() async -> Bool {
 72        guard case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
 73        return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
 74    }
 75
 76    func buy(_ product: Product) async {
 77        busy = true
 78        defer { busy = false }
 79        message = nil
 80        do {
 81            switch try await product.purchase() {
 82            case .success(.verified(let transaction)):
 83                await transaction.finish()
 84                await refresh()
 85            case .success(.unverified):
 86                message = "The App Store couldn't verify the purchase."
 87            case .pending:
 88                message = "The purchase is waiting for approval."
 89            case .userCancelled:
 90                break
 91            @unknown default:
 92                break
 93            }
 94        } catch {
 95            message = "The purchase didn't go through. \(error.localizedDescription)"
 96        }
 97    }
 98
 99    func restore() async {
100        busy = true
101        defer { busy = false }
102        message = nil
103        do {
104            try await AppStore.sync()
105            await refresh()
106            if !ProAccess.shared.isUnlocked { message = "No orgstar+ purchase was found for this Apple Account." }
107        } catch {
108            message = "Restore didn't finish. \(error.localizedDescription)"
109        }
110    }
111}
112
113/// orgstar+'s gold, for its banner in Settings and its screen.
114extension ShapeStyle where Self == LinearGradient {
115    static var plusGold: LinearGradient {
116        LinearGradient(
117            colors: [Color(red: 1.0, green: 0.84, blue: 0.36), Color(red: 0.86, green: 0.6, blue: 0.12)],
118            startPoint: .topLeading, endPoint: .bottomTrailing)
119    }
120}
121
122/// The gold star that marks orgstar+.
123struct PlusBadge: View {
124    var size: CGFloat = 46
125
126    var body: some View {
127        Image(systemName: "star.fill")
128            .font(.system(size: size * 0.48, weight: .semibold))
129            .foregroundStyle(.white)
130            .frame(width: size, height: size)
131            .background(.plusGold, in: .rect(cornerRadius: size * 0.24))
132            .accessibilityHidden(true)
133    }
134}
135
136/// What orgstar+ includes, its prices, and buying, restoring or managing it.
137struct ProScreen: View {
138    /// The feature that led here, if any.
139    var feature: ProFeature?
140    @Environment(\.dismiss) private var dismiss
141    @State private var managing = false
142    private var store: ProStore { .shared }
143    private var access: ProAccess { .shared }
144
145    var body: some View {
146        Form {
147            Section {
148                VStack(spacing: 10) {
149                    PlusBadge(size: 76)
150                        .shadow(color: .orange.opacity(0.35), radius: 14, y: 6)
151                    Text(verbatim: "orgstar+").font(.largeTitle.bold())
152                    if let feature, !access.isUnlocked {
153                        Text("\(feature.title) needs orgstar+.").font(.headline)
154                    }
155                    Text(status).foregroundStyle(.secondary)
156                }
157                .multilineTextAlignment(.center)
158                .frame(maxWidth: .infinity)
159                .padding(.vertical, 6)
160            }
161            .listRowBackground(Color.clear)
162            Section {
163                ForEach(ProFeature.allCases) { feature in
164                    Label {
165                        Text(feature.title)
166                    } icon: {
167                        Image(systemName: feature.systemImage).foregroundStyle(.plusGold)
168                    }
169                }
170            } header: {
171                Text("Included in orgstar+")
172            } footer: {
173                Text("Editing, the agenda, capture, clocking, tables and search stay free.")
174            }
175            if access.grant != .grandfathered, store.activeProductID != ProStore.lifetime {
176                Section {
177                    if store.products.isEmpty {
178                        ProgressView().frame(maxWidth: .infinity)
179                    }
180                    ForEach(store.products) { product in
181                        Button { Task { await store.buy(product) } } label: { plan(product) }
182                            .tint(.primary)
183                            .disabled(store.busy || product.id == store.activeProductID)
184                    }
185                } header: {
186                    Text("Choose a plan")
187                } footer: {
188                    Text("Subscriptions renew automatically until cancelled in your Apple Account settings, at least 24 hours before the period ends.")
189                }
190            }
191            Section {
192                Button("Restore Purchases") { Task { await store.restore() } }.disabled(store.busy)
193                if store.activeProductID == ProStore.monthly || store.activeProductID == ProStore.yearly {
194                    Button("Manage Subscription") { managing = true }
195                }
196                Link("Terms of Use", destination: URL(string: "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/")!)
197                Link("Privacy Policy", destination: URL(string: "https://krz.sh/privacy/orgstar/")!)
198            }
199            if let message = store.message {
200                Section { Text(message).foregroundStyle(.secondary) }
201            }
202        }
203        .navigationTitle(Text(verbatim: "orgstar+"))
204        .navigationBarTitleDisplayMode(.inline)
205        .manageSubscriptionsSheet(isPresented: $managing)
206        .task { await store.loadProducts() }
207    }
208
209    /// One plan: its name, an optional savings tag, what it bills, and its price.
210    private func plan(_ product: Product) -> some View {
211        HStack(alignment: .firstTextBaseline) {
212            VStack(alignment: .leading, spacing: 3) {
213                HStack(spacing: 6) {
214                    Text(product.displayName).font(.headline)
215                    if let percent = savings(product) {
216                        Text("Save \(percent)%")
217                            .font(.caption.bold())
218                            .foregroundStyle(.white)
219                            .padding(.horizontal, 7)
220                            .padding(.vertical, 2)
221                            .background(.plusGold, in: .capsule)
222                    }
223                }
224                detail(product).font(.subheadline).foregroundStyle(.secondary)
225            }
226            Spacer()
227            Text(product.displayPrice + period(product))
228                .font(.headline)
229                .monospacedDigit()
230                .foregroundStyle(Color.accentColor)
231        }
232        .padding(.vertical, 4)
233    }
234
235    private func detail(_ product: Product) -> Text {
236        if product.id == store.activeProductID { return Text("Current plan") }
237        switch product.id {
238        case ProStore.monthly: return Text("Billed monthly")
239        case ProStore.yearly:
240            let perMonth = (product.price / 12).formatted(product.priceFormatStyle)
241            return Text("\(perMonth) a month, billed yearly")
242        default: return Text("One payment, no subscription")
243        }
244    }
245
246    /// How much the yearly plan saves against twelve months, in whole percent.
247    private func savings(_ product: Product) -> Int? {
248        guard product.id == ProStore.yearly,
249              let monthly = store.products.first(where: { $0.id == ProStore.monthly }), monthly.price > 0
250        else { return nil }
251        let ratio = NSDecimalNumber(decimal: product.price / (monthly.price * 12)).doubleValue
252        let percent = Int((1 - ratio) * 100)
253        return percent > 0 ? percent : nil
254    }
255
256    private var status: LocalizedStringKey {
257        switch access.grant {
258        case .grandfathered: "Included, because you downloaded orgstar before orgstar+ existed. Thank you."
259        case .purchase: store.activeProductID == ProStore.lifetime ? "You own orgstar+. Thank you for supporting orgstar." : "Your orgstar+ subscription is active. Thank you for supporting orgstar."
260        case .license, nil: "Power features and Apple integrations, on top of everything that stays free."
261        }
262    }
263
264    private func period(_ product: Product) -> String {
265        switch product.subscription?.subscriptionPeriod.unit {
266        case .month: " / month"
267        case .year: " / year"
268        default: ""
269        }
270    }
271}
272
273/// The paywall as a sheet, with a close button.
274struct ProSheet: View {
275    let feature: ProFeature
276    @Environment(\.dismiss) private var dismiss
277
278    var body: some View {
279        NavigationStack {
280            ProScreen(feature: feature)
281                .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
282        }
283        .onChange(of: ProAccess.shared.isUnlocked) { _, unlocked in if unlocked { dismiss() } }
284    }
285}
286#endif