import Foundation /// The Mac's local store (the iPhone keeps the same files as its cache of what the Mac shared). /// The app and the `--mcp` process open the same folder, so writes are coordinated through /// NSFileCoordinator and each write re-reads the file first, so one process never silently drops /// another's change. /// /// Files: `workspace.json` (accounts, connections, categories, rules, budgets, settings, agent log), /// `transactions.json` (bank data), `edits.json` (the user's changes, keyed by transaction ID) and /// `balances.json` (daily balances for the net worth chart). public final class WorkspaceStore: @unchecked Sendable { public let folder: URL private let lock = NSLock() enum File: String { case workspace, transactions, edits, balances } private func url(_ file: File) -> URL { folder.appendingPathComponent(file.rawValue + ".json") } public static var defaultFolder: URL { if let override = ProcessInfo.processInfo.environment["BUCKSLEY_WORKSPACE"] { return URL(fileURLWithPath: override, isDirectory: true) } let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] return base.appendingPathComponent("Bucksley", isDirectory: true) } public init(folder: URL = WorkspaceStore.defaultFolder) throws { self.folder = folder try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) } // MARK: Reads public func load() throws -> Workspace { try read(.workspace) ?? Workspace() } public func transactions() throws -> [Transaction] { try read(.transactions) ?? [] } public func edits() throws -> [String: TransactionEdit] { try read(.edits) ?? [:] } public func balances() throws -> [BalancePoint] { try read(.balances) ?? [] } public func ledger() throws -> Ledger { Ledger(workspace: try load(), transactions: try transactions(), edits: try edits(), balances: try balances()) } /// When any store file last changed (by this process or the `--mcp` one). public func lastModified() -> Date? { [File.workspace, .transactions, .edits, .balances] .compactMap { try? url($0).resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate }.max() } // MARK: Writes @discardableResult public func update(_ change: (inout Workspace) throws -> Void) throws -> Workspace { try coordinated(.workspace, empty: Workspace(), change) } /// Applies one user edit (merged field by field over any earlier one) and returns the result. @discardableResult public func edit(_ transactionID: String, device: String = DeviceName.current, _ change: (inout TransactionEdit) -> Void) throws -> TransactionEdit { var result = TransactionEdit(transactionID: transactionID) try coordinated(.edits, empty: [String: TransactionEdit]()) { all in var e = all[transactionID] ?? TransactionEdit(transactionID: transactionID, device: device) change(&e) e.updatedAt = .now; e.device = device all[transactionID] = e result = e } return result } /// Takes edits that arrived from iCloud. A newer edit wins field by field; returns how many changed. @discardableResult public func mergeEdits(_ incoming: [TransactionEdit]) throws -> Int { var changed = 0 try coordinated(.edits, empty: [String: TransactionEdit]()) { all in for e in incoming { if let mine = all[e.transactionID] { guard e.updatedAt > mine.updatedAt else { continue } all[e.transactionID] = e.merged(over: mine) } else { all[e.transactionID] = e } changed += 1 } } return changed } /// Adds or replaces bank transactions by ID. A pending charge that posts under a new ID replaces /// the pending one when the same account, amount and description show up within five days. @discardableResult public func upsert(_ fresh: [Transaction]) throws -> (added: Int, updated: Int) { var added = 0, updated = 0 try coordinated(.transactions, empty: [Transaction]()) { all in var index = Dictionary(uniqueKeysWithValues: all.enumerated().map { ($1.id, $0) }) for tx in fresh { if let i = index[tx.id] { if all[i] != tx { all[i] = Transaction(id: tx.id, accountID: tx.accountID, day: tx.day, amount: tx.amount, description: tx.description, payee: tx.payee, bankCategory: tx.bankCategory, pending: tx.pending, importedAt: all[i].importedAt); updated += 1 } continue } if !tx.pending, let i = all.firstIndex(where: { $0.pending && $0.accountID == tx.accountID && $0.amount == tx.amount && abs(Decimal(DayKey.between($0.day, tx.day))) <= 5 && $0.description.prefix(8) == tx.description.prefix(8) }) { index[all[i].id] = nil all[i] = tx; index[tx.id] = i; updated += 1 continue } all.append(tx); index[tx.id] = all.count - 1; added += 1 } all.sort { ($0.day, $0.id) > ($1.day, $1.id) } } return (added, updated) } public func removeTransactions(where drop: (Transaction) -> Bool) throws { try coordinated(.transactions, empty: [Transaction]()) { all in all.removeAll(where: drop) } } /// Records today's balance for each account. The first time an account is seen, its history is /// rebuilt backwards from its transactions so the net worth chart has a past. public func recordBalances(_ accounts: [Account], today: String = DayKey.today) throws { let txs = try transactions() try coordinated(.balances, empty: [BalancePoint]()) { all in let known = Set(all.map(\.accountID)) for account in accounts { all.removeAll { $0.accountID == account.id && $0.day == today } all.append(BalancePoint(accountID: account.id, day: today, balance: account.balance)) if !known.contains(account.id) { all += Ledger.backfill(account: account, transactions: txs.filter { $0.accountID == account.id }, today: today) } } all.sort { ($0.day, $0.accountID) < ($1.day, $1.accountID) } } } public func replaceBalances(_ points: [BalancePoint]) throws { try coordinated(.balances, empty: [BalancePoint]()) { all in all = points } } /// Swaps every file for a backup's contents (used by restore, after its own safety backup). public func replaceAll(workspace: Workspace, transactions: [Transaction], edits: [String: TransactionEdit], balances: [BalancePoint]) throws { try coordinated(.workspace, empty: Workspace()) { $0 = workspace } try coordinated(.transactions, empty: [Transaction]()) { $0 = transactions } try coordinated(.edits, empty: [String: TransactionEdit]()) { $0 = edits } try coordinated(.balances, empty: [BalancePoint]()) { $0 = balances } } // MARK: Files @discardableResult private func coordinated(_ file: File, empty: T, _ change: (inout T) throws -> Void) throws -> T { lock.lock(); defer { lock.unlock() } var result = empty var failure: Error? var coordinationError: NSError? NSFileCoordinator().coordinate(writingItemAt: url(file), options: .forMerging, error: &coordinationError) { target in do { var value: T = try decode(target) ?? empty try change(&value) try JSONEncoder.bucksley.encode(value).write(to: target, options: [.atomic]) result = value } catch { failure = error } } if let coordinationError { throw coordinationError } if let failure { throw failure } return result } private func read(_ file: File) throws -> T? { try decode(url(file)) } private func decode(_ url: URL) throws -> T? { guard FileManager.default.fileExists(atPath: url.path) else { return nil } return try JSONDecoder.bucksley.decode(T.self, from: Data(contentsOf: url)) } } public extension JSONEncoder { static var bucksley: JSONEncoder { let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.sortedKeys]; return e } } public extension JSONDecoder { static var bucksley: JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d } }