import Foundation /// A whole budget plan built from your own recent spending and income: one recommended amount for each /// category you spend in. Fixed spending you can't easily change (rent, insurance, utilities and the like) /// is budgeted at what you actually spend and never cut. Flexible spending is set a little under what you /// spend now, and trimmed a bit more when the plan runs past your savings goal. public struct SmartBudgetPlan: Sendable, Hashable { public struct Item: Identifiable, Sendable, Hashable { public let categoryID: String public let name: String public let fixed: Bool /// The average of the last few full months. public let typical: Decimal public let recommended: Decimal /// The budget already set for this category, if any. public let current: Decimal? public let reason: String public var id: String { categoryID } } public let months: Int /// A typical month of income, or zero when there's none on record. public let income: Decimal /// A typical month of spending across the categories in the plan. public let typicalSpending: Decimal public let savingsRate: Int public let items: [Item] public var total: Decimal { items.reduce(0) { $0 + $1.recommended } } public var savingsGoal: Decimal { (income * Decimal(savingsRate) / 100).rounded(0) } /// What's left each month if every budget is met. public var leftOver: Decimal { income - total } public var fixedItems: [Item] { items.filter(\.fixed) } public var flexible: [Item] { items.filter { !$0.fixed } } /// Plain-language coaching for the plan, a few sentences. public var summary: String { guard !items.isEmpty else { return "There isn't a full month of spending yet, so there's nothing to base budgets on." } var lines: [String] = [] if income > 0 { lines.append("You bring in about \(Money.format(income, cents: false)) a month and have recently spent \(Money.format(typicalSpending, cents: false)) a month across these categories.") lines.append("This plan budgets \(Money.format(total, cents: false)) a month, which leaves \(Money.format(leftOver, cents: false)) against a \(savingsRate)% savings goal of \(Money.format(savingsGoal, cents: false)).") if leftOver < savingsGoal { lines.append("Even with flexible spending trimmed, the goal is out of reach. The biggest lever is \(biggestFlexible?.name ?? "your largest category").") } } else { lines.append("There's no income on record yet, so the plan follows your recent spending without a savings goal.") } if !fixedItems.isEmpty { lines.append("Fixed bills (" + fixedItems.map(\.name).joined(separator: ", ") + ") are budgeted at what you spend.") } return lines.joined(separator: " ") } var biggestFlexible: Item? { flexible.max { $0.typical < $1.typical } } /// Saves the chosen items as budgets. Other budgets stay, and a category's rollover setting is kept. public static func apply(_ items: [Item], amounts: [String: Decimal] = [:], to workspace: inout Workspace, month: String = MonthKey.current) { for item in items { let amount = amounts[item.categoryID] ?? item.recommended guard amount > 0 else { continue } let rollover = workspace.budgets.first { $0.categoryID == item.categoryID }?.rollover ?? false workspace.budgets.removeAll { $0.categoryID == item.categoryID } workspace.budgets.append(Budget(categoryID: item.categoryID, amount: amount, rollover: rollover, startMonth: month)) } } } public extension Ledger { /// How many recent full months a plan averages: enough to smooth one odd month, recent enough to /// follow how you spend now. static let recentMonths = 3 /// Average spending in a category over the last few full months, and how many months that covers. func recentSpending(_ categoryID: String, today: String = DayKey.today) -> (average: Decimal, months: Int) { let months = recentFullMonths(today: today) guard !months.isEmpty else { return (0, 0) } let total = months.reduce(Decimal(0)) { $0 + spent(categoryID, month: $1) } return ((total / Decimal(months.count)).rounded(0), months.count) } func recentFullMonths(today: String = DayKey.today) -> [String] { let thisMonth = MonthKey.of(today) let earliest = entries.map(\.day).min().map(MonthKey.of) ?? thisMonth return (1...Self.recentMonths).map { MonthKey.adding(-$0, to: thisMonth) }.filter { $0 >= earliest } } /// The starting budget for a category: fixed spending at what you spend, flexible spending about 8% /// under, rounded to a friendly number that stays below what you spend. static func startingBudget(_ average: Decimal, fixed: Bool) -> Decimal { if fixed { return friendly(average) } let nearest = friendlyNearest(average * Decimal(string: "0.92")!) return Swift.max(nearest < average ? nearest : friendlyDown(average * Decimal(string: "0.92")!), 5) } static func friendlyNearest(_ 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() * step) } /// Builds a plan from the last full months. `savingsRate` is the share of income to keep free. func smartBudgetPlan(savingsRate: Int = 20, today: String = DayKey.today) -> SmartBudgetPlan { let months = recentFullMonths(today: today) let rate = Swift.min(Swift.max(savingsRate, 0), 60) guard !months.isEmpty else { return SmartBudgetPlan(months: 0, income: 0, typicalSpending: 0, savingsRate: rate, items: []) } let income = (months.reduce(Decimal(0)) { $0 + self.income(month: $1) } / Decimal(months.count)).rounded(0) struct Draft { let category: Category; let fixed: Bool; let typical: Decimal; var amount: Decimal } var drafts: [Draft] = workspace.categories.filter { $0.kind == .expense && !isCoveredByGroupBudget($0.id) }.compactMap { category in let typical = recentSpending(category.id, today: today).average // Under $10 a month isn't worth a budget. guard typical >= 10 else { return nil } return Draft(category: category, fixed: category.isFixed, typical: typical, amount: Ledger.startingBudget(typical, fixed: category.isFixed)) } // Past the savings goal, trim the big flexible categories a little more, largest first, never below // 80% of what's spent now. Small categories barely move the goal, so they stay just under what's // spent, and fixed spending is never cut. var trimmed: Set = [] if income > 0 { let room = income - (income * Decimal(rate) / 100) var over = drafts.reduce(Decimal(0)) { $0 + $1.amount } - room for i in drafts.indices.sorted(by: { drafts[$0].typical > drafts[$1].typical }) where over > 0 && !drafts[i].fixed && drafts[i].typical >= 200 { let floor = Swift.max(Ledger.friendly(drafts[i].typical * Decimal(string: "0.8")!), 5) let target = Swift.max(Ledger.friendlyDown(drafts[i].amount - over), floor) guard target < drafts[i].amount else { continue } over -= drafts[i].amount - target trimmed.insert(drafts[i].category.id) drafts[i].amount = target } } let span = months.count == 1 ? "Last month" : "The last \(months.count) months averaged" let items = drafts.map { d -> SmartBudgetPlan.Item in let current = workspace.budgets.first { $0.categoryID == d.category.id }?.amount let typical = Money.format(d.typical, cents: false) let reason: String if d.fixed { reason = "\(span) \(typical). This is a bill you can't easily change, so the budget matches it." } else if trimmed.contains(d.category.id) { reason = "\(span) \(typical). Set to \(Money.format(d.amount, cents: false)) to make room for your savings goal." } else { reason = "\(span) \(typical). Set a little under that so it nudges you to spend less." } return .init(categoryID: d.category.id, name: d.category.name, fixed: d.fixed, typical: d.typical, recommended: d.amount, current: current, reason: reason) } .sorted { ($0.fixed ? 0 : 1, -$0.typical.double) < ($1.fixed ? 0 : 1, -$1.typical.double) } return SmartBudgetPlan(months: months.count, income: income, typicalSpending: drafts.reduce(0) { $0 + $1.typical }, savingsRate: rate, items: items) } /// Like `friendly`, but rounds down so a trim stays a trim. static func friendlyDown(_ 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(.down) * step) } }