Branchwell

Bucksley / app · bucksley.ai / Apps / iPhone / PhoneScreens.swift

1import SwiftUI
2import BucksleyKit
3import BucksleyUI
4
5/// The review queue: swipe right to mark reviewed, tap to recategorize or add a note. Every change
6/// goes back to the Mac through iCloud.
7struct InboxScreen: View {
8 @Environment(PhoneModel.self) private var model
9 @Environment(\.palette) private var palette
10 @State private var search = ""
11 @State private var editing: LedgerEntry?
12 @State private var showAll = false
13
14 var body: some View {
15 let ledger = model.ledger
16 let queue = search.isEmpty ? (showAll ? ledger.entries : ledger.prioritizedReviewQueue()) : ledger.search(search)
17 let flags = Dictionary(ledger.flags().map { ($0.entryID, $0.reason) }, uniquingKeysWith: { first, _ in first })
18 VStack(spacing: 0) {
19 List {
20 Section {
21 HStack(alignment: .firstTextBaseline) {
22 Text(showAll || !search.isEmpty ? "Transactions" : "Inbox").font(palette.title(32)).tracking(palette.titleTracking)
23 Spacer()
24 Picker("", selection: $showAll) { Text("To review").tag(false); Text("All").tag(true) }.pickerStyle(.segmented).frame(width: 170)
25 }
26 .listRowBackground(Color.clear).listRowSeparator(.hidden)
27 if ledger.entries.isEmpty {
28 EmptyMac().listRowBackground(Color.clear).listRowSeparator(.hidden)
29 } else if queue.isEmpty {
30 VStack(alignment: .leading, spacing: 6) {
31 Image(systemName: "checkmark.seal.fill").font(.system(size: 30)).foregroundStyle(palette.gain)
32 Text("All caught up").font(palette.title(20))
33 Text("New transactions land here after your Mac syncs.").font(.system(size: 14)).foregroundStyle(palette.muted)
34 }
35 .padding(.vertical, 24).listRowBackground(Color.clear).listRowSeparator(.hidden)
36 } else {
37 Text(search.isEmpty ? "\(ledger.reviewQueue.count) to review · swipe right when it looks right" : "\(queue.count) matches")
38 .font(.system(size: 13)).foregroundStyle(palette.muted).listRowBackground(Color.clear).listRowSeparator(.hidden)
39 }
40 }
41 ForEach(queue.prefix(300)) { entry in
42 Button { editing = entry } label: {
43 VStack(alignment: .leading, spacing: 2) {
44 TransactionRow(entry, workspace: ledger.workspace, showAccount: true)
45 if !entry.reviewed, let reason = flags[entry.id] {
46 Label(reason, systemImage: "eye").font(.system(size: 12)).foregroundStyle(palette.loss).padding(.leading, 46)
47 }
48 }
49 }
50 .buttonStyle(.plain)
51 .listRowBackground(palette.canvas)
52 .listRowSeparatorTint(palette.line)
53 .swipeActions(edge: .leading, allowsFullSwipe: true) {
54 Button { model.edit(entry.id) { $0.reviewed = !entry.reviewed } } label: { Label(entry.reviewed ? "Unreview" : "Reviewed", systemImage: "checkmark") }
55 .tint(palette.gain)
56 }
57 .swipeActions(edge: .trailing) {
58 Button { editing = entry } label: { Label("Edit", systemImage: "pencil") }.tint(palette.accent)
59 }
60 }
61 if !queue.isEmpty && search.isEmpty && !showAll {
62 Button("Mark all \(min(queue.count, 300)) reviewed") {
63 for entry in queue.prefix(300) { model.edit(entry.id) { $0.reviewed = true } }
64 }
65 .font(.system(size: 14, weight: .semibold)).foregroundStyle(palette.accent).listRowBackground(Color.clear)
66 }
67 }
68 .listStyle(.plain)
69 .scrollContentBackground(.hidden)
70 }
71 .background(palette.canvas.ignoresSafeArea())
72 .searchable(text: $search, prompt: "Search transactions")
73 .refreshable { await model.refresh() }
74 .toolbar(.hidden, for: .navigationBar)
75 .sheet(item: $editing) { entry in TransactionEditor(entry: entry).presentationDetents([.large]) }
76 .task(id: ledger.entries.count) {
77 if ProcessInfo.processInfo.environment["BUCKSLEY_SHOW"] == "edit", editing == nil, let first = ledger.reviewQueue.first { editing = first }
78 }
79 }
80}
81
82struct TransactionEditor: View {
83 @Environment(PhoneModel.self) private var model
84 @Environment(\.palette) private var palette
85 @Environment(\.dismiss) private var dismiss
86 let entry: LedgerEntry
87 @State private var name = ""
88 @State private var note = ""
89 @State private var categoryID = ""
90 @State private var tags = ""
91
92 var body: some View {
93 let ws = model.workspace
94 NavigationStack {
95 Form {
96 Section {
97 VStack(alignment: .leading, spacing: 6) {
98 HStack { MerchantBadge(name: entry.name, colorIndex: ws.category(categoryID)?.colorIndex ?? 5, size: 40); Spacer(); CategoryTag(ws.category(categoryID)) }
99 MoneyText(entry.amount, size: 30, signed: true)
100 Text("\(TransactionRow.shortDay(entry.day)) · \(ws.account(entry.accountID)?.displayName ?? "")").font(.system(size: 13)).foregroundStyle(palette.muted)
101 Text("Bank: \(entry.transaction.description)").font(.system(size: 12)).foregroundStyle(palette.muted)
102 }
103 .listRowBackground(palette.card)
104 }
105 Section("Name") { TextField(entry.name, text: $name) }.listRowBackground(palette.card)
106 Section("Category") {
107 Picker("Category", selection: $categoryID) {
108 ForEach(ws.groups) { g in Section(g.name) { ForEach(ws.categories.filter { $0.groupID == g.id }) { Text($0.name).tag($0.id) } } }
109 }
110 }
111 .listRowBackground(palette.card)
112 Section("Note") { TextField("Add a note", text: $note, axis: .vertical) }.listRowBackground(palette.card)
113 Section("Tags") { TextField("comma, separated", text: $tags) }.listRowBackground(palette.card)
114 Section {
115 Button(entry.excluded ? "Count in spending again" : "Exclude from spending") { model.edit(entry.id) { $0.excluded = !entry.excluded }; dismiss() }
116 }
117 .listRowBackground(palette.card)
118 }
119 .scrollContentBackground(.hidden)
120 .background(palette.canvas)
121 .navigationTitle(entry.name)
122 .navigationBarTitleDisplayMode(.inline)
123 .toolbar {
124 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
125 ToolbarItem(placement: .confirmationAction) {
126 Button("Save & Review") { save(review: true) }.fontWeight(.semibold)
127 }
128 }
129 }
130 .onAppear { name = entry.name; note = entry.note ?? ""; categoryID = entry.categoryID; tags = entry.tags.joined(separator: ", ") }
131 }
132
133 func save(review: Bool) {
134 let tagList = tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
135 model.edit(entry.id) { e in
136 if name != entry.name { e.name = name }
137 if categoryID != entry.categoryID { e.categoryID = categoryID }
138 if note != (entry.note ?? "") { e.note = note }
139 if tagList != entry.tags { e.tags = tagList }
140 if review { e.reviewed = true }
141 }
142 dismiss()
143 }
144}
145
146struct PhoneAccountsScreen: View {
147 @Environment(PhoneModel.self) private var model
148 @Environment(\.palette) private var palette
149 @State private var range = 90
150
151 var body: some View {
152 let ledger = model.ledger
153 PhoneScreen("Accounts") {
154 if ledger.visibleAccounts.isEmpty { EmptyMac() } else {
155 VStack(alignment: .leading, spacing: 4) {
156 Text(palette.theme == .afterhours ? "NET WORTH" : "Net worth").font(.system(size: 12, weight: .bold)).tracking(palette.theme == .afterhours ? 1 : 0).foregroundStyle(palette.muted)
157 HeroMoney(ledger.netWorth, size: 38)
158 let change = ledger.change(days: range)
159 Text("\(Money.format(change, cents: false, signed: true)) over \(range == 30 ? "the past month" : range == 90 ? "3 months" : "the past year")")
160 .font(palette.figure(13, weight: .medium)).foregroundStyle(change >= 0 ? palette.gain : palette.loss)
161 }
162 PillPicker([(30, "1M"), (90, "3M"), (365, "1Y")], selection: $range)
163 NetWorthChart(ledger.netWorthSeries(days: range)).frame(height: 190)
164 ForEach(AccountGroup.allCases, id: \.self) { group in
165 let accounts = ledger.visibleAccounts.filter { $0.kind.group == group }
166 if !accounts.isEmpty {
167 VStack(alignment: .leading, spacing: 6) {
168 SectionHeader(group.title) { MoneyText(ledger.total(group), size: 13, cents: false) }
169 ForEach(accounts) { a in
170 HStack(spacing: 12) {
171 MerchantBadge(name: a.institution, colorIndex: group == .credit ? 4 : group == .investments ? 0 : 1, size: 34)
172 VStack(alignment: .leading, spacing: 2) {
173 Text(a.displayName).font(.system(size: 15, weight: .semibold)).lineLimit(1)
174 Text(a.institution).font(.system(size: 12)).foregroundStyle(palette.muted).lineLimit(1)
175 }
176 Spacer()
177 MoneyText(a.balance, size: 15)
178 }
179 .padding(12)
180 .background(palette.ruled ? Color.clear : palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius, style: .continuous))
181 .overlay(alignment: .bottom) { if palette.ruled { Rectangle().fill(palette.line).frame(height: 0.5) } }
182 }
183 }
184 }
185 }
186 Panel {
187 VStack(alignment: .leading, spacing: 10) {
188 SectionHeader("Spending this month")
189 SpendingChart(ledger.spending(), workspace: ledger.workspace, compact: true)
190 }
191 }
192 Text(model.status).font(.system(size: 12)).foregroundStyle(palette.muted)
193 }
194 }
195 }
196}
197
198struct PhoneBudgetsScreen: View {
199 @Environment(PhoneModel.self) private var model
200 @Environment(\.palette) private var palette
201
202 var body: some View {
203 let ledger = model.ledger
204 let ws = ledger.workspace
205 let statuses = ledger.budgetStatus()
206 PhoneScreen("Budgets") {
207 Text(MonthKey.title(MonthKey.current)).font(palette.theme == .almanac ? .system(size: 15, design: .serif).italic() : .system(size: 14)).foregroundStyle(palette.muted)
208 if ledger.entries.isEmpty { EmptyMac() }
209 if !statuses.isEmpty {
210 let (total, spent) = ledger.budgetTotals()
211 Panel {
212 HStack {
213 VStack(alignment: .leading, spacing: 2) { Text("Spent").font(.system(size: 12)).foregroundStyle(palette.muted); MoneyText(spent, size: 22, cents: false) }
214 Spacer()
215 VStack(alignment: .trailing, spacing: 2) { Text(total >= spent ? "Left" : "Over").font(.system(size: 12)).foregroundStyle(palette.muted); MoneyText(abs(total - spent), size: 22, cents: false) }
216 }
217 }
218 }
219 ForEach(statuses) { status in
220 BudgetProgress(status, name: ledger.budgetName(status.id), colorIndex: ws.category(status.id)?.colorIndex ?? 0)
221 .padding(.vertical, 4)
222 }
223 let suggestions = ledger.budgetSuggestions()
224 if !suggestions.isEmpty {
225 SectionHeader("Suggested by Bucksley") { Image(systemName: "sparkles").foregroundStyle(palette.accent) }
226 ForEach(suggestions.prefix(5)) { s in
227 VStack(alignment: .leading, spacing: 4) {
228 HStack {
229 Text(ws.category(s.categoryID)?.name ?? s.categoryID).font(.system(size: 15, weight: .semibold))
230 Spacer()
231 MoneyText(s.amount, size: 15, cents: false)
232 Text("/mo").font(.system(size: 12)).foregroundStyle(palette.muted)
233 }
234 Text(s.reason).font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true)
235 }
236 .padding(12).background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius))
237 }
238 Text("Add budgets in Bucksley on your Mac.").font(.system(size: 12)).foregroundStyle(palette.muted)
239 }
240 let recurring = ledger.recurring().filter { $0.status != .dismissed }
241 if !recurring.isEmpty {
242 SectionHeader("Recurring") { MoneyText(recurring.reduce(Decimal(0)) { $0 + $1.amount * 30 / Decimal($1.cadence.days) }.rounded(0), size: 13, cents: false) }
243 ForEach(recurring.prefix(8)) { item in
244 HStack {
245 MerchantBadge(name: item.name, colorIndex: ws.category(item.categoryID)?.colorIndex ?? 5)
246 VStack(alignment: .leading, spacing: 1) {
247 Text(item.name).font(.system(size: 14, weight: .semibold))
248 Text("\(item.cadence.title) · next \(TransactionRow.shortDay(item.nextDay))").font(.system(size: 12)).foregroundStyle(palette.muted)
249 }
250 Spacer()
251 MoneyText(item.amount, size: 14)
252 }
253 }
254 }
255 }
256 }
257}
258
259struct PhoneAskScreen: View {
260 @Environment(PhoneModel.self) private var model
261 @Environment(\.palette) private var palette
262 @State private var question = ""
263 @State private var turns: [(q: String, a: String?, p: String?, ids: [String])] = []
264 @State private var editing: LedgerEntry?
265 @State private var busy = false
266 let starters = ["What did I spend on groceries this month?", "What are my subscriptions costing me?", "How is my net worth trending?"]
267
268 var body: some View {
269 VStack(spacing: 0) {
270 PhoneScreen("Ask") {
271 Text("Apple Intelligence · \(AskBucksley.appleModelStatus). Answers come from your own numbers and stay on this iPhone.")
272 .font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true)
273 if turns.isEmpty {
274 ForEach(starters, id: \.self) { s in
275 Button { send(s) } label: {
276 Text(s).font(.system(size: 15)).frame(maxWidth: .infinity, alignment: .leading).padding(14)
277 .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius))
278 }
279 .buttonStyle(.plain)
280 }
281 }
282 ForEach(turns.indices, id: \.self) { i in
283 VStack(alignment: .leading, spacing: 8) {
284 HStack { Spacer(); Text(turns[i].q).font(.system(size: 15, weight: .medium)).padding(.horizontal, 14).padding(.vertical, 9)
285 .foregroundStyle(palette.accentText).background(palette.accent, in: RoundedRectangle(cornerRadius: 18, style: .continuous)) }
286 if let a = turns[i].a {
287 VStack(alignment: .leading, spacing: 4) {
288 Text(AskBucksley.formatted(a)).font(palette.theme == .almanac ? .system(size: 16, design: .serif) : .system(size: 15)).fixedSize(horizontal: false, vertical: true)
289 ForEach(linked(turns[i].ids)) { entry in
290 Button { editing = entry } label: { TransactionRow(entry, workspace: model.ledger.workspace, showAccount: true).contentShape(Rectangle()) }
291 .buttonStyle(.plain)
292 }
293 if let p = turns[i].p { Text(p).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.muted) }
294 }
295 .padding(14).background(palette.card, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
296 } else { ProgressView() }
297 }
298 }
299 }
300 HStack(spacing: 8) {
301 TextField("Ask about your money…", text: $question).font(.system(size: 15)).onSubmit { send(question) }
302 Button { send(question) } label: { Image(systemName: "arrow.up").font(.system(size: 14, weight: .bold)).frame(width: 32, height: 32) }
303 .foregroundStyle(palette.accentText).background(palette.accent, in: Circle()).disabled(busy).accessibilityLabel("Ask")
304 }
305 .padding(.leading, 16).padding(.trailing, 6).padding(.vertical, 6)
306 .background(palette.card, in: Capsule()).overlay { Capsule().strokeBorder(palette.line) }
307 .padding(.horizontal, 16).padding(.bottom, 10)
308 .background(palette.canvas)
309 }
310 .sheet(item: $editing) { entry in TransactionEditor(entry: entry).presentationDetents([.large]) }
311 .task {
312 #if DEBUG
313 if turns.isEmpty, let q = ProcessInfo.processInfo.environment["BUCKSLEY_TOUR_QUESTION"] { send(q) }
314 #endif
315 }
316 }
317
318 func linked(_ ids: [String]) -> [LedgerEntry] {
319 let byID = Dictionary(model.ledger.entries.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
320 return Array(ids.compactMap { byID[$0] }.prefix(8))
321 }
322
323 func send(_ text: String) {
324 let q = text.trimmingCharacters(in: .whitespacesAndNewlines)
325 guard !q.isEmpty, !busy else { return }
326 question = ""; turns.append((q, nil, nil, [])); busy = true
327 let i = turns.count - 1, ledger = model.ledger
328 Task {
329 do {
330 let answer = try await AskBucksley().ask(q, ledger: ledger, provider: .apple)
331 turns[i].a = answer.text; turns[i].p = answer.provider; turns[i].ids = answer.transactionIDs
332 SupportPrompt.recordCoreAction()
333 } catch { turns[i].a = error.localizedDescription }
334 busy = false
335 }
336 }
337}