Bucksley / app · bucksley.ai / Apps / Mac / PlanningScreens.swift
| 1 | import SwiftUI |
| 2 | import BucksleyKit |
| 3 | import BucksleyUI |
| 4 | |
| 5 | struct CategoriesScreen: View { |
| 6 | /// This month's spending per category, with income categories showing what came in. |
| 7 | func monthTotals(_ ledger: Ledger) -> [String: Decimal] { |
| 8 | var totals = Dictionary(uniqueKeysWithValues: ledger.spending().map { ($0.categoryID, $0.amount) }) |
| 9 | for c in ledger.workspace.categories where c.kind == .income { totals[c.id] = -ledger.spent(c.id, month: MonthKey.current) } |
| 10 | return totals |
| 11 | } |
| 12 | @Environment(AppModel.self) private var model |
| 13 | @Environment(\.palette) private var palette |
| 14 | @State private var newCategory = "" |
| 15 | @State private var newCategoryGroup = "lifestyle" |
| 16 | @State private var newGroup = "" |
| 17 | @State private var ruleText = "" |
| 18 | @State private var ruleCategory = "other" |
| 19 | @State private var ruleRename = "" |
| 20 | @State private var ruleReviewed = false |
| 21 | @State private var ruleOverridesEdits = false |
| 22 | |
| 23 | var body: some View { |
| 24 | let ledger = model.ledger |
| 25 | let ws = ledger.workspace |
| 26 | let spend = monthTotals(ledger) |
| 27 | ScreenScaffold("Categories & Rules", subtitle: "\(ws.categories.count) categories in \(ws.groups.count) groups · \(ws.rules.count) rules") { |
| 28 | EmptyView() |
| 29 | } content: { |
| 30 | HStack(alignment: .top, spacing: 20) { |
| 31 | VStack(alignment: .leading, spacing: 16) { |
| 32 | ForEach(ws.groups) { group in |
| 33 | VStack(alignment: .leading, spacing: 4) { |
| 34 | SectionHeader(group.name) { |
| 35 | MoneyText(ws.categories.filter { $0.groupID == group.id }.reduce(0) { $0 + (spend[$1.id] ?? 0) }, size: 12, cents: false) |
| 36 | } |
| 37 | ForEach(ws.categories.filter { $0.groupID == group.id }) { c in |
| 38 | HStack(spacing: 10) { |
| 39 | EmojiPickerButton(category: c) |
| 40 | Text(c.name).font(.system(size: 13, weight: .medium)) |
| 41 | Text(c.kind == .expense ? "" : c.kind.rawValue.capitalized).font(.system(size: 11)).foregroundStyle(palette.muted) |
| 42 | Spacer() |
| 43 | MoneyText(spend[c.id] ?? 0, size: 12, cents: false, weight: .regular) |
| 44 | Menu { |
| 45 | Menu("Move to group") { ForEach(ws.groups) { g in Button(g.name) { model.updateWorkspace { w in if let i = w.categories.firstIndex(where: { $0.id == c.id }) { w.categories[i].groupID = g.id } } } } } |
| 46 | Menu("Color") { ForEach(0..<6, id: \.self) { n in Button("Color \(n + 1)") { model.updateWorkspace { w in if let i = w.categories.firstIndex(where: { $0.id == c.id }) { w.categories[i].colorIndex = n } } } } } |
| 47 | Button("Show transactions") { TransactionsFilter.shared.categoryID = c.id; model.selection = .transactions } |
| 48 | } label: { Image(systemName: "ellipsis") } |
| 49 | .menuStyle(.borderlessButton).menuIndicator(.hidden).frame(width: 26) |
| 50 | } |
| 51 | .padding(.vertical, 4) |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | Panel { |
| 56 | VStack(alignment: .leading, spacing: 8) { |
| 57 | Text("Add").font(.system(size: 12, weight: .semibold)) |
| 58 | HStack { |
| 59 | TextField("New category", text: $newCategory).textFieldStyle(.roundedBorder) |
| 60 | ChoiceButton(ws.groups.map { (value: $0.id, title: $0.name, emoji: nil) }, selection: $newCategoryGroup).frame(width: 150) |
| 61 | Button("Add") { |
| 62 | let name = newCategory.trimmingCharacters(in: .whitespaces) |
| 63 | guard !name.isEmpty else { return } |
| 64 | model.updateWorkspace { w in w.categories.append(Category(id: UUID().uuidString, name: name, symbol: "tag", groupID: newCategoryGroup, colorIndex: w.categories.count % 6)) } |
| 65 | newCategory = "" |
| 66 | } |
| 67 | } |
| 68 | HStack { |
| 69 | TextField("New group", text: $newGroup).textFieldStyle(.roundedBorder) |
| 70 | Button("Add group") { |
| 71 | let name = newGroup.trimmingCharacters(in: .whitespaces) |
| 72 | guard !name.isEmpty else { return } |
| 73 | model.updateWorkspace { $0.groups.append(CategoryGroup(id: UUID().uuidString, name: name)) } |
| 74 | newGroup = "" |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | .font(.system(size: 12)) |
| 79 | } |
| 80 | } |
| 81 | .frame(maxWidth: .infinity) |
| 82 | |
| 83 | VStack(alignment: .leading, spacing: 12) { |
| 84 | SectionHeader("Rules") { Text("First match wins").font(.system(size: 11)).foregroundStyle(palette.muted) } |
| 85 | Text("Rules set the category, name and tags for matching transactions, past and future. Your own edits on a transaction always win.") |
| 86 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 87 | ForEach(ws.rules) { rule in |
| 88 | let matches = ledger.entries.filter { $0.ruleID == rule.id }.count |
| 89 | let handEdited = ledger.preview(rule).editedByHand |
| 90 | VStack(alignment: .leading, spacing: 8) { |
| 91 | HStack(spacing: 8) { |
| 92 | Toggle("", isOn: Binding(get: { rule.enabled }, set: { v in model.updateWorkspace { w in if let i = w.rules.firstIndex(where: { $0.id == rule.id }) { w.rules[i].enabled = v } } })) |
| 93 | .labelsHidden().toggleStyle(.switch).controlSize(.mini) |
| 94 | VStack(alignment: .leading, spacing: 2) { |
| 95 | Text("Name contains “\(rule.matchText)”").font(.system(size: 12, weight: .semibold)) |
| 96 | Text(ruleSummary(rule, ws) + " · \(matches) match\(matches == 1 ? "" : "es")").font(.system(size: 11)).foregroundStyle(palette.muted) |
| 97 | } |
| 98 | Spacer() |
| 99 | Button { model.updateWorkspace { $0.rules.removeAll { $0.id == rule.id } } } label: { Image(systemName: "trash") } |
| 100 | .buttonStyle(.plain).foregroundStyle(palette.muted).accessibilityLabel("Delete rule") |
| 101 | } |
| 102 | .opacity(rule.enabled ? 1 : 0.55) |
| 103 | if rule.enabled, let target = rule.setCategoryID, !handEdited.isEmpty { |
| 104 | Button("Also apply to \(handEdited.count) you filed by hand") { |
| 105 | for e in handEdited { try? model.store.edit(e.id) { $0.categoryID = target } } |
| 106 | model.reload(force: true); model.shareSoon() |
| 107 | } |
| 108 | .buttonStyle(.plain).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.accent) |
| 109 | .help(handEdited.prefix(5).map(\.name).joined(separator: ", ")) |
| 110 | } |
| 111 | } |
| 112 | .padding(10).background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) |
| 113 | } |
| 114 | Panel { |
| 115 | VStack(alignment: .leading, spacing: 8) { |
| 116 | Text("New rule").font(.system(size: 12, weight: .semibold)) |
| 117 | TextField("When the name contains…", text: $ruleText).textFieldStyle(.roundedBorder) |
| 118 | HStack(spacing: 8) { |
| 119 | Text("Set category").font(.system(size: 12)).foregroundStyle(palette.muted) |
| 120 | ChoiceButton(ws.categoryChoices(), selection: $ruleCategory).frame(maxWidth: 240) |
| 121 | } |
| 122 | TextField("Rename to (optional)", text: $ruleRename).textFieldStyle(.roundedBorder) |
| 123 | Toggle("Mark reviewed", isOn: $ruleReviewed) |
| 124 | let draft = Rule(matchText: ruleText.trimmingCharacters(in: .whitespaces), setCategoryID: ruleCategory) |
| 125 | let preview = ruleText.trimmingCharacters(in: .whitespaces).isEmpty ? nil : ledger.preview(draft) |
| 126 | if let preview, !preview.matches.isEmpty { |
| 127 | VStack(alignment: .leading, spacing: 3) { |
| 128 | ForEach(preview.matches.prefix(4)) { e in |
| 129 | HStack { |
| 130 | Text(e.name).lineLimit(1) |
| 131 | Spacer() |
| 132 | Text(DayKey.short(e.day)).foregroundStyle(palette.muted) |
| 133 | MoneyText(e.amount, size: 11, cents: true, weight: .regular) |
| 134 | } |
| 135 | .font(.system(size: 11)) |
| 136 | } |
| 137 | if preview.matches.count > 4 { Text("and \(preview.matches.count - 4) more").font(.system(size: 11)).foregroundStyle(palette.muted) } |
| 138 | } |
| 139 | .padding(8).background(palette.canvas, in: RoundedRectangle(cornerRadius: 8)) |
| 140 | if !preview.editedByHand.isEmpty { |
| 141 | Toggle("Also change the \(preview.editedByHand.count) you filed by hand", isOn: $ruleOverridesEdits) |
| 142 | } |
| 143 | } |
| 144 | HStack { |
| 145 | Text(preview.map { "Matches \($0.matches.count) existing transaction\($0.matches.count == 1 ? "" : "s")" } ?? "").font(.system(size: 11)).foregroundStyle(palette.muted) |
| 146 | Spacer() |
| 147 | Button("Add rule") { |
| 148 | let text = ruleText.trimmingCharacters(in: .whitespaces) |
| 149 | guard !text.isEmpty else { return } |
| 150 | if ruleOverridesEdits, let preview { |
| 151 | for e in preview.editedByHand { try? model.store.edit(e.id) { $0.categoryID = ruleCategory } } |
| 152 | } |
| 153 | model.updateWorkspace { $0.rules.insert(Rule(matchText: text, setCategoryID: ruleCategory, rename: ruleRename.isEmpty ? nil : ruleRename, markReviewed: ruleReviewed), at: 0) } |
| 154 | ruleText = ""; ruleRename = ""; ruleReviewed = false; ruleOverridesEdits = false |
| 155 | } |
| 156 | .buttonStyle(PrimaryButtonStyle()) |
| 157 | } |
| 158 | } |
| 159 | .font(.system(size: 12)) |
| 160 | } |
| 161 | } |
| 162 | .frame(width: 380) |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | func ruleSummary(_ rule: Rule, _ ws: Workspace) -> String { |
| 168 | var parts: [String] = [] |
| 169 | if let c = rule.setCategoryID { parts.append("→ \(ws.category(c)?.name ?? c)") } |
| 170 | if let r = rule.rename { parts.append("rename “\(r)”") } |
| 171 | if !rule.addTags.isEmpty { parts.append(rule.addTags.map { "#" + $0 }.joined(separator: " ")) } |
| 172 | if rule.markReviewed { parts.append("reviewed") } |
| 173 | return parts.joined(separator: ", ") |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | struct BudgetsScreen: View { |
| 178 | @Environment(AppModel.self) private var model |
| 179 | @Environment(\.palette) private var palette |
| 180 | @State private var month = MonthKey.current |
| 181 | @State private var explanation: String? |
| 182 | @State private var explaining = false |
| 183 | @State private var smart = SmartBudgetFlow.shared |
| 184 | |
| 185 | var body: some View { |
| 186 | if smart.presented { |
| 187 | ScreenScaffold("Smart budgets", subtitle: "Built from your income and spending") { |
| 188 | EmptyView() |
| 189 | } content: { SmartBudgetWalkthrough() } |
| 190 | } else { |
| 191 | budgets |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | @ViewBuilder var budgets: some View { |
| 196 | let ledger = model.ledger |
| 197 | let ws = ledger.workspace |
| 198 | let statuses = ledger.budgetStatus(month: month) |
| 199 | let (budgeted, spent) = ledger.budgetTotals(month: month) |
| 200 | let suggestions = ledger.budgetSuggestions() |
| 201 | ScreenScaffold("Budgets", subtitle: MonthKey.title(month)) { |
| 202 | Button { smart.open() } label: { Label("Smart budgets", systemImage: "sparkles") } |
| 203 | .buttonStyle(PrimaryButtonStyle()).help("Let Bucksley build budgets from your income and spending") |
| 204 | HStack(spacing: 6) { |
| 205 | Button { month = MonthKey.adding(-1, to: month) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous month") |
| 206 | Button { month = MonthKey.adding(1, to: month) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next month").disabled(month >= MonthKey.current) |
| 207 | } |
| 208 | .buttonStyle(SecondaryButtonStyle()) |
| 209 | } content: { |
| 210 | VStack(alignment: .leading, spacing: 18) { |
| 211 | if !statuses.isEmpty { |
| 212 | HStack(spacing: 14) { |
| 213 | Panel { stat("Budgeted", budgeted) } |
| 214 | Panel { stat("Spent", spent) } |
| 215 | Panel { stat(budgeted >= spent ? "Left" : "Over", abs(budgeted - spent)) } |
| 216 | } |
| 217 | } |
| 218 | HStack(alignment: .top, spacing: 20) { |
| 219 | VStack(alignment: .leading, spacing: 12) { |
| 220 | SectionHeader("This month") { Text("Tick shows where you'd be at an even pace").font(.system(size: 11)).foregroundStyle(palette.muted) } |
| 221 | if statuses.isEmpty { |
| 222 | VStack(alignment: .leading, spacing: 10) { |
| 223 | Text("No budgets yet").font(.system(size: 15, weight: .semibold)) |
| 224 | Text("Bucksley can build a budget for every category you spend in, sized from your income and a typical month, with room left to save.") |
| 225 | .font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 226 | Button { smart.open() } label: { Label("Build my budgets", systemImage: "sparkles") }.buttonStyle(PrimaryButtonStyle()) |
| 227 | } |
| 228 | .padding(16).frame(maxWidth: .infinity, alignment: .leading) |
| 229 | .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) |
| 230 | } |
| 231 | ForEach(statuses) { status in |
| 232 | HStack(alignment: .center, spacing: 12) { |
| 233 | BudgetProgress(status, name: budgetLabel(status, ledger), colorIndex: ws.category(status.id)?.colorIndex ?? 0) |
| 234 | budgetMenu(status.budget) |
| 235 | } |
| 236 | .padding(.vertical, 4) |
| 237 | } |
| 238 | AddBudgetRow(month: month) |
| 239 | } |
| 240 | .frame(maxWidth: .infinity) |
| 241 | |
| 242 | VStack(alignment: .leading, spacing: 12) { |
| 243 | SectionHeader("Suggested by Bucksley") { Image(systemName: "sparkles").foregroundStyle(palette.accent) } |
| 244 | Text("From your last \(suggestions.first?.months ?? 6) months of spending. Nothing is set until you add it.").font(.system(size: 12)).foregroundStyle(palette.muted) |
| 245 | if suggestions.isEmpty { Text("Bucksley needs a month or more of transactions to suggest budgets.").font(.system(size: 13)).foregroundStyle(palette.muted) } |
| 246 | ForEach(suggestions.prefix(8)) { s in |
| 247 | VStack(alignment: .leading, spacing: 6) { |
| 248 | HStack { |
| 249 | Text(ws.category(s.categoryID).map { "\($0.icon) \($0.name)" } ?? s.categoryID).font(.system(size: 13, weight: .semibold)) |
| 250 | Spacer() |
| 251 | MoneyText(s.amount, size: 14, cents: false) |
| 252 | Text("/mo").font(.system(size: 11)).foregroundStyle(palette.muted) |
| 253 | } |
| 254 | Text(s.reason).font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 255 | Button(ws.budgets.contains { $0.categoryID == s.categoryID } ? "Update budget" : "Add budget") { |
| 256 | model.updateWorkspace { w in |
| 257 | let rollover = w.budgets.first { $0.categoryID == s.categoryID }?.rollover ?? false |
| 258 | w.budgets.removeAll { $0.categoryID == s.categoryID } |
| 259 | w.budgets.append(Budget(categoryID: s.categoryID, amount: s.amount, rollover: rollover)) |
| 260 | } |
| 261 | SupportPrompt.recordCoreAction() |
| 262 | } |
| 263 | .buttonStyle(SecondaryButtonStyle()) |
| 264 | } |
| 265 | .padding(12).background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) |
| 266 | } |
| 267 | if !suggestions.isEmpty { |
| 268 | Button(explaining ? "Thinking…" : "Explain my budget plan") { explain(ledger) }.buttonStyle(PrimaryButtonStyle()).disabled(explaining) |
| 269 | if let explanation { |
| 270 | Text(explanation).font(palette.theme == .almanac ? .system(size: 14, design: .serif) : .system(size: 13)).fixedSize(horizontal: false, vertical: true) |
| 271 | .padding(12).background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)).textSelection(.enabled) |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | .frame(width: 360) |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | func stat(_ label: String, _ value: Decimal) -> some View { |
| 282 | VStack(alignment: .leading, spacing: 4) { |
| 283 | Text(label).font(.system(size: 12, weight: .medium)).foregroundStyle(palette.muted) |
| 284 | MoneyText(value, size: 22, cents: false) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | /// "🛒 Groceries", or "Food & Drink (group)", plus a note when this month has its own amount. |
| 289 | func budgetLabel(_ status: Ledger.BudgetStatus, _ ledger: Ledger) -> String { |
| 290 | let id = status.budget.categoryID |
| 291 | var name = ledger.workspace.category(id).map { "\($0.icon) \($0.name)" } ?? "\(ledger.budgetName(id)) (group)" |
| 292 | if status.budget.monthAmounts?[month] != nil { name += " · \(MonthKey.title(month).components(separatedBy: " ").first ?? "") only" } |
| 293 | return name |
| 294 | } |
| 295 | |
| 296 | func budgetMenu(_ budget: Budget) -> some View { |
| 297 | let monthName = MonthKey.title(month).components(separatedBy: " ").first ?? "this month" |
| 298 | return Menu { |
| 299 | Button("Edit amount…") { BudgetEditor.shared.open(budget.categoryID, amount: budget.amount) } |
| 300 | Button("Change \(monthName) only…") { BudgetEditor.shared.open(budget.categoryID, amount: budget.amount(for: month), monthOnly: true) } |
| 301 | if budget.monthAmounts?[month] != nil { |
| 302 | Button("Use the usual amount in \(monthName)") { |
| 303 | model.updateWorkspace { w in if let i = w.budgets.firstIndex(where: { $0.categoryID == budget.categoryID }) { w.budgets[i].monthAmounts?[month] = nil } } |
| 304 | } |
| 305 | } |
| 306 | Toggle("Roll over leftover money", isOn: Binding(get: { budget.rollover }, set: { v in model.updateWorkspace { w in if let i = w.budgets.firstIndex(where: { $0.categoryID == budget.categoryID }) { w.budgets[i].rollover = v } } })) |
| 307 | Button("Remove budget", role: .destructive) { model.updateWorkspace { $0.budgets.removeAll { $0.categoryID == budget.categoryID } } } |
| 308 | } label: { Image(systemName: "ellipsis.circle") } |
| 309 | .menuStyle(.borderlessButton).menuIndicator(.hidden).frame(width: 28) |
| 310 | } |
| 311 | |
| 312 | func explain(_ ledger: Ledger) { |
| 313 | explaining = true |
| 314 | let ws = ledger.workspace |
| 315 | let plan = ledger.budgetSuggestions().prefix(8).map { "\(ws.category($0.categoryID)?.name ?? $0.categoryID): \(Money.format($0.amount, cents: false)) (typical \(Money.format($0.typical, cents: false)))" }.joined(separator: "; ") |
| 316 | Task { |
| 317 | let question = "Here is a suggested monthly budget plan based on my spending: \(plan). In 3 or 4 short sentences, explain whether it looks realistic, which category I should watch most, and one practical way to stay under it." |
| 318 | do { |
| 319 | let provider = AskBucksley.provider(for: ws.settings) |
| 320 | let answer = try await AskBucksley().ask(question, ledger: ledger, provider: provider, model: ws.settings.model(for: provider)) |
| 321 | explanation = answer.text + "\n\n— \(answer.provider)" |
| 322 | } catch { explanation = error.localizedDescription } |
| 323 | explaining = false |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | @MainActor @Observable |
| 329 | final class BudgetEditor { |
| 330 | static let shared = BudgetEditor() |
| 331 | var categoryID: String? |
| 332 | var amount: Decimal = 0 |
| 333 | var monthOnly = false |
| 334 | func open(_ id: String, amount: Decimal, monthOnly: Bool = false) { categoryID = id; self.amount = amount; self.monthOnly = monthOnly } |
| 335 | } |
| 336 | |
| 337 | /// Adds or changes a budget on a category or a whole group, for every month or just this one. |
| 338 | struct AddBudgetRow: View { |
| 339 | @Environment(AppModel.self) private var model |
| 340 | @Environment(\.palette) private var palette |
| 341 | let month: String |
| 342 | @State private var editor = BudgetEditor.shared |
| 343 | @State private var onGroup = false |
| 344 | @State private var category = "groceries" |
| 345 | @State private var group = "" |
| 346 | @State private var amount: Decimal = 200 |
| 347 | @State private var rollover = false |
| 348 | @State private var monthOnly = false |
| 349 | |
| 350 | var body: some View { |
| 351 | let ws = model.workspace |
| 352 | let target = onGroup ? (group.isEmpty ? ws.groups.first?.id ?? "" : group) : category |
| 353 | let existing = ws.budgets.first { $0.categoryID == target } |
| 354 | let monthName = MonthKey.title(month).components(separatedBy: " ").first ?? "this month" |
| 355 | VStack(alignment: .leading, spacing: 10) { |
| 356 | HStack(spacing: 8) { |
| 357 | PillPicker([(false, "Category"), (true, "Whole group")], selection: $onGroup).fixedSize() |
| 358 | if onGroup { |
| 359 | ChoiceButton(ws.groups.map { (value: $0.id, title: $0.name, emoji: nil) }, selection: Binding(get: { target }, set: { group = $0 })).frame(width: 170) |
| 360 | } else { |
| 361 | ChoiceButton(ws.categoryChoices { $0.kind == .expense }, selection: $category).frame(width: 190) |
| 362 | } |
| 363 | Spacer() |
| 364 | } |
| 365 | HStack(spacing: 8) { |
| 366 | TextField("Amount", value: $amount, format: .currency(code: "USD").precision(.fractionLength(0))).textFieldStyle(.roundedBorder).frame(width: 90) |
| 367 | if existing != nil { |
| 368 | Toggle("\(monthName) only", isOn: $monthOnly).help("Set a different amount for \(MonthKey.title(month)) and keep the usual amount for other months") |
| 369 | } |
| 370 | if !monthOnly { Toggle("Rollover", isOn: $rollover) } |
| 371 | Spacer() |
| 372 | Button(existing == nil ? "Add budget" : monthOnly ? "Set \(monthName)" : "Update") { save(target, existing: existing) } |
| 373 | .buttonStyle(PrimaryButtonStyle()).disabled(target.isEmpty) |
| 374 | } |
| 375 | if onGroup { |
| 376 | Text("A group budget counts every category in the group. Bucksley won't also count a category budget inside it in your totals.") |
| 377 | .font(.system(size: 11)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 378 | } |
| 379 | } |
| 380 | .font(.system(size: 12)) |
| 381 | .padding(12).background(palette.card.opacity(0.6), in: RoundedRectangle(cornerRadius: palette.cardRadius)) |
| 382 | .onChange(of: editor.categoryID) { _, id in |
| 383 | guard let id else { return } |
| 384 | onGroup = ws.category(id) == nil |
| 385 | if onGroup { group = id } else { category = id } |
| 386 | amount = editor.amount; monthOnly = editor.monthOnly |
| 387 | rollover = ws.budgets.first { $0.categoryID == id }?.rollover ?? false |
| 388 | editor.categoryID = nil |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | func save(_ target: String, existing: Budget?) { |
| 393 | model.updateWorkspace { w in |
| 394 | if monthOnly, existing != nil, let i = w.budgets.firstIndex(where: { $0.categoryID == target }) { |
| 395 | var amounts = w.budgets[i].monthAmounts ?? [:] |
| 396 | amounts[month] = amount |
| 397 | w.budgets[i].monthAmounts = amounts |
| 398 | return |
| 399 | } |
| 400 | let kept = w.budgets.first { $0.categoryID == target }?.monthAmounts |
| 401 | w.budgets.removeAll { $0.categoryID == target } |
| 402 | if amount > 0 { |
| 403 | var budget = Budget(categoryID: target, amount: amount, rollover: rollover) |
| 404 | budget.monthAmounts = kept |
| 405 | w.budgets.append(budget) |
| 406 | } |
| 407 | } |
| 408 | monthOnly = false |
| 409 | SupportPrompt.recordCoreAction() |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | @MainActor @Observable |
| 414 | final class AskModel { |
| 415 | static let shared = AskModel() |
| 416 | struct Turn: Identifiable { let id = UUID(); let question: String; var answer: String?; var provider: String?; var transactionIDs: [String] = []; var offersBudgetPlan = false } |
| 417 | var turns: [Turn] = [] |
| 418 | var pending: String? |
| 419 | var busy = false |
| 420 | } |
| 421 | |
| 422 | struct AskScreen: View { |
| 423 | @Environment(AppModel.self) private var model |
| 424 | @Environment(\.palette) private var palette |
| 425 | @State private var ask = AskModel.shared |
| 426 | @State private var question = "" |
| 427 | |
| 428 | let starters = ["Help me set up budgets", "Where could I cut back next month?", "What are my subscriptions costing me?", "How much did I spend on dining this month?"] |
| 429 | |
| 430 | var body: some View { |
| 431 | let ws = model.workspace |
| 432 | let provider = AskBucksley.provider(for: ws.settings) |
| 433 | let answerer = AskBucksley.answerer(provider) |
| 434 | VStack(spacing: 0) { |
| 435 | ScreenScaffold(AskBucksley.title(for: answerer), subtitle: providerLine(ws), provider: answerer) { |
| 436 | if !ask.turns.isEmpty { Button("Clear") { ask.turns = [] }.buttonStyle(SecondaryButtonStyle()) } |
| 437 | } content: { |
| 438 | VStack(alignment: .leading, spacing: 16) { |
| 439 | if answerer == .apple, let agent = AskBucksley.installedAgents().first { |
| 440 | agentOffer(agent) |
| 441 | } |
| 442 | if ask.turns.isEmpty { |
| 443 | Text("Ask anything about your accounts, spending, budgets or bills. Answers come from your own numbers.") |
| 444 | .font(palette.theme == .almanac ? .system(size: 18, design: .serif) : .system(size: 15)).foregroundStyle(palette.muted) |
| 445 | LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 10) { |
| 446 | ForEach(starters, id: \.self) { s in |
| 447 | Button { send(s) } label: { |
| 448 | Text(s).font(.system(size: 13)).frame(maxWidth: .infinity, alignment: .leading).padding(14) |
| 449 | .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)).contentShape(Rectangle()) |
| 450 | } |
| 451 | .buttonStyle(.plain) |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | ForEach(ask.turns) { turn in |
| 456 | VStack(alignment: .leading, spacing: 8) { |
| 457 | HStack { Spacer(); Text(turn.question).font(.system(size: 13, weight: .medium)).padding(.horizontal, 14).padding(.vertical, 9) |
| 458 | .foregroundStyle(palette.accentText).background(palette.accent, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) } |
| 459 | if let answer = turn.answer { |
| 460 | VStack(alignment: .leading, spacing: 6) { |
| 461 | Text(AskBucksley.formatted(answer)).font(palette.theme == .almanac ? .system(size: 15, design: .serif) : .system(size: 14)).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) |
| 462 | let linked = linkedEntries(turn) |
| 463 | if !linked.isEmpty { |
| 464 | VStack(alignment: .leading, spacing: 2) { |
| 465 | Text(linked.count == 1 ? "TRANSACTION" : "TRANSACTIONS").font(.system(size: 10, weight: .semibold)).foregroundStyle(palette.muted).padding(.top, 6) |
| 466 | ForEach(linked) { entry in |
| 467 | Button { model.selection = .transactions; model.open(entry) } label: { |
| 468 | TransactionRow(entry, workspace: model.workspace, showAccount: true).contentShape(Rectangle()) |
| 469 | } |
| 470 | .buttonStyle(.plain).help("Open in Transactions") |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | if turn.offersBudgetPlan { |
| 475 | Button { model.selection = .budgets; SmartBudgetFlow.shared.open() } label: { Label("Set up smart budgets", systemImage: "sparkles") } |
| 476 | .buttonStyle(PrimaryButtonStyle()).padding(.top, 4) |
| 477 | } |
| 478 | if let p = turn.provider { Text(p).font(.system(size: 10, weight: .semibold)).foregroundStyle(palette.muted) } |
| 479 | } |
| 480 | .padding(14).frame(maxWidth: 620, alignment: .leading) |
| 481 | .background(palette.card, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) |
| 482 | } else { |
| 483 | ProgressView().controlSize(.small).padding(10) |
| 484 | } |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 | HStack(spacing: 8) { |
| 490 | Image(systemName: "sparkles").foregroundStyle(palette.accent) |
| 491 | TextField("Ask about your money…", text: $question).textFieldStyle(.plain).font(.system(size: 14)).onSubmit { send(question) } |
| 492 | Button { send(question) } label: { Image(systemName: "arrow.up").font(.system(size: 13, weight: .bold)).frame(width: 30, height: 30) } |
| 493 | .buttonStyle(.plain).foregroundStyle(palette.accentText).background(palette.accent, in: Circle()).disabled(ask.busy) |
| 494 | .accessibilityLabel("Ask") |
| 495 | } |
| 496 | .padding(.leading, 16).padding(.trailing, 6).padding(.vertical, 6) |
| 497 | .background(palette.card, in: Capsule()).overlay { Capsule().strokeBorder(palette.line) } |
| 498 | .padding(.horizontal, 28).padding(.bottom, 20) |
| 499 | } |
| 500 | .onAppear { if let p = ask.pending { ask.pending = nil; send(p) } } |
| 501 | } |
| 502 | |
| 503 | /// The transactions the answer looked up, newest ledger data, at most eight. |
| 504 | func linkedEntries(_ turn: AskModel.Turn) -> [LedgerEntry] { |
| 505 | let byID = Dictionary(model.ledger.entries.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) |
| 506 | return Array(turn.transactionIDs.compactMap { byID[$0] }.prefix(8)) |
| 507 | } |
| 508 | |
| 509 | /// An agent is signed in on this Mac but Ask still uses Apple Intelligence: offer the switch here, |
| 510 | /// behind the same confirm step as Settings. |
| 511 | func agentOffer(_ agent: AskProvider) -> some View { |
| 512 | let name = agent == .claudeCode ? "Claude" : agent.title |
| 513 | return HStack(spacing: 12) { |
| 514 | ProviderMark(agent, size: 18, tint: agent == .claudeCode ? nil : palette.text) |
| 515 | VStack(alignment: .leading, spacing: 2) { |
| 516 | Text("\(agent.title) is on this Mac").font(.system(size: 13, weight: .semibold)) |
| 517 | Text("Answer with \(name) for deeper answers. Bucksley shows what it would read before anything leaves this Mac.") |
| 518 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 519 | } |
| 520 | Spacer() |
| 521 | Button("Use \(name)") { AskSource.choose(agent, current: .apple, model: model) }.buttonStyle(PrimaryButtonStyle()) |
| 522 | } |
| 523 | .padding(14) |
| 524 | .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) |
| 525 | } |
| 526 | |
| 527 | func providerLine(_ ws: Workspace) -> String { |
| 528 | let provider = AskBucksley.provider(for: ws.settings) |
| 529 | switch provider { |
| 530 | case .apple: return "Apple Intelligence on this Mac · \(AskBucksley.appleModelStatus)" |
| 531 | case .claude: return "Claude with your key (\(ws.settings.claudeModel))" |
| 532 | case .openai: return "OpenAI with your key (\(ws.settings.openAIModel))" |
| 533 | case .gemini: |
| 534 | let model = AskAgent.models(provider).first { $0.id == ws.settings.model(for: provider) }?.name ?? "Gemini 4 Carbon" |
| 535 | return "Gemini on this Mac (\(model)) · answers from a summary of your numbers" |
| 536 | case .claudeCode, .codex: |
| 537 | let model = AskAgent.models(provider).first { $0.id == ws.settings.model(for: provider) }?.name ?? "default model" |
| 538 | return "\(provider.title) on this Mac (\(model)) · reads your numbers through Bucksley's tools" |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | func send(_ text: String) { |
| 543 | let q = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 544 | guard !q.isEmpty, !ask.busy else { return } |
| 545 | question = "" |
| 546 | ask.turns.append(.init(question: q)) |
| 547 | let index = ask.turns.count - 1 |
| 548 | ask.busy = true |
| 549 | let ledger = model.ledger, settings = model.workspace.settings |
| 550 | Task { |
| 551 | do { |
| 552 | let provider = AskBucksley.provider(for: settings) |
| 553 | let answer = try await AskBucksley().ask(q, ledger: ledger, provider: provider, model: settings.model(for: provider)) |
| 554 | ask.turns[index].answer = answer.text; ask.turns[index].provider = answer.provider |
| 555 | ask.turns[index].transactionIDs = answer.transactionIDs |
| 556 | ask.turns[index].offersBudgetPlan = answer.offersBudgetPlan |
| 557 | SupportPrompt.recordCoreAction() |
| 558 | } catch { |
| 559 | ask.turns[index].answer = error.localizedDescription |
| 560 | } |
| 561 | ask.busy = false |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | /// A category's emoji in its tinted tile. Click it to pick another from a grid of buttons. |
| 567 | struct EmojiPickerButton: View { |
| 568 | @Environment(AppModel.self) private var model |
| 569 | @Environment(\.palette) private var palette |
| 570 | let category: BucksleyKit.Category |
| 571 | @State private var picking = false |
| 572 | |
| 573 | var body: some View { |
| 574 | Button { picking = true } label: { |
| 575 | Text(category.icon).font(.system(size: 14)) |
| 576 | .frame(width: 28, height: 28) |
| 577 | .background(palette.color(category.colorIndex).opacity(palette.dark ? 0.22 : 0.15), in: RoundedRectangle(cornerRadius: 7, style: .continuous)) |
| 578 | } |
| 579 | .buttonStyle(.plain) |
| 580 | .help("Change the emoji for \(category.name)") |
| 581 | .accessibilityLabel("Emoji for \(category.name)") |
| 582 | .popover(isPresented: $picking, arrowEdge: .bottom) { |
| 583 | LazyVGrid(columns: Array(repeating: GridItem(.fixed(32), spacing: 4), count: 8), spacing: 4) { |
| 584 | ForEach(Defaults.emojiChoices, id: \.self) { emoji in |
| 585 | Button { |
| 586 | model.updateWorkspace { w in if let i = w.categories.firstIndex(where: { $0.id == category.id }) { w.categories[i].emoji = emoji } } |
| 587 | picking = false |
| 588 | } label: { |
| 589 | Text(emoji).font(.system(size: 18)).frame(width: 32, height: 32) |
| 590 | .background(emoji == category.icon ? palette.accent.opacity(0.2) : .clear, in: RoundedRectangle(cornerRadius: 6)) |
| 591 | } |
| 592 | .buttonStyle(.plain) |
| 593 | } |
| 594 | } |
| 595 | .padding(10) |
| 596 | } |
| 597 | } |
| 598 | } |