Bucksley / app · bucksley.ai / Apps / Mac / TransactionsScreen.swift
| 1 | import SwiftUI |
| 2 | import BucksleyKit |
| 3 | import BucksleyUI |
| 4 | |
| 5 | /// Filters that other screens can set before opening Transactions (an account's "Transactions" button). |
| 6 | @MainActor @Observable |
| 7 | final class TransactionsFilter { |
| 8 | static let shared = TransactionsFilter() |
| 9 | var text = "" |
| 10 | var categoryID: String? |
| 11 | var accountID: String? |
| 12 | var tag: String? |
| 13 | var unreviewedOnly = false |
| 14 | /// Only transactions Bucksley has a category suggestion for. |
| 15 | var suggestedOnly = false |
| 16 | } |
| 17 | |
| 18 | struct TransactionsScreen: View { |
| 19 | @Environment(AppModel.self) private var model |
| 20 | @Environment(\.palette) private var palette |
| 21 | @State private var filter = TransactionsFilter.shared |
| 22 | |
| 23 | var body: some View { |
| 24 | @Bindable var filter = filter |
| 25 | @Bindable var model = model |
| 26 | let ledger = model.ledger |
| 27 | let found = ledger.search(filter.text, categoryID: filter.categoryID, accountID: filter.accountID, unreviewedOnly: filter.unreviewedOnly, tag: filter.tag) |
| 28 | let rows = ordered(found) |
| 29 | HStack(spacing: 0) { |
| 30 | ScreenScaffold("Transactions", subtitle: "\(rows.count) shown · \(ledger.reviewQueue.count) to review") { |
| 31 | EmptyView() |
| 32 | } content: { |
| 33 | TransactionFilterBar(filter: filter, ledger: ledger, |
| 34 | hasSuggestions: model.insights.suggestions.values.contains { !$0.categoryID.isEmpty }, |
| 35 | export: exportCSV) |
| 36 | if ledger.entries.isEmpty { ConnectFirst() } |
| 37 | else if rows.isEmpty { |
| 38 | VStack(alignment: .leading, spacing: 10) { |
| 39 | Text("No transactions match these filters.").font(.system(size: 14, weight: .semibold)) |
| 40 | Text(emptyHint(ledger)).font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 41 | Button("Clear filters") { filter.clearAll() }.buttonStyle(SecondaryButtonStyle()) |
| 42 | } |
| 43 | .padding(.vertical, 24).frame(maxWidth: 520, alignment: .leading) |
| 44 | } |
| 45 | if filter.suggestedOnly { |
| 46 | SuggestionList(entries: rows) |
| 47 | } else if filter.unreviewedOnly { |
| 48 | LazyVStack(alignment: .leading, spacing: 0) { |
| 49 | ForEach(rows.prefix(800)) { entry in |
| 50 | VStack(alignment: .leading, spacing: 0) { |
| 51 | row(entry, ledger) |
| 52 | if let flag = model.insights.flagByEntry[entry.id] { |
| 53 | Label(flag.reason, systemImage: "eye").font(.system(size: 11)).foregroundStyle(palette.loss) |
| 54 | .padding(.leading, 52).padding(.bottom, 6) |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | } else { |
| 60 | LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) { |
| 61 | ForEach(Dictionary(grouping: rows.prefix(800), by: { MonthKey.of($0.day) }).sorted { $0.key > $1.key }, id: \.key) { month, entries in |
| 62 | Section { |
| 63 | ForEach(entries) { entry in row(entry, ledger) } |
| 64 | } header: { |
| 65 | HStack { |
| 66 | Text(MonthKey.title(month)).font(palette.sectionFont) |
| 67 | Spacer() |
| 68 | MoneyText(entries.reduce(0) { $0 + $1.amount }, size: 11, signed: true) |
| 69 | } |
| 70 | .padding(.vertical, 6).padding(.horizontal, 10).background(palette.canvas) |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | if let id = model.selectedTransactionID, let entry = ledger.entries.first(where: { $0.id == id }) { |
| 77 | Rectangle().fill(palette.line).frame(width: 1) |
| 78 | TransactionDetail(entry: entry).frame(width: 340).id(entry.id) |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | extension TransactionsScreen { |
| 85 | /// Why an account filter can come up empty: investment accounts often have no activity for weeks. |
| 86 | func emptyHint(_ ledger: Ledger) -> String { |
| 87 | if let account = ledger.workspace.account(filter.accountID ?? "") { |
| 88 | let all = ledger.entries.filter { $0.accountID == account.id }.count |
| 89 | if all > 0 { return "\(account.displayName) has \(all) transaction\(all == 1 ? "" : "s"), but none match the other filters." } |
| 90 | return account.kind == .investment |
| 91 | ? "Your bank hasn't sent any transactions for \(account.displayName) in the last 90 days. Investment accounts often have none until a dividend, trade or deposit. Its balance and holdings still update on the Investments screen." |
| 92 | : "Your bank hasn't sent any transactions for \(account.displayName) yet." |
| 93 | } |
| 94 | return "Try a different filter or clear them all." |
| 95 | } |
| 96 | |
| 97 | func row(_ entry: LedgerEntry, _ ledger: Ledger) -> some View { |
| 98 | Button { model.open(entry) } label: { |
| 99 | TransactionRow(entry, workspace: ledger.workspace, showAccount: true) |
| 100 | .padding(.horizontal, 10) |
| 101 | .background(model.selectedTransactionID == entry.id ? palette.accent.opacity(0.12) : .clear, in: RoundedRectangle(cornerRadius: 8)) |
| 102 | } |
| 103 | .buttonStyle(.plain) |
| 104 | .contextMenu { |
| 105 | Button(entry.reviewed ? "Mark unreviewed" : "Mark reviewed") { model.edit(entry.id) { $0.reviewed = !entry.reviewed } } |
| 106 | Menu("Category") { ForEach(ledger.workspace.categories) { c in Button(c.name) { model.edit(entry.id) { $0.categoryID = c.id } } } } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// In review mode the inbox order (flagged, uncategorized, biggest); with suggestions on, only those. |
| 111 | func ordered(_ found: [LedgerEntry]) -> [LedgerEntry] { |
| 112 | if filter.suggestedOnly { return found.filter { model.suggestion(for: $0.id) != nil } } |
| 113 | guard filter.unreviewedOnly else { return found } |
| 114 | let keep = Set(found.map(\.id)) |
| 115 | return model.insights.reviewOrder.filter { keep.contains($0.id) } |
| 116 | } |
| 117 | |
| 118 | func exportCSV() { |
| 119 | let panel = NSSavePanel() |
| 120 | panel.nameFieldStringValue = "Bucksley transactions \(DayKey.today).csv" |
| 121 | panel.allowedContentTypes = [.commaSeparatedText] |
| 122 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 123 | do { |
| 124 | try Backup.csv(model.ledger).write(to: url, atomically: true, encoding: .utf8) |
| 125 | model.message = "Saved \(model.ledger.entries.count) transactions to \(url.lastPathComponent)." |
| 126 | } catch { model.message = error.localizedDescription } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// Uncategorized transactions with the category Bucksley would pick, one click to accept. |
| 131 | struct SuggestionList: View { |
| 132 | @Environment(AppModel.self) private var model |
| 133 | @Environment(\.palette) private var palette |
| 134 | let entries: [LedgerEntry] |
| 135 | |
| 136 | var body: some View { |
| 137 | let ws = model.workspace |
| 138 | VStack(alignment: .leading, spacing: 8) { |
| 139 | if entries.count > 1 { |
| 140 | Button("Accept all \(entries.count)") { |
| 141 | for e in entries { if let s = model.suggestion(for: e.id) { try? model.store.edit(e.id) { $0.categoryID = s.categoryID } } } |
| 142 | model.reload(force: true); model.shareSoon() |
| 143 | } |
| 144 | .buttonStyle(PrimaryButtonStyle()) |
| 145 | } |
| 146 | ForEach(entries) { entry in |
| 147 | if let s = model.suggestion(for: entry.id) { |
| 148 | HStack(spacing: 10) { |
| 149 | TransactionRow(entry, workspace: ws, showAccount: true).frame(maxWidth: .infinity) |
| 150 | VStack(alignment: .trailing, spacing: 4) { |
| 151 | HStack(spacing: 6) { |
| 152 | Image(systemName: "arrow.right").font(.system(size: 10)).foregroundStyle(palette.muted) |
| 153 | CategoryTag(ws.category(s.categoryID)) |
| 154 | } |
| 155 | Text(s.reason).font(.system(size: 10)).foregroundStyle(palette.muted).lineLimit(1) |
| 156 | } |
| 157 | .frame(width: 230, alignment: .trailing) |
| 158 | Button("Accept") { model.edit(entry.id) { $0.categoryID = s.categoryID } }.buttonStyle(SecondaryButtonStyle()) |
| 159 | } |
| 160 | .padding(.horizontal, 10).padding(.vertical, 2) |
| 161 | } |
| 162 | } |
| 163 | if entries.isEmpty { Text("Nothing left to file.").font(.system(size: 13)).foregroundStyle(palette.muted) } |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | struct TransactionDetail: View { |
| 169 | @Environment(AppModel.self) private var model |
| 170 | @Environment(\.palette) private var palette |
| 171 | let entry: LedgerEntry |
| 172 | @State private var name = "" |
| 173 | @State private var note = "" |
| 174 | @State private var tags = "" |
| 175 | @State private var splitting = false |
| 176 | @State private var splits: [Split] = [] |
| 177 | @State private var ruleMade = false |
| 178 | |
| 179 | var body: some View { |
| 180 | let ws = model.workspace |
| 181 | let account = ws.account(entry.accountID) |
| 182 | ScrollView { |
| 183 | VStack(alignment: .leading, spacing: 16) { |
| 184 | HStack { |
| 185 | Spacer() |
| 186 | Button { model.selectedTransactionID = nil } label: { Image(systemName: "xmark").font(.system(size: 11, weight: .bold)) } |
| 187 | .buttonStyle(.plain).foregroundStyle(palette.muted).accessibilityLabel("Close") |
| 188 | } |
| 189 | VStack(alignment: .leading, spacing: 10) { |
| 190 | HStack { |
| 191 | MerchantBadge(name: entry.name, colorIndex: ws.category(entry.categoryID)?.colorIndex ?? 5, size: 40) |
| 192 | Spacer() |
| 193 | CategoryTag(ws.category(entry.categoryID)) |
| 194 | } |
| 195 | Text(entry.name).font(palette.title(20)).tracking(palette.titleTracking) |
| 196 | MoneyText(entry.amount, size: 30, signed: true) |
| 197 | HStack { |
| 198 | Text(DayKey.date(entry.day)?.formatted(date: .long, time: .omitted) ?? entry.day) |
| 199 | Spacer() |
| 200 | Text(account?.displayName ?? "") |
| 201 | } |
| 202 | .font(.system(size: 12)).foregroundStyle(palette.muted) |
| 203 | .padding(.top, 6).overlay(alignment: .top) { Rectangle().fill(palette.line).frame(height: 0.5) } |
| 204 | Text("Bank: \(entry.transaction.description)").font(.system(size: 11)).foregroundStyle(palette.muted).textSelection(.enabled) |
| 205 | if entry.transaction.pending { Label("Pending", systemImage: "clock").font(.system(size: 11)).foregroundStyle(palette.muted) } |
| 206 | } |
| 207 | |
| 208 | insight(ws) |
| 209 | VStack(alignment: .leading, spacing: 10) { |
| 210 | if entry.reviewed { |
| 211 | Label("Reviewed", systemImage: "checkmark.circle.fill") |
| 212 | .font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.gain) |
| 213 | .accessibilityIdentifier("detail.reviewed") |
| 214 | } |
| 215 | HStack(spacing: 8) { |
| 216 | let key = Ledger.recurringKey(entry.name) |
| 217 | let recurring = model.workspace.recurring[key] == .confirmed |
| 218 | Button { model.updateWorkspace { $0.recurring[key] = recurring ? nil : .confirmed } } label: { |
| 219 | Label(recurring ? "Recurring" : "Mark recurring", systemImage: recurring ? "checkmark" : "repeat").fixedSize() |
| 220 | } |
| 221 | .buttonStyle(SecondaryButtonStyle()).help("Show this merchant on the Recurring screen") |
| 222 | Button { model.edit(entry.id) { $0.excluded = !entry.excluded } } label: { |
| 223 | Label(entry.excluded ? "Include" : "Exclude", systemImage: entry.excluded ? "plus.circle" : "minus.circle").fixedSize() |
| 224 | } |
| 225 | .buttonStyle(SecondaryButtonStyle()).help("Excluded transactions don't count toward spending or budgets") |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | field("Name") { |
| 230 | TextField(entry.name, text: $name).textFieldStyle(.roundedBorder).onSubmit { model.edit(entry.id) { $0.name = name } } |
| 231 | } |
| 232 | field("Category") { |
| 233 | ChoiceButton(ws.categoryChoices().map { (value: Optional($0.value), title: $0.title, emoji: $0.emoji) }, |
| 234 | selection: Binding(get: { entry.categoryID }, set: { c in model.edit(entry.id) { $0.categoryID = c } })) |
| 235 | .frame(maxWidth: 240, alignment: .leading) |
| 236 | } |
| 237 | field("Note") { |
| 238 | TextField("Add a note", text: $note, axis: .vertical).textFieldStyle(.roundedBorder).lineLimit(2...5) |
| 239 | .onSubmit { model.edit(entry.id) { $0.note = note } } |
| 240 | } |
| 241 | field("Tags") { |
| 242 | TextField("comma, separated", text: $tags).textFieldStyle(.roundedBorder) |
| 243 | .onSubmit { model.edit(entry.id) { $0.tags = tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } } } |
| 244 | } |
| 245 | Button("Save changes") { save() }.buttonStyle(SecondaryButtonStyle()) |
| 246 | |
| 247 | VStack(alignment: .leading, spacing: 8) { |
| 248 | HStack { |
| 249 | Text("Split").font(.system(size: 12, weight: .semibold)) |
| 250 | Spacer() |
| 251 | Button(splitting ? "Cancel" : (entry.splits.isEmpty ? "Split transaction" : "Edit split")) { |
| 252 | splitting.toggle() |
| 253 | if splitting { splits = entry.splits.isEmpty ? [Split(amount: abs(entry.amount), categoryID: entry.categoryID)] : entry.splits } |
| 254 | } |
| 255 | .buttonStyle(.plain).foregroundStyle(palette.accent).font(.system(size: 12, weight: .semibold)) |
| 256 | } |
| 257 | if !splitting { |
| 258 | ForEach(entry.splits) { s in |
| 259 | HStack { CategoryTag(ws.category(s.categoryID)); Spacer(); MoneyText(s.amount, size: 12) } |
| 260 | } |
| 261 | } else { |
| 262 | ForEach($splits) { $s in |
| 263 | HStack { |
| 264 | ChoiceButton(ws.categoryChoices(), selection: $s.categoryID) |
| 265 | TextField("Amount", value: $s.amount, format: .number.precision(.fractionLength(2))).textFieldStyle(.roundedBorder).frame(width: 80) |
| 266 | } |
| 267 | } |
| 268 | let rest = abs(entry.amount) - splits.reduce(0) { $0 + $1.amount } |
| 269 | HStack { |
| 270 | Button("Add part") { splits.append(Split(amount: max(0, rest), categoryID: "other")) }.buttonStyle(.plain).foregroundStyle(palette.accent) |
| 271 | Spacer() |
| 272 | Text(rest == 0 ? "Adds up" : "\(Money.format(rest)) left").font(.system(size: 11)).foregroundStyle(rest == 0 ? palette.gain : palette.loss) |
| 273 | } |
| 274 | .font(.system(size: 12)) |
| 275 | HStack { |
| 276 | Button("Save split") { model.edit(entry.id) { $0.splits = splits.count > 1 ? splits : [] }; splitting = false } |
| 277 | .buttonStyle(PrimaryButtonStyle()).disabled(rest != 0) |
| 278 | if !entry.splits.isEmpty { Button("Remove split") { model.edit(entry.id) { $0.splits = [] }; splitting = false }.buttonStyle(SecondaryButtonStyle()) } |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | .padding(12).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) |
| 283 | |
| 284 | Button(ruleMade ? "Rule added" : "Always categorize “\(Ledger.ruleText(for: entry))” as \(ws.category(entry.categoryID)?.name ?? "this")") { |
| 285 | model.updateWorkspace { $0.rules.insert(Rule(matchText: Ledger.ruleText(for: entry), setCategoryID: entry.categoryID), at: 0) } |
| 286 | ruleMade = true |
| 287 | } |
| 288 | .buttonStyle(.plain).font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.accent).disabled(ruleMade) |
| 289 | if let edit = try? model.store.edits()[entry.id] { |
| 290 | Text("Edited on \(edit.device), \(edit.updatedAt.formatted(.relative(presentation: .named)))").font(.system(size: 11)).foregroundStyle(palette.muted) |
| 291 | } |
| 292 | } |
| 293 | .padding(20) |
| 294 | } |
| 295 | .background(palette.sidebar.ignoresSafeArea()) |
| 296 | .onAppear { |
| 297 | name = entry.name; note = entry.note ?? ""; tags = entry.tags.joined(separator: ", ") |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Why this charge was flagged, a likely refund match, or a category suggestion. |
| 302 | @ViewBuilder func insight(_ ws: Workspace) -> some View { |
| 303 | let ledger = model.ledger |
| 304 | if let flag = model.insights.flagByEntry[entry.id] { |
| 305 | Label(flag.reason, systemImage: "eye").font(.system(size: 12)).foregroundStyle(palette.loss).fixedSize(horizontal: false, vertical: true) |
| 306 | } |
| 307 | if let purchaseID = entry.refundOf, let purchase = ledger.entry(purchaseID) { |
| 308 | HStack { |
| 309 | Label("Refund of \(purchase.name), \(DayKey.short(purchase.day))", systemImage: "arrow.uturn.backward").font(.system(size: 12)).foregroundStyle(palette.gain) |
| 310 | Spacer() |
| 311 | Button("Unlink") { model.edit(entry.id) { $0.refundOf = "" } }.buttonStyle(.plain).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.accent) |
| 312 | } |
| 313 | } else if let match = model.insights.refundByEntry[entry.id], let purchase = ledger.entry(match.purchaseID) { |
| 314 | VStack(alignment: .leading, spacing: 6) { |
| 315 | Text("Looks like a refund of \(purchase.name) (\(Money.format(purchase.amount)) on \(DayKey.short(purchase.day))).") |
| 316 | .font(.system(size: 12)).fixedSize(horizontal: false, vertical: true) |
| 317 | Button("Count it as a refund") { model.acceptRefund(match) }.buttonStyle(SecondaryButtonStyle()) |
| 318 | } |
| 319 | .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) |
| 320 | } |
| 321 | if let s = model.suggestion(for: entry.id), let category = ws.category(s.categoryID) { |
| 322 | VStack(alignment: .leading, spacing: 6) { |
| 323 | Text(s.reason).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true) |
| 324 | Button("File under \(category.icon) \(category.name)") { model.edit(entry.id) { $0.categoryID = s.categoryID } }.buttonStyle(SecondaryButtonStyle()) |
| 325 | } |
| 326 | .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | func save() { |
| 331 | let tagList = tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } |
| 332 | model.edit(entry.id) { e in |
| 333 | if name != entry.name { e.name = name } |
| 334 | if note != (entry.note ?? "") { e.note = note } |
| 335 | if tagList != entry.tags { e.tags = tagList } |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | func field<Content: View>(_ label: String, @ViewBuilder _ content: () -> Content) -> some View { |
| 340 | VStack(alignment: .leading, spacing: 4) { |
| 341 | Text(label).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.muted) |
| 342 | content() |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | extension Ledger { |
| 348 | /// The first word or two of the bank text, used when making a rule from a transaction. |
| 349 | static func ruleText(for entry: LedgerEntry) -> String { |
| 350 | let words = Defaults.cleanName(entry.transaction.payee ?? entry.transaction.description).split(separator: " ").prefix(2) |
| 351 | return words.joined(separator: " ") |
| 352 | } |
| 353 | } |