BolusStateModel.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import CoreData
  2. import Foundation
  3. import LoopKit
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. final class StateModel: BaseStateModel<Provider> {
  8. @Injected() var unlockmanager: UnlockManager!
  9. @Injected() var apsManager: APSManager!
  10. @Injected() var broadcaster: Broadcaster!
  11. @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  12. // added for bolus calculator
  13. @Injected() var settings: SettingsManager!
  14. @Injected() var nsManager: NightscoutManager!
  15. @Injected() var carbsStorage: CarbsStorage!
  16. @Injected() var glucoseStorage: GlucoseStorage!
  17. @Injected() var determinationStorage: DeterminationStorage!
  18. @Published var lowGlucose: Decimal = 4 / 0.0555
  19. @Published var highGlucose: Decimal = 10 / 0.0555
  20. @Published var predictions: Predictions?
  21. @Published var amount: Decimal = 0
  22. @Published var insulinRecommended: Decimal = 0
  23. @Published var insulinRequired: Decimal = 0
  24. @Published var units: GlucoseUnits = .mgdL
  25. @Published var percentage: Decimal = 0
  26. @Published var threshold: Decimal = 0
  27. @Published var maxBolus: Decimal = 0
  28. @Published var errorString: Decimal = 0
  29. @Published var evBG: Decimal = 0
  30. @Published var insulin: Decimal = 0
  31. @Published var isf: Decimal = 0
  32. @Published var error: Bool = false
  33. @Published var minGuardBG: Decimal = 0
  34. @Published var minDelta: Decimal = 0
  35. @Published var expectedDelta: Decimal = 0
  36. @Published var minPredBG: Decimal = 0
  37. @Published var waitForSuggestion: Bool = false
  38. @Published var carbRatio: Decimal = 0
  39. @Published var addButtonPressed: Bool = false
  40. var waitForSuggestionInitial: Bool = false
  41. // added for bolus calculator
  42. @Published var target: Decimal = 0
  43. @Published var cob: Int16 = 0
  44. @Published var iob: Decimal = 0
  45. @Published var currentBG: Decimal = 0
  46. @Published var fifteenMinInsulin: Decimal = 0
  47. @Published var deltaBG: Decimal = 0
  48. @Published var targetDifferenceInsulin: Decimal = 0
  49. @Published var targetDifference: Decimal = 0
  50. @Published var wholeCob: Decimal = 0
  51. @Published var wholeCobInsulin: Decimal = 0
  52. @Published var iobInsulinReduction: Decimal = 0
  53. @Published var wholeCalc: Decimal = 0
  54. @Published var insulinCalculated: Decimal = 0
  55. @Published var fraction: Decimal = 0
  56. @Published var useCalc: Bool = false
  57. @Published var basal: Decimal = 0
  58. @Published var fattyMeals: Bool = false
  59. @Published var fattyMealFactor: Decimal = 0
  60. @Published var useFattyMealCorrectionFactor: Bool = false
  61. @Published var displayPresets: Bool = true
  62. @Published var currentBasal: Decimal = 0
  63. @Published var sweetMeals: Bool = false
  64. @Published var sweetMealFactor: Decimal = 0
  65. @Published var useSuperBolus: Bool = false
  66. @Published var superBolusInsulin: Decimal = 0
  67. @Published var meal: [CarbsEntry]?
  68. @Published var carbs: Decimal = 0
  69. @Published var fat: Decimal = 0
  70. @Published var protein: Decimal = 0
  71. @Published var note: String = ""
  72. @Published var date = Date()
  73. @Published var carbsRequired: Decimal?
  74. @Published var useFPUconversion: Bool = false
  75. @Published var dish: String = ""
  76. @Published var selection: MealPresetStored?
  77. @Published var summation: [String] = []
  78. @Published var maxCarbs: Decimal = 0
  79. @Published var id_: String = ""
  80. @Published var summary: String = ""
  81. @Published var skipBolus: Bool = false
  82. @Published var externalInsulin: Bool = false
  83. @Published var showInfo: Bool = false
  84. @Published var glucoseFromPersistence: [GlucoseStored] = []
  85. @Published var determination: [OrefDetermination] = []
  86. @Published var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  87. let now = Date.now
  88. let context = CoreDataStack.shared.persistentContainer.viewContext
  89. let backgroundContext = CoreDataStack.shared.newTaskContext()
  90. private var coreDataObserver: CoreDataObserver?
  91. typealias PumpEvent = PumpEventStored.EventType
  92. override func subscribe() {
  93. setupGlucoseNotification()
  94. coreDataObserver = CoreDataObserver()
  95. registerHandlers()
  96. setupGlucoseArray()
  97. setupDeterminationsArray()
  98. broadcaster.register(DeterminationObserver.self, observer: self)
  99. broadcaster.register(BolusFailureObserver.self, observer: self)
  100. units = settingsManager.settings.units
  101. percentage = settingsManager.settings.insulinReqPercentage
  102. maxBolus = provider.pumpSettings().maxBolus
  103. // added
  104. fraction = settings.settings.overrideFactor
  105. useCalc = settings.settings.useCalc
  106. fattyMeals = settings.settings.fattyMeals
  107. fattyMealFactor = settings.settings.fattyMealFactor
  108. sweetMeals = settings.settings.sweetMeals
  109. sweetMealFactor = settings.settings.sweetMealFactor
  110. displayPresets = settings.settings.displayPresets
  111. lowGlucose = settingsManager.settings.low
  112. highGlucose = settingsManager.settings.high
  113. maxCarbs = settings.settings.maxCarbs
  114. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  115. useFPUconversion = settingsManager.settings.useFPUconversion
  116. if waitForSuggestionInitial {
  117. Task {
  118. let ok = await apsManager.determineBasal()
  119. if !ok {
  120. self.waitForSuggestion = false
  121. self.insulinRequired = 0
  122. self.insulinRecommended = 0
  123. }
  124. }
  125. }
  126. }
  127. // MARK: - Basal
  128. func getCurrentBasal() {
  129. let basalEntries = provider.getProfile()
  130. let now = Date()
  131. let calendar = Calendar.current
  132. let dateFormatter = DateFormatter()
  133. dateFormatter.dateFormat = "HH:mm:ss"
  134. dateFormatter.timeZone = TimeZone.current
  135. for (index, entry) in basalEntries.enumerated() {
  136. guard let entryTime = dateFormatter.date(from: entry.start) else {
  137. print("Invalid entry start time: \(entry.start)")
  138. continue
  139. }
  140. // Combine the current date with the time from entry.start
  141. let entryStartTime = calendar.date(
  142. bySettingHour: calendar.component(.hour, from: entryTime),
  143. minute: calendar.component(.minute, from: entryTime),
  144. second: calendar.component(.second, from: entryTime),
  145. of: now
  146. )!
  147. let entryEndTime: Date
  148. if index < basalEntries.count - 1,
  149. let nextEntryTime = dateFormatter.date(from: basalEntries[index + 1].start)
  150. {
  151. let nextEntryStartTime = calendar.date(
  152. bySettingHour: calendar.component(.hour, from: nextEntryTime),
  153. minute: calendar.component(.minute, from: nextEntryTime),
  154. second: calendar.component(.second, from: nextEntryTime),
  155. of: now
  156. )!
  157. entryEndTime = nextEntryStartTime
  158. } else {
  159. // If it's the last entry, use the same start time plus one day as the end time
  160. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  161. }
  162. if now >= entryStartTime, now < entryEndTime {
  163. currentBasal = entry.rate
  164. break
  165. }
  166. }
  167. }
  168. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  169. /// Calculate insulin recommendation
  170. func calculateInsulin() -> Decimal {
  171. // ensure that isf is in mg/dL
  172. var conversion: Decimal {
  173. units == .mmolL ? 0.0555 : 1
  174. }
  175. let isfForCalculation = isf / conversion
  176. // insulin needed for the current blood glucose
  177. targetDifference = currentBG - target
  178. targetDifferenceInsulin = targetDifference / isfForCalculation
  179. // more or less insulin because of bg trend in the last 15 minutes
  180. fifteenMinInsulin = deltaBG / isfForCalculation
  181. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  182. wholeCob = Decimal(cob) + carbs
  183. wholeCobInsulin = wholeCob / carbRatio
  184. // determine how much the calculator reduces/ increases the bolus because of IOB
  185. iobInsulinReduction = (-1) * iob
  186. // adding everything together
  187. // add a calc for the case that no fifteenMinInsulin is available
  188. if deltaBG != 0 {
  189. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  190. } else {
  191. // add (rare) case that no glucose value is available -> maybe display warning?
  192. // if no bg is available, ?? sets its value to 0
  193. if currentBG == 0 {
  194. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  195. } else {
  196. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  197. }
  198. }
  199. // apply custom factor at the end of the calculations
  200. let result = wholeCalc * fraction
  201. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  202. if useFattyMealCorrectionFactor {
  203. insulinCalculated = result * fattyMealFactor
  204. } else if useSuperBolus {
  205. superBolusInsulin = sweetMealFactor * currentBasal
  206. insulinCalculated = result + superBolusInsulin
  207. } else {
  208. insulinCalculated = result
  209. }
  210. // display no negative insulinCalculated
  211. insulinCalculated = max(insulinCalculated, 0)
  212. insulinCalculated = min(insulinCalculated, maxBolus)
  213. guard let apsManager = apsManager else {
  214. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  215. return insulinCalculated
  216. }
  217. return apsManager.roundBolus(amount: insulinCalculated)
  218. }
  219. // MARK: - Button tasks
  220. @MainActor func invokeTreatmentsTask() {
  221. Task {
  222. addButtonPressed = true
  223. let isInsulinGiven = amount > 0
  224. let isCarbsPresent = carbs > 0
  225. let isFatPresent = fat > 0
  226. let isProteinPresent = protein > 0
  227. if isInsulinGiven {
  228. try await handleInsulin(isExternal: externalInsulin)
  229. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  230. waitForSuggestion = true
  231. } else {
  232. hideModal()
  233. return
  234. }
  235. await saveMeal()
  236. // if glucose data is stale end the custom loading animation by hiding the modal
  237. // guard glucoseOfLast20Min.first?.date ?? now >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  238. // return hideModal()
  239. // }
  240. }
  241. }
  242. // MARK: - Insulin
  243. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  244. if !isExternal {
  245. await addPumpInsulin()
  246. } else {
  247. await addExternalInsulin()
  248. }
  249. waitForSuggestion = true
  250. }
  251. @MainActor func addPumpInsulin() async {
  252. guard amount > 0 else {
  253. showModal(for: nil)
  254. return
  255. }
  256. let maxAmount = Double(min(amount, maxBolus))
  257. do {
  258. let authenticated = try await unlockmanager.unlock()
  259. if authenticated {
  260. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  261. } else {
  262. print("authentication failed")
  263. }
  264. } catch {
  265. print("authentication error for pump bolus: \(error.localizedDescription)")
  266. DispatchQueue.main.async {
  267. self.waitForSuggestion = false
  268. if self.addButtonPressed {
  269. self.hideModal()
  270. }
  271. }
  272. }
  273. }
  274. private func savePumpInsulin(amount _: Decimal) {
  275. context.perform {
  276. // create pump event
  277. let newPumpEvent = PumpEventStored(context: self.context)
  278. newPumpEvent.timestamp = Date()
  279. newPumpEvent.type = PumpEvent.bolus.rawValue
  280. // create bolus entry and specify relationship to pump event
  281. let newBolusEntry = BolusStored(context: self.context)
  282. newBolusEntry.pumpEvent = newPumpEvent
  283. newBolusEntry.amount = self.amount as NSDecimalNumber
  284. newBolusEntry.isExternal = false
  285. newBolusEntry.isSMB = false
  286. do {
  287. guard self.context.hasChanges else { return }
  288. try self.context.save()
  289. } catch {
  290. print(error.localizedDescription)
  291. }
  292. }
  293. }
  294. // MARK: - EXTERNAL INSULIN
  295. @MainActor func addExternalInsulin() async {
  296. guard amount > 0 else {
  297. showModal(for: nil)
  298. return
  299. }
  300. amount = min(amount, maxBolus * 3)
  301. do {
  302. let authenticated = try await unlockmanager.unlock()
  303. if authenticated {
  304. // store external dose to pump history
  305. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  306. // perform determine basal sync
  307. await apsManager.determineBasalSync()
  308. } else {
  309. print("authentication failed")
  310. }
  311. } catch {
  312. print("authentication error for external insulin: \(error.localizedDescription)")
  313. DispatchQueue.main.async {
  314. self.waitForSuggestion = false
  315. if self.addButtonPressed {
  316. self.hideModal()
  317. }
  318. }
  319. }
  320. }
  321. // MARK: - Carbs
  322. @MainActor func saveMeal() async {
  323. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  324. carbs = min(carbs, maxCarbs)
  325. id_ = UUID().uuidString
  326. let carbsToStore = [CarbsEntry(
  327. id: id_,
  328. createdAt: now,
  329. actualDate: date,
  330. carbs: carbs,
  331. fat: fat,
  332. protein: protein,
  333. note: note,
  334. enteredBy: CarbsEntry.manual,
  335. isFPU: false, fpuID: UUID().uuidString
  336. )]
  337. await carbsStorage.storeCarbs(carbsToStore)
  338. if carbs > 0 || fat > 0 || protein > 0 {
  339. // only perform determine basal sync if the user doesn't use the pump bolus, otherwise the enact bolus func in the APSManger does a sync
  340. if amount <= 0 {
  341. await apsManager.determineBasalSync()
  342. }
  343. }
  344. }
  345. // MARK: - Presets
  346. func deletePreset() {
  347. if selection != nil {
  348. context.delete(selection!)
  349. do {
  350. guard context.hasChanges else { return }
  351. try context.save()
  352. } catch {
  353. print(error.localizedDescription)
  354. }
  355. carbs = 0
  356. fat = 0
  357. protein = 0
  358. }
  359. selection = nil
  360. }
  361. func removePresetFromNewMeal() {
  362. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  363. if a != nil, summation[a ?? 0] != "" {
  364. summation.remove(at: a!)
  365. }
  366. }
  367. func addPresetToNewMeal() {
  368. let test: String = selection?.dish ?? "dontAdd"
  369. if test != "dontAdd" {
  370. summation.append(test)
  371. }
  372. }
  373. func addNewPresetToWaitersNotepad(_ dish: String) {
  374. summation.append(dish)
  375. }
  376. func addToSummation() {
  377. summation.append(selection?.dish ?? "")
  378. }
  379. func waitersNotepad() -> String {
  380. var filteredArray = summation.filter { !$0.isEmpty }
  381. if carbs == 0, protein == 0, fat == 0 {
  382. filteredArray = []
  383. }
  384. guard filteredArray != [] else {
  385. return ""
  386. }
  387. var carbs_: Decimal = 0.0
  388. var fat_: Decimal = 0.0
  389. var protein_: Decimal = 0.0
  390. var presetArray = [MealPresetStored]()
  391. context.performAndWait {
  392. let requestPresets = MealPresetStored.fetchRequest() as NSFetchRequest<MealPresetStored>
  393. try? presetArray = context.fetch(requestPresets)
  394. }
  395. var waitersNotepad = [String]()
  396. var stringValue = ""
  397. for each in filteredArray {
  398. let countedSet = NSCountedSet(array: filteredArray)
  399. let count = countedSet.count(for: each)
  400. if each != stringValue {
  401. waitersNotepad.append("\(count) \(each)")
  402. }
  403. stringValue = each
  404. for sel in presetArray {
  405. if sel.dish == each {
  406. carbs_ += (sel.carbs)! as Decimal
  407. fat_ += (sel.fat)! as Decimal
  408. protein_ += (sel.protein)! as Decimal
  409. break
  410. }
  411. }
  412. }
  413. let extracarbs = carbs - carbs_
  414. let extraFat = fat - fat_
  415. let extraProtein = protein - protein_
  416. var addedString = ""
  417. if extracarbs > 0, filteredArray.isNotEmpty {
  418. addedString += "Additional carbs: \(extracarbs) ,"
  419. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  420. if extraFat > 0, filteredArray.isNotEmpty {
  421. addedString += "Additional fat: \(extraFat) ,"
  422. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  423. if extraProtein > 0, filteredArray.isNotEmpty {
  424. addedString += "Additional protein: \(extraProtein) ,"
  425. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  426. if addedString != "" {
  427. waitersNotepad.append(addedString)
  428. }
  429. var waitersNotepadString = ""
  430. if waitersNotepad.count == 1 {
  431. waitersNotepadString = waitersNotepad[0]
  432. } else if waitersNotepad.count > 1 {
  433. for each in waitersNotepad {
  434. if each != waitersNotepad.last {
  435. waitersNotepadString += " " + each + ","
  436. } else { waitersNotepadString += " " + each }
  437. }
  438. }
  439. return waitersNotepadString
  440. }
  441. }
  442. }
  443. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  444. func determinationDidUpdate(_: Determination) {
  445. DispatchQueue.main.async {
  446. self.waitForSuggestion = false
  447. if self.addButtonPressed {
  448. self.hideModal()
  449. }
  450. }
  451. }
  452. func bolusDidFail() {
  453. DispatchQueue.main.async {
  454. self.waitForSuggestion = false
  455. if self.addButtonPressed {
  456. self.hideModal()
  457. }
  458. }
  459. }
  460. }
  461. extension Bolus.StateModel {
  462. private func registerHandlers() {
  463. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  464. guard let self = self else { return }
  465. self.setupDeterminationsArray()
  466. }
  467. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  468. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  469. guard let self = self else { return }
  470. self.setupGlucoseArray()
  471. }
  472. }
  473. private func setupGlucoseNotification() {
  474. /// custom notification that is sent when a batch insert of glucose objects is done
  475. Foundation.NotificationCenter.default.addObserver(
  476. self,
  477. selector: #selector(handleBatchInsert),
  478. name: .didPerformBatchInsert,
  479. object: nil
  480. )
  481. }
  482. @objc private func handleBatchInsert() {
  483. setupGlucoseArray()
  484. }
  485. }
  486. // MARK: - Setup Glucose and Determinations
  487. extension Bolus.StateModel {
  488. // Glucose
  489. private func setupGlucoseArray() {
  490. Task {
  491. let ids = await self.fetchGlucose()
  492. await updateGlucoseArray(with: ids)
  493. }
  494. }
  495. private func fetchGlucose() async -> [NSManagedObjectID] {
  496. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  497. ofType: GlucoseStored.self,
  498. onContext: backgroundContext,
  499. predicate: NSPredicate.predicateForFourHoursAgo,
  500. key: "date",
  501. ascending: false,
  502. fetchLimit: 48
  503. )
  504. return await backgroundContext.perform {
  505. return results.map(\.objectID)
  506. }
  507. }
  508. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  509. do {
  510. let glucoseObjects = try IDs.compactMap { id in
  511. try context.existingObject(with: id) as? GlucoseStored
  512. }
  513. glucoseFromPersistence = glucoseObjects
  514. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  515. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  516. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  517. currentBG = Decimal(lastGlucose)
  518. deltaBG = delta
  519. } catch {
  520. debugPrint(
  521. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  522. )
  523. }
  524. }
  525. // Determinations
  526. private func setupDeterminationsArray() {
  527. Task {
  528. let ids = await determinationStorage.fetchLastDeterminationObjectID(
  529. predicate: NSPredicate.enactedDetermination
  530. )
  531. await updateDeterminationsArray(with: ids)
  532. await updateForecastData()
  533. }
  534. }
  535. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  536. do {
  537. let determinationObjects = try IDs.compactMap { id in
  538. try context.existingObject(with: id) as? OrefDetermination
  539. }
  540. guard let mostRecentDetermination = determinationObjects.first else { return }
  541. determination = determinationObjects
  542. // setup vars for bolus calculation
  543. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  544. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  545. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  546. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  547. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  548. cob = mostRecentDetermination.cob as Int16
  549. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  550. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  551. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  552. getCurrentBasal()
  553. insulinCalculated = calculateInsulin()
  554. } catch {
  555. debugPrint(
  556. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  557. )
  558. }
  559. }
  560. }
  561. extension Bolus.StateModel {
  562. func preprocessForecastData() async
  563. -> [(id: UUID, forecastID: NSManagedObjectID, forecastValueIDs: [NSManagedObjectID])]
  564. {
  565. guard let id = determination.first?.objectID else {
  566. return []
  567. }
  568. // Get forecast and forecast values
  569. let forecastIDs = await determinationStorage.getForecastIDs(for: id, in: context)
  570. var result: [(id: UUID, forecastID: NSManagedObjectID, forecastValueIDs: [NSManagedObjectID])] = []
  571. for forecastID in forecastIDs {
  572. // Get the forecast value IDs for the given forecast ID
  573. let forecastValueIDs = await determinationStorage.getForecastValueIDs(for: forecastID, in: context)
  574. let uuid = UUID()
  575. result.append((id: uuid, forecastID: forecastID, forecastValueIDs: forecastValueIDs))
  576. }
  577. return result
  578. }
  579. @MainActor func updateForecastData() async {
  580. let forecastData = await preprocessForecastData()
  581. preprocessedData = forecastData.reduce(into: []) { result, data in
  582. guard let forecast = try? context.existingObject(with: data.forecastID) as? Forecast else {
  583. return
  584. }
  585. for forecastValueID in data.forecastValueIDs {
  586. if let forecastValue = try? context.existingObject(with: forecastValueID) as? ForecastValue {
  587. result.append((id: data.id, forecast: forecast, forecastValue: forecastValue))
  588. }
  589. }
  590. }
  591. }
  592. }