Branchwell

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

Raw 9.6 KB on 07e410940d4dd3ce1e1e51286babef75b272eb4f
1import Foundation
2
3/// Runs every bank connection on the Mac and writes the results into the local store. A failing
4/// connection is recorded and skipped; it never blocks the others.
5public struct BankSync: Sendable {
6 let store: WorkspaceStore
7 let http: HTTPClient
8
9 public init(store: WorkspaceStore, http: HTTPClient = URLSessionHTTP()) { self.store = store; self.http = http }
10
11 public struct Report: Sendable {
12 public var synced: [String] = []
13 public var failed: [String: String] = [:]
14 public var added = 0
15 public var updated = 0
16 }
17
18 public func syncAll(now: Date = .now) async -> Report {
19 var report = Report()
20 let connections = (try? store.load().connections) ?? []
21 for connection in connections where connection.kind.syncs {
22 do {
23 let counts = try await sync(connection, now: now)
24 report.synced.append(connection.name); report.added += counts.added; report.updated += counts.updated
25 } catch {
26 report.failed[connection.name] = error.localizedDescription
27 _ = try? store.update { ws in
28 if let i = ws.connections.firstIndex(where: { $0.id == connection.id }) { ws.connections[i].lastError = error.localizedDescription }
29 }
30 }
31 }
32 _ = try? store.update { $0.settings.lastSyncAt = now }
33 return report
34 }
35
36 @discardableResult
37 public func sync(_ connection: Connection, now: Date = .now) async throws -> (added: Int, updated: Int) {
38 guard let secret = Keychain.get(.connection(connection.id)) else {
39 throw BucksleyError.missing("\(connection.name) has no saved credentials on this Mac. Connect it again in Settings → Connections.")
40 }
41 let pull: BankPull
42 switch connection.kind {
43 case .simplefin:
44 // First sync reaches back 90 days; later ones re-read two weeks so pending charges settle.
45 let since = connection.lastSyncAt.map { $0.addingTimeInterval(-14 * 86_400) } ?? now.addingTimeInterval(-90 * 86_400)
46 var simplefin = try await SimpleFIN(http: http).pull(accessURL: secret, connectionID: connection.id, since: since, now: now)
47 // Accounts added since the first sync (or from before this check existed) get their 90 days once.
48 let known = Dictionary(((try? store.load().accounts) ?? []).map { ($0.id, $0.historyLoaded == true) }, uniquingKeysWith: { a, _ in a })
49 let backfill = Set(simplefin.accounts.map(\.id).filter { known[$0] != true })
50 let firstSync = connection.lastSyncAt == nil
51 if !backfill.isEmpty, !firstSync {
52 let history = try await SimpleFIN(http: http).pull(accessURL: secret, connectionID: connection.id, since: now.addingTimeInterval(-90 * 86_400), now: since)
53 let have = Set(simplefin.transactions.map(\.id))
54 simplefin.transactions += history.transactions.filter { backfill.contains($0.accountID) && !have.contains($0.id) }
55 }
56 for i in simplefin.accounts.indices { simplefin.accounts[i].historyLoaded = true }
57 pull = simplefin
58 case .plaid:
59 guard let env = Plaid.Environment(rawValue: connection.plaidEnvironment ?? "production"),
60 let id = Keychain.get(.plaidClientID), let key = Keychain.get(.plaidSecret) else {
61 throw BucksleyError.missing("Add your Plaid client ID and secret in Settings → Connections.")
62 }
63 pull = try await Plaid(environment: env, clientID: id, secret: key, http: http)
64 .pull(accessToken: secret, connectionID: connection.id, institution: connection.name, cursor: connection.plaidCursor)
65 case .coinbase:
66 pull = try await pullCoinbase(secret: secret, connectionID: connection.id, now: now)
67 default:
68 return (0, 0)
69 }
70 return try apply(pull, to: connection, now: now)
71 }
72
73 /// Writes one pull into the store. Also used for CSV and Apple Wallet imports.
74 @discardableResult
75 public func apply(_ pull: BankPull, to connection: Connection, now: Date = .now) throws -> (added: Int, updated: Int) {
76 if !pull.removedTransactionIDs.isEmpty {
77 let gone = Set(pull.removedTransactionIDs)
78 try store.removeTransactions { gone.contains($0.id) }
79 }
80 let counts = try store.upsert(pull.transactions)
81 var accounts: [Account] = []
82 try store.update { ws in
83 for var account in pull.accounts {
84 if let i = ws.accounts.firstIndex(where: { $0.id == account.id }) {
85 account.hidden = ws.accounts[i].hidden; account.nickname = ws.accounts[i].nickname
86 account.historyLoaded = account.historyLoaded ?? ws.accounts[i].historyLoaded
87 if connection.kind == .csv { account.balance = ws.accounts[i].balance }
88 // A chosen type wins, except "Other", which is never worth keeping over a real guess.
89 if ws.accounts[i].kindChosen == true, ws.accounts[i].kind != .other || account.kind == .other { account.kind = ws.accounts[i].kind; account.kindChosen = true }
90 ws.accounts[i] = account
91 } else {
92 ws.accounts.append(account)
93 }
94 accounts.append(account)
95 }
96 if let i = ws.connections.firstIndex(where: { $0.id == connection.id }) {
97 ws.connections[i].lastSyncAt = now
98 ws.connections[i].lastError = pull.warnings.isEmpty ? nil : pull.warnings.joined(separator: " ")
99 if let cursor = pull.plaidCursor { ws.connections[i].plaidCursor = cursor }
100 } else {
101 var c = connection; c.lastSyncAt = now; ws.connections.append(c)
102 }
103 }
104 if connection.kind != .csv { try store.recordBalances(accounts, today: DayKey.from(now)) }
105 return counts
106 }
107
108 /// Connects SimpleFIN from a setup token (or the demo), saves the access URL and runs a first sync.
109 public func connectSimpleFIN(setupToken: String?, name: String = "SimpleFIN Bridge") async throws -> Connection {
110 var access = SimpleFIN.demoAccessURL
111 if let setupToken { access = try await SimpleFIN(http: http).claim(setupToken: setupToken) }
112 let connection = Connection(kind: .simplefin, name: setupToken == nil ? "SimpleFIN Demo" : name)
113 try Keychain.set(access, for: .connection(connection.id))
114 try store.update { $0.connections.append(connection) }
115 try await sync(connection)
116 return connection
117 }
118
119 /// Saves a Plaid item after Link (or the sandbox shortcut) and runs a first sync.
120 public func connectPlaid(publicToken: String, institution: String, environment: Plaid.Environment) async throws -> Connection {
121 guard let plaid = Plaid.fromKeychain(environment: environment) else { throw BucksleyError.missing("Add your Plaid client ID and secret first.") }
122 let access = try await Plaid(environment: environment, clientID: plaid.clientID, secret: plaid.secret, http: http).exchange(publicToken: publicToken)
123 let connection = Connection(kind: .plaid, name: institution, plaidEnvironment: environment.rawValue)
124 try Keychain.set(access, for: .connection(connection.id))
125 try store.update { $0.connections.append(connection) }
126 try await sync(connection)
127 return connection
128 }
129
130 public func importCSV(_ text: String, fileName: String) throws -> (transactions: Int, accounts: Int) {
131 let ws = try store.load()
132 let connection = ws.connections.first { $0.kind == .csv && $0.name == fileName } ?? Connection(kind: .csv, name: fileName)
133 let result = try CSVImport.parse(text, connectionID: connection.id, categories: ws.categories)
134 try store.update { ws in
135 for c in result.newCategories where !ws.categories.contains(where: { $0.id == c.id }) { ws.categories.append(c) }
136 }
137 var pull = BankPull(); pull.accounts = result.accounts; pull.transactions = result.transactions
138 try apply(pull, to: connection)
139 try store.mergeEdits(result.edits)
140 return (result.transactions.count, result.accounts.count)
141 }
142
143 /// CSV and manual accounts have no live balance; the user types it and Bucksley rebuilds the
144 /// account's history from its transactions.
145 public func setManualBalance(_ accountID: String, balance: Decimal, today: String = DayKey.today) throws {
146 var updated: Account?
147 try store.update { ws in
148 guard let i = ws.accounts.firstIndex(where: { $0.id == accountID }) else { return }
149 ws.accounts[i].balance = balance; ws.accounts[i].balanceDate = .now
150 updated = ws.accounts[i]
151 }
152 guard let account = updated else { throw BucksleyError.missing("No account \(accountID).") }
153 try store.replaceBalances(try store.balances().filter { $0.accountID != accountID })
154 try store.recordBalances([account], today: today)
155 }
156
157 /// Removes a connection, its accounts, transactions, balances and Keychain secret.
158 public func disconnect(_ connectionID: String) throws {
159 Keychain.remove(.connection(connectionID))
160 let accountIDs = Set(try store.load().accounts.filter { $0.connectionID == connectionID }.map(\.id))
161 try store.removeTransactions { accountIDs.contains($0.accountID) }
162 try store.replaceBalances(try store.balances().filter { !accountIDs.contains($0.accountID) })
163 try store.update { ws in
164 ws.connections.removeAll { $0.id == connectionID }
165 ws.accounts.removeAll { accountIDs.contains($0.id) }
166 }
167 }
168}