93 lines
3 KiB
Swift
93 lines
3 KiB
Swift
import Foundation
|
|
|
|
class AccountsStore: ObservableObject {
|
|
static let shared = AccountsStore()
|
|
|
|
@Published private(set) var accounts: [AccountModel] = []
|
|
@Published private(set) var defaultAccountId: String?
|
|
|
|
var totalBalance: Double {
|
|
accounts.reduce(0) { $0 + $1.balance }
|
|
}
|
|
|
|
var defaultAccount: AccountModel? {
|
|
accounts.first { $0.id == defaultAccountId }
|
|
}
|
|
|
|
private init() {
|
|
#if DEBUG
|
|
self.accounts = AccountModel.previewItems
|
|
if let firstAccount = accounts.first {
|
|
self.defaultAccountId = firstAccount.id
|
|
}
|
|
#endif
|
|
}
|
|
|
|
func addAccount(_ account: AccountModel) {
|
|
if account.isDefault {
|
|
defaultAccountId = account.id
|
|
// Remove default flag from other accounts
|
|
accounts = accounts.map { existingAccount in
|
|
existingAccount.with(isDefault: false)
|
|
}
|
|
} else if accounts.isEmpty {
|
|
// Make first account default
|
|
defaultAccountId = account.id
|
|
let newAccount = account.with(isDefault: true)
|
|
accounts.append(newAccount)
|
|
return
|
|
}
|
|
accounts.append(account)
|
|
objectWillChange.send()
|
|
}
|
|
|
|
func updateAccount(_ account: AccountModel) {
|
|
guard let index = accounts.firstIndex(where: { $0.id == account.id }) else { return }
|
|
|
|
if account.isDefault {
|
|
defaultAccountId = account.id
|
|
// Remove default flag from other accounts
|
|
accounts = accounts.map { existingAccount in
|
|
if existingAccount.id == account.id {
|
|
return account
|
|
}
|
|
return existingAccount.with(isDefault: false)
|
|
}
|
|
} else {
|
|
// If this was the default account, make sure we have a new default
|
|
if accounts[index].isDefault {
|
|
if let firstOtherAccount = accounts.first(where: { $0.id != account.id }) {
|
|
defaultAccountId = firstOtherAccount.id
|
|
updateAccount(firstOtherAccount.with(isDefault: true))
|
|
}
|
|
}
|
|
accounts[index] = account
|
|
}
|
|
objectWillChange.send()
|
|
}
|
|
|
|
func deleteAccount(_ account: AccountModel) {
|
|
accounts.removeAll { $0.id == account.id }
|
|
|
|
// If we deleted the default account, make another one default
|
|
if account.isDefault {
|
|
if let firstAccount = accounts.first {
|
|
defaultAccountId = firstAccount.id
|
|
updateAccount(firstAccount.with(isDefault: true))
|
|
} else {
|
|
defaultAccountId = nil
|
|
}
|
|
}
|
|
|
|
objectWillChange.send()
|
|
}
|
|
|
|
func setDefaultAccount(_ account: AccountModel) {
|
|
defaultAccountId = account.id
|
|
updateAccount(account.with(isDefault: true))
|
|
}
|
|
|
|
func getAccount(withId id: String) -> AccountModel? {
|
|
accounts.first { $0.id == id }
|
|
}
|
|
}
|