Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / Insights.swift

1import Foundation
2
3/// The smart parts of Bucksley, all computed from the user's own numbers on the device: cash flow,
4/// the monthly recap, unusual-charge flags, refund matches, the review order, category suggestions
5/// and rule previews. Nothing here guesses with a model; `AskBucksley` only rewords the recap.
6extension Ledger {
7
8 // MARK: Cash flow
9
10 public struct CashFlowMonth: Identifiable, Hashable, Sendable {
11 public let month: String
12 public let income: Decimal
13 /// Money out on expense categories, net of refunds.
14 public let spend: Decimal
15 public var net: Decimal { income - spend }
16 /// Share of income kept, nil in a month with no income.
17 public var savingsRate: Double? { income > 0 ? (net / income).double : nil }
18 public var id: String { month }
19 }
20
21 /// Income, spend and net for the last `months` months, oldest first, ending with `through`.
22 public func cashFlow(months: Int = 12, through: String = MonthKey.current) -> [CashFlowMonth] {
23 (0..<months).reversed().map { back in
24 let month = MonthKey.adding(-back, to: through)
25 return CashFlowMonth(month: month, income: income(month: month), spend: spending(month: month).reduce(0) { $0 + $1.amount })
26 }
27 }
28
29 /// Averages over the months that have any activity, so a new user's empty months don't drag them down.
30 public func cashFlowAverages(_ months: [CashFlowMonth]) -> (income: Decimal, spend: Decimal, net: Decimal, savingsRate: Double?) {
31 let active = months.filter { $0.income != 0 || $0.spend != 0 }
32 guard !active.isEmpty else { return (0, 0, 0, nil) }
33 let n = Decimal(active.count)
34 let income = active.reduce(0) { $0 + $1.income } / n, spend = active.reduce(0) { $0 + $1.spend } / n
35 return (income.rounded(), spend.rounded(), (income - spend).rounded(), income > 0 ? ((income - spend) / income).double : nil)
36 }
37
38 // MARK: Unusual charges
39
40 public enum FlagKind: String, Codable, Sendable { case duplicate, aboveUsual, newMerchant, priceChange }
41
42 public struct Flag: Identifiable, Hashable, Sendable {
43 public let entryID: String
44 public let kind: FlagKind
45 public let reason: String
46 public var id: String { entryID + kind.rawValue }
47 }
48
49 /// Charges worth a second look, from the last `days` days and not yet reviewed. Each flag says why.
50 public func flags(days: Int = 45, today: String = DayKey.today) -> [Flag] {
51 let since = DayKey.adding(-days, to: today)
52 let outflows = entries.filter { $0.amount < 0 && !$0.excluded && kind($0.categoryID) == .expense }
53 let byMerchant = Dictionary(grouping: outflows) { Self.merchantKey($0.name) }
54 let recurringKeys = Set(recurring(today: today).filter { $0.status != .dismissed }.map(\.id))
55 var out: [Flag] = []
56 for entry in outflows where entry.day >= since && !entry.reviewed {
57 let key = Self.merchantKey(entry.name)
58 let size = abs(entry.amount)
59 let history = (byMerchant[key] ?? []).filter { $0.id != entry.id }
60 if let twin = history.first(where: { $0.accountID == entry.accountID && $0.amount == entry.amount
61 && Swift.abs(DayKey.between($0.day, entry.day)) <= 2 && !$0.transaction.pending && !entry.transaction.pending }),
62 twin.id < entry.id || twin.reviewed {
63 out.append(Flag(entryID: entry.id, kind: .duplicate,
64 reason: "Same \(Money.format(size)) charge from \(entry.name) on \(DayKey.short(twin.day)). It might be a double charge."))
65 continue
66 }
67 let earlier = history.filter { $0.day < entry.day }
68 if recurringKeys.contains(key), let last = earlier.max(by: { $0.day < $1.day }) {
69 let before = abs(last.amount)
70 if size - before >= 1 && size >= before * Decimal(string: "1.05")! {
71 out.append(Flag(entryID: entry.id, kind: .priceChange,
72 reason: "\(entry.name) went up from \(Money.format(before)) to \(Money.format(size))."))
73 continue
74 }
75 }
76 if earlier.count >= 3 {
77 let usual = earlier.map { abs($0.amount) }.sorted()[earlier.count / 2]
78 if size >= usual * 2 && size - usual >= 25 {
79 out.append(Flag(entryID: entry.id, kind: .aboveUsual,
80 reason: "\(Money.format(size)) at \(entry.name), where you usually spend about \(Money.format(usual))."))
81 continue
82 }
83 }
84 if earlier.isEmpty && size >= 150 {
85 out.append(Flag(entryID: entry.id, kind: .newMerchant, reason: "First charge from \(entry.name), and a big one: \(Money.format(size))."))
86 }
87 }
88 return out.sorted { lhs, rhs in
89 (entry(lhs.entryID)?.day ?? "") > (entry(rhs.entryID)?.day ?? "")
90 }
91 }
92
93 public func entry(_ id: String) -> LedgerEntry? { entries.first { $0.id == id } }
94
95 // MARK: Refunds
96
97 public struct RefundMatch: Identifiable, Hashable, Sendable {
98 public let refundID: String
99 public let purchaseID: String
100 public var id: String { refundID }
101 }
102
103 /// Credits that look like a refund of an earlier purchase: same merchant, no bigger than the
104 /// purchase, within 90 days. Only suggestions; nothing changes until the user accepts one.
105 public func refundMatches(today: String = DayKey.today) -> [RefundMatch] {
106 let purchases = entries.filter { $0.amount < 0 && !$0.excluded && kind($0.categoryID) == .expense }
107 let byMerchant = Dictionary(grouping: purchases) { Self.merchantKey($0.name) }
108 let alreadyMatched = Set(entries.compactMap(\.refundOf))
109 return entries.compactMap { credit -> RefundMatch? in
110 guard credit.amount > 0, credit.refundOf == nil, !credit.excluded, !credit.categoryChosen,
111 kind(credit.categoryID) != .transfer, DayKey.between(credit.day, today) <= 120 else { return nil }
112 let key = Self.merchantKey(credit.name)
113 guard !key.isEmpty else { return nil }
114 let candidates = (byMerchant[key] ?? []).filter {
115 $0.day <= credit.day && DayKey.between($0.day, credit.day) <= 90 && abs($0.amount) >= credit.amount && !alreadyMatched.contains($0.id)
116 }
117 // The closest amount wins, then the most recent purchase.
118 guard let best = candidates.min(by: { (abs($0.amount) - credit.amount, $1.day) < (abs($1.amount) - credit.amount, $0.day) }) else { return nil }
119 return RefundMatch(refundID: credit.id, purchaseID: best.id)
120 }
121 }
122
123 // MARK: Review order
124
125 /// The review inbox in the order worth reading: flagged charges, then ones Bucksley couldn't
126 /// categorize, then the largest, newest first within each.
127 public func prioritizedReviewQueue(today: String = DayKey.today) -> [LedgerEntry] {
128 let flagged = Set(flags(today: today).map(\.entryID))
129 func rank(_ e: LedgerEntry) -> Int {
130 if flagged.contains(e.id) { return 0 }
131 if needsCategory(e) { return 1 }
132 if abs(e.amount) >= 100 { return 2 }
133 return 3
134 }
135 return reviewQueue.sorted { (rank($0), $1.day, abs($1.amount)) < (rank($1), $0.day, abs($0.amount)) }
136 }
137
138 /// Bucksley fell back to "Other" and nothing (a rule or the user) picked a category.
139 public func needsCategory(_ e: LedgerEntry) -> Bool {
140 e.categoryID == "other" && !e.categoryChosen && e.ruleID == nil
141 }
142
143 // MARK: Category suggestions
144
145 public struct CategorySuggestion: Identifiable, Hashable, Sendable {
146 public let entryID: String
147 public let categoryID: String
148 public let reason: String
149 public var id: String { entryID }
150 public init(entryID: String, categoryID: String, reason: String) { self.entryID = entryID; self.categoryID = categoryID; self.reason = reason }
151 }
152
153 /// For uncategorized transactions, the category the user chose for the same merchant before.
154 /// The on-device model (`AskBucksley.suggestCategories`) fills in the ones history can't.
155 public func historySuggestions() -> [CategorySuggestion] {
156 var chosen: [String: [String: Int]] = [:]
157 for e in entries where e.categoryChosen { chosen[Self.merchantKey(e.name), default: [:]][e.categoryID, default: 0] += 1 }
158 return entries.filter(needsCategory).compactMap { e in
159 guard let votes = chosen[Self.merchantKey(e.name)], let best = votes.max(by: { $0.value < $1.value }),
160 let category = workspace.category(best.key) else { return nil }
161 return CategorySuggestion(entryID: e.id, categoryID: best.key,
162 reason: "You put \(e.name) in \(category.name) \(best.value == 1 ? "before" : "\(best.value) times").")
163 }
164 }
165
166 // MARK: Rules
167
168 /// What a rule would match, newest first: every bank transaction it fits, and which of those
169 /// the user already changed by hand (their edits keep winning over the rule).
170 public func preview(_ rule: Rule) -> (matches: [LedgerEntry], editedByHand: [LedgerEntry]) {
171 var probe = rule; probe.enabled = true
172 let matches = entries.filter { probe.matches($0.transaction) }
173 return (matches, matches.filter { $0.categoryChosen && rule.setCategoryID != nil && $0.categoryID != rule.setCategoryID })
174 }
175
176 // MARK: Monthly recap
177
178 public struct Recap: Hashable, Sendable {
179 public let month: String
180 public let income: Decimal
181 public let spend: Decimal
182 public let net: Decimal
183 public let savingsRate: Double?
184 public let spendChange: Decimal?
185 /// Categories that moved the most against the month before: (name, this month, change).
186 public let movers: [Mover]
187 public let topMerchant: (name: String, amount: Decimal)?
188 public let budgetsOver: [String]
189 public struct Mover: Hashable, Sendable { public let name: String; public let amount: Decimal; public let change: Decimal }
190
191 public static func == (a: Recap, b: Recap) -> Bool { a.month == b.month && a.facts == b.facts }
192 public func hash(into h: inout Hasher) { h.combine(month); h.combine(facts) }
193
194 /// Every figure the recap may mention, as Bucksley formats it. A reworded recap that quotes
195 /// any other dollar figure is thrown away.
196 public var allowedFigures: Set<String> {
197 var out: Set<String> = [income, spend, abs(net)].flatMap { [Money.format($0), Money.format($0, cents: false)] }.reduce(into: []) { $0.insert($1) }
198 if let spendChange { out.insert(Money.format(abs(spendChange), cents: false)); out.insert(Money.format(abs(spendChange))) }
199 for m in movers { [m.amount, abs(m.change)].forEach { out.insert(Money.format($0, cents: false)); out.insert(Money.format($0)) } }
200 if let t = topMerchant { out.insert(Money.format(t.amount, cents: false)); out.insert(Money.format(t.amount)) }
201 return out
202 }
203
204 /// The recap as plain sentences, built from the numbers alone.
205 public var facts: String {
206 var lines: [String] = []
207 let title = MonthKey.title(month)
208 if income > 0 {
209 let rate = savingsRate.map { " That's \(Int(($0 * 100).rounded()))% of what came in." } ?? ""
210 lines.append(net >= 0
211 ? "In \(title) you brought in \(Money.format(income, cents: false)), spent \(Money.format(spend, cents: false)) and kept \(Money.format(net, cents: false)).\(rate)"
212 : "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.")
213 } else {
214 lines.append("In \(title) you spent \(Money.format(spend, cents: false)).")
215 }
216 if let spendChange, abs(spendChange) >= 1 {
217 lines.append("Spending was \(Money.format(abs(spendChange), cents: false)) \(spendChange > 0 ? "more" : "less") than the month before.")
218 }
219 if let up = movers.first(where: { $0.change > 0 }) {
220 lines.append("\(up.name) rose the most, up \(Money.format(up.change, cents: false)) to \(Money.format(up.amount, cents: false)).")
221 }
222 if let down = movers.first(where: { $0.change < 0 }) {
223 lines.append("\(down.name) dropped \(Money.format(abs(down.change), cents: false)) to \(Money.format(down.amount, cents: false)).")
224 }
225 if let t = topMerchant { lines.append("You spent the most at \(t.name): \(Money.format(t.amount, cents: false)).") }
226 if !budgetsOver.isEmpty { lines.append("Over budget: \(budgetsOver.joined(separator: ", ")).") }
227 return lines.joined(separator: " ")
228 }
229 }
230
231 /// Last month's story by default; any month on request.
232 public func recap(month: String = MonthKey.adding(-1, to: MonthKey.current)) -> Recap? {
233 let now = spending(month: month)
234 let spend = now.reduce(0) { $0 + $1.amount }, inc = income(month: month)
235 guard spend > 0 || inc > 0 else { return nil }
236 let previous = MonthKey.adding(-1, to: month)
237 let before = Dictionary(spending(month: previous).map { ($0.categoryID, $0.amount) }, uniquingKeysWith: +)
238 let hadBefore = !before.isEmpty || income(month: previous) > 0
239 let names = Set(now.map(\.categoryID)).union(before.keys)
240 let movers = names.map { id -> Recap.Mover in
241 let amount = now.first { $0.categoryID == id }?.amount ?? 0
242 return Recap.Mover(name: workspace.category(id)?.name ?? id, amount: amount, change: amount - (before[id] ?? 0))
243 }
244 .filter { abs($0.change) >= 20 }
245 .sorted { abs($0.change) > abs($1.change) }
246 let merchants = Dictionary(grouping: entries(in: month).filter { $0.amount < 0 && !$0.excluded && kind($0.categoryID) == .expense }, by: \.name)
247 .mapValues { $0.reduce(Decimal(0)) { $0 + abs($1.amount) } }
248 let top = merchants.max { $0.value < $1.value }
249 let over = budgetStatus(month: month).filter { $0.remaining < 0 }.map { budgetName($0.budget.categoryID) }
250 let net = inc - spend
251 return Recap(month: month, income: inc, spend: spend, net: net, savingsRate: inc > 0 ? (net / inc).double : nil,
252 spendChange: hadBefore ? spend - before.values.reduce(0, +) : nil, movers: Array(movers.prefix(3)),
253 topMerchant: top.map { ($0.key, $0.value) }, budgetsOver: over)
254 }
255}
256
257extension DayKey {
258 /// "Nov 3".
259 public static func short(_ key: String) -> String {
260 guard let d = date(key) else { return key }
261 return d.formatted(.dateTime.month(.abbreviated).day())
262 }
263}