Преглед изворни кода

Add back a few mistakenly removed comments; ensure cancelation of OR and TT

Deniz Cengiz пре 1 година
родитељ
комит
5c8f5f8ef1

+ 40 - 2
Trio/Sources/Shortcuts/Override/OverridePresetsIntentRequest.swift

@@ -19,7 +19,10 @@ import UIKit
      */
     func fetchAndProcessOverrides() async throws -> [OverridePreset] {
         do {
+            // Fetch all Override Presets via OverrideStorage
             let allOverridePresetsIDs = try await overrideStorage.fetchForOverridePresets()
+
+            // Since we are fetching on a different background Thread we need to unpack the NSManagedObjectID on the correct Thread first
             return try await coredataContext.perform {
                 let overrideObjects = try allOverridePresetsIDs.compactMap { id in
                     try self.coredataContext.existingObject(with: id) as? OverrideStored
@@ -128,12 +131,15 @@ import UIKit
             if viewContext.hasChanges {
                 debug(.default, "Saving changes...")
                 try viewContext.save()
+                debug(.default, "Waiting for notification...")
                 Foundation.NotificationCenter.default.post(name: .willUpdateOverrideConfiguration, object: nil)
                 await awaitNotification(.didUpdateOverrideConfiguration)
+                debug(.default, "Notification received, continuing...")
                 intentSuccess = true
             }
 
             endBackgroundTaskSafely(&backgroundTaskID, taskName: "Override Enact")
+            debug(.default, "Finished. Override enacted via Shortcut.")
             return intentSuccess
         } catch {
             debug(
@@ -162,42 +168,74 @@ import UIKit
         var backgroundTaskID: UIBackgroundTaskIdentifier?
 
         if shouldStartBackgroundTask {
+            debug(.default, "Starting background task for override cancel")
             backgroundTaskID = .invalid
             backgroundTaskID = startBackgroundTask(withName: "Override Cancel")
         }
 
         do {
+            // Get NSManagedObjectID of all active overrides
             let ids = try await overrideStorage.loadLatestOverrideConfigurations(fetchLimit: 0)
             let results = try ids.compactMap { id in
                 try self.viewContext.existingObject(with: id) as? OverrideStored
             }
 
+            // Return early if no results
             guard !results.isEmpty else {
                 debug(.default, "No active overrides to cancel… returning early")
                 if var backgroundTaskID = backgroundTaskID {
+                    debug(.default, "Ending background task for override cancel")
                     endBackgroundTaskSafely(&backgroundTaskID, taskName: "Override Cancel")
                 }
                 return
             }
 
+            // Create OverrideRunStored entry if needed
+            if let canceledOverride = results.first {
+                let newOverrideRunStored = OverrideRunStored(context: viewContext)
+                newOverrideRunStored.id = UUID()
+                newOverrideRunStored.name = canceledOverride.name
+                newOverrideRunStored.startDate = canceledOverride.date ?? .distantPast
+                newOverrideRunStored.endDate = Date()
+                newOverrideRunStored.target = NSDecimalNumber(
+                    decimal: overrideStorage.calculateTarget(override: canceledOverride)
+                )
+                newOverrideRunStored.override = canceledOverride
+                newOverrideRunStored.isUploadedToNS = false
+            }
+
+            // Disable all active overrides
             for overrideToCancel in results {
+                let endTime = overrideToCancel.date?
+                    .addingTimeInterval(TimeInterval(truncating: overrideToCancel.duration ?? 0))
+
+                debugPrint(
+                    "Disabling override: \(overrideToCancel.name ?? "Unnamed") with end time: \(endTime?.description ?? "Unknown")"
+                )
                 overrideToCancel.enabled = false
                 overrideToCancel.isUploadedToNS = false
             }
 
             if viewContext.hasChanges {
                 try viewContext.save()
+                debug(.default, "Waiting for notification...")
                 Foundation.NotificationCenter.default.post(name: .willUpdateOverrideConfiguration, object: nil)
+                await awaitNotification(.didUpdateOverrideConfiguration)
+                debug(.default, "Notification received, continuing...")
             }
 
-            await awaitNotification(.didUpdateOverrideConfiguration)
             if var backgroundTaskID = backgroundTaskID {
+                debug(.default, "Ending background task for override cancel")
                 endBackgroundTaskSafely(&backgroundTaskID, taskName: "Override Cancel")
             }
         } catch {
             debugPrint(
-                "\(DebuggingIdentifiers.failed) Failed to disable active Overrides with error: \(error.localizedDescription)"
+                "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to disable active Overrides with error: \(error.localizedDescription)"
             )
+            if var backgroundTaskID = backgroundTaskID {
+                debug(.default, "Ending background task for override cancel")
+                endBackgroundTaskSafely(&backgroundTaskID, taskName: "Override Cancel")
+            }
         }
     }
 }

+ 34 - 5
Trio/Sources/Shortcuts/TempPresets/TempPresetsIntentRequest.swift

@@ -130,10 +130,29 @@ final class TempPresetsIntentRequest: BaseIntentsRequest {
             if viewContext.hasChanges {
                 debug(.default, "Saving changes...")
                 try viewContext.save()
-
-                // Update state variables
+                debug(.default, "Waiting for notification...")
+                // Update State variables in TempTargetView
                 Foundation.NotificationCenter.default.post(name: .willUpdateTempTargetConfiguration, object: nil)
 
+                // Prepare JSON for oref
+                guard let tempTargetDate = tempTargetObject.date, let tempTarget = tempTargetObject.target,
+                      let tempTargetDuration = tempTargetObject.duration else { return false }
+
+                let tempTargetToStoreAsJSON = TempTarget(
+                    name: tempTargetObject.name,
+                    createdAt: tempTargetDate,
+                    targetTop: tempTarget as Decimal,
+                    targetBottom: tempTarget as Decimal,
+                    duration: tempTargetDuration as Decimal,
+                    enteredBy: TempTarget.local,
+                    reason: TempTarget.custom,
+                    isPreset: tempTargetObject.isPreset,
+                    enabled: tempTargetObject.enabled,
+                    halfBasalTarget: tempTargetObject.halfBasalTarget as Decimal?
+                )
+                // Save the temp targets to JSON so that they get used by oref
+                tempTargetsStorage.saveTempTargetsToStorage([tempTargetToStoreAsJSON])
+
                 await awaitNotification(.didUpdateTempTargetConfiguration)
 
                 debug(.default, "Notification received, continuing...")
@@ -170,6 +189,7 @@ final class TempPresetsIntentRequest: BaseIntentsRequest {
         var backgroundTaskID: UIBackgroundTaskIdentifier?
 
         if shouldStartBackgroundTask {
+            debug(.default, "Starting background task for temp target cancel")
             backgroundTaskID = .invalid
             backgroundTaskID = startBackgroundTask(withName: "TempTarget Cancel")
         }
@@ -185,6 +205,7 @@ final class TempPresetsIntentRequest: BaseIntentsRequest {
                 debug(.default, "No active temp targets to cancel... returning early")
 
                 if var backgroundTaskID = backgroundTaskID {
+                    debug(.default, "Ending background task for temp target cancel")
                     endBackgroundTaskSafely(&backgroundTaskID, taskName: "TempTarget Cancel")
                 }
                 return
@@ -210,16 +231,24 @@ final class TempPresetsIntentRequest: BaseIntentsRequest {
 
             if viewContext.hasChanges {
                 try viewContext.save()
+                debug(.default, "Waiting for notification...")
                 Foundation.NotificationCenter.default.post(name: .willUpdateTempTargetConfiguration, object: nil)
+                await awaitNotification(.didUpdateOverrideConfiguration)
+                debug(.default, "Notification received, continuing...")
             }
 
-            await awaitNotification(.didUpdateOverrideConfiguration)
-
             if var backgroundTaskID = backgroundTaskID {
+                debug(.default, "Ending background task for temp target cancel")
                 endBackgroundTaskSafely(&backgroundTaskID, taskName: "TempTarget Cancel")
             }
         } catch {
-            debugPrint("Failed to disable active Temp Targets with error: \(error.localizedDescription)")
+            debugPrint(
+                "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to disable active Temp Targets with error: \(error.localizedDescription)"
+            )
+            if var backgroundTaskID = backgroundTaskID {
+                debug(.default, "Ending background task for temp target cancel")
+                endBackgroundTaskSafely(&backgroundTaskID, taskName: "TempTarget Cancel")
+            }
         }
     }
 }