InvestmentTrackerApp/PortfolioJournal/Views/Accounts/AccountsView.swift

106 lines
4.0 KiB
Swift

import SwiftUI
struct AccountsView: View {
@EnvironmentObject private var iapService: IAPService
@EnvironmentObject private var accountStore: AccountStore
@StateObject private var accountRepository = AccountRepository()
@State private var showingAddAccount = false
@State private var selectedAccount: Account?
@State private var showingPaywall = false
@State private var accountToDelete: Account?
var body: some View {
ZStack {
AppBackground()
List {
Section {
ForEach(accountRepository.accounts) { account in
Button {
selectedAccount = account
} label: {
HStack {
VStack(alignment: .leading) {
Text(account.name)
.font(.headline)
Text(account.currencyCode ?? AppSettings.getOrCreate(in: CoreDataStack.shared.viewContext).currency)
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
if accountStore.selectedAccount?.id == account.id && !accountStore.showAllAccounts {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.appPrimary)
}
}
}
.swipeActions(edge: .trailing) {
Button(role: .destructive) {
accountToDelete = account
} label: {
Label("Delete", systemImage: "trash")
}
}
}
} header: {
Text("Accounts")
} footer: {
Text(iapService.isPremium ? "Create multiple accounts for business, family, or goals." : "Free users can create one account.")
}
}
.scrollContentBackground(.hidden)
}
.navigationTitle("Accounts")
.confirmationDialog(
"Delete Account",
isPresented: Binding(
get: { accountToDelete != nil },
set: { if !$0 { accountToDelete = nil } }
),
titleVisibility: .visible
) {
Button("Delete", role: .destructive) {
guard let accountToDelete else { return }
if accountStore.selectedAccount?.id == accountToDelete.id {
accountStore.selectAllAccounts()
}
accountRepository.deleteAccount(accountToDelete)
self.accountToDelete = nil
}
} message: {
Text("This will remove the account and unlink its sources.")
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
if accountStore.canAddAccount() {
showingAddAccount = true
} else {
showingPaywall = true
}
} label: {
Image(systemName: "plus")
}
}
}
.sheet(isPresented: $showingAddAccount) {
AccountEditorView(account: nil)
}
.sheet(isPresented: $showingPaywall) {
PaywallView()
}
.sheet(item: $selectedAccount) { account in
AccountEditorView(account: account)
}
.onAppear {
accountRepository.fetchAccounts()
}
}
}
#Preview {
AccountsView()
.environmentObject(IAPService())
.environmentObject(AccountStore(iapService: IAPService()))
}