Primera build enviada

This commit is contained in:
2026-01-19 14:40:43 +01:00
parent c6be398e5a
commit b03d35194f
36 changed files with 1641 additions and 561 deletions
@@ -2,11 +2,14 @@ import Foundation
import CoreData
import Combine
@MainActor
class GoalRepository: ObservableObject {
private let context: NSManagedObjectContext
@Published private(set) var goals: [Goal] = []
private var cancellables = Set<AnyCancellable>()
init(context: NSManagedObjectContext = CoreDataStack.shared.viewContext) {
self.context = context
fetchGoals()
@@ -14,47 +17,59 @@ class GoalRepository: ObservableObject {
}
private func setupNotificationObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(contextDidChange),
name: .NSManagedObjectContextObjectsDidChange,
object: context
)
}
@objc private func contextDidChange(_ notification: Notification) {
fetchGoals()
NotificationCenter.default.publisher(for: .NSManagedObjectContextObjectsDidChange, object: context)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.fetchGoals()
}
.store(in: &cancellables)
}
// MARK: - Fetch
func fetchGoals(for account: Account? = nil) {
context.perform { [weak self] in
guard let self else { return }
let request: NSFetchRequest<Goal> = Goal.fetchRequest()
if let account = account {
request.predicate = NSPredicate(format: "account == %@", account)
}
request.sortDescriptors = [
NSSortDescriptor(keyPath: \Goal.createdAt, ascending: true)
]
let request: NSFetchRequest<Goal> = Goal.fetchRequest()
if let account = account {
request.predicate = NSPredicate(format: "account == %@", account)
}
request.sortDescriptors = [
NSSortDescriptor(keyPath: \Goal.createdAt, ascending: true)
]
// Performance: Add batch size for fetches
request.fetchBatchSize = 50
do {
let fetched = try self.context.fetch(request)
DispatchQueue.main.async {
self.goals = fetched
}
} catch {
print("Failed to fetch goals: \(error)")
DispatchQueue.main.async {
self.goals = []
}
}
do {
goals = try context.fetch(request)
} catch {
print("Failed to fetch goals: \(error)")
goals = []
}
}
// MARK: - Create
/// Check if a goal with the given name already exists in the account (case-insensitive)
func goalExists(name: String, in account: Account?) -> Bool {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
let normalized = trimmed.lowercased()
return goals.contains { goal in
let nameMatches = goal.name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == normalized
let accountMatches = goal.account?.id == account?.id
return nameMatches && accountMatches
}
}
/// Find an existing goal by name (case-insensitive) within the same account
func findGoal(byName name: String, in account: Account?) -> Goal? {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
let normalized = trimmed.lowercased()
return goals.first { goal in
let nameMatches = goal.name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == normalized
let accountMatches = goal.account?.id == account?.id
return nameMatches && accountMatches
}
}
@discardableResult
func createGoal(
name: String,
@@ -62,8 +77,13 @@ class GoalRepository: ObservableObject {
targetDate: Date? = nil,
account: Account?
) -> Goal {
// Check if goal with same name already exists in this account
if let existing = findGoal(byName: name, in: account) {
return existing
}
let goal = Goal(context: context)
goal.name = name
goal.name = name.trimmingCharacters(in: .whitespacesAndNewlines)
goal.targetAmount = NSDecimalNumber(decimal: targetAmount)
goal.targetDate = targetDate
goal.account = account
@@ -109,7 +129,8 @@ class GoalRepository: ObservableObject {
guard context.hasChanges else { return }
do {
try context.save()
fetchGoals()
// Note: Removed redundant fetchGoals() call - the NotificationCenter observer
// in setupNotificationObserver() already handles refetching on context changes
} catch {
print("Failed to save goals: \(error)")
}