import Foundation /// The smart parts of Bucksley, all computed from the user's own numbers on the device: cash flow, /// the monthly recap, unusual-charge flags, refund matches, the review order, category suggestions /// and rule previews. Nothing here guesses with a model; `AskBucksley` only rewords the recap. extension Ledger { // MARK: Cash flow public struct CashFlowMonth: Identifiable, Hashable, Sendable { public let month: String public let income: Decimal /// Money out on expense categories, net of refunds. public let spend: Decimal public var net: Decimal { income - spend } /// Share of income kept, nil in a month with no income. public var savingsRate: Double? { income > 0 ? (net / income).double : nil } public var id: String { month } } /// Income, spend and net for the last `months` months, oldest first, ending with `through`. public func cashFlow(months: Int = 12, through: String = MonthKey.current) -> [CashFlowMonth] { (0.. (income: Decimal, spend: Decimal, net: Decimal, savingsRate: Double?) { let active = months.filter { $0.income != 0 || $0.spend != 0 } guard !active.isEmpty else { return (0, 0, 0, nil) } let n = Decimal(active.count) let income = active.reduce(0) { $0 + $1.income } / n, spend = active.reduce(0) { $0 + $1.spend } / n return (income.rounded(), spend.rounded(), (income - spend).rounded(), income > 0 ? ((income - spend) / income).double : nil) } // MARK: Unusual charges public enum FlagKind: String, Codable, Sendable { case duplicate, aboveUsual, newMerchant, priceChange } public struct Flag: Identifiable, Hashable, Sendable { public let entryID: String public let kind: FlagKind public let reason: String public var id: String { entryID + kind.rawValue } } /// Charges worth a second look, from the last `days` days and not yet reviewed. Each flag says why. public func flags(days: Int = 45, today: String = DayKey.today) -> [Flag] { let since = DayKey.adding(-days, to: today) let outflows = entries.filter { $0.amount < 0 && !$0.excluded && kind($0.categoryID) == .expense } let byMerchant = Dictionary(grouping: outflows) { Self.merchantKey($0.name) } let recurringKeys = Set(recurring(today: today).filter { $0.status != .dismissed }.map(\.id)) var out: [Flag] = [] for entry in outflows where entry.day >= since && !entry.reviewed { let key = Self.merchantKey(entry.name) let size = abs(entry.amount) let history = (byMerchant[key] ?? []).filter { $0.id != entry.id } if let twin = history.first(where: { $0.accountID == entry.accountID && $0.amount == entry.amount && Swift.abs(DayKey.between($0.day, entry.day)) <= 2 && !$0.transaction.pending && !entry.transaction.pending }), twin.id < entry.id || twin.reviewed { out.append(Flag(entryID: entry.id, kind: .duplicate, reason: "Same \(Money.format(size)) charge from \(entry.name) on \(DayKey.short(twin.day)). It might be a double charge.")) continue } let earlier = history.filter { $0.day < entry.day } if recurringKeys.contains(key), let last = earlier.max(by: { $0.day < $1.day }) { let before = abs(last.amount) if size - before >= 1 && size >= before * Decimal(string: "1.05")! { out.append(Flag(entryID: entry.id, kind: .priceChange, reason: "\(entry.name) went up from \(Money.format(before)) to \(Money.format(size)).")) continue } } if earlier.count >= 3 { let usual = earlier.map { abs($0.amount) }.sorted()[earlier.count / 2] if size >= usual * 2 && size - usual >= 25 { out.append(Flag(entryID: entry.id, kind: .aboveUsual, reason: "\(Money.format(size)) at \(entry.name), where you usually spend about \(Money.format(usual)).")) continue } } if earlier.isEmpty && size >= 150 { out.append(Flag(entryID: entry.id, kind: .newMerchant, reason: "First charge from \(entry.name), and a big one: \(Money.format(size)).")) } } return out.sorted { lhs, rhs in (entry(lhs.entryID)?.day ?? "") > (entry(rhs.entryID)?.day ?? "") } } public func entry(_ id: String) -> LedgerEntry? { entries.first { $0.id == id } } // MARK: Refunds public struct RefundMatch: Identifiable, Hashable, Sendable { public let refundID: String public let purchaseID: String public var id: String { refundID } } /// Credits that look like a refund of an earlier purchase: same merchant, no bigger than the /// purchase, within 90 days. Only suggestions; nothing changes until the user accepts one. public func refundMatches(today: String = DayKey.today) -> [RefundMatch] { let purchases = entries.filter { $0.amount < 0 && !$0.excluded && kind($0.categoryID) == .expense } let byMerchant = Dictionary(grouping: purchases) { Self.merchantKey($0.name) } let alreadyMatched = Set(entries.compactMap(\.refundOf)) return entries.compactMap { credit -> RefundMatch? in guard credit.amount > 0, credit.refundOf == nil, !credit.excluded, !credit.categoryChosen, kind(credit.categoryID) != .transfer, DayKey.between(credit.day, today) <= 120 else { return nil } let key = Self.merchantKey(credit.name) guard !key.isEmpty else { return nil } let candidates = (byMerchant[key] ?? []).filter { $0.day <= credit.day && DayKey.between($0.day, credit.day) <= 90 && abs($0.amount) >= credit.amount && !alreadyMatched.contains($0.id) } // The closest amount wins, then the most recent purchase. guard let best = candidates.min(by: { (abs($0.amount) - credit.amount, $1.day) < (abs($1.amount) - credit.amount, $0.day) }) else { return nil } return RefundMatch(refundID: credit.id, purchaseID: best.id) } } // MARK: Review order /// The review inbox in the order worth reading: flagged charges, then ones Bucksley couldn't /// categorize, then the largest, newest first within each. public func prioritizedReviewQueue(today: String = DayKey.today) -> [LedgerEntry] { let flagged = Set(flags(today: today).map(\.entryID)) func rank(_ e: LedgerEntry) -> Int { if flagged.contains(e.id) { return 0 } if needsCategory(e) { return 1 } if abs(e.amount) >= 100 { return 2 } return 3 } return reviewQueue.sorted { (rank($0), $1.day, abs($1.amount)) < (rank($1), $0.day, abs($0.amount)) } } /// Bucksley fell back to "Other" and nothing (a rule or the user) picked a category. public func needsCategory(_ e: LedgerEntry) -> Bool { e.categoryID == "other" && !e.categoryChosen && e.ruleID == nil } // MARK: Category suggestions public struct CategorySuggestion: Identifiable, Hashable, Sendable { public let entryID: String public let categoryID: String public let reason: String public var id: String { entryID } public init(entryID: String, categoryID: String, reason: String) { self.entryID = entryID; self.categoryID = categoryID; self.reason = reason } } /// For uncategorized transactions, the category the user chose for the same merchant before. /// The on-device model (`AskBucksley.suggestCategories`) fills in the ones history can't. public func historySuggestions() -> [CategorySuggestion] { var chosen: [String: [String: Int]] = [:] for e in entries where e.categoryChosen { chosen[Self.merchantKey(e.name), default: [:]][e.categoryID, default: 0] += 1 } return entries.filter(needsCategory).compactMap { e in guard let votes = chosen[Self.merchantKey(e.name)], let best = votes.max(by: { $0.value < $1.value }), let category = workspace.category(best.key) else { return nil } return CategorySuggestion(entryID: e.id, categoryID: best.key, reason: "You put \(e.name) in \(category.name) \(best.value == 1 ? "before" : "\(best.value) times").") } } // MARK: Rules /// What a rule would match, newest first: every bank transaction it fits, and which of those /// the user already changed by hand (their edits keep winning over the rule). public func preview(_ rule: Rule) -> (matches: [LedgerEntry], editedByHand: [LedgerEntry]) { var probe = rule; probe.enabled = true let matches = entries.filter { probe.matches($0.transaction) } return (matches, matches.filter { $0.categoryChosen && rule.setCategoryID != nil && $0.categoryID != rule.setCategoryID }) } // MARK: Monthly recap public struct Recap: Hashable, Sendable { public let month: String public let income: Decimal public let spend: Decimal public let net: Decimal public let savingsRate: Double? public let spendChange: Decimal? /// Categories that moved the most against the month before: (name, this month, change). public let movers: [Mover] public let topMerchant: (name: String, amount: Decimal)? public let budgetsOver: [String] public struct Mover: Hashable, Sendable { public let name: String; public let amount: Decimal; public let change: Decimal } public static func == (a: Recap, b: Recap) -> Bool { a.month == b.month && a.facts == b.facts } public func hash(into h: inout Hasher) { h.combine(month); h.combine(facts) } /// Every figure the recap may mention, as Bucksley formats it. A reworded recap that quotes /// any other dollar figure is thrown away. public var allowedFigures: Set { var out: Set = [income, spend, abs(net)].flatMap { [Money.format($0), Money.format($0, cents: false)] }.reduce(into: []) { $0.insert($1) } if let spendChange { out.insert(Money.format(abs(spendChange), cents: false)); out.insert(Money.format(abs(spendChange))) } for m in movers { [m.amount, abs(m.change)].forEach { out.insert(Money.format($0, cents: false)); out.insert(Money.format($0)) } } if let t = topMerchant { out.insert(Money.format(t.amount, cents: false)); out.insert(Money.format(t.amount)) } return out } /// The recap as plain sentences, built from the numbers alone. public var facts: String { var lines: [String] = [] let title = MonthKey.title(month) if income > 0 { let rate = savingsRate.map { " That's \(Int(($0 * 100).rounded()))% of what came in." } ?? "" lines.append(net >= 0 ? "In \(title) you brought in \(Money.format(income, cents: false)), spent \(Money.format(spend, cents: false)) and kept \(Money.format(net, cents: false)).\(rate)" : "In \(title) you brought in \(Money.format(income, cents: false)) and spent \(Money.format(spend, cents: false)), \(Money.format(abs(net), cents: false)) more than came in.") } else { lines.append("In \(title) you spent \(Money.format(spend, cents: false)).") } if let spendChange, abs(spendChange) >= 1 { lines.append("Spending was \(Money.format(abs(spendChange), cents: false)) \(spendChange > 0 ? "more" : "less") than the month before.") } if let up = movers.first(where: { $0.change > 0 }) { lines.append("\(up.name) rose the most, up \(Money.format(up.change, cents: false)) to \(Money.format(up.amount, cents: false)).") } if let down = movers.first(where: { $0.change < 0 }) { lines.append("\(down.name) dropped \(Money.format(abs(down.change), cents: false)) to \(Money.format(down.amount, cents: false)).") } if let t = topMerchant { lines.append("You spent the most at \(t.name): \(Money.format(t.amount, cents: false)).") } if !budgetsOver.isEmpty { lines.append("Over budget: \(budgetsOver.joined(separator: ", ")).") } return lines.joined(separator: " ") } } /// Last month's story by default; any month on request. public func recap(month: String = MonthKey.adding(-1, to: MonthKey.current)) -> Recap? { let now = spending(month: month) let spend = now.reduce(0) { $0 + $1.amount }, inc = income(month: month) guard spend > 0 || inc > 0 else { return nil } let previous = MonthKey.adding(-1, to: month) let before = Dictionary(spending(month: previous).map { ($0.categoryID, $0.amount) }, uniquingKeysWith: +) let hadBefore = !before.isEmpty || income(month: previous) > 0 let names = Set(now.map(\.categoryID)).union(before.keys) let movers = names.map { id -> Recap.Mover in let amount = now.first { $0.categoryID == id }?.amount ?? 0 return Recap.Mover(name: workspace.category(id)?.name ?? id, amount: amount, change: amount - (before[id] ?? 0)) } .filter { abs($0.change) >= 20 } .sorted { abs($0.change) > abs($1.change) } let merchants = Dictionary(grouping: entries(in: month).filter { $0.amount < 0 && !$0.excluded && kind($0.categoryID) == .expense }, by: \.name) .mapValues { $0.reduce(Decimal(0)) { $0 + abs($1.amount) } } let top = merchants.max { $0.value < $1.value } let over = budgetStatus(month: month).filter { $0.remaining < 0 }.map { budgetName($0.budget.categoryID) } let net = inc - spend return Recap(month: month, income: inc, spend: spend, net: net, savingsRate: inc > 0 ? (net / inc).double : nil, spendChange: hadBefore ? spend - before.values.reduce(0, +) : nil, movers: Array(movers.prefix(3)), topMerchant: top.map { ($0.key, $0.value) }, budgetsOver: over) } } extension DayKey { /// "Nov 3". public static func short(_ key: String) -> String { guard let d = date(key) else { return key } return d.formatted(.dateTime.month(.abbreviated).day()) } }