Bucksley / app · bucksley.ai / Sources / BucksleyKit / Ledger.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Everything the screens, the iPhone and agents read, computed from the store in one place: |
| 4 | /// resolved transactions, net worth over time, spending, budgets, suggestions and recurring items. |
| 5 | public struct Ledger: Sendable { |
| 6 | public let workspace: Workspace |
| 7 | public let entries: [LedgerEntry] |
| 8 | public let balances: [BalancePoint] |
| 9 | |
| 10 | public init(workspace: Workspace, transactions: [Transaction], edits: [String: TransactionEdit], balances: [BalancePoint]) { |
| 11 | self.workspace = workspace |
| 12 | self.balances = balances |
| 13 | let hidden = Set(workspace.accounts.filter(\.hidden).map(\.id)) |
| 14 | let resolved = transactions.filter { !hidden.contains($0.accountID) } |
| 15 | .map { Ledger.resolve($0, rules: workspace.rules, edit: edits[$0.id]) } |
| 16 | .sorted { ($0.day, $0.id) > ($1.day, $1.id) } |
| 17 | entries = Ledger.matchTransfers(resolved, workspace: workspace) |
| 18 | } |
| 19 | |
| 20 | /// Money that leaves one of your accounts and lands in another (a card payment from checking) |
| 21 | /// is a transfer, not spending and income. Pairs equal and opposite amounts in two different |
| 22 | /// accounts within four days. A category you or a rule chose always wins. |
| 23 | static func matchTransfers(_ entries: [LedgerEntry], workspace: Workspace) -> [LedgerEntry] { |
| 24 | var result = entries |
| 25 | func open(_ e: LedgerEntry) -> Bool { !e.categoryChosen && e.ruleID == nil && !e.transaction.pending } |
| 26 | let transferIDs = Set(workspace.categories.filter { $0.kind == .transfer }.map(\.id)) |
| 27 | var byAmount: [Decimal: [Int]] = [:] |
| 28 | for (i, e) in result.enumerated() where open(e) && e.amount > 0 { byAmount[e.amount, default: []].append(i) } |
| 29 | var used = Set<Int>() |
| 30 | for (i, out) in result.enumerated() where open(out) && out.amount < 0 { |
| 31 | guard let j = byAmount[-out.amount]?.first(where: { j in |
| 32 | !used.contains(j) && result[j].accountID != out.accountID && abs(DayKey.between(out.day, result[j].day)) <= 4 |
| 33 | }) else { continue } |
| 34 | used.insert(j) |
| 35 | for k in [i, j] where !transferIDs.contains(result[k].categoryID) { result[k].categoryID = "transfer" } |
| 36 | } |
| 37 | return result |
| 38 | } |
| 39 | |
| 40 | /// Bank data, then the first matching rule, then the user's edit. |
| 41 | public static func resolve(_ tx: Transaction, rules: [Rule], edit: TransactionEdit?) -> LedgerEntry { |
| 42 | var entry = LedgerEntry(transaction: tx, name: Defaults.cleanName(tx.payee?.isEmpty == false ? tx.payee! : tx.description), |
| 43 | categoryID: Defaults.guessCategory(tx), note: nil, tags: [], reviewed: false, splits: [], |
| 44 | excluded: false, ruleID: nil, edited: edit != nil) |
| 45 | if let rule = rules.first(where: { $0.matches(tx) }) { |
| 46 | entry.ruleID = rule.id |
| 47 | if let c = rule.setCategoryID { entry.categoryID = c } |
| 48 | if let r = rule.rename, !r.isEmpty { entry.name = r } |
| 49 | entry.tags = rule.addTags |
| 50 | if rule.markReviewed { entry.reviewed = true } |
| 51 | } |
| 52 | if let edit { |
| 53 | if let v = edit.name, !v.isEmpty { entry.name = v } |
| 54 | if let v = edit.categoryID { entry.categoryID = v; entry.categoryChosen = true } |
| 55 | if let v = edit.note { entry.note = v.isEmpty ? nil : v } |
| 56 | if let v = edit.tags { entry.tags = v } |
| 57 | if let v = edit.reviewed { entry.reviewed = v } |
| 58 | if let v = edit.splits { entry.splits = v } |
| 59 | if let v = edit.excluded { entry.excluded = v } |
| 60 | entry.refundOf = edit.refundOf.flatMap { $0.isEmpty ? nil : $0 } |
| 61 | } |
| 62 | return entry |
| 63 | } |
| 64 | |
| 65 | // MARK: Accounts and net worth |
| 66 | |
| 67 | public var visibleAccounts: [Account] { workspace.accounts.filter { !$0.hidden } } |
| 68 | public var netWorth: Decimal { visibleAccounts.reduce(0) { $0 + $1.balance } } |
| 69 | public var assets: Decimal { visibleAccounts.filter { $0.balance > 0 }.reduce(0) { $0 + $1.balance } } |
| 70 | public var debts: Decimal { visibleAccounts.filter { $0.balance < 0 }.reduce(0) { $0 + $1.balance } } |
| 71 | |
| 72 | public func total(_ group: AccountGroup) -> Decimal { |
| 73 | visibleAccounts.filter { $0.kind.group == group }.reduce(0) { $0 + $1.balance } |
| 74 | } |
| 75 | |
| 76 | public struct NetWorthPoint: Hashable, Sendable { |
| 77 | public let day: String |
| 78 | public let total: Decimal |
| 79 | public let byGroup: [AccountGroup: Decimal] |
| 80 | public init(day: String, total: Decimal, byGroup: [AccountGroup: Decimal]) { self.day = day; self.total = total; self.byGroup = byGroup } |
| 81 | } |
| 82 | |
| 83 | /// One point per day for the last `days` days. Each account's last known balance carries forward |
| 84 | /// across days with no reading. |
| 85 | public func netWorthSeries(days: Int) -> [NetWorthPoint] { |
| 86 | let accounts = visibleAccounts |
| 87 | let byAccount = Dictionary(grouping: balances, by: \.accountID).mapValues { $0.sorted { $0.day < $1.day } } |
| 88 | let active = accountsWithActivity |
| 89 | return DayKey.lastDays(days).map { day in |
| 90 | var groups: [AccountGroup: Decimal] = [:] |
| 91 | for account in accounts { |
| 92 | // An account with no activity held the same balance before Bucksley first saw it. |
| 93 | guard let points = byAccount[account.id], |
| 94 | let value = (points.last(where: { $0.day <= day }) ?? (active.contains(account.id) ? nil : points.first))?.balance else { continue } |
| 95 | groups[account.kind.group, default: 0] += value |
| 96 | } |
| 97 | return NetWorthPoint(day: day, total: groups.values.reduce(0, +), byGroup: groups) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Change over the window, measured from the first day every visible account has history, |
| 102 | /// so a new connection doesn't read as a gain from zero. |
| 103 | public func change(days: Int) -> Decimal { |
| 104 | let series = netWorthSeries(days: days + 1) |
| 105 | let start = historyStart |
| 106 | guard let first = series.first(where: { start == nil || $0.day >= start! })?.total, let last = series.last?.total else { return 0 } |
| 107 | return last - first |
| 108 | } |
| 109 | |
| 110 | var accountsWithActivity: Set<String> { Set(entries.map(\.accountID)) } |
| 111 | |
| 112 | /// The first day on which every visible account with activity has a balance. |
| 113 | public var historyStart: String? { |
| 114 | let ids = Set(visibleAccounts.map(\.id)).intersection(accountsWithActivity) |
| 115 | let firsts = Dictionary(grouping: balances.filter { ids.contains($0.accountID) }, by: \.accountID).compactMap { $0.value.map(\.day).min() } |
| 116 | return firsts.max() |
| 117 | } |
| 118 | |
| 119 | public func accountSeries(_ id: String, days: Int) -> [(day: String, balance: Decimal)] { |
| 120 | let points = balances.filter { $0.accountID == id }.sorted { $0.day < $1.day } |
| 121 | return DayKey.lastDays(days).compactMap { day in points.last { $0.day <= day }.map { (day, $0.balance) } } |
| 122 | } |
| 123 | |
| 124 | /// Walks backwards from today's balance: yesterday's close = today's close minus today's activity. |
| 125 | public static func backfill(account: Account, transactions: [Transaction], today: String, days: Int = 365) -> [BalancePoint] { |
| 126 | let byDay = Dictionary(grouping: transactions.filter { !$0.pending }, by: \.day).mapValues { $0.reduce(Decimal(0)) { $0 + $1.amount } } |
| 127 | guard let oldest = transactions.map(\.day).min() else { return [] } |
| 128 | var balance = account.balance, out: [BalancePoint] = [] |
| 129 | var day = today |
| 130 | for _ in 0..<days { |
| 131 | balance -= byDay[day] ?? 0 |
| 132 | day = DayKey.adding(-1, to: day) |
| 133 | if day < DayKey.adding(-1, to: oldest) { break } |
| 134 | out.append(BalancePoint(accountID: account.id, day: day, balance: balance)) |
| 135 | } |
| 136 | return out |
| 137 | } |
| 138 | |
| 139 | // MARK: Spending |
| 140 | |
| 141 | public func entries(in month: String) -> [LedgerEntry] { entries.filter { MonthKey.of($0.day) == month } } |
| 142 | |
| 143 | func kind(_ categoryID: String) -> CategoryKind { workspace.category(categoryID)?.kind ?? .expense } |
| 144 | |
| 145 | /// Money out per expense category in a month, largest first. Refunds in a category reduce it. |
| 146 | public func spending(month: String = MonthKey.current) -> [(categoryID: String, amount: Decimal)] { |
| 147 | var totals: [String: Decimal] = [:] |
| 148 | for entry in entries(in: month) where !entry.excluded { |
| 149 | for part in entry.parts where kind(part.categoryID) == .expense { totals[part.categoryID, default: 0] -= part.amount } |
| 150 | } |
| 151 | return totals.filter { $0.value > 0 }.map { ($0.key, $0.value) }.sorted { $0.1 > $1.1 } |
| 152 | } |
| 153 | |
| 154 | /// Spent in a category, or in every category of a group when the ID is a group's. |
| 155 | public func spent(_ categoryID: String, month: String) -> Decimal { |
| 156 | let ids = categoryIDs(for: categoryID) |
| 157 | return entries(in: month).filter { !$0.excluded }.flatMap(\.parts).filter { ids.contains($0.categoryID) }.reduce(0) { $0 - $1.amount } |
| 158 | } |
| 159 | |
| 160 | /// A category's own ID, or a group's member categories. |
| 161 | public func categoryIDs(for id: String) -> Set<String> { |
| 162 | guard isGroup(id) else { return [id] } |
| 163 | return Set(workspace.categories.filter { $0.groupID == id }.map(\.id)) |
| 164 | } |
| 165 | |
| 166 | public func isGroup(_ id: String) -> Bool { |
| 167 | workspace.groups.contains { $0.id == id } && !workspace.categories.contains { $0.id == id } |
| 168 | } |
| 169 | |
| 170 | /// The name a budget shows: the category's or the group's. |
| 171 | public func budgetName(_ id: String) -> String { |
| 172 | workspace.category(id)?.name ?? workspace.groups.first { $0.id == id }?.name ?? id |
| 173 | } |
| 174 | |
| 175 | public func income(month: String = MonthKey.current) -> Decimal { |
| 176 | entries(in: month).filter { !$0.excluded }.flatMap(\.parts).filter { kind($0.categoryID) == .income }.reduce(0) { $0 + $1.amount } |
| 177 | } |
| 178 | |
| 179 | // MARK: Budgets |
| 180 | |
| 181 | public struct BudgetStatus: Identifiable, Hashable, Sendable { |
| 182 | public let budget: Budget |
| 183 | public let spent: Decimal |
| 184 | public let carried: Decimal |
| 185 | /// Share of the month gone, 0...1, for the pace tick. |
| 186 | public let pace: Double |
| 187 | public var id: String { budget.categoryID } |
| 188 | public let month: String |
| 189 | public var allowed: Decimal { budget.amount(for: month) } |
| 190 | public var available: Decimal { allowed + carried } |
| 191 | public var remaining: Decimal { available - spent } |
| 192 | public var progress: Double { available > 0 ? (spent / available).double : (spent > 0 ? 1 : 0) } |
| 193 | public var aheadOfPace: Bool { progress > pace + 0.05 } |
| 194 | } |
| 195 | |
| 196 | public func budgetStatus(month: String = MonthKey.current, today: String = DayKey.today) -> [BudgetStatus] { |
| 197 | let pace: Double = { |
| 198 | if month < MonthKey.of(today) { return 1 } |
| 199 | if month > MonthKey.of(today) { return 0 } |
| 200 | let day = Int(today.suffix(2)) ?? 1 |
| 201 | return Double(day) / Double(MonthKey.days(in: month)) |
| 202 | }() |
| 203 | return workspace.budgets.map { budget in |
| 204 | var carried: Decimal = 0 |
| 205 | if budget.rollover { |
| 206 | var m = budget.startMonth |
| 207 | while m < month { |
| 208 | carried += budget.amount(for: m) - spent(budget.categoryID, month: m) |
| 209 | m = MonthKey.adding(1, to: m) |
| 210 | } |
| 211 | } |
| 212 | return BudgetStatus(budget: budget, spent: spent(budget.categoryID, month: month), carried: carried, pace: pace, month: month) |
| 213 | }.sorted { $0.progress > $1.progress } |
| 214 | } |
| 215 | |
| 216 | /// Budgeted and spent for the month as a whole. A group budget stands for its categories, so a |
| 217 | /// category budget inside a budgeted group is not counted twice. |
| 218 | public func budgetTotals(month: String = MonthKey.current, today: String = DayKey.today) -> (budgeted: Decimal, spent: Decimal) { |
| 219 | let statuses = budgetStatus(month: month, today: today) |
| 220 | let budgetedGroups = Set(workspace.budgets.map(\.categoryID).filter(isGroup)) |
| 221 | let counted = statuses.filter { s in |
| 222 | isGroup(s.budget.categoryID) || !budgetedGroups.contains(workspace.category(s.budget.categoryID)?.groupID ?? "") |
| 223 | } |
| 224 | return (counted.reduce(0) { $0 + $1.available }, counted.reduce(0) { $0 + $1.spent }) |
| 225 | } |
| 226 | |
| 227 | /// True when a category budget sits inside a group that has its own budget. |
| 228 | public func isCoveredByGroupBudget(_ categoryID: String) -> Bool { |
| 229 | guard let group = workspace.category(categoryID)?.groupID else { return false } |
| 230 | return workspace.budgets.contains { $0.categoryID == group } && isGroup(group) |
| 231 | } |
| 232 | |
| 233 | public struct BudgetSuggestion: Identifiable, Hashable, Sendable { |
| 234 | public let categoryID: String |
| 235 | public let amount: Decimal |
| 236 | public let typical: Decimal |
| 237 | public let months: Int |
| 238 | public let reason: String |
| 239 | public var id: String { categoryID } |
| 240 | } |
| 241 | |
| 242 | /// Suggested monthly budgets from recent spending, the same way smart budgets start: fixed bills at |
| 243 | /// what you spend, flexible categories a little under. Categories with a budget already are suggested |
| 244 | /// only when the budget is far from what is actually spent. |
| 245 | public func budgetSuggestions(today: String = DayKey.today) -> [BudgetSuggestion] { |
| 246 | let months = recentFullMonths(today: today).count |
| 247 | guard months > 0 else { return [] } |
| 248 | let span = months == 1 ? "last month" : "a month over the last \(months) months" |
| 249 | return workspace.categories.filter { $0.kind == .expense }.compactMap { category -> BudgetSuggestion? in |
| 250 | let average = recentSpending(category.id, today: today).average |
| 251 | guard average > 0, !isCoveredByGroupBudget(category.id) else { return nil } |
| 252 | let target = Self.startingBudget(average, fixed: category.isFixed) |
| 253 | let spent = "You've spent about \(Money.format(average, cents: false)) on \(category.name) \(span)" |
| 254 | if let existing = workspace.budgets.first(where: { $0.categoryID == category.id }) { |
| 255 | let gap = abs(existing.amount - target) |
| 256 | guard gap >= Swift.max(25, (existing.amount * Decimal(0.2)).rounded(0)) else { return nil } |
| 257 | let reason = existing.amount < average |
| 258 | ? "\(spent), above your \(Money.format(existing.amount, cents: false)) budget." |
| 259 | : "\(spent), well under your \(Money.format(existing.amount, cents: false)) budget." |
| 260 | return BudgetSuggestion(categoryID: category.id, amount: target, typical: average, months: months, reason: reason) |
| 261 | } |
| 262 | return BudgetSuggestion(categoryID: category.id, amount: target, typical: average, months: months, |
| 263 | reason: category.isFixed ? "\(spent). It's a fixed bill, so the budget matches it." |
| 264 | : "\(spent). Set a little under that to nudge it down.") |
| 265 | }.sorted { $0.amount > $1.amount } |
| 266 | } |
| 267 | |
| 268 | /// $12 → $15, $87 → $90, $312 → $325, $1,140 → $1,150. |
| 269 | static func friendly(_ value: Decimal) -> Decimal { |
| 270 | let v = value.double |
| 271 | guard v > 0 else { return 0 } |
| 272 | let step: Double = v < 50 ? 5 : v < 200 ? 10 : v < 1000 ? 25 : 50 |
| 273 | return Decimal((v / step).rounded(.up) * step) |
| 274 | } |
| 275 | |
| 276 | // MARK: Recurring |
| 277 | |
| 278 | /// Finds charges that repeat on a steady schedule at a steady amount: three or more from the same |
| 279 | /// merchant, spaced like weekly, every two weeks, monthly, quarterly or yearly. |
| 280 | public func recurring(today: String = DayKey.today) -> [RecurringItem] { |
| 281 | let outflows = entries.filter { $0.amount < 0 && !$0.transaction.pending && kind($0.categoryID) != .transfer } |
| 282 | let byMerchant = Dictionary(grouping: outflows) { Self.merchantKey($0.name) } |
| 283 | var items: [RecurringItem] = [] |
| 284 | for (key, group) in byMerchant where group.count >= 3 && !key.isEmpty { |
| 285 | let sorted = group.sorted { $0.day < $1.day } |
| 286 | let gaps = zip(sorted, sorted.dropFirst()).map { DayKey.between($0.day, $1.day) }.filter { $0 > 2 } |
| 287 | guard gaps.count >= 2 else { continue } |
| 288 | let median = gaps.sorted()[gaps.count / 2] |
| 289 | guard let cadence = Cadence.allCases.first(where: { Swift.abs(median - $0.days) <= Swift.max(3, $0.days / 10) }) else { continue } |
| 290 | let steady = gaps.filter { Swift.abs($0 - median) <= Swift.max(4, median / 5) }.count |
| 291 | guard Double(steady) / Double(gaps.count) >= 0.66 else { continue } |
| 292 | let amounts = sorted.suffix(4).map { abs($0.amount) } |
| 293 | let average = (amounts.reduce(0, +) / Decimal(amounts.count)).rounded() |
| 294 | guard let lo = amounts.min(), let hi = amounts.max(), hi - lo <= Swift.max(Decimal(5), average * Decimal(0.25)) else { continue } |
| 295 | let last = sorted.last! |
| 296 | var next = DayKey.adding(cadence == .monthly ? 0 : median, to: last.day) |
| 297 | if cadence == .monthly, let d = DayKey.date(last.day), let n = Calendar.current.date(byAdding: .month, value: 1, to: d) { next = DayKey.from(n) } |
| 298 | let status = workspace.recurring[key] ?? .detected |
| 299 | // A subscription that stopped long ago isn't recurring anymore. |
| 300 | guard DayKey.between(last.day, today) <= cadence.days * 2 + 7 || status == .confirmed else { continue } |
| 301 | items.append(RecurringItem(id: key, name: last.name, cadence: cadence, amount: average, lastDay: last.day, nextDay: next, |
| 302 | categoryID: last.categoryID, count: sorted.count, status: status)) |
| 303 | } |
| 304 | // Merchants the user marked recurring by hand, even with too few charges to detect. |
| 305 | for (key, status) in workspace.recurring where status == .confirmed && !items.contains(where: { $0.id == key }) { |
| 306 | guard let last = (byMerchant[key] ?? []).max(by: { $0.day < $1.day }) else { continue } |
| 307 | var next = last.day |
| 308 | if let d = DayKey.date(last.day), let n = Calendar.current.date(byAdding: .month, value: 1, to: d) { next = DayKey.from(n) } |
| 309 | items.append(RecurringItem(id: key, name: last.name, cadence: .monthly, amount: abs(last.amount), lastDay: last.day, nextDay: next, |
| 310 | categoryID: last.categoryID, count: byMerchant[key]?.count ?? 1, status: .confirmed)) |
| 311 | } |
| 312 | return items.sorted { $0.nextDay < $1.nextDay } |
| 313 | } |
| 314 | |
| 315 | /// One recurring charge in a month: paid (and when), still due, or overdue. |
| 316 | public struct MonthBill: Identifiable, Sendable { |
| 317 | public var item: RecurringItem |
| 318 | public var day: String |
| 319 | public var paid: Decimal? |
| 320 | public var overdue: Bool |
| 321 | public var id: String { item.id } |
| 322 | } |
| 323 | |
| 324 | /// This month's recurring charges, for "left to pay" and "paid so far". |
| 325 | public func monthBills(today: String = DayKey.today) -> [MonthBill] { |
| 326 | let month = MonthKey.of(today) |
| 327 | return recurring(today: today).filter { $0.status != .dismissed }.compactMap { item in |
| 328 | let charges = entries.filter { MonthKey.of($0.day) == month && $0.amount < 0 && Self.merchantKey($0.name) == item.id } |
| 329 | if let latest = charges.max(by: { $0.day < $1.day }) { |
| 330 | return MonthBill(item: item, day: latest.day, paid: charges.reduce(0) { $0 + abs($1.amount) }, overdue: false) |
| 331 | } |
| 332 | if MonthKey.of(item.nextDay) == month { return MonthBill(item: item, day: item.nextDay, paid: nil, overdue: item.nextDay < today) } |
| 333 | if item.nextDay < today && item.cadence.days <= 31 { return MonthBill(item: item, day: item.nextDay, paid: nil, overdue: true) } |
| 334 | return nil |
| 335 | } |
| 336 | .sorted { $0.day < $1.day } |
| 337 | } |
| 338 | |
| 339 | /// The key that ties a transaction to its recurring merchant. |
| 340 | public static func recurringKey(_ name: String) -> String { merchantKey(name) } |
| 341 | |
| 342 | static func merchantKey(_ name: String) -> String { |
| 343 | name.lowercased().filter { $0.isLetter || $0 == " " }.split(separator: " ").prefix(3).joined(separator: " ") |
| 344 | } |
| 345 | |
| 346 | // MARK: Review |
| 347 | |
| 348 | /// The review inbox: everything not yet marked reviewed, newest first. |
| 349 | public var reviewQueue: [LedgerEntry] { entries.filter { !$0.reviewed && !$0.excluded } } |
| 350 | |
| 351 | public func search(_ text: String = "", categoryID: String? = nil, accountID: String? = nil, unreviewedOnly: Bool = false, |
| 352 | from: String? = nil, to: String? = nil, tag: String? = nil) -> [LedgerEntry] { |
| 353 | let q = text.trimmingCharacters(in: .whitespaces).lowercased() |
| 354 | return entries.filter { e in |
| 355 | if let categoryID, e.categoryID != categoryID && !e.splits.contains(where: { $0.categoryID == categoryID }) { return false } |
| 356 | if let accountID, e.accountID != accountID { return false } |
| 357 | if unreviewedOnly && e.reviewed { return false } |
| 358 | if let from, e.day < from { return false } |
| 359 | if let to, e.day > to { return false } |
| 360 | if let tag, !e.tags.contains(tag) { return false } |
| 361 | guard !q.isEmpty else { return true } |
| 362 | let category = workspace.category(e.categoryID)?.name ?? "" |
| 363 | return [e.name, e.transaction.description, e.note ?? "", category, e.tags.joined(separator: " "), Money.format(abs(e.amount))] |
| 364 | .contains { $0.lowercased().contains(q) } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | public var allTags: [String] { Array(Set(entries.flatMap(\.tags))).sorted() } |
| 369 | } |