Bucksley / app · bucksley.ai / Apps / iPhone / PhoneApp.swift
| 1 | import SwiftUI |
| 2 | import UIKit |
| 3 | import StoreKit |
| 4 | import BucksleyKit |
| 5 | import BucksleyUI |
| 6 | |
| 7 | @main |
| 8 | struct BucksleyPhoneApp: App { |
| 9 | @UIApplicationDelegateAdaptor(PhoneDelegate.self) private var delegate |
| 10 | @State private var model = PhoneModel() |
| 11 | |
| 12 | var body: some Scene { |
| 13 | WindowGroup { |
| 14 | ThemedRoot { |
| 15 | PhoneRoot() |
| 16 | .environment(model) |
| 17 | .task { await model.start() } |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | final class PhoneDelegate: NSObject, UIApplicationDelegate { |
| 24 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { |
| 25 | application.registerForRemoteNotifications() |
| 26 | return true |
| 27 | } |
| 28 | func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult { |
| 29 | await PhoneModel.shared?.refresh() |
| 30 | return .newData |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | enum PhoneTab: String, CaseIterable, Identifiable { |
| 35 | case inbox, accounts, budgets, ask, settings |
| 36 | var id: Self { self } |
| 37 | var title: String { |
| 38 | switch self { case .inbox: "Inbox"; case .accounts: "Accounts"; case .budgets: "Budgets"; case .ask: "Ask"; case .settings: "Settings" } |
| 39 | } |
| 40 | var symbol: String { |
| 41 | switch self { case .inbox: "tray.full"; case .accounts: "chart.line.uptrend.xyaxis"; case .budgets: "chart.pie"; case .ask: "sparkles"; case .settings: "gearshape" } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | @MainActor @Observable |
| 46 | final class PhoneModel { |
| 47 | static weak var shared: PhoneModel? |
| 48 | let store: WorkspaceStore |
| 49 | let cloud: CloudSync |
| 50 | var ledger: Ledger |
| 51 | var tab: PhoneTab = .inbox |
| 52 | var status = "Waiting for your Mac" |
| 53 | var refreshing = false |
| 54 | var message: String? |
| 55 | private var started = false |
| 56 | |
| 57 | init() { |
| 58 | let store = try! WorkspaceStore() |
| 59 | self.store = store |
| 60 | cloud = CloudSync(store: store) |
| 61 | ledger = (try? store.ledger()) ?? Ledger(workspace: Workspace(), transactions: [], edits: [:], balances: []) |
| 62 | if let raw = ProcessInfo.processInfo.environment["BUCKSLEY_SCREEN"], let tab = PhoneTab(rawValue: raw) { self.tab = tab } |
| 63 | Self.shared = self |
| 64 | } |
| 65 | |
| 66 | var workspace: Workspace { ledger.workspace } |
| 67 | |
| 68 | func start() async { |
| 69 | guard !started else { return } |
| 70 | started = true |
| 71 | #if DEBUG |
| 72 | // Screenshots and tests: run a Mac workspace through the same snapshot and adopt code iCloud uses. |
| 73 | if let path = ProcessInfo.processInfo.environment["BUCKSLEY_ADOPT_FROM"] { |
| 74 | do { |
| 75 | let snapshot = try CloudSync.snapshot(from: WorkspaceStore(folder: URL(fileURLWithPath: path))) |
| 76 | try store.adopt(snapshot) |
| 77 | status = "Updated from your Mac " + snapshot.sharedAt.formatted(.relative(presentation: .named)) |
| 78 | reload() |
| 79 | } catch { status = "Test snapshot: \(error.localizedDescription)" } |
| 80 | return |
| 81 | } |
| 82 | #endif |
| 83 | if cloud.isAvailable, await cloud.accountReady() { try? await cloud.subscribe() } |
| 84 | await refresh() |
| 85 | } |
| 86 | |
| 87 | func reload() { if let l = try? store.ledger() { ledger = l } } |
| 88 | |
| 89 | /// Pulls the Mac's latest snapshot and anything edited elsewhere, then sends this phone's edits. |
| 90 | func refresh() async { |
| 91 | guard !refreshing else { return } |
| 92 | refreshing = true; defer { refreshing = false } |
| 93 | guard cloud.isAvailable else { status = "iCloud sync is off in this build"; return } |
| 94 | guard await cloud.accountReady() else { status = "Sign in to iCloud to see your Mac's data"; return } |
| 95 | do { |
| 96 | try await cloud.pushEdits(from: store) |
| 97 | if let snapshot = try await cloud.pullSnapshot() { |
| 98 | try store.adopt(snapshot) |
| 99 | status = "Updated from your Mac " + snapshot.sharedAt.formatted(.relative(presentation: .named)) |
| 100 | } else { |
| 101 | status = "Open Bucksley on your Mac to share your accounts" |
| 102 | } |
| 103 | _ = try await cloud.pullChanges(into: store) |
| 104 | reload() |
| 105 | } catch { |
| 106 | status = "iCloud: \(error.localizedDescription)" |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | private var push: Task<Void, Never>? |
| 111 | func edit(_ id: String, _ change: (inout TransactionEdit) -> Void) { |
| 112 | do { |
| 113 | try store.edit(id, device: UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone", change) |
| 114 | reload() |
| 115 | SupportPrompt.recordCoreAction() |
| 116 | } catch { message = error.localizedDescription; return } |
| 117 | push?.cancel() |
| 118 | push = Task { [cloud, store] in |
| 119 | try? await Task.sleep(for: .seconds(1)) |
| 120 | guard !Task.isCancelled, cloud.isAvailable else { return } |
| 121 | do { try await cloud.pushEdits(from: store); status = "Synced with iCloud " + Date.now.formatted(date: .omitted, time: .shortened) } |
| 122 | catch { status = "iCloud: \(error.localizedDescription)" } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Apple Card, Apple Cash and Savings through FinanceKit, shown here at once and handed to the Mac. |
| 127 | func importWallet() async { |
| 128 | #if canImport(FinanceKit) |
| 129 | do { |
| 130 | guard WalletImport.isSupported else { message = "Apple Wallet data isn't available on this device."; return } |
| 131 | guard try await WalletImport.requestAccess() else { message = "Bucksley needs permission to read Apple Wallet. You can allow it in Settings → Privacy & Security → Wallet."; return } |
| 132 | let pull = try await WalletImport.pull() |
| 133 | try WalletImport.apply(pull, store: store) |
| 134 | reload() |
| 135 | if cloud.isAvailable { try await cloud.pushWallet(pull) } |
| 136 | message = "Added \(pull.accounts.count) Apple Wallet account\(pull.accounts.count == 1 ? "" : "s") with \(pull.transactions.count) transactions. Your Mac picks them up through iCloud." |
| 137 | } catch { message = error.localizedDescription } |
| 138 | #endif |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | struct PhoneRoot: View { |
| 143 | @Environment(PhoneModel.self) private var model |
| 144 | @Environment(\.palette) private var palette |
| 145 | @Environment(\.requestReview) private var requestReview |
| 146 | @AppStorage(BucksleyTheme.preferenceKey) private var themeRaw = BucksleyTheme.defaultPreference.rawValue |
| 147 | |
| 148 | var body: some View { |
| 149 | @Bindable var model = model |
| 150 | TabView(selection: $model.tab) { |
| 151 | ForEach(PhoneTab.allCases) { tab in |
| 152 | NavigationStack { screen(tab) } |
| 153 | .tabItem { Label(tab.title, systemImage: tab.symbol) } |
| 154 | .badge(tab == .inbox ? model.ledger.reviewQueue.count : 0) |
| 155 | .tag(tab) |
| 156 | } |
| 157 | } |
| 158 | .tint(palette.accent) |
| 159 | .onChange(of: themeRaw) { _, raw in setIcon(BucksleyTheme(preference: raw)) } |
| 160 | .alert("Bucksley", isPresented: Binding(get: { model.message != nil }, set: { if !$0 { model.message = nil } })) { |
| 161 | Button("OK") { model.message = nil } |
| 162 | } message: { Text(model.message ?? "") } |
| 163 | .task(id: SupportPrompt.coreActions()) { |
| 164 | // Ask for a rating once, after five core actions, only in production App Store builds. |
| 165 | guard SupportPrompt.coreActions() >= SupportPrompt.milestone else { return } |
| 166 | try? await Task.sleep(for: .seconds(2)) |
| 167 | guard case .verified(let transaction) = try? await AppTransaction.shared, transaction.environment == .production, |
| 168 | SupportPrompt.claimReview() else { return } |
| 169 | requestReview() |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | @ViewBuilder func screen(_ tab: PhoneTab) -> some View { |
| 174 | switch tab { |
| 175 | case .inbox: InboxScreen() |
| 176 | case .accounts: PhoneAccountsScreen() |
| 177 | case .budgets: PhoneBudgetsScreen() |
| 178 | case .ask: PhoneAskScreen() |
| 179 | case .settings: PhoneSettingsScreen() |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// The home screen icon follows the theme. |
| 184 | func setIcon(_ theme: BucksleyTheme) { |
| 185 | guard UIApplication.shared.supportsAlternateIcons, UIApplication.shared.alternateIconName != theme.iconName else { return } |
| 186 | UIApplication.shared.setAlternateIconName(theme.iconName) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// Screen background and nav styling for the theme. |
| 191 | struct PhoneScreen<Content: View>: View { |
| 192 | @Environment(\.palette) private var palette |
| 193 | @Environment(PhoneModel.self) private var model |
| 194 | let title: String |
| 195 | let content: Content |
| 196 | init(_ title: String, @ViewBuilder content: () -> Content) { self.title = title; self.content = content() } |
| 197 | var body: some View { |
| 198 | ScrollView { |
| 199 | VStack(alignment: .leading, spacing: 16) { |
| 200 | Text(title).font(palette.title(32)).tracking(palette.titleTracking).padding(.top, 4) |
| 201 | content |
| 202 | } |
| 203 | .padding(.horizontal, 18).padding(.bottom, 28) |
| 204 | .frame(maxWidth: 720) |
| 205 | .frame(maxWidth: .infinity) |
| 206 | } |
| 207 | .scrollContentBackground(.hidden) |
| 208 | .background(palette.canvas.ignoresSafeArea()) |
| 209 | .refreshable { await model.refresh() } |
| 210 | .toolbar(.hidden, for: .navigationBar) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | struct EmptyMac: View { |
| 215 | @Environment(PhoneModel.self) private var model |
| 216 | @Environment(\.palette) private var palette |
| 217 | var body: some View { |
| 218 | Panel(padding: 20) { |
| 219 | VStack(alignment: .leading, spacing: 8) { |
| 220 | Text("Your Mac does the bank sync").font(palette.title(18)) |
| 221 | Text("Connect your banks in Bucksley on your Mac. It shares your accounts with this iPhone through your private iCloud, and what you review here goes back to the Mac.") |
| 222 | .font(.system(size: 14)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 223 | Text(model.status).font(.system(size: 12)).foregroundStyle(palette.muted) |
| 224 | Button("Check again") { Task { await model.refresh() } }.buttonStyle(SecondaryButtonStyle()) |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | } |