Commit 511a22a63d

511a22a63dd5d3a2da46b6486ffeb40713d49c34

parent: bff4593da6

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 04:48 UTC

Move ProStore and TipStore into OrgApp

- ProStore and TipStore live in OrgApp under canImport(StoreKit), public
- iOS views stay in OrgstarMobile, renamed ProScreen.swift and TipSection.swift
- ProStore.grandfathers: only iOS grandfathers; macOS never does
- ProStoreTests: product IDs, no overlap with tips, grandfathering by platform

Layout: unified · split

Sources/OrgApp/ProStore.swift added +122
@@ -0,0 +1,122 @@
1#if canImport(StoreKit)
2import Foundation
3import Observation
4import StoreKit
5
6/// orgstar+ from the App Store: a monthly or yearly subscription, or a lifetime purchase. It
7/// keeps `ProAccess.shared` current; iOS installs from before Pro keep it without buying.
8@MainActor @Observable
9public final class ProStore {
10 public static let shared = ProStore()
11
12 public static let monthly = "sh.krz.orgstar.pro.monthly"
13 public static let yearly = "sh.krz.orgstar.pro.yearly"
14 public static let lifetime = "sh.krz.orgstar.pro.lifetime"
15 public static let productIDs = [monthly, yearly, lifetime]
16
17 /// Whether downloads from before Pro keep it free. Only on iOS; the Mac App Store app never
18 /// grandfathers.
19 public static let grandfathers: Bool = {
20 #if os(iOS)
21 true
22 #else
23 false
24 #endif
25 }()
26
27 public private(set) var products: [Product] = []
28 public private(set) var activeProductID: String?
29 public private(set) var busy = false
30 public var message: String?
31
32 @ObservationIgnored private var updates: Task<Void, Never>?
33
34 private init() {}
35
36 /// Starts listening for transactions and checks what's owned. Call once at launch, and only
37 /// from App Store builds: it sets the grant from StoreKit alone, replacing a license grant.
38 public func start() {
39 guard updates == nil else { return }
40 updates = Task.detached(priority: .background) {
41 for await result in Transaction.updates {
42 guard case .verified(let transaction) = result else { continue }
43 await transaction.finish()
44 await ProStore.shared.refresh()
45 }
46 }
47 Task { await refresh() }
48 }
49
50 public func loadProducts() async {
51 guard products.isEmpty else { return }
52 do {
53 let fetched = try await Product.products(for: Self.productIDs)
54 products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
55 } catch {
56 message = "The App Store can't be reached right now."
57 }
58 }
59
60 /// Sets Pro from the current entitlements, or from the original download predating Pro.
61 public func refresh() async {
62 var active: String?
63 for await result in Transaction.currentEntitlements {
64 guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
65 transaction.revocationDate == nil else { continue }
66 if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
67 }
68 activeProductID = active
69 if active != nil {
70 ProAccess.shared.set(.purchase)
71 } else if await Self.predatesPro() {
72 ProAccess.shared.set(.grandfathered)
73 } else if ProAccess.shared.grant != .grandfathered {
74 // A cached grandfathered grant survives the App Store being unreachable.
75 ProAccess.shared.set(nil)
76 }
77 }
78
79 /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
80 /// Store reports real original versions; sandbox and Xcode always say "1.0".
81 private static func predatesPro() async -> Bool {
82 guard grandfathers, case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
83 return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
84 }
85
86 public func buy(_ product: Product) async {
87 busy = true
88 defer { busy = false }
89 message = nil
90 do {
91 switch try await product.purchase() {
92 case .success(.verified(let transaction)):
93 await transaction.finish()
94 await refresh()
95 case .success(.unverified):
96 message = "The App Store couldn't verify the purchase."
97 case .pending:
98 message = "The purchase is waiting for approval."
99 case .userCancelled:
100 break
101 @unknown default:
102 break
103 }
104 } catch {
105 message = "The purchase didn't go through. \(error.localizedDescription)"
106 }
107 }
108
109 public func restore() async {
110 busy = true
111 defer { busy = false }
112 message = nil
113 do {
114 try await AppStore.sync()
115 await refresh()
116 if !ProAccess.shared.isUnlocked { message = "No orgstar+ purchase was found for this Apple Account." }
117 } catch {
118 message = "Restore didn't finish. \(error.localizedDescription)"
119 }
120 }
121}
122#endif
Sources/OrgApp/TipStore.swift added +60
@@ -0,0 +1,60 @@
1#if canImport(StoreKit)
2import Foundation
3import Observation
4import StoreKit
5
6/// Tips from the App Store. `ProStore`'s transaction listener finishes any that arrive later.
7@MainActor @Observable
8public final class TipStore {
9 public private(set) var products: [Product] = []
10 public private(set) var isLoading = false
11 public private(set) var purchasingProductID: String?
12 /// A failure, or a tip waiting for approval, shown in the section.
13 public private(set) var message: String?
14 /// Set after a tip goes through; the thank-you alert clears it.
15 public var thanked = false
16
17 public init() {}
18
19 public func loadProducts() async {
20 guard !isLoading else { return }
21 isLoading = true
22 message = nil
23 defer { isLoading = false }
24 do {
25 let fetched = try await Product.products(for: Tip.productIDs)
26 products = Tip.productIDs.compactMap { id in fetched.first { $0.id == id } }
27 if products.count < Tip.productIDs.count {
28 message = String(localized: "Some tips aren't available from the App Store right now.")
29 }
30 } catch {
31 products = []
32 message = String(localized: "The App Store can't be reached right now.")
33 }
34 }
35
36 public func purchase(_ product: Product) async {
37 guard purchasingProductID == nil else { return }
38 purchasingProductID = product.id
39 message = nil
40 defer { purchasingProductID = nil }
41 do {
42 switch try await product.purchase() {
43 case .success(.verified(let transaction)):
44 await transaction.finish()
45 thanked = true
46 case .success(.unverified):
47 message = String(localized: "The App Store couldn't verify the purchase.")
48 case .pending:
49 message = String(localized: "The tip is waiting for approval.")
50 case .userCancelled:
51 break
52 @unknown default:
53 break
54 }
55 } catch {
56 message = String(localized: "The purchase didn't go through. \(error.localizedDescription)")
57 }
58 }
59}
60#endif
Sources/OrgstarMobile/ProStore.swift → Sources/OrgstarMobile/ProScreen.swift renamed −106
@@ -4,112 +4,6 @@ import StoreKit
4import SwiftUI 4import SwiftUI
5import UIKit 5import UIKit
6 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. 7/// orgstar+'s gold, for its banner in Settings and its screen.
114extension ShapeStyle where Self == LinearGradient { 8extension ShapeStyle where Self == LinearGradient {
115 static var plusGold: LinearGradient { 9 static var plusGold: LinearGradient {
Sources/OrgstarMobile/TipSection.swift added +49
@@ -0,0 +1,49 @@
1#if os(iOS)
2import OrgApp
3import StoreKit
4import SwiftUI
5
6/// Tips in About, for everyone, with or without orgstar+.
7struct TipSection: View {
8 @State private var store = TipStore()
9
10 var body: some View {
11 Section {
12 if store.isLoading && store.products.isEmpty {
13 ProgressView().frame(maxWidth: .infinity)
14 }
15 ForEach(store.products) { product in
16 Button { Task { await store.purchase(product) } } label: {
17 HStack {
18 Text(product.displayName)
19 Spacer()
20 if store.purchasingProductID == product.id {
21 ProgressView().controlSize(.small)
22 } else {
23 Text(product.displayPrice).monospacedDigit().foregroundStyle(.secondary)
24 }
25 }
26 }
27 .tint(.primary)
28 .disabled(store.purchasingProductID != nil)
29 }
30 if let message = store.message {
31 Text(message).foregroundStyle(.secondary)
32 if store.products.count < Tip.productIDs.count {
33 Button("Try Again") { Task { await store.loadProducts() } }.disabled(store.isLoading)
34 }
35 }
36 } header: {
37 Text("Support Development")
38 } footer: {
39 Text("Tips are one-time purchases that help pay for orgstar's development. They don't unlock anything.")
40 }
41 .task { await store.loadProducts() }
42 .alert("Thank You", isPresented: $store.thanked) {
43 Button("OK") {}
44 } message: {
45 Text("Your tip helps keep orgstar going.")
46 }
47 }
48}
49#endif
Sources/OrgstarMobile/TipStore.swift deleted −102
@@ -1,102 +0,0 @@
1#if os(iOS)
2import OrgApp
3import StoreKit
4import SwiftUI
5
6/// Tips from the App Store. `ProStore`'s transaction listener finishes any that arrive later.
7@MainActor @Observable
8final class TipStore {
9 private(set) var products: [Product] = []
10 private(set) var isLoading = false
11 private(set) var purchasingProductID: String?
12 /// A failure, or a tip waiting for approval, shown in the section.
13 private(set) var message: String?
14 /// Set after a tip goes through; the thank-you alert clears it.
15 var thanked = false
16
17 func loadProducts() async {
18 guard !isLoading else { return }
19 isLoading = true
20 message = nil
21 defer { isLoading = false }
22 do {
23 let fetched = try await Product.products(for: Tip.productIDs)
24 products = Tip.productIDs.compactMap { id in fetched.first { $0.id == id } }
25 if products.count < Tip.productIDs.count {
26 message = String(localized: "Some tips aren't available from the App Store right now.")
27 }
28 } catch {
29 products = []
30 message = String(localized: "The App Store can't be reached right now.")
31 }
32 }
33
34 func purchase(_ product: Product) async {
35 guard purchasingProductID == nil else { return }
36 purchasingProductID = product.id
37 message = nil
38 defer { purchasingProductID = nil }
39 do {
40 switch try await product.purchase() {
41 case .success(.verified(let transaction)):
42 await transaction.finish()
43 thanked = true
44 case .success(.unverified):
45 message = String(localized: "The App Store couldn't verify the purchase.")
46 case .pending:
47 message = String(localized: "The tip is waiting for approval.")
48 case .userCancelled:
49 break
50 @unknown default:
51 break
52 }
53 } catch {
54 message = String(localized: "The purchase didn't go through. \(error.localizedDescription)")
55 }
56 }
57}
58
59/// Tips in About, for everyone, with or without orgstar+.
60struct TipSection: View {
61 @State private var store = TipStore()
62
63 var body: some View {
64 Section {
65 if store.isLoading && store.products.isEmpty {
66 ProgressView().frame(maxWidth: .infinity)
67 }
68 ForEach(store.products) { product in
69 Button { Task { await store.purchase(product) } } label: {
70 HStack {
71 Text(product.displayName)
72 Spacer()
73 if store.purchasingProductID == product.id {
74 ProgressView().controlSize(.small)
75 } else {
76 Text(product.displayPrice).monospacedDigit().foregroundStyle(.secondary)
77 }
78 }
79 }
80 .tint(.primary)
81 .disabled(store.purchasingProductID != nil)
82 }
83 if let message = store.message {
84 Text(message).foregroundStyle(.secondary)
85 if store.products.count < Tip.productIDs.count {
86 Button("Try Again") { Task { await store.loadProducts() } }.disabled(store.isLoading)
87 }
88 }
89 } header: {
90 Text("Support Development")
91 } footer: {
92 Text("Tips are one-time purchases that help pay for orgstar's development. They don't unlock anything.")
93 }
94 .task { await store.loadProducts() }
95 .alert("Thank You", isPresented: $store.thanked) {
96 Button("OK") {}
97 } message: {
98 Text("Your tip helps keep orgstar going.")
99 }
100 }
101}
102#endif
Tests/OrgAppTests/TipTests.swift +22
@@ -15,3 +15,25 @@ struct TipTests {
15 #expect(Tip.productIDs.allSatisfy { !$0.hasPrefix("sh.krz.orgstar.pro.") }) 15 #expect(Tip.productIDs.allSatisfy { !$0.hasPrefix("sh.krz.orgstar.pro.") })
16 } 16 }
17} 17}
18
19#if canImport(StoreKit)
20@MainActor
21struct ProStoreTests {
22 @Test func productIDsAreOrgstarPlusAndNotTips() {
23 #expect(ProStore.productIDs == [
24 "sh.krz.orgstar.pro.monthly",
25 "sh.krz.orgstar.pro.yearly",
26 "sh.krz.orgstar.pro.lifetime",
27 ])
28 #expect(Set(ProStore.productIDs).isDisjoint(with: Tip.productIDs))
29 }
30
31 @Test func grandfathersOnlyOnIOS() {
32 #if os(iOS)
33 #expect(ProStore.grandfathers)
34 #else
35 #expect(!ProStore.grandfathers)
36 #endif
37 }
38}
39#endif