Files
todos/App/Sources/View Models/TaskGroupListViewModel.swift
T

87 lines
3.3 KiB
Swift

import SwiftData
import SwiftUI
extension TaskGroupListView {
/// View model for managing the logic for the task group list view.
///
/// This observable class encapsulates the state and business logic for the task group list view.
/// It follows the MVVM pattern to separate presentation logic from the view layer.
///
/// ## Responsibilities
/// - Providing access to all task groups for iteration
/// - Efficiently counting tasks per group using SwiftData fetch descriptors
/// - Managing date calculations for group categorization
@Observable
final class ViewModel {
// MARK: Properties
/// The calendar used for date calculations.
///
/// This calendar is used to determine day boundaries for categorizing tasks into date groups: today, upcoming, overdue.
/// Defaults to the current calendar.
private let calendar: Calendar
// MARK: Initialization
/// Initializes a new view model instance.
///
/// - Parameter calendar: The calendar to use for date calculations. Defaults to `.current`.
init(calendar: Calendar = .current) {
self.calendar = calendar
}
// MARK: Computed
/// Returns all available task groups in an predetermined order.
///
/// This computed property provides access to all task group cases for iteration in the view.
///
/// - Returns: An array of all `TodoGroup` cases in a predetermined order.
var groups: [TodoGroup] {
TodoGroup.allCases
}
// MARK: Functions
/// Calculates the number of tasks for a given task group using SwiftData.
///
/// This method performs an efficient database-level count using SwiftData's `fetchCount` method with predicate-based filtering.
/// Tasks are categorized based on their due date and completion status.
///
/// - Parameters:
/// - group: The task group to count tasks for.
/// - modelContext: The SwiftData model context to query.
/// - Returns: The number of tasks in the specified group, or 0 if an error occurs.
func count(
for group: TodoGroup,
in modelContext: ModelContext
) -> Int {
let today = calendar.startOfDay(for: .now)
let tomorrow = calendar.date(byAdding: .day, value: 1, to: today) ?? .now
let fetchDescriptor: FetchDescriptor<Todo> =
switch group {
case .completed:
.init(predicate: #Predicate { $0.completed != nil })
case .overdue:
.init(predicate: #Predicate { $0.completed == nil && $0.due < today })
case .today:
.init(predicate: #Predicate { $0.completed == nil && $0.due >= today && $0.due < tomorrow })
case .upcoming:
.init(predicate: #Predicate { $0.completed == nil && $0.due >= tomorrow })
}
do {
return try modelContext.fetchCount(fetchDescriptor)
}
catch {
print("Error fetching count for group \(group): \(error)")
return 0
}
}
}
}