Bucksley / app / Sources / BucksleyKit / WorkspaceStore.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// The Mac's local store (the iPhone keeps the same files as its cache of what the Mac shared). |
| 4 | /// The app and the `--mcp` process open the same folder, so writes are coordinated through |
| 5 | /// NSFileCoordinator and each write re-reads the file first, so one process never silently drops |
| 6 | /// another's change. |
| 7 | /// |
| 8 | /// Files: `workspace.json` (accounts, connections, categories, rules, budgets, settings, agent log), |
| 9 | /// `transactions.json` (bank data), `edits.json` (the user's changes, keyed by transaction ID) and |
| 10 | /// `balances.json` (daily balances for the net worth chart). |
| 11 | public final class WorkspaceStore: @unchecked Sendable { |
| 12 | public let folder: URL |
| 13 | private let lock = NSLock() |
| 14 | |
| 15 | enum File: String { case workspace, transactions, edits, balances } |
| 16 | private func url(_ file: File) -> URL { folder.appendingPathComponent(file.rawValue + ".json") } |
| 17 | |
| 18 | public static var defaultFolder: URL { |
| 19 | if let override = ProcessInfo.processInfo.environment["BUCKSLEY_WORKSPACE"] { return URL(fileURLWithPath: override, isDirectory: true) } |
| 20 | let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 21 | return base.appendingPathComponent("Bucksley", isDirectory: true) |
| 22 | } |
| 23 | |
| 24 | public init(folder: URL = WorkspaceStore.defaultFolder) throws { |
| 25 | self.folder = folder |
| 26 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 27 | } |
| 28 | |
| 29 | // MARK: Reads |
| 30 | |
| 31 | public func load() throws -> Workspace { try read(.workspace) ?? Workspace() } |
| 32 | public func transactions() throws -> [Transaction] { try read(.transactions) ?? [] } |
| 33 | public func edits() throws -> [String: TransactionEdit] { try read(.edits) ?? [:] } |
| 34 | public func balances() throws -> [BalancePoint] { try read(.balances) ?? [] } |
| 35 | |
| 36 | public func ledger() throws -> Ledger { |
| 37 | Ledger(workspace: try load(), transactions: try transactions(), edits: try edits(), balances: try balances()) |
| 38 | } |
| 39 | |
| 40 | /// When any store file last changed (by this process or the `--mcp` one). |
| 41 | public func lastModified() -> Date? { |
| 42 | [File.workspace, .transactions, .edits, .balances] |
| 43 | .compactMap { try? url($0).resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate }.max() |
| 44 | } |
| 45 | |
| 46 | // MARK: Writes |
| 47 | |
| 48 | @discardableResult |
| 49 | public func update(_ change: (inout Workspace) throws -> Void) throws -> Workspace { |
| 50 | try coordinated(.workspace, empty: Workspace(), change) |
| 51 | } |
| 52 | |
| 53 | /// Applies one user edit (merged field by field over any earlier one) and returns the result. |
| 54 | @discardableResult |
| 55 | public func edit(_ transactionID: String, device: String = DeviceName.current, _ change: (inout TransactionEdit) -> Void) throws -> TransactionEdit { |
| 56 | var result = TransactionEdit(transactionID: transactionID) |
| 57 | try coordinated(.edits, empty: [String: TransactionEdit]()) { all in |
| 58 | var e = all[transactionID] ?? TransactionEdit(transactionID: transactionID, device: device) |
| 59 | change(&e) |
| 60 | e.updatedAt = .now; e.device = device |
| 61 | all[transactionID] = e |
| 62 | result = e |
| 63 | } |
| 64 | return result |
| 65 | } |
| 66 | |
| 67 | /// Takes edits that arrived from iCloud. A newer edit wins field by field; returns how many changed. |
| 68 | @discardableResult |
| 69 | public func mergeEdits(_ incoming: [TransactionEdit]) throws -> Int { |
| 70 | var changed = 0 |
| 71 | try coordinated(.edits, empty: [String: TransactionEdit]()) { all in |
| 72 | for e in incoming { |
| 73 | if let mine = all[e.transactionID] { |
| 74 | guard e.updatedAt > mine.updatedAt else { continue } |
| 75 | all[e.transactionID] = e.merged(over: mine) |
| 76 | } else { |
| 77 | all[e.transactionID] = e |
| 78 | } |
| 79 | changed += 1 |
| 80 | } |
| 81 | } |
| 82 | return changed |
| 83 | } |
| 84 | |
| 85 | /// Adds or replaces bank transactions by ID. A pending charge that posts under a new ID replaces |
| 86 | /// the pending one when the same account, amount and description show up within five days. |
| 87 | @discardableResult |
| 88 | public func upsert(_ fresh: [Transaction]) throws -> (added: Int, updated: Int) { |
| 89 | var added = 0, updated = 0 |
| 90 | try coordinated(.transactions, empty: [Transaction]()) { all in |
| 91 | var index = Dictionary(uniqueKeysWithValues: all.enumerated().map { ($1.id, $0) }) |
| 92 | for tx in fresh { |
| 93 | if let i = index[tx.id] { |
| 94 | if all[i] != tx { all[i] = Transaction(id: tx.id, accountID: tx.accountID, day: tx.day, amount: tx.amount, description: tx.description, |
| 95 | payee: tx.payee, bankCategory: tx.bankCategory, pending: tx.pending, importedAt: all[i].importedAt); updated += 1 } |
| 96 | continue |
| 97 | } |
| 98 | if !tx.pending, let i = all.firstIndex(where: { $0.pending && $0.accountID == tx.accountID && $0.amount == tx.amount |
| 99 | && abs(Decimal(DayKey.between($0.day, tx.day))) <= 5 && $0.description.prefix(8) == tx.description.prefix(8) }) { |
| 100 | index[all[i].id] = nil |
| 101 | all[i] = tx; index[tx.id] = i; updated += 1 |
| 102 | continue |
| 103 | } |
| 104 | all.append(tx); index[tx.id] = all.count - 1; added += 1 |
| 105 | } |
| 106 | all.sort { ($0.day, $0.id) > ($1.day, $1.id) } |
| 107 | } |
| 108 | return (added, updated) |
| 109 | } |
| 110 | |
| 111 | public func removeTransactions(where drop: (Transaction) -> Bool) throws { |
| 112 | try coordinated(.transactions, empty: [Transaction]()) { all in all.removeAll(where: drop) } |
| 113 | } |
| 114 | |
| 115 | /// Records today's balance for each account. The first time an account is seen, its history is |
| 116 | /// rebuilt backwards from its transactions so the net worth chart has a past. |
| 117 | public func recordBalances(_ accounts: [Account], today: String = DayKey.today) throws { |
| 118 | let txs = try transactions() |
| 119 | try coordinated(.balances, empty: [BalancePoint]()) { all in |
| 120 | let known = Set(all.map(\.accountID)) |
| 121 | for account in accounts { |
| 122 | all.removeAll { $0.accountID == account.id && $0.day == today } |
| 123 | all.append(BalancePoint(accountID: account.id, day: today, balance: account.balance)) |
| 124 | if !known.contains(account.id) { |
| 125 | all += Ledger.backfill(account: account, transactions: txs.filter { $0.accountID == account.id }, today: today) |
| 126 | } |
| 127 | } |
| 128 | all.sort { ($0.day, $0.accountID) < ($1.day, $1.accountID) } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | public func replaceBalances(_ points: [BalancePoint]) throws { |
| 133 | try coordinated(.balances, empty: [BalancePoint]()) { all in all = points } |
| 134 | } |
| 135 | |
| 136 | /// Swaps every file for a backup's contents (used by restore, after its own safety backup). |
| 137 | public func replaceAll(workspace: Workspace, transactions: [Transaction], edits: [String: TransactionEdit], balances: [BalancePoint]) throws { |
| 138 | try coordinated(.workspace, empty: Workspace()) { $0 = workspace } |
| 139 | try coordinated(.transactions, empty: [Transaction]()) { $0 = transactions } |
| 140 | try coordinated(.edits, empty: [String: TransactionEdit]()) { $0 = edits } |
| 141 | try coordinated(.balances, empty: [BalancePoint]()) { $0 = balances } |
| 142 | } |
| 143 | |
| 144 | // MARK: Files |
| 145 | |
| 146 | @discardableResult |
| 147 | private func coordinated<T: Codable>(_ file: File, empty: T, _ change: (inout T) throws -> Void) throws -> T { |
| 148 | lock.lock(); defer { lock.unlock() } |
| 149 | var result = empty |
| 150 | var failure: Error? |
| 151 | var coordinationError: NSError? |
| 152 | NSFileCoordinator().coordinate(writingItemAt: url(file), options: .forMerging, error: &coordinationError) { target in |
| 153 | do { |
| 154 | var value: T = try decode(target) ?? empty |
| 155 | try change(&value) |
| 156 | try JSONEncoder.bucksley.encode(value).write(to: target, options: [.atomic]) |
| 157 | result = value |
| 158 | } catch { failure = error } |
| 159 | } |
| 160 | if let coordinationError { throw coordinationError } |
| 161 | if let failure { throw failure } |
| 162 | return result |
| 163 | } |
| 164 | |
| 165 | private func read<T: Decodable>(_ file: File) throws -> T? { try decode(url(file)) } |
| 166 | |
| 167 | private func decode<T: Decodable>(_ url: URL) throws -> T? { |
| 168 | guard FileManager.default.fileExists(atPath: url.path) else { return nil } |
| 169 | return try JSONDecoder.bucksley.decode(T.self, from: Data(contentsOf: url)) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | public extension JSONEncoder { |
| 174 | static var bucksley: JSONEncoder { |
| 175 | let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.sortedKeys]; return e |
| 176 | } |
| 177 | } |
| 178 | public extension JSONDecoder { |
| 179 | static var bucksley: JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d } |
| 180 | } |