import SwiftUI import UIKit import StoreKit import BucksleyKit import BucksleyUI @main struct BucksleyPhoneApp: App { @UIApplicationDelegateAdaptor(PhoneDelegate.self) private var delegate @State private var model = PhoneModel() var body: some Scene { WindowGroup { ThemedRoot { PhoneRoot() .environment(model) .task { await model.start() } } } } } final class PhoneDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { application.registerForRemoteNotifications() return true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult { await PhoneModel.shared?.refresh() return .newData } } enum PhoneTab: String, CaseIterable, Identifiable { case inbox, accounts, budgets, ask, settings var id: Self { self } var title: String { switch self { case .inbox: "Inbox"; case .accounts: "Accounts"; case .budgets: "Budgets"; case .ask: "Ask"; case .settings: "Settings" } } var symbol: String { switch self { case .inbox: "tray.full"; case .accounts: "chart.line.uptrend.xyaxis"; case .budgets: "chart.pie"; case .ask: "sparkles"; case .settings: "gearshape" } } } @MainActor @Observable final class PhoneModel { static weak var shared: PhoneModel? let store: WorkspaceStore let cloud: CloudSync var ledger: Ledger var tab: PhoneTab = .inbox var status = "Waiting for your Mac" var refreshing = false var message: String? private var started = false init() { let store = try! WorkspaceStore() self.store = store cloud = CloudSync(store: store) ledger = (try? store.ledger()) ?? Ledger(workspace: Workspace(), transactions: [], edits: [:], balances: []) if let raw = ProcessInfo.processInfo.environment["BUCKSLEY_SCREEN"], let tab = PhoneTab(rawValue: raw) { self.tab = tab } Self.shared = self } var workspace: Workspace { ledger.workspace } func start() async { guard !started else { return } started = true #if DEBUG // Screenshots and tests: run a Mac workspace through the same snapshot and adopt code iCloud uses. if let path = ProcessInfo.processInfo.environment["BUCKSLEY_ADOPT_FROM"] { do { let snapshot = try CloudSync.snapshot(from: WorkspaceStore(folder: URL(fileURLWithPath: path))) try store.adopt(snapshot) status = "Updated from your Mac " + snapshot.sharedAt.formatted(.relative(presentation: .named)) reload() } catch { status = "Test snapshot: \(error.localizedDescription)" } return } #endif if cloud.isAvailable, await cloud.accountReady() { try? await cloud.subscribe() } await refresh() } func reload() { if let l = try? store.ledger() { ledger = l } } /// Pulls the Mac's latest snapshot and anything edited elsewhere, then sends this phone's edits. func refresh() async { guard !refreshing else { return } refreshing = true; defer { refreshing = false } guard cloud.isAvailable else { status = "iCloud sync is off in this build"; return } guard await cloud.accountReady() else { status = "Sign in to iCloud to see your Mac's data"; return } do { try await cloud.pushEdits(from: store) if let snapshot = try await cloud.pullSnapshot() { try store.adopt(snapshot) status = "Updated from your Mac " + snapshot.sharedAt.formatted(.relative(presentation: .named)) } else { status = "Open Bucksley on your Mac to share your accounts" } _ = try await cloud.pullChanges(into: store) reload() } catch { status = "iCloud: \(error.localizedDescription)" } } private var push: Task? func edit(_ id: String, _ change: (inout TransactionEdit) -> Void) { do { try store.edit(id, device: UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone", change) reload() SupportPrompt.recordCoreAction() } catch { message = error.localizedDescription; return } push?.cancel() push = Task { [cloud, store] in try? await Task.sleep(for: .seconds(1)) guard !Task.isCancelled, cloud.isAvailable else { return } do { try await cloud.pushEdits(from: store); status = "Synced with iCloud " + Date.now.formatted(date: .omitted, time: .shortened) } catch { status = "iCloud: \(error.localizedDescription)" } } } /// Apple Card, Apple Cash and Savings through FinanceKit, shown here at once and handed to the Mac. func importWallet() async { #if canImport(FinanceKit) do { guard WalletImport.isSupported else { message = "Apple Wallet data isn't available on this device."; return } guard try await WalletImport.requestAccess() else { message = "Bucksley needs permission to read Apple Wallet. You can allow it in Settings → Privacy & Security → Wallet."; return } let pull = try await WalletImport.pull() try WalletImport.apply(pull, store: store) reload() if cloud.isAvailable { try await cloud.pushWallet(pull) } 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." } catch { message = error.localizedDescription } #endif } } struct PhoneRoot: View { @Environment(PhoneModel.self) private var model @Environment(\.palette) private var palette @Environment(\.requestReview) private var requestReview @AppStorage(BucksleyTheme.preferenceKey) private var themeRaw = BucksleyTheme.defaultPreference.rawValue var body: some View { @Bindable var model = model TabView(selection: $model.tab) { ForEach(PhoneTab.allCases) { tab in NavigationStack { screen(tab) } .tabItem { Label(tab.title, systemImage: tab.symbol) } .badge(tab == .inbox ? model.ledger.reviewQueue.count : 0) .tag(tab) } } .tint(palette.accent) .onChange(of: themeRaw) { _, raw in setIcon(BucksleyTheme(preference: raw)) } .alert("Bucksley", isPresented: Binding(get: { model.message != nil }, set: { if !$0 { model.message = nil } })) { Button("OK") { model.message = nil } } message: { Text(model.message ?? "") } .task(id: SupportPrompt.coreActions()) { // Ask for a rating once, after five core actions, only in production App Store builds. guard SupportPrompt.coreActions() >= SupportPrompt.milestone else { return } try? await Task.sleep(for: .seconds(2)) guard case .verified(let transaction) = try? await AppTransaction.shared, transaction.environment == .production, SupportPrompt.claimReview() else { return } requestReview() } } @ViewBuilder func screen(_ tab: PhoneTab) -> some View { switch tab { case .inbox: InboxScreen() case .accounts: PhoneAccountsScreen() case .budgets: PhoneBudgetsScreen() case .ask: PhoneAskScreen() case .settings: PhoneSettingsScreen() } } /// The home screen icon follows the theme. func setIcon(_ theme: BucksleyTheme) { guard UIApplication.shared.supportsAlternateIcons, UIApplication.shared.alternateIconName != theme.iconName else { return } UIApplication.shared.setAlternateIconName(theme.iconName) } } /// Screen background and nav styling for the theme. struct PhoneScreen: View { @Environment(\.palette) private var palette @Environment(PhoneModel.self) private var model let title: String let content: Content init(_ title: String, @ViewBuilder content: () -> Content) { self.title = title; self.content = content() } var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { Text(title).font(palette.title(32)).tracking(palette.titleTracking).padding(.top, 4) content } .padding(.horizontal, 18).padding(.bottom, 28) .frame(maxWidth: 720) .frame(maxWidth: .infinity) } .scrollContentBackground(.hidden) .background(palette.canvas.ignoresSafeArea()) .refreshable { await model.refresh() } .toolbar(.hidden, for: .navigationBar) } } struct EmptyMac: View { @Environment(PhoneModel.self) private var model @Environment(\.palette) private var palette var body: some View { Panel(padding: 20) { VStack(alignment: .leading, spacing: 8) { Text("Your Mac does the bank sync").font(palette.title(18)) 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.") .font(.system(size: 14)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) Text(model.status).font(.system(size: 12)).foregroundStyle(palette.muted) Button("Check again") { Task { await model.refresh() } }.buttonStyle(SecondaryButtonStyle()) } } } }