Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / WalletImport.swift

Raw 3.7 KB on 07e410940d4dd3ce1e1e51286babef75b272eb4f
1import Foundation
2#if os(iOS) && canImport(FinanceKit)
3import FinanceKit
4#endif
5
6/// Apple Wallet accounts (Apple Card, Apple Cash, Savings) through FinanceKit, iPhone only. The
7/// phone reads them with the user's permission and hands them to the Mac through iCloud.
8public enum WalletImport {
9 public static let connectionID = "apple-wallet"
10
11 public static var isSupported: Bool {
12 #if os(iOS) && canImport(FinanceKit)
13 FinanceStore.isDataAvailable(.financialData)
14 #else
15 false
16 #endif
17 }
18
19 #if os(iOS) && canImport(FinanceKit)
20 public static func requestAccess() async throws -> Bool {
21 try await FinanceStore.shared.requestAuthorization() == .authorized
22 }
23
24 /// The last `days` days of Wallet transactions and current balances, ready for `BankSync.apply`.
25 public static func pull(days: Int = 365) async throws -> BankPull {
26 let store = FinanceStore.shared
27 var pull = BankPull()
28 let accounts = try await store.accounts(query: AccountQuery())
29 let balances = try await store.accountBalances(query: AccountBalanceQuery())
30 for account in accounts {
31 let id = "\(connectionID):\(account.id.uuidString)"
32 let liability: Bool
33 switch account { case .liability: liability = true; default: liability = false }
34 var value: Decimal = 0
35 let latest = balances.filter { $0.accountID == account.id }.compactMap { $0.booked ?? $0.available }.max { $0.asOfDate < $1.asOfDate }
36 if let amount = latest {
37 value = amount.amount.amount * (amount.creditDebitIndicator == .debit ? -1 : 1)
38 if liability { value = -abs(value) }
39 }
40 pull.accounts.append(Account(id: id, connectionID: connectionID, name: account.displayName, institution: account.institutionName,
41 kind: liability ? .credit : AccountKind.guess(from: account.displayName) == .other ? .savings : AccountKind.guess(from: account.displayName),
42 balance: value, currency: account.currencyCode))
43 }
44 let since = Calendar.current.date(byAdding: .day, value: -days, to: .now) ?? .now
45 let query = TransactionQuery(sortDescriptors: [SortDescriptor(\.transactionDate, order: .reverse)],
46 predicate: #Predicate<FinanceKit.Transaction> { $0.transactionDate >= since })
47 for t in try await store.transactions(query: query) {
48 let sign: Decimal = t.creditDebitIndicator == .debit ? -1 : 1
49 let mcc = t.merchantCategoryCode.map { "mcc:\($0.rawValue)" }
50 pull.transactions.append(Transaction(id: "\(connectionID):\(t.accountID.uuidString):\(t.id.uuidString)",
51 accountID: "\(connectionID):\(t.accountID.uuidString)",
52 day: DayKey.from(t.transactionDate), amount: t.transactionAmount.amount * sign,
53 description: t.originalTransactionDescription, payee: t.merchantName,
54 bankCategory: mcc, pending: t.status == .pending || t.status == .authorized))
55 }
56 return pull
57 }
58 #endif
59
60 /// Mac: files a Wallet import from the iPhone under its own connection.
61 public static func apply(_ pull: BankPull, store: WorkspaceStore) throws {
62 let existing = try store.load().connections.first { $0.id == connectionID }
63 let connection = existing ?? Connection(id: connectionID, kind: .financekit, name: "Apple Wallet (iPhone)")
64 try BankSync(store: store).apply(pull, to: connection)
65 }
66}