twigs-ios/Twigs/Category/CategoryDetailsView.swift

98 lines
3 KiB
Swift
Raw Normal View History

2021-10-21 22:13:32 +00:00
//
// CategoryDetailsView.swift
// Twigs
//
// Created by William Brawner on 10/19/21.
// Copyright © 2021 William Brawner. All rights reserved.
//
import SwiftUI
2022-01-03 17:56:43 +00:00
import TwigsCore
2021-10-21 22:13:32 +00:00
struct CategoryDetailsView: View {
@EnvironmentObject var dataStore: DataStore
2023-03-05 04:56:15 +00:00
@ObservedObject var categoryDataStore: CategoryDataStore
@EnvironmentObject var apiService: TwigsApiService
2021-10-21 22:13:32 +00:00
let budget: Budget
2022-01-03 17:56:43 +00:00
@State var sum: Int? = 0
2021-10-21 22:13:32 +00:00
var spent: Int {
get {
if case let .success(sum) = categoryDataStore.sum {
2022-01-03 17:56:43 +00:00
return abs(sum)
2021-10-21 22:13:32 +00:00
} else {
return 0
}
}
}
func middleLabel(_ category: TwigsCore.Category) -> LocalizedStringKey {
if category.expense {
return LocalizedStringKey("amount_spent")
} else {
return LocalizedStringKey("amount_earned")
2021-10-21 22:13:32 +00:00
}
}
2021-10-21 22:13:32 +00:00
var body: some View {
if let category = dataStore.selectedCategory {
TransactionListView() {
VStack {
Text(verbatim: category.description ?? "")
.padding()
HStack {
LabeledCounter(title: LocalizedStringKey("amount_budgeted"), amount: category.amount)
LabeledCounter(title: middleLabel(category), amount: spent)
LabeledCounter(title: LocalizedStringKey("amount_remaining"), amount: category.amount - spent)
}
}.frame(maxWidth: .infinity, alignment: .center)
}.task {
await categoryDataStore.sum(categoryId: category.id)
2021-10-21 22:13:32 +00:00
}
2023-03-05 04:56:15 +00:00
.toolbar {
ToolbarItem(placement: .navigationBarTrailing, content: {
Button(action: {
Task {
await dataStore.edit(category)
}
}) {
Text("edit")
}
})
}
2022-05-18 03:40:08 +00:00
.sheet(isPresented: self.$dataStore.editingCategory, onDismiss: {
self.dataStore.cancelEditCategory()
}, content: {
CategoryFormSheet(categoryForm: CategoryForm(
category: category,
dataStore: dataStore,
budgetId: category.budgetId
))
})
}
2021-10-21 22:13:32 +00:00
}
2023-03-05 04:56:15 +00:00
init (_ budget: Budget, categoryDataStore: CategoryDataStore) {
2021-10-21 22:13:32 +00:00
self.budget = budget
2023-03-05 04:56:15 +00:00
self.categoryDataStore = categoryDataStore
2021-10-21 22:13:32 +00:00
}
}
struct LabeledCounter: View {
let title: LocalizedStringKey
let amount: Int
var body: some View {
VStack {
Text(title)
Text(verbatim: amount.toCurrencyString())
}
}
}
#if DEBUG
struct CategoryDetailsView_Previews: PreviewProvider {
static var previews: some View {
2023-03-05 04:56:15 +00:00
CategoryDetailsView(MockBudgetRepository.budget, categoryDataStore: CategoryDataStore(TwigsInMemoryCacheService()))
.environmentObject(TwigsInMemoryCacheService())
2021-10-21 22:13:32 +00:00
}
}
#endif