|
|
@@ -22,6 +22,7 @@ final class BasePumpHistoryStorage: PumpHistoryStorage, Injectable {
|
|
|
private let processQueue = DispatchQueue(label: "BasePumpHistoryStorage.processQueue")
|
|
|
@Injected() private var storage: FileStorage!
|
|
|
@Injected() private var broadcaster: Broadcaster!
|
|
|
+ @Injected() private var settings: SettingsManager!
|
|
|
|
|
|
init(resolver: Resolver) {
|
|
|
injectServices(resolver)
|
|
|
@@ -32,6 +33,11 @@ final class BasePumpHistoryStorage: PumpHistoryStorage, Injectable {
|
|
|
|
|
|
private let context = CoreDataStack.shared.persistentContainer.newBackgroundContext()
|
|
|
|
|
|
+ private func roundDose(_ dose: Double, toIncrement increment: Double) -> Decimal {
|
|
|
+ let roundedValue = (dose / increment).rounded() * increment
|
|
|
+ return Decimal(roundedValue)
|
|
|
+ }
|
|
|
+
|
|
|
func storePumpEvents(_ events: [NewPumpEvent]) {
|
|
|
processQueue.async {
|
|
|
self.context.perform {
|
|
|
@@ -51,15 +57,30 @@ final class BasePumpHistoryStorage: PumpHistoryStorage, Injectable {
|
|
|
switch event.type {
|
|
|
case .bolus:
|
|
|
|
|
|
+ guard let dose = event.dose else { continue }
|
|
|
+ let amount = self.roundDose(
|
|
|
+ dose.unitsInDeliverableIncrements,
|
|
|
+ toIncrement: Double(self.settings.preferences.bolusIncrement)
|
|
|
+ )
|
|
|
+
|
|
|
guard existingEvents.isEmpty else {
|
|
|
// Duplicate found, do not store the event
|
|
|
print("Duplicate event found with timestamp: \(event.date)")
|
|
|
+
|
|
|
+ if let existingEvent = existingEvents.first(where: { $0.type == PumpEvent.bolus.rawValue }) {
|
|
|
+ if existingEvent.timestamp == event.date {
|
|
|
+ if let existingAmount = existingEvent.bolus?.amount, amount < existingAmount as Decimal {
|
|
|
+ // Update existing event with new smaller value
|
|
|
+ existingEvent.bolus?.amount = amount as NSDecimalNumber
|
|
|
+ existingEvent.bolus?.isSMB = dose.automatic ?? true
|
|
|
+
|
|
|
+ print("Updated existing event with smaller value: \(amount)")
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
continue
|
|
|
}
|
|
|
|
|
|
- guard let dose = event.dose else { continue }
|
|
|
- let amount = Decimal(string: dose.unitsInDeliverableIncrements.description)
|
|
|
-
|
|
|
let newPumpEvent = PumpEventStored(context: self.context)
|
|
|
newPumpEvent.timestamp = event.date
|
|
|
newPumpEvent.type = PumpEvent.bolus.rawValue
|