diff --git a/Levain/Features/Shared/RootTabView.swift b/Levain/Features/Shared/RootTabView.swift index 05c46bf..3051dc8 100644 --- a/Levain/Features/Shared/RootTabView.swift +++ b/Levain/Features/Shared/RootTabView.swift @@ -2,6 +2,7 @@ import SwiftData import SwiftUI struct RootTabView: View { + @Environment(\.scenePhase) private var scenePhase @Environment(\.modelContext) private var modelContext @EnvironmentObject private var environment: AppEnvironment @EnvironmentObject private var router: AppRouter @@ -50,6 +51,19 @@ struct RootTabView: View { .onOpenURL { url in router.open(url: url, modelContext: modelContext) } + .onChange(of: scenePhase) { _, newPhase in + guard newPhase == .active, didBootstrap else { return } + guard ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] != "1" else { return } + guard AppLaunchOptions.shouldSuppressNotifications == false else { return } + + let appSettings = loadOrCreateAppSettings() + let notificationService = environment.prepareNotificationServiceIfNeeded() + syncNotificationsForLifecycle( + notificationService: notificationService, + appSettings: appSettings, + showDisabledBanner: false + ) + } } // MARK: - Tab content + aligned bottom bar @@ -145,7 +159,11 @@ struct RootTabView: View { guard AppLaunchOptions.shouldSuppressNotifications == false else { return } - scheduleNotificationBootstrap(notificationService: notificationService, appSettings: appSettings) + syncNotificationsForLifecycle( + notificationService: notificationService, + appSettings: appSettings, + showDisabledBanner: true + ) } @MainActor @@ -160,14 +178,11 @@ struct RootTabView: View { } @MainActor - private func scheduleNotificationBootstrap( + private func syncNotificationsForLifecycle( notificationService: NotificationService, - appSettings: AppSettings + appSettings: AppSettings, + showDisabledBanner: Bool ) { - let needsLaunchSync = appSettings.lastNotificationSync == nil - let needsAuthorizationPrompt = appSettings.hasRequestedNotificationPermission == false - guard needsLaunchSync || needsAuthorizationPrompt else { return } - Task(priority: .utility) { let authorizationState = await notificationService.requestAuthorizationIfNeeded(settings: appSettings) if authorizationState == .authorized { @@ -176,11 +191,11 @@ struct RootTabView: View { try? modelContext.save() } if authorizationState == .denied { - if appSettings.lastNotificationSync == nil { - appSettings.lastNotificationSync = .now - try? modelContext.save() + appSettings.lastNotificationSync = .now + try? modelContext.save() + if showDisabledBanner { + router.showNotificationsDisabledBanner() } - router.showNotificationsDisabledBanner() } } } diff --git a/Levain/Services/BakeReminderPlanner.swift b/Levain/Services/BakeReminderPlanner.swift index 7e5910f..0faa913 100644 --- a/Levain/Services/BakeReminderPlanner.swift +++ b/Levain/Services/BakeReminderPlanner.swift @@ -15,6 +15,9 @@ enum BakeReminderPlanner { } var reminders: [BakeReminder] = [] + if let activeStep = bake.activeStep, activeStep.isOverdue(now: now) { + reminders.append(contentsOf: overdueReminders(for: bake, step: activeStep, now: now)) + } for step in bake.sortedSteps where step.isTerminal == false { if step.isWindowBased, step.status == .running { @@ -39,9 +42,10 @@ enum BakeReminderPlanner { return reminders } - static func identifiers(for bake: Bake) -> [String] { + static func identifiers(for bake: Bake, now: Date = .now) -> [String] { bake.steps.flatMap { step in - ReminderPhase.allCases.map { identifier(for: bake, step: step, phase: $0) } + ReminderPhase.allCases.map { identifier(for: bake, step: step, phase: $0) } + + RollingOverdueReminderPlanner.identifierDates(now: now).map { overdueIdentifier(for: bake, step: step, on: $0) } } } @@ -75,6 +79,18 @@ enum BakeReminderPlanner { return reminders } + private static func overdueReminders(for bake: Bake, step: BakeStep, now: Date) -> [BakeReminder] { + RollingOverdueReminderPlanner.reminderDates(overdueSince: step.windowEnd, now: now).map { fireDate in + BakeReminder( + identifier: overdueIdentifier(for: bake, step: step, on: fireDate), + title: "\(step.displayName) · \(bake.name)", + body: "Non hai ancora completato \(step.displayName) di \(bake.name).", + route: AppRouter.DeepLink.bake(id: bake.id, stepID: step.id), + fireDate: fireDate + ) + } + } + private enum ReminderPhase: String, CaseIterable { case start case windowClose @@ -83,4 +99,8 @@ enum BakeReminderPlanner { private static func identifier(for bake: Bake, step: BakeStep, phase: ReminderPhase) -> String { "bake-\(phase.rawValue)-\(bake.id.uuidString)-\(step.id.uuidString)" } + + private static func overdueIdentifier(for bake: Bake, step: BakeStep, on fireDate: Date) -> String { + "bake-overdue-\(bake.id.uuidString)-\(step.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: fireDate))" + } } diff --git a/Levain/Services/KefirReminderPlanner.swift b/Levain/Services/KefirReminderPlanner.swift index 186b4a4..9528d9a 100644 --- a/Levain/Services/KefirReminderPlanner.swift +++ b/Levain/Services/KefirReminderPlanner.swift @@ -45,11 +45,24 @@ enum KefirReminderPlanner { ) } + reminders.append(contentsOf: + RollingOverdueReminderPlanner.reminderDates(overdueSince: dueAt, now: now).map { fireDate in + KefirReminderRequest( + identifier: overdueIdentifier(for: batch, on: fireDate), + fireDate: fireDate, + title: batch.name, + body: overdueBody(for: batch), + route: route + ) + } + ) + return reminders } - static func identifiers(for batch: KefirBatch) -> [String] { - Phase.allCases.map { identifier(for: batch, phase: $0) } + static func identifiers(for batch: KefirBatch, now: Date = .now) -> [String] { + Phase.allCases.map { identifier(for: batch, phase: $0) } + + RollingOverdueReminderPlanner.identifierDates(now: now).map { overdueIdentifier(for: batch, on: $0) } } private static func identifier(for batch: KefirBatch, phase: Phase) -> String { @@ -77,4 +90,19 @@ enum KefirReminderPlanner { return "È il momento di riattivare il batch." } } + + private static func overdueBody(for batch: KefirBatch) -> String { + switch batch.storageMode { + case .roomTemperature: + return "Non hai ancora rinnovato \(batch.name)." + case .fridge: + return "Non hai ancora controllato \(batch.name)." + case .freezer: + return "Non hai ancora riattivato \(batch.name)." + } + } + + private static func overdueIdentifier(for batch: KefirBatch, on fireDate: Date) -> String { + "kefir-overdue-\(batch.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: fireDate))" + } } diff --git a/Levain/Services/NotificationService.swift b/Levain/Services/NotificationService.swift index 121c7d1..c9bf6d7 100644 --- a/Levain/Services/NotificationService.swift +++ b/Levain/Services/NotificationService.swift @@ -2,7 +2,7 @@ import Foundation import SwiftData import UserNotifications -private struct NotificationRequestPayload: Sendable { +struct NotificationRequestPayload: Sendable, Equatable { let identifier: String let title: String let body: String @@ -10,11 +10,162 @@ private struct NotificationRequestPayload: Sendable { let fireDate: Date } -private struct NotificationSyncPlan: Sendable { +struct NotificationSyncPlan: Sendable, Equatable { let identifiersToRemove: [String] let requests: [NotificationRequestPayload] } +enum NotificationPlanningDefaults { + static let overdueReminderHour = 19 + static let overdueReminderMinute = 0 + static let overdueWindowDays = 7 + static let maxPendingRequests = 60 +} + +enum RollingOverdueReminderPlanner { + static func reminderDates( + overdueSince: Date, + now: Date = .now, + windowDays: Int = NotificationPlanningDefaults.overdueWindowDays + ) -> [Date] { + guard windowDays > 0 else { return [] } + + let windowDates = identifierDates(now: now, windowDays: windowDays) + guard let windowEnd = windowDates.last else { return [] } + + let firstEligibleDate = max(firstReminderDate(after: overdueSince), firstReminderDate(after: now)) + guard firstEligibleDate <= windowEnd else { return [] } + + return windowDates.filter { $0 >= firstEligibleDate } + } + + static func identifierDates( + now: Date = .now, + windowDays: Int = NotificationPlanningDefaults.overdueWindowDays + ) -> [Date] { + guard windowDays > 0 else { return [] } + + let firstFutureReminder = firstReminderDate(after: now) + return (0.. String { + let components = Calendar.current.dateComponents([.year, .month, .day], from: date) + let year = components.year ?? 0 + let month = components.month ?? 0 + let day = components.day ?? 0 + return String(format: "%04d%02d%02d", year, month, day) + } + + private static func firstReminderDate(after reference: Date) -> Date { + let sameDayReminder = reference.settingTime( + hour: NotificationPlanningDefaults.overdueReminderHour, + minute: NotificationPlanningDefaults.overdueReminderMinute + ) + + if sameDayReminder > reference { + return sameDayReminder + } + + let nextDay = Calendar.current.date(byAdding: .day, value: 1, to: reference.startOfDay) ?? reference + return nextDay.settingTime( + hour: NotificationPlanningDefaults.overdueReminderHour, + minute: NotificationPlanningDefaults.overdueReminderMinute + ) + } +} + +enum NotificationPlanBuilder { + static func buildGlobalPlan( + bakes: [Bake], + starters: [Starter], + kefirBatches: [KefirBatch], + now: Date = .now + ) -> NotificationSyncPlan { + let plans = + bakes.map { makePlan(for: $0, now: now) } + + starters.map { makePlan(for: $0, now: now) } + + kefirBatches.map { makePlan(for: $0, now: now) } + + return merge(plans: plans, now: now) + } + + static func merge(plans: [NotificationSyncPlan], now: Date = .now) -> NotificationSyncPlan { + let identifiersToRemove = Array(Set(plans.flatMap(\.identifiersToRemove))).sorted() + + let sortedRequests = plans + .flatMap(\.requests) + .filter { $0.fireDate > now } + .sorted { + if $0.fireDate == $1.fireDate { + return $0.identifier < $1.identifier + } + return $0.fireDate < $1.fireDate + } + + var seenIdentifiers = Set() + var requests: [NotificationRequestPayload] = [] + requests.reserveCapacity(min(sortedRequests.count, NotificationPlanningDefaults.maxPendingRequests)) + + for request in sortedRequests where requests.count < NotificationPlanningDefaults.maxPendingRequests { + guard seenIdentifiers.insert(request.identifier).inserted else { continue } + requests.append(request) + } + + return NotificationSyncPlan( + identifiersToRemove: identifiersToRemove, + requests: requests + ) + } + + private static func makePlan(for bake: Bake, now: Date) -> NotificationSyncPlan { + NotificationSyncPlan( + identifiersToRemove: BakeReminderPlanner.identifiers(for: bake, now: now), + requests: BakeReminderPlanner.planReminders(for: bake, now: now).map { reminder in + NotificationRequestPayload( + identifier: reminder.identifier, + title: reminder.title, + body: reminder.body, + route: reminder.route, + fireDate: reminder.fireDate + ) + } + ) + } + + private static func makePlan(for starter: Starter, now: Date) -> NotificationSyncPlan { + NotificationSyncPlan( + identifiersToRemove: StarterReminderPlanner.identifiers(for: starter, now: now), + requests: StarterReminderPlanner.planReminders(for: starter, now: now).map { reminder in + NotificationRequestPayload( + identifier: reminder.identifier, + title: reminder.title, + body: reminder.body, + route: reminder.route, + fireDate: reminder.fireDate + ) + } + ) + } + + private static func makePlan(for batch: KefirBatch, now: Date) -> NotificationSyncPlan { + NotificationSyncPlan( + identifiersToRemove: KefirReminderPlanner.identifiers(for: batch, now: now), + requests: KefirReminderPlanner.planReminders(for: batch, now: now).map { reminder in + NotificationRequestPayload( + identifier: reminder.identifier, + title: reminder.title, + body: reminder.body, + route: reminder.route, + fireDate: reminder.fireDate + ) + } + ) + } +} + private enum NotificationScheduler { @MainActor static func apply(_ plans: [NotificationSyncPlan]) async { @@ -116,29 +267,24 @@ final class NotificationService: NSObject, ObservableObject, UNUserNotificationC let starters = (try? modelContext.fetch(FetchDescriptor())) ?? [] let kefirBatches = (try? modelContext.fetch(FetchDescriptor())) ?? [] - let plans = - bakes.map { makeSyncPlan(for: $0) } + - starters.map { makeSyncPlan(for: $0) } + - kefirBatches.map { makeSyncPlan(for: $0) } - await NotificationScheduler.apply(plans) + let plan = NotificationPlanBuilder.buildGlobalPlan( + bakes: bakes, + starters: starters, + kefirBatches: kefirBatches + ) + await NotificationScheduler.apply([plan]) } - func syncNotifications(forBake bakeID: UUID, in context: ModelContext) async { - let descriptor = FetchDescriptor(predicate: #Predicate { $0.id == bakeID }) - guard let bake = (try? context.fetch(descriptor))?.first else { return } - await NotificationScheduler.apply([makeSyncPlan(for: bake)]) + func syncNotifications(forBake _: UUID, in context: ModelContext) async { + await resyncAll(using: context) } - func syncNotifications(forStarter starterID: UUID, in context: ModelContext) async { - let descriptor = FetchDescriptor(predicate: #Predicate { $0.id == starterID }) - guard let starter = (try? context.fetch(descriptor))?.first else { return } - await NotificationScheduler.apply([makeSyncPlan(for: starter)]) + func syncNotifications(forStarter _: UUID, in context: ModelContext) async { + await resyncAll(using: context) } - func syncNotifications(forKefirBatch batchID: UUID, in context: ModelContext) async { - let descriptor = FetchDescriptor(predicate: #Predicate { $0.id == batchID }) - guard let batch = (try? context.fetch(descriptor))?.first else { return } - await NotificationScheduler.apply([makeSyncPlan(for: batch)]) + func syncNotifications(forKefirBatch _: UUID, in context: ModelContext) async { + await resyncAll(using: context) } nonisolated func userNotificationCenter( @@ -187,56 +333,9 @@ final class NotificationService: NSObject, ObservableObject, UNUserNotificationC } private func fridgeReminderIdentifier(_ id: UUID) -> String { "refresh-fridge-\(id.uuidString)" } - private func dueIdentifier(_ id: UUID) -> String { "starter-due-\(id.uuidString)" } - private func followUpIdentifier(_ id: UUID) -> String { "starter-followup-\(id.uuidString)" } func fridgeReminderRoute(for refresh: StarterRefresh) -> String? { guard let starterID = refresh.starter?.id else { return nil } return AppRouter.DeepLink.starter(id: starterID) } - - private func makeSyncPlan(for bake: Bake) -> NotificationSyncPlan { - NotificationSyncPlan( - identifiersToRemove: BakeReminderPlanner.identifiers(for: bake), - requests: BakeReminderPlanner.planReminders(for: bake).map { reminder in - NotificationRequestPayload( - identifier: reminder.identifier, - title: reminder.title, - body: reminder.body, - route: reminder.route, - fireDate: reminder.fireDate - ) - } - ) - } - - private func makeSyncPlan(for starter: Starter) -> NotificationSyncPlan { - NotificationSyncPlan( - identifiersToRemove: [dueIdentifier(starter.id), followUpIdentifier(starter.id)], - requests: StarterReminderPlanner.planReminders(for: starter).map { reminder in - NotificationRequestPayload( - identifier: reminder.identifier, - title: reminder.title, - body: reminder.body, - route: reminder.route, - fireDate: reminder.fireDate - ) - } - ) - } - - private func makeSyncPlan(for batch: KefirBatch) -> NotificationSyncPlan { - NotificationSyncPlan( - identifiersToRemove: KefirReminderPlanner.identifiers(for: batch), - requests: KefirReminderPlanner.planReminders(for: batch).map { reminder in - NotificationRequestPayload( - identifier: reminder.identifier, - title: reminder.title, - body: reminder.body, - route: reminder.route, - fireDate: reminder.fireDate - ) - } - ) - } } diff --git a/Levain/Services/StarterReminderPlanner.swift b/Levain/Services/StarterReminderPlanner.swift index 9660b3a..12557bb 100644 --- a/Levain/Services/StarterReminderPlanner.swift +++ b/Levain/Services/StarterReminderPlanner.swift @@ -9,30 +9,57 @@ struct StarterReminderRequest: Equatable { } enum StarterReminderPlanner { - static func planReminders(for starter: Starter) -> [StarterReminderRequest] { - guard starter.remindersEnabled else { return [] } + static func planReminders(for starter: Starter, now: Date = .now) -> [StarterReminderRequest] { + guard starter.remindersEnabled, starter.isArchived == false else { return [] } let due = starter.nextDueDate.settingTime(hour: 9, minute: 0) - let followUp = due.adding(minutes: 24 * 60) - let route = AppRouter.DeepLink.starter(id: starter.id) + let overdueSince = (Calendar.current.date(byAdding: .day, value: 1, to: starter.nextDueDate.startOfDay) ?? starter.nextDueDate) + .startOfDay - let dueRequest = StarterReminderRequest( - identifier: "starter-due-\(starter.id.uuidString)", - fireDate: due, - title: starter.name, - body: "Oggi è previsto un rinfresco. Apri lo starter per registrarlo.", - route: route - ) + var reminders: [StarterReminderRequest] = [] + + if due > now { + reminders.append( + StarterReminderRequest( + identifier: dueIdentifier(for: starter), + fireDate: due, + title: starter.name, + body: "Oggi è previsto un rinfresco. Apri lo starter per registrarlo.", + route: route + ) + ) + } - let followUpRequest = StarterReminderRequest( - identifier: "starter-followup-\(starter.id.uuidString)", - fireDate: followUp, - title: starter.name, - body: "Non hai ancora registrato il rinfresco di oggi. Apri lo starter per farlo adesso.", - route: route + reminders.append(contentsOf: + RollingOverdueReminderPlanner.reminderDates(overdueSince: overdueSince, now: now).map { fireDate in + StarterReminderRequest( + identifier: overdueIdentifier(for: starter, on: fireDate), + fireDate: fireDate, + title: starter.name, + body: "Non hai ancora rinfrescato \(starter.name).", + route: route + ) + } ) - return [dueRequest, followUpRequest] + return reminders + } + + static func identifiers(for starter: Starter, now: Date = .now) -> [String] { + [dueIdentifier(for: starter), legacyFollowUpIdentifier(for: starter)] + + RollingOverdueReminderPlanner.identifierDates(now: now).map { overdueIdentifier(for: starter, on: $0) } + } + + private static func dueIdentifier(for starter: Starter) -> String { + "starter-due-\(starter.id.uuidString)" + } + + private static func legacyFollowUpIdentifier(for starter: Starter) -> String { + "starter-followup-\(starter.id.uuidString)" + } + + private static func overdueIdentifier(for starter: Starter, on fireDate: Date) -> String { + "starter-overdue-\(starter.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: fireDate))" } } diff --git a/LevainTests/BakeReminderPlannerTests.swift b/LevainTests/BakeReminderPlannerTests.swift index b028df1..0466160 100644 --- a/LevainTests/BakeReminderPlannerTests.swift +++ b/LevainTests/BakeReminderPlannerTests.swift @@ -58,7 +58,7 @@ struct BakeReminderPlannerTests { if let reminder = reminders.first { #expect(reminder.title == "Shape · My Bread") - #expect(reminder.body == "È il momento di intervenire su questo passaggio. Apri l'impasto per continuare.") + #expect(reminder.body == "È il momento della prossima fase.") #expect(reminder.route == "levain://bake/\(bake.id.uuidString)?step=\(pendingStep.id.uuidString)") #expect(reminder.fireDate == now.addingTimeInterval(2700)) #expect(reminder.identifier == "bake-start-\(bake.id.uuidString)-\(pendingStep.id.uuidString)") @@ -86,7 +86,62 @@ struct BakeReminderPlannerTests { let reminders = BakeReminderPlanner.planReminders(for: bake, now: now) #expect(reminders.count == 2) - #expect(reminders[0].body == "Il tuo impasto è pronto per il prossimo passaggio. Aprilo per continuare.") - #expect(reminders[1].body == "La finestra utile sta per chiudersi. Apri l'impasto se devi intervenire ora.") + #expect(reminders[0].body == "Il tuo impasto è pronto per la fase successiva. Aprilo per continuare.") + #expect(reminders[1].body == "È il momento di completare questa fase.") + } + + @Test("Overdue reminders are generated only for the active overdue step") + func testActiveOverdueStepGeneratesDailyReminders() { + let now = Date.fixedNow.startOfDay.settingTime(hour: 10, minute: 0) + let bake = DomainFixtures.makeBake(name: "Pane in ritardo", target: now.addingTimeInterval(3600 * 24)) + + let activeOverdueStep = BakeStep( + orderIndex: 0, + type: .bulk, + nameOverride: "Puntata", + plannedStart: now.adding(minutes: -(26 * 60)), + plannedDurationMinutes: 60 + ) + activeOverdueStep.status = .running + activeOverdueStep.bake = bake + + let laterStep = BakeStep( + orderIndex: 1, + type: .shape, + nameOverride: "Formatura", + plannedStart: now.adding(minutes: 180), + plannedDurationMinutes: 30 + ) + laterStep.status = .pending + laterStep.bake = bake + bake.steps = [activeOverdueStep, laterStep] + + let reminders = BakeReminderPlanner.planReminders(for: bake, now: now) + + #expect(reminders.count == NotificationPlanningDefaults.overdueWindowDays + 1) + #expect(reminders.contains { $0.identifier == "bake-start-\(bake.id.uuidString)-\(laterStep.id.uuidString)" }) + let overdue = reminders.filter { $0.identifier.contains("bake-overdue-\(bake.id.uuidString)-") } + #expect(overdue.count == NotificationPlanningDefaults.overdueWindowDays) + #expect(overdue.allSatisfy { $0.identifier.contains(activeOverdueStep.id.uuidString) }) + #expect(overdue.first?.identifier == "bake-overdue-\(bake.id.uuidString)-\(activeOverdueStep.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: now.settingTime(hour: 19, minute: 0)))") + #expect(overdue.first?.body == "Non hai ancora completato Puntata di Pane in ritardo.") + #expect(overdue.first?.fireDate == now.settingTime(hour: 19, minute: 0)) + } + + @Test("Identifier cleanup covers overdue slots for every step in the rolling window") + func testIdentifiersIncludeOverdueWindowForAllSteps() { + let now = Date.fixedNow.startOfDay.settingTime(hour: 10, minute: 0) + let bake = DomainFixtures.makeBake(name: "Batch cleanup", target: now.addingTimeInterval(3600 * 24)) + bake.steps = [ + BakeStep(orderIndex: 0, type: .mix, nameOverride: "Mix", plannedStart: now.adding(minutes: -180), plannedDurationMinutes: 30, bake: bake), + BakeStep(orderIndex: 1, type: .bulk, nameOverride: "Bulk", plannedStart: now.adding(minutes: 120), plannedDurationMinutes: 30, bake: bake) + ] + + let identifiers = BakeReminderPlanner.identifiers(for: bake, now: now) + + #expect( + identifiers.filter { $0.contains("bake-overdue-\(bake.id.uuidString)-") }.count == + bake.steps.count * NotificationPlanningDefaults.overdueWindowDays + ) } } diff --git a/LevainTests/KefirReminderPlannerTests.swift b/LevainTests/KefirReminderPlannerTests.swift index cf14a5f..939192a 100644 --- a/LevainTests/KefirReminderPlannerTests.swift +++ b/LevainTests/KefirReminderPlannerTests.swift @@ -6,7 +6,7 @@ import Testing struct KefirReminderPlannerTests { @Test("Room-temperature batch schedules warning and due reminders on the daily cadence") func testRoomTemperatureReminderPlan() { - let now = Date.fixedNow + let now = Date.fixedNow.startOfDay.settingTime(hour: 8, minute: 0) let batch = DomainFixtures.makeKefirBatch( name: "Batch cucina", storageMode: .roomTemperature, @@ -15,17 +15,20 @@ struct KefirReminderPlannerTests { let reminders = KefirReminderPlanner.planReminders(for: batch, now: now) - #expect(reminders.count == 2) + #expect(reminders.count == 8) #expect(reminders[0].fireDate == now.addingTimeInterval(20 * 60 * 60)) #expect(reminders[1].fireDate == now.addingTimeInterval(24 * 60 * 60)) - #expect(reminders[0].body == "Tra poco entra nella finestra di rinnovo.") + #expect(reminders[0].body == "Tra poco sarà il momento di rinnovare il batch.") #expect(reminders[1].body == "È il momento di rinnovare il batch.") #expect(reminders[0].route == AppRouter.DeepLink.kefirBatch(id: batch.id)) + #expect(reminders[2].identifier == "kefir-overdue-\(batch.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: now.startOfDay.adding(minutes: 24 * 60).settingTime(hour: 19, minute: 0)))") + #expect(reminders[2].body == "Non hai ancora rinnovato \(batch.name).") + #expect(reminders[2].fireDate == now.startOfDay.adding(minutes: 24 * 60).settingTime(hour: 19, minute: 0)) } @Test("Fridge batch schedules next-day warning and due reminders on the weekly cadence") func testFridgeReminderPlan() { - let now = Date.fixedNow + let now = Date.fixedNow.startOfDay.settingTime(hour: 8, minute: 0) let batch = DomainFixtures.makeKefirBatch( name: "Backup frigo", storageMode: .fridge, @@ -37,7 +40,7 @@ struct KefirReminderPlannerTests { #expect(reminders.count == 2) #expect(reminders[0].fireDate == now.addingTimeInterval(6 * 24 * 60 * 60)) #expect(reminders[1].fireDate == now.addingTimeInterval(7 * 24 * 60 * 60)) - #expect(reminders[0].body == "Domani conviene controllare il batch in frigo.") + #expect(reminders[0].body == "Domani dovrai controllare il batch in frigo.") #expect(reminders[1].body == "È il momento di controllare il batch in frigo.") } @@ -56,7 +59,7 @@ struct KefirReminderPlannerTests { @Test("Planned freezer reactivation schedules warning and due reminders") func testPlannedFreezerReactivationReminderPlan() { - let now = Date.fixedNow + let now = Date.fixedNow.startOfDay.settingTime(hour: 8, minute: 0) let dueAt = now.addingTimeInterval(5 * 24 * 60 * 60) let batch = DomainFixtures.makeKefirBatch( name: "Scorta freezer", @@ -67,16 +70,18 @@ struct KefirReminderPlannerTests { let reminders = KefirReminderPlanner.planReminders(for: batch, now: now) - #expect(reminders.count == 2) + #expect(reminders.count == 4) #expect(reminders[0].fireDate == dueAt.addingTimeInterval(-(24 * 60 * 60))) #expect(reminders[1].fireDate == dueAt) - #expect(reminders[0].body == "La riattivazione pianificata si avvicina.") + #expect(reminders[0].body == "Tra poco sarà il momento di riattivare il batch.") #expect(reminders[1].body == "È il momento di riattivare il batch.") + #expect(reminders[2].body == "Non hai ancora riattivato \(batch.name).") + #expect(reminders[2].fireDate == dueAt.settingTime(hour: 19, minute: 0)) } @Test("Archived or alerts-disabled batches do not schedule reminders") func testArchivedOrAlertsDisabledBatchesReturnNoReminders() { - let now = Date.fixedNow + let now = Date.fixedNow.startOfDay.settingTime(hour: 8, minute: 0) let archived = DomainFixtures.makeKefirBatch( storageMode: .roomTemperature, lastManagedAt: now, @@ -90,6 +95,6 @@ struct KefirReminderPlannerTests { #expect(KefirReminderPlanner.planReminders(for: archived, now: now).isEmpty) #expect(KefirReminderPlanner.planReminders(for: silenced, now: now).isEmpty) - #expect(KefirReminderPlanner.identifiers(for: silenced).count == 2) + #expect(KefirReminderPlanner.identifiers(for: silenced, now: now).count == 2 + NotificationPlanningDefaults.overdueWindowDays) } } diff --git a/LevainTests/StarterReminderPlannerTests.swift b/LevainTests/StarterReminderPlannerTests.swift index 2f931c7..7049451 100644 --- a/LevainTests/StarterReminderPlannerTests.swift +++ b/LevainTests/StarterReminderPlannerTests.swift @@ -6,32 +6,125 @@ final class StarterReminderPlannerTests: XCTestCase { let starter = DomainFixtures.makeStarter() starter.remindersEnabled = false - let requests = StarterReminderPlanner.planReminders(for: starter) + let requests = StarterReminderPlanner.planReminders(for: starter, now: .fixedNow) XCTAssertTrue(requests.isEmpty) } - func testRemindersEnabledReturnsDueAndFollowUp() { - let today = Date.fixedNow + func testDueReminderStaysAtNineAndOverdueSeriesStartsTheDayAfter() { + let now = Date.fixedNow.startOfDay.settingTime(hour: 8, minute: 0) let starter = DomainFixtures.makeStarter( refreshIntervalDays: 7, - lastRefresh: today + lastRefresh: now.adding(minutes: -(7 * 24 * 60)) ) starter.remindersEnabled = true - let requests = StarterReminderPlanner.planReminders(for: starter) - XCTAssertEqual(requests.count, 2) + let requests = StarterReminderPlanner.planReminders(for: starter, now: now) + XCTAssertEqual(requests.count, 7) let due = requests[0] XCTAssertEqual(due.identifier, "starter-due-\(starter.id.uuidString)") XCTAssertEqual(due.title, starter.name) XCTAssertEqual(due.body, "Oggi è previsto un rinfresco. Apri lo starter per registrarlo.") - let nextDueDate = Calendar.current.date(byAdding: .day, value: 7, to: today.startOfDay)! + let nextDueDate = Calendar.current.date(byAdding: .day, value: 7, to: starter.lastRefresh.startOfDay)! XCTAssertEqual(due.fireDate, nextDueDate.settingTime(hour: 9, minute: 0)) - let followUp = requests[1] - XCTAssertEqual(followUp.identifier, "starter-followup-\(starter.id.uuidString)") - XCTAssertEqual(followUp.title, starter.name) - XCTAssertEqual(followUp.body, "Non hai ancora registrato il rinfresco di oggi. Apri lo starter per farlo adesso.") - XCTAssertEqual(followUp.fireDate, nextDueDate.settingTime(hour: 9, minute: 0).adding(minutes: 24 * 60)) + let overdue = Array(requests.dropFirst()) + XCTAssertEqual(overdue.count, 6) + XCTAssertEqual(overdue.first?.identifier, "starter-overdue-\(starter.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: now.startOfDay.adding(minutes: 24 * 60).settingTime(hour: 19, minute: 0)))") + XCTAssertEqual(overdue.first?.title, starter.name) + XCTAssertEqual(overdue.first?.body, "Non hai ancora rinfrescato \(starter.name).") + XCTAssertEqual(overdue.first?.fireDate, now.startOfDay.adding(minutes: 24 * 60).settingTime(hour: 19, minute: 0)) + XCTAssertEqual(overdue.last?.fireDate, now.startOfDay.adding(minutes: 6 * 24 * 60).settingTime(hour: 19, minute: 0)) + } + + func testAlreadyOverdueStarterSchedulesTodayAtSevenPm() { + let now = Date.fixedNow.startOfDay.settingTime(hour: 10, minute: 0) + let starter = DomainFixtures.makeStarter( + name: "Madre attiva", + refreshIntervalDays: 1, + lastRefresh: now.adding(minutes: -(2 * 24 * 60)) + ) + + let requests = StarterReminderPlanner.planReminders(for: starter, now: now) + + XCTAssertEqual(requests.first?.identifier, "starter-overdue-\(starter.id.uuidString)-\(RollingOverdueReminderPlanner.identifierSuffix(for: now.settingTime(hour: 19, minute: 0)))") + XCTAssertEqual(requests.first?.fireDate, now.settingTime(hour: 19, minute: 0)) + XCTAssertEqual(requests.count, NotificationPlanningDefaults.overdueWindowDays) + } + + func testArchivedStarterReturnsNoRequestsButIdentifiersStillCoverLegacyAndWindow() { + let now = Date.fixedNow.startOfDay.settingTime(hour: 10, minute: 0) + let starter = DomainFixtures.makeStarter(refreshIntervalDays: 1, lastRefresh: now.adding(minutes: -(2 * 24 * 60))) + starter.archive() + + XCTAssertTrue(StarterReminderPlanner.planReminders(for: starter, now: now).isEmpty) + + let identifiers = StarterReminderPlanner.identifiers(for: starter, now: now) + XCTAssertTrue(identifiers.contains("starter-due-\(starter.id.uuidString)")) + XCTAssertTrue(identifiers.contains("starter-followup-\(starter.id.uuidString)")) + XCTAssertEqual( + identifiers.filter { $0.contains("starter-overdue-\(starter.id.uuidString)-") }.count, + NotificationPlanningDefaults.overdueWindowDays + ) + } +} + +final class NotificationPlanBuilderTests: XCTestCase { + func testMergeSortsDeduplicatesAndCapsBudget() { + let now = Date.fixedNow.startOfDay.settingTime(hour: 8, minute: 0) + let duplicateIdentifier = "duplicate-id" + + let plan = NotificationPlanBuilder.merge( + plans: [ + NotificationSyncPlan( + identifiersToRemove: ["b", "a"], + requests: [ + NotificationRequestPayload( + identifier: duplicateIdentifier, + title: "Later duplicate", + body: "", + route: "levain://starter/1", + fireDate: now.settingTime(hour: 12, minute: 0) + ), + NotificationRequestPayload( + identifier: "late-unique", + title: "Late", + body: "", + route: "levain://starter/2", + fireDate: now.settingTime(hour: 18, minute: 0) + ) + ] + ), + NotificationSyncPlan( + identifiersToRemove: ["a", "c"], + requests: [ + NotificationRequestPayload( + identifier: duplicateIdentifier, + title: "Earlier duplicate", + body: "", + route: "levain://starter/3", + fireDate: now.settingTime(hour: 9, minute: 0) + ) + ] + + (0..