import Foundation /// Everything the screens, the iPhone and agents read, computed from the store in one place: /// resolved transactions, net worth over time, spending, budgets, suggestions and recurring items. public struct Ledger: Sendable { public let workspace: Workspace public let entries: [LedgerEntry] public let balances: [BalancePoint] public init(workspace: Workspace, transactions: [Transaction], edits: [String: TransactionEdit], balances: [BalancePoint]) { self.workspace = workspace self.balances = balances let hidden = Set(workspace.accounts.filter(\.hidden).map(\.id)) let resolved = transactions.filter { !hidden.contains($0.accountID) } .map { Ledger.resolve($0, rules: workspace.rules, edit: edits[$0.id]) } .sorted { ($0.day, $0.id) > ($1.day, $1.id) } entries = Ledger.matchTransfers(resolved, workspace: workspace) } /// Money that leaves one of your accounts and lands in another (a card payment from checking) /// is a transfer, not spending and income. Pairs equal and opposite amounts in two different /// accounts within four days. A category you or a rule chose always wins. static func matchTransfers(_ entries: [LedgerEntry], workspace: Workspace) -> [LedgerEntry] { var result = entries func open(_ e: LedgerEntry) -> Bool { !e.categoryChosen && e.ruleID == nil && !e.transaction.pending } let transferIDs = Set(workspace.categories.filter { $0.kind == .transfer }.map(\.id)) var byAmount: [Decimal: [Int]] = [:] for (i, e) in result.enumerated() where open(e) && e.amount > 0 { byAmount[e.amount, default: []].append(i) } var used = Set() for (i, out) in result.enumerated() where open(out) && out.amount < 0 { guard let j = byAmount[-out.amount]?.first(where: { j in !used.contains(j) && result[j].accountID != out.accountID && abs(DayKey.between(out.day, result[j].day)) <= 4 }) else { continue } used.insert(j) for k in [i, j] where !transferIDs.contains(result[k].categoryID) { result[k].categoryID = "transfer" } } return result } /// Bank data, then the first matching rule, then the user's edit. public static func resolve(_ tx: Transaction, rules: [Rule], edit: TransactionEdit?) -> LedgerEntry { var entry = LedgerEntry(transaction: tx, name: Defaults.cleanName(tx.payee?.isEmpty == false ? tx.payee! : tx.description), categoryID: Defaults.guessCategory(tx), note: nil, tags: [], reviewed: false, splits: [], excluded: false, ruleID: nil, edited: edit != nil) if let rule = rules.first(where: { $0.matches(tx) }) { entry.ruleID = rule.id if let c = rule.setCategoryID { entry.categoryID = c } if let r = rule.rename, !r.isEmpty { entry.name = r } entry.tags = rule.addTags if rule.markReviewed { entry.reviewed = true } } if let edit { if let v = edit.name, !v.isEmpty { entry.name = v } if let v = edit.categoryID { entry.categoryID = v; entry.categoryChosen = true } if let v = edit.note { entry.note = v.isEmpty ? nil : v } if let v = edit.tags { entry.tags = v } if let v = edit.reviewed { entry.reviewed = v } if let v = edit.splits { entry.splits = v } if let v = edit.excluded { entry.excluded = v } entry.refundOf = edit.refundOf.flatMap { $0.isEmpty ? nil : $0 } } return entry } // MARK: Accounts and net worth public var visibleAccounts: [Account] { workspace.accounts.filter { !$0.hidden } } public var netWorth: Decimal { visibleAccounts.reduce(0) { $0 + $1.balance } } public var assets: Decimal { visibleAccounts.filter { $0.balance > 0 }.reduce(0) { $0 + $1.balance } } public var debts: Decimal { visibleAccounts.filter { $0.balance < 0 }.reduce(0) { $0 + $1.balance } } public func total(_ group: AccountGroup) -> Decimal { visibleAccounts.filter { $0.kind.group == group }.reduce(0) { $0 + $1.balance } } public struct NetWorthPoint: Hashable, Sendable { public let day: String public let total: Decimal public let byGroup: [AccountGroup: Decimal] public init(day: String, total: Decimal, byGroup: [AccountGroup: Decimal]) { self.day = day; self.total = total; self.byGroup = byGroup } } /// One point per day for the last `days` days. Each account's last known balance carries forward /// across days with no reading. public func netWorthSeries(days: Int) -> [NetWorthPoint] { let accounts = visibleAccounts let byAccount = Dictionary(grouping: balances, by: \.accountID).mapValues { $0.sorted { $0.day < $1.day } } let active = accountsWithActivity return DayKey.lastDays(days).map { day in var groups: [AccountGroup: Decimal] = [:] for account in accounts { // An account with no activity held the same balance before Bucksley first saw it. guard let points = byAccount[account.id], let value = (points.last(where: { $0.day <= day }) ?? (active.contains(account.id) ? nil : points.first))?.balance else { continue } groups[account.kind.group, default: 0] += value } return NetWorthPoint(day: day, total: groups.values.reduce(0, +), byGroup: groups) } } /// Change over the window, measured from the first day every visible account has history, /// so a new connection doesn't read as a gain from zero. public func change(days: Int) -> Decimal { let series = netWorthSeries(days: days + 1) let start = historyStart guard let first = series.first(where: { start == nil || $0.day >= start! })?.total, let last = series.last?.total else { return 0 } return last - first } var accountsWithActivity: Set { Set(entries.map(\.accountID)) } /// The first day on which every visible account with activity has a balance. public var historyStart: String? { let ids = Set(visibleAccounts.map(\.id)).intersection(accountsWithActivity) let firsts = Dictionary(grouping: balances.filter { ids.contains($0.accountID) }, by: \.accountID).compactMap { $0.value.map(\.day).min() } return firsts.max() } public func accountSeries(_ id: String, days: Int) -> [(day: String, balance: Decimal)] { let points = balances.filter { $0.accountID == id }.sorted { $0.day < $1.day } return DayKey.lastDays(days).compactMap { day in points.last { $0.day <= day }.map { (day, $0.balance) } } } /// Walks backwards from today's balance: yesterday's close = today's close minus today's activity. public static func backfill(account: Account, transactions: [Transaction], today: String, days: Int = 365) -> [BalancePoint] { let byDay = Dictionary(grouping: transactions.filter { !$0.pending }, by: \.day).mapValues { $0.reduce(Decimal(0)) { $0 + $1.amount } } guard let oldest = transactions.map(\.day).min() else { return [] } var balance = account.balance, out: [BalancePoint] = [] var day = today for _ in 0.. [LedgerEntry] { entries.filter { MonthKey.of($0.day) == month } } func kind(_ categoryID: String) -> CategoryKind { workspace.category(categoryID)?.kind ?? .expense } /// Money out per expense category in a month, largest first. Refunds in a category reduce it. public func spending(month: String = MonthKey.current) -> [(categoryID: String, amount: Decimal)] { var totals: [String: Decimal] = [:] for entry in entries(in: month) where !entry.excluded { for part in entry.parts where kind(part.categoryID) == .expense { totals[part.categoryID, default: 0] -= part.amount } } return totals.filter { $0.value > 0 }.map { ($0.key, $0.value) }.sorted { $0.1 > $1.1 } } /// Spent in a category, or in every category of a group when the ID is a group's. public func spent(_ categoryID: String, month: String) -> Decimal { let ids = categoryIDs(for: categoryID) return entries(in: month).filter { !$0.excluded }.flatMap(\.parts).filter { ids.contains($0.categoryID) }.reduce(0) { $0 - $1.amount } } /// A category's own ID, or a group's member categories. public func categoryIDs(for id: String) -> Set { guard isGroup(id) else { return [id] } return Set(workspace.categories.filter { $0.groupID == id }.map(\.id)) } public func isGroup(_ id: String) -> Bool { workspace.groups.contains { $0.id == id } && !workspace.categories.contains { $0.id == id } } /// The name a budget shows: the category's or the group's. public func budgetName(_ id: String) -> String { workspace.category(id)?.name ?? workspace.groups.first { $0.id == id }?.name ?? id } public func income(month: String = MonthKey.current) -> Decimal { entries(in: month).filter { !$0.excluded }.flatMap(\.parts).filter { kind($0.categoryID) == .income }.reduce(0) { $0 + $1.amount } } // MARK: Budgets public struct BudgetStatus: Identifiable, Hashable, Sendable { public let budget: Budget public let spent: Decimal public let carried: Decimal /// Share of the month gone, 0...1, for the pace tick. public let pace: Double public var id: String { budget.categoryID } public let month: String public var allowed: Decimal { budget.amount(for: month) } public var available: Decimal { allowed + carried } public var remaining: Decimal { available - spent } public var progress: Double { available > 0 ? (spent / available).double : (spent > 0 ? 1 : 0) } public var aheadOfPace: Bool { progress > pace + 0.05 } } public func budgetStatus(month: String = MonthKey.current, today: String = DayKey.today) -> [BudgetStatus] { let pace: Double = { if month < MonthKey.of(today) { return 1 } if month > MonthKey.of(today) { return 0 } let day = Int(today.suffix(2)) ?? 1 return Double(day) / Double(MonthKey.days(in: month)) }() return workspace.budgets.map { budget in var carried: Decimal = 0 if budget.rollover { var m = budget.startMonth while m < month { carried += budget.amount(for: m) - spent(budget.categoryID, month: m) m = MonthKey.adding(1, to: m) } } return BudgetStatus(budget: budget, spent: spent(budget.categoryID, month: month), carried: carried, pace: pace, month: month) }.sorted { $0.progress > $1.progress } } /// Budgeted and spent for the month as a whole. A group budget stands for its categories, so a /// category budget inside a budgeted group is not counted twice. public func budgetTotals(month: String = MonthKey.current, today: String = DayKey.today) -> (budgeted: Decimal, spent: Decimal) { let statuses = budgetStatus(month: month, today: today) let budgetedGroups = Set(workspace.budgets.map(\.categoryID).filter(isGroup)) let counted = statuses.filter { s in isGroup(s.budget.categoryID) || !budgetedGroups.contains(workspace.category(s.budget.categoryID)?.groupID ?? "") } return (counted.reduce(0) { $0 + $1.available }, counted.reduce(0) { $0 + $1.spent }) } /// True when a category budget sits inside a group that has its own budget. public func isCoveredByGroupBudget(_ categoryID: String) -> Bool { guard let group = workspace.category(categoryID)?.groupID else { return false } return workspace.budgets.contains { $0.categoryID == group } && isGroup(group) } public struct BudgetSuggestion: Identifiable, Hashable, Sendable { public let categoryID: String public let amount: Decimal public let typical: Decimal public let months: Int public let reason: String public var id: String { categoryID } } /// Suggested monthly budgets from recent spending, the same way smart budgets start: fixed bills at /// what you spend, flexible categories a little under. Categories with a budget already are suggested /// only when the budget is far from what is actually spent. public func budgetSuggestions(today: String = DayKey.today) -> [BudgetSuggestion] { let months = recentFullMonths(today: today).count guard months > 0 else { return [] } let span = months == 1 ? "last month" : "a month over the last \(months) months" return workspace.categories.filter { $0.kind == .expense }.compactMap { category -> BudgetSuggestion? in let average = recentSpending(category.id, today: today).average guard average > 0, !isCoveredByGroupBudget(category.id) else { return nil } let target = Self.startingBudget(average, fixed: category.isFixed) let spent = "You've spent about \(Money.format(average, cents: false)) on \(category.name) \(span)" if let existing = workspace.budgets.first(where: { $0.categoryID == category.id }) { let gap = abs(existing.amount - target) guard gap >= Swift.max(25, (existing.amount * Decimal(0.2)).rounded(0)) else { return nil } let reason = existing.amount < average ? "\(spent), above your \(Money.format(existing.amount, cents: false)) budget." : "\(spent), well under your \(Money.format(existing.amount, cents: false)) budget." return BudgetSuggestion(categoryID: category.id, amount: target, typical: average, months: months, reason: reason) } return BudgetSuggestion(categoryID: category.id, amount: target, typical: average, months: months, reason: category.isFixed ? "\(spent). It's a fixed bill, so the budget matches it." : "\(spent). Set a little under that to nudge it down.") }.sorted { $0.amount > $1.amount } } /// $12 → $15, $87 → $90, $312 → $325, $1,140 → $1,150. static func friendly(_ value: Decimal) -> Decimal { let v = value.double guard v > 0 else { return 0 } let step: Double = v < 50 ? 5 : v < 200 ? 10 : v < 1000 ? 25 : 50 return Decimal((v / step).rounded(.up) * step) } // MARK: Recurring /// Finds charges that repeat on a steady schedule at a steady amount: three or more from the same /// merchant, spaced like weekly, every two weeks, monthly, quarterly or yearly. public func recurring(today: String = DayKey.today) -> [RecurringItem] { let outflows = entries.filter { $0.amount < 0 && !$0.transaction.pending && kind($0.categoryID) != .transfer } let byMerchant = Dictionary(grouping: outflows) { Self.merchantKey($0.name) } var items: [RecurringItem] = [] for (key, group) in byMerchant where group.count >= 3 && !key.isEmpty { let sorted = group.sorted { $0.day < $1.day } let gaps = zip(sorted, sorted.dropFirst()).map { DayKey.between($0.day, $1.day) }.filter { $0 > 2 } guard gaps.count >= 2 else { continue } let median = gaps.sorted()[gaps.count / 2] guard let cadence = Cadence.allCases.first(where: { Swift.abs(median - $0.days) <= Swift.max(3, $0.days / 10) }) else { continue } let steady = gaps.filter { Swift.abs($0 - median) <= Swift.max(4, median / 5) }.count guard Double(steady) / Double(gaps.count) >= 0.66 else { continue } let amounts = sorted.suffix(4).map { abs($0.amount) } let average = (amounts.reduce(0, +) / Decimal(amounts.count)).rounded() guard let lo = amounts.min(), let hi = amounts.max(), hi - lo <= Swift.max(Decimal(5), average * Decimal(0.25)) else { continue } let last = sorted.last! var next = DayKey.adding(cadence == .monthly ? 0 : median, to: last.day) if cadence == .monthly, let d = DayKey.date(last.day), let n = Calendar.current.date(byAdding: .month, value: 1, to: d) { next = DayKey.from(n) } let status = workspace.recurring[key] ?? .detected // A subscription that stopped long ago isn't recurring anymore. guard DayKey.between(last.day, today) <= cadence.days * 2 + 7 || status == .confirmed else { continue } items.append(RecurringItem(id: key, name: last.name, cadence: cadence, amount: average, lastDay: last.day, nextDay: next, categoryID: last.categoryID, count: sorted.count, status: status)) } // Merchants the user marked recurring by hand, even with too few charges to detect. for (key, status) in workspace.recurring where status == .confirmed && !items.contains(where: { $0.id == key }) { guard let last = (byMerchant[key] ?? []).max(by: { $0.day < $1.day }) else { continue } var next = last.day if let d = DayKey.date(last.day), let n = Calendar.current.date(byAdding: .month, value: 1, to: d) { next = DayKey.from(n) } items.append(RecurringItem(id: key, name: last.name, cadence: .monthly, amount: abs(last.amount), lastDay: last.day, nextDay: next, categoryID: last.categoryID, count: byMerchant[key]?.count ?? 1, status: .confirmed)) } return items.sorted { $0.nextDay < $1.nextDay } } /// One recurring charge in a month: paid (and when), still due, or overdue. public struct MonthBill: Identifiable, Sendable { public var item: RecurringItem public var day: String public var paid: Decimal? public var overdue: Bool public var id: String { item.id } } /// This month's recurring charges, for "left to pay" and "paid so far". public func monthBills(today: String = DayKey.today) -> [MonthBill] { let month = MonthKey.of(today) return recurring(today: today).filter { $0.status != .dismissed }.compactMap { item in let charges = entries.filter { MonthKey.of($0.day) == month && $0.amount < 0 && Self.merchantKey($0.name) == item.id } if let latest = charges.max(by: { $0.day < $1.day }) { return MonthBill(item: item, day: latest.day, paid: charges.reduce(0) { $0 + abs($1.amount) }, overdue: false) } if MonthKey.of(item.nextDay) == month { return MonthBill(item: item, day: item.nextDay, paid: nil, overdue: item.nextDay < today) } if item.nextDay < today && item.cadence.days <= 31 { return MonthBill(item: item, day: item.nextDay, paid: nil, overdue: true) } return nil } .sorted { $0.day < $1.day } } /// The key that ties a transaction to its recurring merchant. public static func recurringKey(_ name: String) -> String { merchantKey(name) } static func merchantKey(_ name: String) -> String { name.lowercased().filter { $0.isLetter || $0 == " " }.split(separator: " ").prefix(3).joined(separator: " ") } // MARK: Review /// The review inbox: everything not yet marked reviewed, newest first. public var reviewQueue: [LedgerEntry] { entries.filter { !$0.reviewed && !$0.excluded } } public func search(_ text: String = "", categoryID: String? = nil, accountID: String? = nil, unreviewedOnly: Bool = false, from: String? = nil, to: String? = nil, tag: String? = nil) -> [LedgerEntry] { let q = text.trimmingCharacters(in: .whitespaces).lowercased() return entries.filter { e in if let categoryID, e.categoryID != categoryID && !e.splits.contains(where: { $0.categoryID == categoryID }) { return false } if let accountID, e.accountID != accountID { return false } if unreviewedOnly && e.reviewed { return false } if let from, e.day < from { return false } if let to, e.day > to { return false } if let tag, !e.tags.contains(tag) { return false } guard !q.isEmpty else { return true } let category = workspace.category(e.categoryID)?.name ?? "" return [e.name, e.transaction.description, e.note ?? "", category, e.tags.joined(separator: " "), Money.format(abs(e.amount))] .contains { $0.lowercased().contains(q) } } } public var allTags: [String] { Array(Set(entries.flatMap(\.tags))).sorted() } }