Files
FrenoCorp/Lendair/ViewModels/NotificationsViewModel.swift
Senior Engineer 57eb01f5af FRE-4738: Implement mark-as-read and mark-all-read actions
- Extract NotificationItem/NotificationType to Models/Notification.swift
- Create NotificationsServiceProtocol with testable service layer
- Implement markAsRead(id:) and markAllAsRead() with HTTP calls
- Add NotificationError enum with localized descriptions
- Update NotificationsViewModel to use protocol-based service
- Add 18 unit tests (12 ViewModel + 6 Model) with mock service
- Update README with architecture documentation
2026-05-03 12:17:15 -04:00

70 lines
2.0 KiB
Swift

import Foundation
import SwiftUI
@MainActor
class NotificationsViewModel: ObservableObject {
@Published var notifications: [NotificationItem] = []
@Published var isLoading: Bool = false
@Published var lastRefreshDate: Date?
@Published var error: NotificationError?
private let notificationsService: NotificationsServiceProtocol
init(notificationsService: NotificationsServiceProtocol = NotificationsService()) {
self.notificationsService = notificationsService
}
func fetchNotifications() async {
isLoading = true
error = nil
defer {
isLoading = false
lastRefreshDate = Date()
}
do {
let fetchedNotifications = try await notificationsService.list()
notifications = fetchedNotifications.sorted { $0.createdAt > $1.createdAt }
} catch let error as NotificationError {
self.error = error
} catch {
print("Failed to fetch notifications: \(error)")
}
}
func refresh() async {
await fetchNotifications()
}
func markAsRead(id: String) async {
guard let index = notifications.firstIndex(where: { $0.id == id }) else { return }
do {
try await notificationsService.markAsRead(id: id)
notifications[index].isRead = true
objectWillChange.send()
} catch {
print("Failed to mark notification as read: \(error)")
}
}
func markAllAsRead() async {
let unreadIds = notifications.filter { !$0.isRead }.map { $0.id }
guard !unreadIds.isEmpty else { return }
do {
try await notificationsService.markAllAsRead()
for index in notifications.indices {
notifications[index].isRead = true
}
objectWillChange.send()
} catch {
print("Failed to mark all as read: \(error)")
}
}
var unreadCount: Int {
notifications.filter { !$0.isRead }.count
}
}