import Foundation /// Runs every bank connection on the Mac and writes the results into the local store. A failing /// connection is recorded and skipped; it never blocks the others. public struct BankSync: Sendable { let store: WorkspaceStore let http: HTTPClient public init(store: WorkspaceStore, http: HTTPClient = URLSessionHTTP()) { self.store = store; self.http = http } public struct Report: Sendable { public var synced: [String] = [] public var failed: [String: String] = [:] public var added = 0 public var updated = 0 } public func syncAll(now: Date = .now) async -> Report { var report = Report() let connections = (try? store.load().connections) ?? [] for connection in connections where connection.kind.syncs { do { let counts = try await sync(connection, now: now) report.synced.append(connection.name); report.added += counts.added; report.updated += counts.updated } catch { report.failed[connection.name] = error.localizedDescription _ = try? store.update { ws in if let i = ws.connections.firstIndex(where: { $0.id == connection.id }) { ws.connections[i].lastError = error.localizedDescription } } } } _ = try? store.update { $0.settings.lastSyncAt = now } return report } @discardableResult public func sync(_ connection: Connection, now: Date = .now) async throws -> (added: Int, updated: Int) { guard let secret = Keychain.get(.connection(connection.id)) else { throw BucksleyError.missing("\(connection.name) has no saved credentials on this Mac. Connect it again in Settings → Connections.") } let pull: BankPull switch connection.kind { case .simplefin: // First sync reaches back 90 days; later ones re-read two weeks so pending charges settle. let since = connection.lastSyncAt.map { $0.addingTimeInterval(-14 * 86_400) } ?? now.addingTimeInterval(-90 * 86_400) var simplefin = try await SimpleFIN(http: http).pull(accessURL: secret, connectionID: connection.id, since: since, now: now) // Accounts added since the first sync (or from before this check existed) get their 90 days once. let known = Dictionary(((try? store.load().accounts) ?? []).map { ($0.id, $0.historyLoaded == true) }, uniquingKeysWith: { a, _ in a }) let backfill = Set(simplefin.accounts.map(\.id).filter { known[$0] != true }) let firstSync = connection.lastSyncAt == nil if !backfill.isEmpty, !firstSync { let history = try await SimpleFIN(http: http).pull(accessURL: secret, connectionID: connection.id, since: now.addingTimeInterval(-90 * 86_400), now: since) let have = Set(simplefin.transactions.map(\.id)) simplefin.transactions += history.transactions.filter { backfill.contains($0.accountID) && !have.contains($0.id) } } for i in simplefin.accounts.indices { simplefin.accounts[i].historyLoaded = true } pull = simplefin case .plaid: guard let env = Plaid.Environment(rawValue: connection.plaidEnvironment ?? "production"), let id = Keychain.get(.plaidClientID), let key = Keychain.get(.plaidSecret) else { throw BucksleyError.missing("Add your Plaid client ID and secret in Settings → Connections.") } pull = try await Plaid(environment: env, clientID: id, secret: key, http: http) .pull(accessToken: secret, connectionID: connection.id, institution: connection.name, cursor: connection.plaidCursor) case .coinbase: pull = try await pullCoinbase(secret: secret, connectionID: connection.id, now: now) default: return (0, 0) } return try apply(pull, to: connection, now: now) } /// Writes one pull into the store. Also used for CSV and Apple Wallet imports. @discardableResult public func apply(_ pull: BankPull, to connection: Connection, now: Date = .now) throws -> (added: Int, updated: Int) { if !pull.removedTransactionIDs.isEmpty { let gone = Set(pull.removedTransactionIDs) try store.removeTransactions { gone.contains($0.id) } } let counts = try store.upsert(pull.transactions) var accounts: [Account] = [] try store.update { ws in for var account in pull.accounts { if let i = ws.accounts.firstIndex(where: { $0.id == account.id }) { account.hidden = ws.accounts[i].hidden; account.nickname = ws.accounts[i].nickname account.historyLoaded = account.historyLoaded ?? ws.accounts[i].historyLoaded if connection.kind == .csv { account.balance = ws.accounts[i].balance } // A chosen type wins, except "Other", which is never worth keeping over a real guess. if ws.accounts[i].kindChosen == true, ws.accounts[i].kind != .other || account.kind == .other { account.kind = ws.accounts[i].kind; account.kindChosen = true } ws.accounts[i] = account } else { ws.accounts.append(account) } accounts.append(account) } if let i = ws.connections.firstIndex(where: { $0.id == connection.id }) { ws.connections[i].lastSyncAt = now ws.connections[i].lastError = pull.warnings.isEmpty ? nil : pull.warnings.joined(separator: " ") if let cursor = pull.plaidCursor { ws.connections[i].plaidCursor = cursor } } else { var c = connection; c.lastSyncAt = now; ws.connections.append(c) } } if connection.kind != .csv { try store.recordBalances(accounts, today: DayKey.from(now)) } return counts } /// Connects SimpleFIN from a setup token (or the demo), saves the access URL and runs a first sync. public func connectSimpleFIN(setupToken: String?, name: String = "SimpleFIN Bridge") async throws -> Connection { var access = SimpleFIN.demoAccessURL if let setupToken { access = try await SimpleFIN(http: http).claim(setupToken: setupToken) } let connection = Connection(kind: .simplefin, name: setupToken == nil ? "SimpleFIN Demo" : name) try Keychain.set(access, for: .connection(connection.id)) try store.update { $0.connections.append(connection) } try await sync(connection) return connection } /// Saves a Plaid item after Link (or the sandbox shortcut) and runs a first sync. public func connectPlaid(publicToken: String, institution: String, environment: Plaid.Environment) async throws -> Connection { guard let plaid = Plaid.fromKeychain(environment: environment) else { throw BucksleyError.missing("Add your Plaid client ID and secret first.") } let access = try await Plaid(environment: environment, clientID: plaid.clientID, secret: plaid.secret, http: http).exchange(publicToken: publicToken) let connection = Connection(kind: .plaid, name: institution, plaidEnvironment: environment.rawValue) try Keychain.set(access, for: .connection(connection.id)) try store.update { $0.connections.append(connection) } try await sync(connection) return connection } public func importCSV(_ text: String, fileName: String) throws -> (transactions: Int, accounts: Int) { let ws = try store.load() let connection = ws.connections.first { $0.kind == .csv && $0.name == fileName } ?? Connection(kind: .csv, name: fileName) let result = try CSVImport.parse(text, connectionID: connection.id, categories: ws.categories) try store.update { ws in for c in result.newCategories where !ws.categories.contains(where: { $0.id == c.id }) { ws.categories.append(c) } } var pull = BankPull(); pull.accounts = result.accounts; pull.transactions = result.transactions try apply(pull, to: connection) try store.mergeEdits(result.edits) return (result.transactions.count, result.accounts.count) } /// CSV and manual accounts have no live balance; the user types it and Bucksley rebuilds the /// account's history from its transactions. public func setManualBalance(_ accountID: String, balance: Decimal, today: String = DayKey.today) throws { var updated: Account? try store.update { ws in guard let i = ws.accounts.firstIndex(where: { $0.id == accountID }) else { return } ws.accounts[i].balance = balance; ws.accounts[i].balanceDate = .now updated = ws.accounts[i] } guard let account = updated else { throw BucksleyError.missing("No account \(accountID).") } try store.replaceBalances(try store.balances().filter { $0.accountID != accountID }) try store.recordBalances([account], today: today) } /// Removes a connection, its accounts, transactions, balances and Keychain secret. public func disconnect(_ connectionID: String) throws { Keychain.remove(.connection(connectionID)) let accountIDs = Set(try store.load().accounts.filter { $0.connectionID == connectionID }.map(\.id)) try store.removeTransactions { accountIDs.contains($0.accountID) } try store.replaceBalances(try store.balances().filter { !accountIDs.contains($0.accountID) }) try store.update { ws in ws.connections.removeAll { $0.id == connectionID } ws.accounts.removeAll { accountIDs.contains($0.id) } } } }