Files
AboTracker/AboTracker/views/HomeView.swift
2024-07-02 18:31:49 +02:00

109 lines
4.0 KiB
Swift

import SwiftUI
import SwiftData
struct HomeView: View {
@Environment(\.modelContext) private var modelContext
@Query var subs: [Subscription]
@State private var showAddSubscriptionSheet = false
var body: some View {
NavigationView {
VStack {
List {
ForEach(subs) { sub in
Section {
VStack(alignment: .leading, spacing: 8) {
Text(sub.name)
.font(.headline)
ForEach(sub.payments) { payment in
HStack {
Text("\(payment.amount, specifier: "%.2f")\(Currency.euro.description)")
Spacer()
Text("/\(payment.intervall.description)")
.foregroundColor(.gray)
}
.font(.subheadline)
}
}
.padding(.vertical, 8)
}
.listRowBackground(sub.getColorOrAccent().opacity(0.2))
.cornerRadius(8)
}
.onDelete(perform: deleteSubscription)
Section(header: Text("Totals")) {
HStack {
Text("Monthly Total")
Spacer()
Text("\(getMonthlyTotal(subs: subs), specifier: "%.2f")\(Currency.euro.description)")
.foregroundColor(.gray)
}
HStack {
Text("Remaining for Current Month")
Spacer()
Text("\(getRemainingForCurrentMonth(subs: subs), specifier: "%.2f")\(Currency.euro.description)")
.foregroundColor(.gray)
}
}
}
.navigationTitle("Subscriptions")
.toolbar {
#if os(iOS)
ToolbarItem(placement: .navigationBarLeading) {
EditButton()
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
showAddSubscriptionSheet.toggle()
}) {
Image(systemName: "plus")
}
}
#elseif os(macOS)
ToolbarItem(placement: .primaryAction) {
Button(action: {
showAddSubscriptionSheet.toggle()
}) {
Image(systemName: "plus")
}
}
#endif
}
.sheet(isPresented: $showAddSubscriptionSheet) {
AddSubscriptionView()
}
}
}
}
func deleteSubscription(at offsets: IndexSet) {
// ToDo: Add delete
// subs.remove(atOffsets: offsets)
}
func getMonthlyTotal(subs: [Subscription]) -> Float {
var monthlyTotal: Float = 0.0
for sub in subs {
monthlyTotal += sub.getMonthlyAmount()
}
return monthlyTotal
}
func getRemainingForCurrentMonth(subs: [Subscription]) -> Float {
var remainingTotal: Float = 0.0
for sub in subs {
remainingTotal += sub.getRemainingForCurrentMonth()
}
return remainingTotal
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
.modelContainer(for: [Subscription.self, Payment.self])
}
}