63 lines
1.8 KiB
Swift
63 lines
1.8 KiB
Swift
import Foundation
|
|
import CoreData
|
|
|
|
class TransactionRepository {
|
|
private let context: NSManagedObjectContext
|
|
|
|
init(context: NSManagedObjectContext = CoreDataStack.shared.viewContext) {
|
|
self.context = context
|
|
}
|
|
|
|
func fetchTransactions(for source: InvestmentSource) -> [Transaction] {
|
|
let request: NSFetchRequest<Transaction> = Transaction.fetchRequest()
|
|
request.predicate = NSPredicate(format: "source == %@", source)
|
|
request.sortDescriptors = [
|
|
NSSortDescriptor(keyPath: \Transaction.date, ascending: false)
|
|
]
|
|
return (try? context.fetch(request)) ?? []
|
|
}
|
|
|
|
@discardableResult
|
|
func createTransaction(
|
|
source: InvestmentSource,
|
|
type: TransactionType,
|
|
date: Date,
|
|
shares: Decimal?,
|
|
price: Decimal?,
|
|
amount: Decimal?,
|
|
notes: String?
|
|
) -> Transaction {
|
|
let transaction = Transaction(context: context)
|
|
transaction.source = source
|
|
transaction.type = type.rawValue
|
|
transaction.date = date
|
|
if let shares = shares {
|
|
transaction.shares = NSDecimalNumber(decimal: shares)
|
|
}
|
|
if let price = price {
|
|
transaction.price = NSDecimalNumber(decimal: price)
|
|
}
|
|
if let amount = amount {
|
|
transaction.amount = NSDecimalNumber(decimal: amount)
|
|
}
|
|
transaction.notes = notes
|
|
|
|
save()
|
|
return transaction
|
|
}
|
|
|
|
func deleteTransaction(_ transaction: Transaction) {
|
|
context.delete(transaction)
|
|
save()
|
|
}
|
|
|
|
private func save() {
|
|
guard context.hasChanges else { return }
|
|
do {
|
|
try context.save()
|
|
} catch {
|
|
print("Failed to save transaction: \(error)")
|
|
}
|
|
}
|
|
}
|