import SwiftUI import BucksleyKit import BucksleyUI /// Filters that other screens can set before opening Transactions (an account's "Transactions" button). @MainActor @Observable final class TransactionsFilter { static let shared = TransactionsFilter() var text = "" var categoryID: String? var accountID: String? var tag: String? var unreviewedOnly = false /// Only transactions Bucksley has a category suggestion for. var suggestedOnly = false } struct TransactionsScreen: View { @Environment(AppModel.self) private var model @Environment(\.palette) private var palette @State private var filter = TransactionsFilter.shared var body: some View { @Bindable var filter = filter @Bindable var model = model let ledger = model.ledger let found = ledger.search(filter.text, categoryID: filter.categoryID, accountID: filter.accountID, unreviewedOnly: filter.unreviewedOnly, tag: filter.tag) let rows = ordered(found) HStack(spacing: 0) { ScreenScaffold("Transactions", subtitle: "\(rows.count) shown · \(ledger.reviewQueue.count) to review") { EmptyView() } content: { TransactionFilterBar(filter: filter, ledger: ledger, hasSuggestions: model.insights.suggestions.values.contains { !$0.categoryID.isEmpty }, export: exportCSV) if ledger.entries.isEmpty { ConnectFirst() } else if rows.isEmpty { VStack(alignment: .leading, spacing: 10) { Text("No transactions match these filters.").font(.system(size: 14, weight: .semibold)) Text(emptyHint(ledger)).font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) Button("Clear filters") { filter.clearAll() }.buttonStyle(SecondaryButtonStyle()) } .padding(.vertical, 24).frame(maxWidth: 520, alignment: .leading) } if filter.suggestedOnly { SuggestionList(entries: rows) } else if filter.unreviewedOnly { LazyVStack(alignment: .leading, spacing: 0) { ForEach(rows.prefix(800)) { entry in VStack(alignment: .leading, spacing: 0) { row(entry, ledger) if let flag = model.insights.flagByEntry[entry.id] { Label(flag.reason, systemImage: "eye").font(.system(size: 11)).foregroundStyle(palette.loss) .padding(.leading, 52).padding(.bottom, 6) } } } } } else { LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) { ForEach(Dictionary(grouping: rows.prefix(800), by: { MonthKey.of($0.day) }).sorted { $0.key > $1.key }, id: \.key) { month, entries in Section { ForEach(entries) { entry in row(entry, ledger) } } header: { HStack { Text(MonthKey.title(month)).font(palette.sectionFont) Spacer() MoneyText(entries.reduce(0) { $0 + $1.amount }, size: 11, signed: true) } .padding(.vertical, 6).padding(.horizontal, 10).background(palette.canvas) } } } } } if let id = model.selectedTransactionID, let entry = ledger.entries.first(where: { $0.id == id }) { Rectangle().fill(palette.line).frame(width: 1) TransactionDetail(entry: entry).frame(width: 340).id(entry.id) } } } } extension TransactionsScreen { /// Why an account filter can come up empty: investment accounts often have no activity for weeks. func emptyHint(_ ledger: Ledger) -> String { if let account = ledger.workspace.account(filter.accountID ?? "") { let all = ledger.entries.filter { $0.accountID == account.id }.count if all > 0 { return "\(account.displayName) has \(all) transaction\(all == 1 ? "" : "s"), but none match the other filters." } return account.kind == .investment ? "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." : "Your bank hasn't sent any transactions for \(account.displayName) yet." } return "Try a different filter or clear them all." } func row(_ entry: LedgerEntry, _ ledger: Ledger) -> some View { Button { model.open(entry) } label: { TransactionRow(entry, workspace: ledger.workspace, showAccount: true) .padding(.horizontal, 10) .background(model.selectedTransactionID == entry.id ? palette.accent.opacity(0.12) : .clear, in: RoundedRectangle(cornerRadius: 8)) } .buttonStyle(.plain) .contextMenu { Button(entry.reviewed ? "Mark unreviewed" : "Mark reviewed") { model.edit(entry.id) { $0.reviewed = !entry.reviewed } } Menu("Category") { ForEach(ledger.workspace.categories) { c in Button(c.name) { model.edit(entry.id) { $0.categoryID = c.id } } } } } } /// In review mode the inbox order (flagged, uncategorized, biggest); with suggestions on, only those. func ordered(_ found: [LedgerEntry]) -> [LedgerEntry] { if filter.suggestedOnly { return found.filter { model.suggestion(for: $0.id) != nil } } guard filter.unreviewedOnly else { return found } let keep = Set(found.map(\.id)) return model.insights.reviewOrder.filter { keep.contains($0.id) } } func exportCSV() { let panel = NSSavePanel() panel.nameFieldStringValue = "Bucksley transactions \(DayKey.today).csv" panel.allowedContentTypes = [.commaSeparatedText] guard panel.runModal() == .OK, let url = panel.url else { return } do { try Backup.csv(model.ledger).write(to: url, atomically: true, encoding: .utf8) model.message = "Saved \(model.ledger.entries.count) transactions to \(url.lastPathComponent)." } catch { model.message = error.localizedDescription } } } /// Uncategorized transactions with the category Bucksley would pick, one click to accept. struct SuggestionList: View { @Environment(AppModel.self) private var model @Environment(\.palette) private var palette let entries: [LedgerEntry] var body: some View { let ws = model.workspace VStack(alignment: .leading, spacing: 8) { if entries.count > 1 { Button("Accept all \(entries.count)") { for e in entries { if let s = model.suggestion(for: e.id) { try? model.store.edit(e.id) { $0.categoryID = s.categoryID } } } model.reload(force: true); model.shareSoon() } .buttonStyle(PrimaryButtonStyle()) } ForEach(entries) { entry in if let s = model.suggestion(for: entry.id) { HStack(spacing: 10) { TransactionRow(entry, workspace: ws, showAccount: true).frame(maxWidth: .infinity) VStack(alignment: .trailing, spacing: 4) { HStack(spacing: 6) { Image(systemName: "arrow.right").font(.system(size: 10)).foregroundStyle(palette.muted) CategoryTag(ws.category(s.categoryID)) } Text(s.reason).font(.system(size: 10)).foregroundStyle(palette.muted).lineLimit(1) } .frame(width: 230, alignment: .trailing) Button("Accept") { model.edit(entry.id) { $0.categoryID = s.categoryID } }.buttonStyle(SecondaryButtonStyle()) } .padding(.horizontal, 10).padding(.vertical, 2) } } if entries.isEmpty { Text("Nothing left to file.").font(.system(size: 13)).foregroundStyle(palette.muted) } } } } struct TransactionDetail: View { @Environment(AppModel.self) private var model @Environment(\.palette) private var palette let entry: LedgerEntry @State private var name = "" @State private var note = "" @State private var tags = "" @State private var splitting = false @State private var splits: [Split] = [] @State private var ruleMade = false var body: some View { let ws = model.workspace let account = ws.account(entry.accountID) ScrollView { VStack(alignment: .leading, spacing: 16) { HStack { Spacer() Button { model.selectedTransactionID = nil } label: { Image(systemName: "xmark").font(.system(size: 11, weight: .bold)) } .buttonStyle(.plain).foregroundStyle(palette.muted).accessibilityLabel("Close") } VStack(alignment: .leading, spacing: 10) { HStack { MerchantBadge(name: entry.name, colorIndex: ws.category(entry.categoryID)?.colorIndex ?? 5, size: 40) Spacer() CategoryTag(ws.category(entry.categoryID)) } Text(entry.name).font(palette.title(20)).tracking(palette.titleTracking) MoneyText(entry.amount, size: 30, signed: true) HStack { Text(DayKey.date(entry.day)?.formatted(date: .long, time: .omitted) ?? entry.day) Spacer() Text(account?.displayName ?? "") } .font(.system(size: 12)).foregroundStyle(palette.muted) .padding(.top, 6).overlay(alignment: .top) { Rectangle().fill(palette.line).frame(height: 0.5) } Text("Bank: \(entry.transaction.description)").font(.system(size: 11)).foregroundStyle(palette.muted).textSelection(.enabled) if entry.transaction.pending { Label("Pending", systemImage: "clock").font(.system(size: 11)).foregroundStyle(palette.muted) } } insight(ws) VStack(alignment: .leading, spacing: 10) { if entry.reviewed { Label("Reviewed", systemImage: "checkmark.circle.fill") .font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.gain) .accessibilityIdentifier("detail.reviewed") } HStack(spacing: 8) { let key = Ledger.recurringKey(entry.name) let recurring = model.workspace.recurring[key] == .confirmed Button { model.updateWorkspace { $0.recurring[key] = recurring ? nil : .confirmed } } label: { Label(recurring ? "Recurring" : "Mark recurring", systemImage: recurring ? "checkmark" : "repeat").fixedSize() } .buttonStyle(SecondaryButtonStyle()).help("Show this merchant on the Recurring screen") Button { model.edit(entry.id) { $0.excluded = !entry.excluded } } label: { Label(entry.excluded ? "Include" : "Exclude", systemImage: entry.excluded ? "plus.circle" : "minus.circle").fixedSize() } .buttonStyle(SecondaryButtonStyle()).help("Excluded transactions don't count toward spending or budgets") } } field("Name") { TextField(entry.name, text: $name).textFieldStyle(.roundedBorder).onSubmit { model.edit(entry.id) { $0.name = name } } } field("Category") { ChoiceButton(ws.categoryChoices().map { (value: Optional($0.value), title: $0.title, emoji: $0.emoji) }, selection: Binding(get: { entry.categoryID }, set: { c in model.edit(entry.id) { $0.categoryID = c } })) .frame(maxWidth: 240, alignment: .leading) } field("Note") { TextField("Add a note", text: $note, axis: .vertical).textFieldStyle(.roundedBorder).lineLimit(2...5) .onSubmit { model.edit(entry.id) { $0.note = note } } } field("Tags") { TextField("comma, separated", text: $tags).textFieldStyle(.roundedBorder) .onSubmit { model.edit(entry.id) { $0.tags = tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } } } } Button("Save changes") { save() }.buttonStyle(SecondaryButtonStyle()) VStack(alignment: .leading, spacing: 8) { HStack { Text("Split").font(.system(size: 12, weight: .semibold)) Spacer() Button(splitting ? "Cancel" : (entry.splits.isEmpty ? "Split transaction" : "Edit split")) { splitting.toggle() if splitting { splits = entry.splits.isEmpty ? [Split(amount: abs(entry.amount), categoryID: entry.categoryID)] : entry.splits } } .buttonStyle(.plain).foregroundStyle(palette.accent).font(.system(size: 12, weight: .semibold)) } if !splitting { ForEach(entry.splits) { s in HStack { CategoryTag(ws.category(s.categoryID)); Spacer(); MoneyText(s.amount, size: 12) } } } else { ForEach($splits) { $s in HStack { ChoiceButton(ws.categoryChoices(), selection: $s.categoryID) TextField("Amount", value: $s.amount, format: .number.precision(.fractionLength(2))).textFieldStyle(.roundedBorder).frame(width: 80) } } let rest = abs(entry.amount) - splits.reduce(0) { $0 + $1.amount } HStack { Button("Add part") { splits.append(Split(amount: max(0, rest), categoryID: "other")) }.buttonStyle(.plain).foregroundStyle(palette.accent) Spacer() Text(rest == 0 ? "Adds up" : "\(Money.format(rest)) left").font(.system(size: 11)).foregroundStyle(rest == 0 ? palette.gain : palette.loss) } .font(.system(size: 12)) HStack { Button("Save split") { model.edit(entry.id) { $0.splits = splits.count > 1 ? splits : [] }; splitting = false } .buttonStyle(PrimaryButtonStyle()).disabled(rest != 0) if !entry.splits.isEmpty { Button("Remove split") { model.edit(entry.id) { $0.splits = [] }; splitting = false }.buttonStyle(SecondaryButtonStyle()) } } } } .padding(12).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) Button(ruleMade ? "Rule added" : "Always categorize “\(Ledger.ruleText(for: entry))” as \(ws.category(entry.categoryID)?.name ?? "this")") { model.updateWorkspace { $0.rules.insert(Rule(matchText: Ledger.ruleText(for: entry), setCategoryID: entry.categoryID), at: 0) } ruleMade = true } .buttonStyle(.plain).font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.accent).disabled(ruleMade) if let edit = try? model.store.edits()[entry.id] { Text("Edited on \(edit.device), \(edit.updatedAt.formatted(.relative(presentation: .named)))").font(.system(size: 11)).foregroundStyle(palette.muted) } } .padding(20) } .background(palette.sidebar.ignoresSafeArea()) .onAppear { name = entry.name; note = entry.note ?? ""; tags = entry.tags.joined(separator: ", ") } } /// Why this charge was flagged, a likely refund match, or a category suggestion. @ViewBuilder func insight(_ ws: Workspace) -> some View { let ledger = model.ledger if let flag = model.insights.flagByEntry[entry.id] { Label(flag.reason, systemImage: "eye").font(.system(size: 12)).foregroundStyle(palette.loss).fixedSize(horizontal: false, vertical: true) } if let purchaseID = entry.refundOf, let purchase = ledger.entry(purchaseID) { HStack { Label("Refund of \(purchase.name), \(DayKey.short(purchase.day))", systemImage: "arrow.uturn.backward").font(.system(size: 12)).foregroundStyle(palette.gain) Spacer() Button("Unlink") { model.edit(entry.id) { $0.refundOf = "" } }.buttonStyle(.plain).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.accent) } } else if let match = model.insights.refundByEntry[entry.id], let purchase = ledger.entry(match.purchaseID) { VStack(alignment: .leading, spacing: 6) { Text("Looks like a refund of \(purchase.name) (\(Money.format(purchase.amount)) on \(DayKey.short(purchase.day))).") .font(.system(size: 12)).fixedSize(horizontal: false, vertical: true) Button("Count it as a refund") { model.acceptRefund(match) }.buttonStyle(SecondaryButtonStyle()) } .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) } if let s = model.suggestion(for: entry.id), let category = ws.category(s.categoryID) { VStack(alignment: .leading, spacing: 6) { Text(s.reason).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true) Button("File under \(category.icon) \(category.name)") { model.edit(entry.id) { $0.categoryID = s.categoryID } }.buttonStyle(SecondaryButtonStyle()) } .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) } } func save() { let tagList = tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } model.edit(entry.id) { e in if name != entry.name { e.name = name } if note != (entry.note ?? "") { e.note = note } if tagList != entry.tags { e.tags = tagList } } } func field(_ label: String, @ViewBuilder _ content: () -> Content) -> some View { VStack(alignment: .leading, spacing: 4) { Text(label).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.muted) content() } } } extension Ledger { /// The first word or two of the bank text, used when making a rule from a transaction. static func ruleText(for entry: LedgerEntry) -> String { let words = Defaults.cleanName(entry.transaction.payee ?? entry.transaction.description).split(separator: " ").prefix(2) return words.joined(separator: " ") } }